mosquitto-2.0.11/0000775000175000017500000000000014060132747012663 5ustar rogerrogermosquitto-2.0.11/pskfile.example0000664000175000017500000000002714060132747015674 0ustar rogerrogerid:deadbeef easy:12345 mosquitto-2.0.11/security/0000775000175000017500000000000014060132747014532 5ustar rogerrogermosquitto-2.0.11/security/mosquitto.apparmor0000664000175000017500000000115414060132747020342 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/lib/mosquitto/mosquitto.db.new 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-2.0.11/service/0000775000175000017500000000000014060132747014323 5ustar rogerrogermosquitto-2.0.11/service/upstart/0000775000175000017500000000000014060132747016025 5ustar rogerrogermosquitto-2.0.11/service/upstart/mosquitto.conf0000664000175000017500000000026214060132747020740 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-2.0.11/service/svscan/0000775000175000017500000000000014060132747015620 5ustar rogerrogermosquitto-2.0.11/service/svscan/run0000775000175000017500000000010014060132747016341 0ustar rogerroger#!/bin/sh /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf mosquitto-2.0.11/service/systemd/0000775000175000017500000000000014060132747016013 5ustar rogerrogermosquitto-2.0.11/service/systemd/mosquitto.service.simple0000664000175000017500000000077214060132747022737 0ustar rogerroger[Unit] Description=Mosquitto MQTT Broker Documentation=man:mosquitto.conf(5) man:mosquitto(8) After=network.target Wants=network.target [Service] ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf ExecReload=/bin/kill -HUP $MAINPID Restart=on-failure ExecStartPre=/bin/mkdir -m 740 -p /var/log/mosquitto ExecStartPre=/bin/chown mosquitto /var/log/mosquitto ExecStartPre=/bin/mkdir -m 740 -p /run/mosquitto ExecStartPre=/bin/chown mosquitto /run/mosquitto [Install] WantedBy=multi-user.target mosquitto-2.0.11/service/systemd/README0000664000175000017500000000101014060132747016663 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-2.0.11/service/systemd/mosquitto.service.notify0000664000175000017500000000103014060132747022742 0ustar rogerroger[Unit] Description=Mosquitto MQTT Broker Documentation=man:mosquitto.conf(5) man:mosquitto(8) After=network.target Wants=network.target [Service] Type=notify NotifyAccess=main ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf ExecReload=/bin/kill -HUP $MAINPID Restart=on-failure ExecStartPre=/bin/mkdir -m 740 -p /var/log/mosquitto ExecStartPre=/bin/chown mosquitto /var/log/mosquitto ExecStartPre=/bin/mkdir -m 740 -p /run/mosquitto ExecStartPre=/bin/chown mosquitto /run/mosquitto [Install] WantedBy=multi-user.target mosquitto-2.0.11/service/monit/0000775000175000017500000000000014060132747015451 5ustar rogerrogermosquitto-2.0.11/service/monit/mosquitto.monit0000664000175000017500000000020514060132747020562 0ustar rogerrogercheck process mosquitto with pidfile /run/mosquitto.pid start = "/etc/init.d/mosquitto start" stop = "/etc/init.d/mosquitto stop" mosquitto-2.0.11/config.mk0000664000175000017500000002502614060132747014466 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. # Setting to yes means the libsystemd-dev or similar package will need to be # installed. 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 # Build with unix domain socket support WITH_UNIX_SOCKETS:=yes # Build mosquitto_sub with cJSON support WITH_CJSON:=yes # Build mosquitto with support for the $CONTROL topics. WITH_CONTROL:=yes # Build the broker with the jemalloc allocator WITH_JEMALLOC:=no # Build with xtreport capability. This is for debugging purposes and is # probably of no particular interest to end users. WITH_XTREPORT=no # ============================================================================= # End of user configuration # ============================================================================= # Also bump lib/mosquitto.h, CMakeLists.txt, # installer/mosquitto.nsi, installer/mosquitto64.nsi VERSION=2.0.11 # 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) ARCH:=$(shell uname -p) ifeq ($(UNAME),SunOS) ifeq ($(CC),cc) CFLAGS?=-O else CFLAGS?=-Wall -ggdb -O2 endif else CFLAGS?=-Wall -ggdb -O2 -Wconversion -Wextra endif STATIC_LIB_DEPS:= APP_CPPFLAGS=$(CPPFLAGS) -I. -I../../ -I../../include -I../../src -I../../lib APP_CFLAGS=$(CFLAGS) -DVERSION=\""${VERSION}\"" APP_LDFLAGS:=$(LDFLAGS) LIB_CPPFLAGS=$(CPPFLAGS) -I. -I.. -I../include -I../../include LIB_CFLAGS:=$(CFLAGS) LIB_CXXFLAGS:=$(CXXFLAGS) LIB_LDFLAGS:=$(LDFLAGS) LIB_LIBADD:=$(LIBADD) BROKER_CPPFLAGS:=$(LIB_CPPFLAGS) -I../lib BROKER_CFLAGS:=${CFLAGS} -DVERSION="\"${VERSION}\"" -DWITH_BROKER BROKER_LDFLAGS:=${LDFLAGS} BROKER_LDADD:= CLIENT_CPPFLAGS:=$(CPPFLAGS) -I.. -I../include CLIENT_CFLAGS:=${CFLAGS} -DVERSION="\"${VERSION}\"" CLIENT_LDFLAGS:=$(LDFLAGS) -L../lib CLIENT_LDADD:= PASSWD_LDADD:= PLUGIN_CPPFLAGS:=$(CPPFLAGS) -I../.. -I../../include PLUGIN_CFLAGS:=$(CFLAGS) -fPIC PLUGIN_LDFLAGS:=$(LDFLAGS) ifneq ($(or $(findstring $(UNAME),FreeBSD), $(findstring $(UNAME),OpenBSD), $(findstring $(UNAME),NetBSD)),) BROKER_LDADD:=$(BROKER_LDADD) -lm BROKER_LDFLAGS:=$(BROKER_LDFLAGS) -Wl,--dynamic-list=linker.syms SEDINPLACE:=-i "" else BROKER_LDADD:=$(BROKER_LDADD) -ldl -lm SEDINPLACE:=-i 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) SEDINPLACE:= ifeq ($(ARCH),sparc) ifeq ($(CC),cc) LIB_CFLAGS:=$(LIB_CFLAGS) -xc99 -KPIC else LIB_CFLAGS:=$(LIB_CFLAGS) -fPIC endif endif ifeq ($(ARCH),i386) 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) APP_CPPFLAGS:=$(APP_CPPFLAGS) -DWITH_TLS BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_TLS BROKER_LDADD:=$(BROKER_LDADD) -lssl -lcrypto CLIENT_CPPFLAGS:=$(CLIENT_CPPFLAGS) -DWITH_TLS LIB_CPPFLAGS:=$(LIB_CPPFLAGS) -DWITH_TLS LIB_LIBADD:=$(LIB_LIBADD) -lssl -lcrypto PASSWD_LDADD:=$(PASSWD_LDADD) -lcrypto 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 ifeq ($(WITH_CONTROL),yes) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_CONTROL endif MAKE_ALL:=mosquitto ifeq ($(WITH_DOCS),yes) MAKE_ALL:=$(MAKE_ALL) docs endif ifeq ($(WITH_JEMALLOC),yes) BROKER_LDADD:=$(BROKER_LDADD) -ljemalloc endif ifeq ($(WITH_UNIX_SOCKETS),yes) BROKER_CPPFLAGS:=$(BROKER_CPPFLAGS) -DWITH_UNIX_SOCKETS LIB_CPPFLAGS:=$(LIB_CPPFLAGS) -DWITH_UNIX_SOCKETS CLIENT_CPPFLAGS:=$(CLIENT_CPPFLAGS) -DWITH_UNIX_SOCKETS 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) -I../deps LIB_CPPFLAGS:=$(LIB_CPPFLAGS) -I../deps PLUGIN_CPPFLAGS:=$(PLUGIN_CPPFLAGS) -I../../deps endif ifeq ($(WITH_COVERAGE),yes) BROKER_CFLAGS:=$(BROKER_CFLAGS) -coverage BROKER_LDFLAGS:=$(BROKER_LDFLAGS) -coverage PLUGIN_CFLAGS:=$(PLUGIN_CFLAGS) -coverage PLUGIN_LDFLAGS:=$(PLUGIN_LDFLAGS) -coverage LIB_CFLAGS:=$(LIB_CFLAGS) -coverage LIB_LDFLAGS:=$(LIB_LDFLAGS) -coverage CLIENT_CFLAGS:=$(CLIENT_CFLAGS) -coverage CLIENT_LDFLAGS:=$(CLIENT_LDFLAGS) -coverage endif ifeq ($(WITH_CJSON),yes) CLIENT_CFLAGS:=$(CLIENT_CFLAGS) -DWITH_CJSON CLIENT_LDADD:=$(CLIENT_LDADD) -lcjson CLIENT_STATIC_LDADD:=$(CLIENT_STATIC_LDADD) -lcjson CLIENT_LDFLAGS:=$(CLIENT_LDFLAGS) endif ifeq ($(WITH_XTREPORT),yes) BROKER_CFLAGS:=$(BROKER_CFLAGS) -DWITH_XTREPORT endif BROKER_LDADD:=${BROKER_LDADD} ${LDADD} CLIENT_LDADD:=${CLIENT_LDADD} ${LDADD} PASSWD_LDADD:=${PASSWD_LDADD} ${LDADD} mosquitto-2.0.11/CMakeLists.txt0000664000175000017500000001126514060132747015430 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. cmake_minimum_required(VERSION 3.0) cmake_policy(SET CMP0042 NEW) project(mosquitto) set (VERSION 2.0.11) list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/") add_definitions (-DCMAKE -DVERSION=\"${VERSION}\") if (WIN32) add_definitions("-D_CRT_SECURE_NO_WARNINGS") add_definitions("-D_CRT_NONSTDC_NO_DEPRECATE") endif (WIN32) if(APPLE) set(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "${CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS} -undefined dynamic_lookup") endif(APPLE) include(GNUInstallDirs) option(WITH_BUNDLED_DEPS "Build with bundled dependencies?" ON) 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_UNIX_SOCKETS "Include Unix Domain Socket support?" ON) if (WITH_UNIX_SOCKETS AND NOT WIN32) add_definitions("-DWITH_UNIX_SOCKETS") endif (WITH_UNIX_SOCKETS AND NOT WIN32) 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) elseif (ANDROID) set (PTHREAD_LIBRARIES "") set (PTHREAD_INCLUDE_DIR "") 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(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) option(WITH_CJSON "Build with cJSON support (required for dynamic security plugin and useful for mosquitto_sub)?" ON) if (WITH_CJSON) FIND_PACKAGE(cJSON) if (CJSON_FOUND) message(STATUS ${CJSON_FOUND}) else (CJSON_FOUND) message(STATUS "Optional dependency cJSON not found. Some features will be disabled.") endif(CJSON_FOUND) endif() # ======================================== # Include projects # ======================================== option(WITH_CLIENTS "Build clients?" ON) option(WITH_BROKER "Build broker?" ON) option(WITH_APPS "Build apps?" ON) option(WITH_PLUGINS "Build plugins?" ON) option(DOCUMENTATION "Build documentation?" ON) add_subdirectory(lib) if (WITH_CLIENTS) add_subdirectory(client) endif (WITH_CLIENTS) if (WITH_BROKER) add_subdirectory(src) endif (WITH_BROKER) if (WITH_APPS) add_subdirectory(apps) endif (WITH_APPS) if (WITH_PLUGINS) add_subdirectory(plugins) endif (WITH_PLUGINS) if (DOCUMENTATION) add_subdirectory(man) endif (DOCUMENTATION) # ======================================== # Install config file # ======================================== if (WITH_BROKER) install(FILES mosquitto.conf aclfile.example pskfile.example pwfile.example DESTINATION "${CMAKE_INSTALL_SYSCONFDIR}/mosquitto") endif (WITH_BROKER) # ======================================== # 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-2.0.11/about.html0000664000175000017500000000471514060132747014672 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 2.0 ("EPL") and Eclipse Distribution License Version 1.0 ("EDL"). A copy of the EPL is available at https://www.eclipse.org/legal/epl-2.0/ 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-2.0.11/aclfile.example0000664000175000017500000000034614060132747015642 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-2.0.11/ChangeLog.txt0000664000175000017500000037006114060132747015262 0ustar rogerroger2.0.11 - 2021-06-08 =================== Security: - If a MQTT v5 client connects with a crafted CONNECT packet a memory leak will occur. This has been fixed. Broker: - Fix possible crash having just upgraded from 1.6 if `per_listener_settings true` is set, and a SIGHUP is sent to the broker before a client has reconnected to the broker. Closes #2167. - Fix bridge not reconnectng if the first reconnection attempt fails. Closes #2207. - Improve QoS 0 outgoing packet queueing. - Fix non-reachable bridge blocking the broker on Windows. Closes #2172. - Fix possible corruption of pollfd array on Windows when bridges were reconnecting. Closes #2173. - Fix QoS 0 messages not being queued when `queue_qos0_messages` was enabled. Closes #2224. Clients: - If sending mosquitto_sub output to a pipe, mosquitto_sub will now detect that the pipe has closed and disconnect. Closes #2164. - Fix `mosquitto_pub -l` quitting if a message publication is attempted when the broker is temporarily unavailable. Closes #2187. 2.0.10 - 2021-04-03 ================== Security: - CVE-2021-23980: If an authenticated client connected with MQTT v5 sent a malformed CONNACK message to the broker a NULL pointer dereference occurred, most likely resulting in a segfault. Affects versions 2.0.0 to 2.0.9 inclusive. Broker: - Don't over write new receive-maximum if a v5 client connects and takes over an old session. Closes #2134. - Fix CVE-xxxx-xxxx. Closes #2163. Clients: - Set `receive-maximum` to not exceed the `-C` message count in mosquitto_sub and mosquitto_rr, to avoid potentially lost messages. Closes #2134. - Fix TLS-PSK mode not working with port 8883. Closes #2152. Client library: - Fix possible socket leak. This would occur if a client was using `mosquitto_loop_start()`, then if the connection failed due to the remote server being inaccessible they called `mosquitto_loop_stop(, true)` and recreated the mosquitto object. Build: - A variety of minor build related fixes, like functions not having previous declarations. - Fix CMake cross compile builds not finding opensslconf.h. Closes #2160. - Fix build on Solaris non-sparc. Closes #2136. 2.0.9 - 2021-03-11 ================== Security: - If an empty or invalid CA file was provided to the client library for verifying the remote broker, then the initial connection would fail but subsequent connections would succeed without verifying the remote broker certificate. Closes #2130. - If an empty or invalid CA file was provided to the broker for verifying the remote broker for an outgoing bridge connection then the initial connection would fail but subsequent connections would succeed without verifying the remote broker certificate. Closes #2130. Broker: - Fix encrypted bridge connections incorrectly connecting when `bridge_cafile` is empty or invalid. Closes #2130. - Fix `tls_version` behaviour not matching documentation. It was setting the exact TLS version to use, not the minimium TLS version to use. Closes #2110. - Fix messages to `$` prefixed topics being rejected. Closes #2111. - Fix QoS 0 messages not being delivered when max_queued_bytes was configured. Closes #2123. - Fix bridge increasing backoff calculation. - Improve handling of invalid combinations of listener address and bind interface configurations. Closes #2081. - Fix `max_keepalive` option not applying to clients connecting with keepalive set to 0. Closes #2117. Client library: - Fix encrypted connections incorrectly connecting when the CA file passed to `mosquitto_tls_set()` is empty or invalid. Closes #2130. - Fix connections retrying very rapidly in some situations. Build: - Fix cmake epoll detection. 2.0.8 - 2021-02-25 ================== Broker: - Fix incorrect datatypes in `struct mosquitto_evt_tick`. This changes the size and offset of two of the members of this struct, and changes the size of the struct. This is an ABI break, but is considered to be acceptable because plugins should never be allocating their own instance of this struct, and currently none of the struct members are used for anything, so a plugin should not be accessing them. It would also be safe to read/write from the existing struct parameters. - Give compile time warning if libwebsockets compiled without external poll support. Closes #2060. - Fix memory tracking not being available on FreeBSD or macOS. Closes #2096. Client library: - Fix mosquitto_{pub|sub}_topic_check() functions not returning MOSQ_ERR_INVAL on topic == NULL. Clients: - Fix possible loss of data in `mosquitto_pub -l` when sending multiple long lines. Closes #2078. Build: - Provide a mechanism for Docker users to run a broker that doesn't use authentication, without having to provide their own configuration file. Closes #2040. 2.0.7 - 2021-02-04 ================== Broker: - Fix exporting of executable symbols on BSD when building via makefile. - Fix some minor memory leaks on exit only. - Fix possible memory leak on connect. Closes #2057. - Fix openssl engine not being able to load private key. Closes #2066. Clients: - Fix config files truncating options after the first space. Closes #2059. Build: - Fix man page building to not absolutely require xsltproc when using CMake. This now handles the case where we are building from the released tar, or building from git if xsltproc is available, or building from git if xsltproc is not available. 1.6.13 - 2021-02-04 =================== Broker: - Fix crash on Windows if loading a plugin fails. Closes #1866. - Fix DH group not being set for TLS connections, which meant ciphers using DHE couldn't be used. Closes #1925. Closes #1476. - Fix local bridges being disconnected on SIGHUP. Closes #1942. - Fix $SYS/broker/publish/messages/+ counters not being updated for QoS 1, 2 messages. Closes #1968. - Fix listener not being reassociated with client when reloading a persistence file and `per_listener_settings true` is set and the client did not set a username. Closes #1891. - Fix file logging on Windows. Closes #1880. - Fix bridge sock not being removed from sock hash on error. Closes #1897. Client library: - Fix build on Mac Big Sur. Closes #1905. - Fix DH group not being set for TLS connections, which meant ciphers using DHE couldn't be used. Closes #1925. Closes #1476. Clients: - mosquitto_sub will now quit with an error if the %U option is used on Windows, rather than just quitting. Closes #1908. - Fix config files truncating options after the first space. Closes #2059. Apps: - Perform stricter parsing of input username in mosquitto_passwd. Closes #570126 (Eclipse bugzilla). Build: - Enable epoll support in CMake builds. 2.0.6 - 2021-01-28 ================== Broker: - Fix calculation of remaining length parameter for websockets clients that send fragmented packets. Closes #1974. Broker: - Fix potential duplicate Will messages being sent when a will delay interval has been set. - Fix message expiry interval property not being honoured in `mosquitto_broker_publish` and `mosquitto_broker_publish_copy`. - Fix websockets listeners with TLS not responding. Closes #2020. - Add notes that libsystemd-dev or similar is needed if building with systemd support. Closes #2019. - Improve logging in obscure cases when a client disconnects. Closes #2017. - Fix reloading of listeners where multiple listeners have been defined with the same port but different bind addresses. Closes #2029. - Fix `message_size_limit` not applying to the Will payload. Closes #2022. - The error topic-alias-invalid was being sent if an MQTT v5 client published a message with empty topic and topic alias set, but the topic alias hadn't already been configured on the broker. This has been fixed to send a protocol error, as per section 3.3.4 of the specification. - Note in the man pages that SIGHUP reloads TLS certificates. Closes #2037. - Fix bridges not always connecting on Windows. Closes #2043. Apps: - Allow command line arguments to override config file options in mosquitto_ctrl. Closes #2010. - mosquitto_ctrl: produce an error when requesting a new password if both attempts do not match. Closes #2011. Build: - Fix cmake builds using `WITH_CJSON=no` not working if cJSON not found. Closes #2026. Other: - The SPDX identifiers for EDL-1.0 have been changed to BSD-3-Clause as per The Eclipse legal documentation generator. The licenses are identical. 2.0.5 - 2021-01-11 ================== Broker: - Fix `auth_method` not being provided to the extended auth plugin event. Closes #1975. - Fix large packets not being completely published to slow clients. Closes #1977. - Fix bridge connection not relinquishing POLLOUT after messages are sent. Closes #1979. - Fix apparmor incorrectly denying access to /var/lib/mosquitto/mosquitto.db.new. Closes #1978. - Fix potential intermittent initial bridge connections when using poll(). - Fix `bind_interface` option. Closes #1999. - Fix invalid behaviour in dynsec plugin if a group or client is deleted before a role that was attached to the group or client is deleted. Closes #1998. - Improve logging in dynsec addGroupRole command. Closes #2005. - Improve logging in dynsec addGroupClient command. Closes #2008. Client library: - Improve documentation around the `_v5()` and non-v5 functions, e.g. `mosquitto_publish()` and `mosquitto_publish_v5(). Build: - `install` Makefile target should depend on `all`, not `mosquitto`, to ensure that man pages are always built. Closes #1989. - Fixes for lots of minor build warnings highlighted by Visual Studio. Apps: - Disallow control characters in mosquitto_passwd usernames. - Fix incorrect description in mosquitto_ctrl man page. Closes #1995. - Fix `mosquitto_ctrl dynsec getGroup` not showing roles. Closes #1997. 2.0.4 - 2020-12-22 ================== Broker: - Fix $SYS/broker/publish/messages/+ counters not being updated for QoS 1, 2 messages. Closes #1968. - mosquitto_connect_bind_async() and mosquitto_connect_bind_v5() should not reset the bind address option if called with bind_address == NULL. - Fix dynamic security configuration possibly not being reloaded on Windows only. Closes #1962. - Add more log messages for dynsec load/save error conditions. - Fix websockets connections blocking non-websockets connections on Windows. Closes #1934. Build: - Fix man pages not being built when using CMake. Closes #1969. 2.0.3 - 2020-12-17 ================== Security: - Running mosquitto_passwd with the following arguments only `mosquitto_passwd -b password_file username password` would cause the username to be used as the password. Broker: - Fix excessive CPU use on non-Linux systems when the open file limit is set high. Closes #1947. - Fix LWT not being sent on client takeover when the existing session wasn't being continued. Closes #1946. - Fix bridges possibly not completing connections when WITH_ADNS is in use. Closes #1960. - Fix QoS 0 messages not being delivered if max_queued_messages was set to 0. Closes #1956. - Fix local bridges being disconnected on SIGHUP. Closes #1942. - Fix slow initial bridge connections for WITH_ADNS=no. - Fix persistence_location not appending a '/'. Clients: - Fix mosquitto_sub being unable to terminate with Ctrl-C if a successful connection is not made. Closes #1957. Apps: - Fix `mosquitto_passwd -b` using username as password (not if `-c` is also used). Closes #1949. Build: - Fix `install` target when using WITH_CJSON=no. Closes #1938. - Fix `generic` docker build. Closes #1945. 2.0.2 - 2020-12-10 ================== Broker: - Fix build regression for WITH_WEBSOCKETS=yes on non-Linux systems. 2.0.1 - 2020-12-10 ================== Broker: - Fix websockets connections on Windows blocking subsequent connections. Closes #1934. - Fix DH group not being set for TLS connections, which meant ciphers using DHE couldn't be used. Closes #1925. Closes #1476. - Fix websockets listeners not causing the main loop not to wake up. Closes #1936. Client library: - Fix DH group not being set for TLS connections, which meant ciphers using DHE couldn't be used. Closes #1925. Closes #1476. Apps: - Fix `mosquitto_passwd -U` Build: - Fix cjson include paths. - Fix build using WITH_TLS=no when the openssl headers aren't available. - Distribute cmake/ and snap/ directories in tar. 2.0.0 - 2020-12-03 ================== Breaking changes: - When the Mosquitto broker is run without configuring any listeners it will now bind to the loopback interfaces 127.0.0.1 and/or ::1. This means that only connections from the local host will be possible. Running the broker as `mosquitto` or `mosquitto -p 1883` will bind to the loopback interface. Running the broker with a configuration file with no listeners configured will bind to the loopback interface with port 1883. Running the broker with a listener defined will bind by default to `0.0.0.0` / `::` and so will be accessible from any interface. It is still possible to bind to a specific address/interface. If the broker is run as `mosquitto -c mosquitto.conf -p 1884`, and a listener is defined in the configuration file, then the port defined on the command line will be IGNORED, and no listener configured for it. - All listeners now default to `allow_anonymous false` unless explicitly set to true in the configuration file. This means that when configuring a listener the user must either configure an authentication and access control method, or set `allow_anonymous true`. When the broker is run without a configured listener, and so binds to the loopback interface, anonymous connections are allowed. - If Mosquitto is run on as root on a unix like system, it will attempt to drop privileges as soon as the configuration file has been read. This is in contrast to the previous behaviour where elevated privileges were only dropped after listeners had been started (and hence TLS certificates loaded) and logging had been started. The change means that clients will never be able to connect to the broker when it is running as root, unless the user explicitly sets it to run as root, which is not advised. It also means that all locations that the broker needs to access must be available to the unprivileged user. In particular those people using TLS certificates from Lets Encrypt will need to do something to allow Mosquitto to access those certificates. An example deploy renewal hook script to help with this is at `misc/letsencrypt/mosquitto-copy.sh`. The user that Mosquitto will change to are the one provided in the configuration, `mosquitto`, or `nobody`, in order of availability. - The `pid_file` option will now always attempt to write a pid file, regardless of whether the `-d` argument is used when running the broker. - The `tls_version` option now defines the *minimum* TLS protocol version to be used, rather than the exact version. Closes #1258. - The `max_queued_messages` option has been increased from 100 to 1000 by default, and now also applies to QoS 0 messages, when a client is connected. - The mosquitto_sub, mosquitto_pub, and mosquitto_rr clients will now load OS provided CA certificates by default if `-L mqtts://...` is used, or if the port is set to 8883 and no other CA certificates are loaded. - Minimum support libwebsockets version is now 2.4.0 - The license has changed from "EPL-1.0 OR EDL-1.0" to "EPL-2.0 OR EDL-1.0". Broker features: - New plugin interface which is more flexible, easier to develop for and easier to extend. - New dynamic security plugin, which allows clients, groups, and roles to be defined and updated as the broker is running. - Performance improvements, particularly for higher numbers of clients. - When running as root, if dropping privileges to the "mosquitto" user fails, then try "nobody" instead. This reduces the burden on users installing Mosquitto themselves. - Add support for Unix domain socket listeners. - Add `bridge_outgoing_retain` option, to allow outgoing messages from a bridge to have the retain bit completely disabled, which is useful when bridging to e.g. Amazon or Google. - Add support for MQTT v5 bridges to handle the "retain-available" property being false. - Allow MQTT v5.0 outgoing bridges to fall back to MQTT v3.1.1 if connecting to a v3.x only broker. - DLT logging is now configurable at runtime with `log_dest dlt`. Closes #1735. - Add `mosquitto_broker_publish()` and `mosquitto_broker_publish_copy()` functions, which can be used by plugins to publish messages. - Add `mosquitto_client_protocol_version()` function which can be used by plugins to determine which version of MQTT a client has connected with. - Add `mosquitto_kick_client_by_clientid()` and `mosquitto_kick_client_by_username()` functions, which can be used by plugins to disconnect clients. - Add support for handling $CONTROL/ topics in plugins. - Add support for PBKDF2-SHA512 password hashing. - Enabling certificate based TLS encryption is now through certfile and keyfile, not capath or cafile. - Added support for controlling UNSUBSCRIBE calls in v5 plugin ACL checks. - Add "deny" acl type. Closes #1611. - The broker now sends the receive-maximum property for MQTT v5 CONNACKs. - Add the `bridge_max_packet_size` option. Closes #265. - Add the `bridge_bind_address` option. Closes #1311. - TLS certificates for the server are now reloaded on SIGHUP. - Default for max_queued_messages has been changed to 1000. - Add `ciphers_tls1.3` option, to allow setting TLS v1.3 ciphersuites. Closes #1825. - Bridges now obey MQTT v5 server-keepalive. - Add bridge support for the MQTT v5 maximum-qos property. - Log client port on new connections. Closes #1911. Broker fixes: - Send DISCONNECT with `malformed-packet` reason code on invalid PUBLISH, SUBSCRIBE, and UNSUBSCRIBE packets. - Document that X509_free() must be called after using mosquitto_client_certificate(). Closes #1842. - Fix listener not being reassociated with client when reloading a persistence file and `per_listener_settings true` is set and the client did not set a username. Closes #1891. - Fix bridge sock not being removed from sock hash on error. Closes #1897. - mosquitto_password now forbids the : character. Closes #1833. - Fix `log_timestamp_format` not applying to `log_dest topic`. Closes #1862. - Fix crash on Windows if loading a plugin fails. Closes #1866. - Fix file logging on Windows. Closes #1880. - Report an error if the config file is set to a directory. Closes #1814. - Fix bridges incorrectly setting Wills to manage remote notifications when `notifications_local_only` was set true. Closes #1902. Client library features: - Client no longer generates random client ids for v3.1.1 clients, these are now expected to be generated on the broker. This matches the behaviour for v5 clients. Closes #291. - Add support for connecting to brokers through Unix domain sockets. - Add `mosquitto_property_identifier()`, for retrieving the identifier integer for a property. - Add `mosquitto_property_identifier_to_string()` for converting a property identifier integer to the corresponding property name string. - Add `mosquitto_property_next()` to retrieve the next property in a list, for iterating over property lists. - mosquitto_pub now handles the MQTT v5 retain-available property by never setting the retain bit. - Added MOSQ_OPT_TCP_NODELAY, to allow disabling Nagle's algorithm on client sockets. Closes #1526. - Add `mosquitto_ssl_get()` to allow clients to access their SSL structure and perform additional verification. - Add MOSQ_OPT_BIND_ADDRESS to allow setting of a bind address independently of the `mosquitto_connect*()` call. - Add `MOSQ_OPT_TLS_USE_OS_CERTS` option, to instruct the client to load and trust OS provided CA certificates for use with TLS connections. Client library fixes: - Fix send quota being incorrecly reset on reconnect. Closes #1822. - Don't use logging until log mutex is initialised. Closes #1819. - Fix missing mach/mach_time.h header on OS X. Closes #1831. - Fix connect properties not being sent when the client automatically reconnects. Closes #1846. Client features: - Add timeout return code (27) for `mosquitto_sub -W ` and `mosquitto_rr -W `. Closes #275. - Add support for connecting to brokers through Unix domain sockets with the `--unix` argument. - Use cJSON library for producing JSON output, where available. Closes #1222. - Add support for outputting MQTT v5 property information to mosquitto_sub/rr JSON output. Closes #1416. - Add `--pretty` option to mosquitto_sub/rr for formatted/unformatted JSON output. - Add support for v5 property printing to mosquitto_sub/rr in non-JSON mode. Closes #1416. - Add `--nodelay` to all clients to allow them to use the MOSQ_OPT_TCP_NODELAY option. - Add `-x` to all clients to all the session-expiry-interval property to be easily set for MQTT v5 clients. - Add `--random-filter` to mosquitto_sub, to allow only a certain proportion of received messages to be printed. - mosquitto_sub %j and %J timestamps are now in a ISO 8601 compatible format. - mosquitto_sub now supports extra format specifiers for field width and precision for some parameters. - Add `--version` for all clients. - All clients now load OS provided CA certificates if used with `-L mqtts://...`, or if port is set to 8883 and no other CA certificates are used. Closes #1824. - Add the `--tls-use-os-certs` option to all clients. Client fixes: - mosquitto_sub will now exit if all subscriptions were denied. - mosquitto_pub now sends 0 length files without an error when using `-f`. - Fix description of `-e` and `-t` arguments in mosquitto_rr. Closes #1881. - mosquitto_sub will now quit with an error if the %U option is used on Windows, rather than just quitting. Closes #1908. 1.6.12 - 2020-08-19 =================== Security: - In some circumstances, Mosquitto could leak memory when handling PUBLISH messages. This is limited to incoming QoS 2 messages, and is related to the combination of the broker having persistence enabled, a clean session=false client, which was connected prior to the broker restarting, then has reconnected and has now sent messages at a sufficiently high rate that the incoming queue at the broker has filled up and hence messages are being dropped. This is more likely to have an effect where max_queued_messages is a small value. This has now been fixed. Closes #1793. Broker: - Build warning fixes when building with WITH_BRIDGE=no and WITH_TLS=no. Clients: - All clients exit with an error exit code on CONNACK failure. Closes #1778. - Don't busy loop with `mosquitto_pub -l` on a slow connection. 1.5.10 - 2020-08-19 =================== Security: - In some circumstances, Mosquitto could leak memory when handling PUBLISH messages. This is limited to incoming QoS 2 messages, and is related to the combination of the broker having persistence enabled, a clean session=false client, which was connected prior to the broker restarting, then has reconnected and has now sent messages at a sufficiently high rate that the incoming queue at the broker has filled up and hence messages are being dropped. This is more likely to have an effect where max_queued_messages is a small value. This has now been fixed. Closes #1793. 1.6.11 - 2020-08-11 =================== Security: - On Windows the Mosquitto service was being installed without appropriate path quoting, this has been fixed. Broker: - Fix usage message only mentioning v3.1.1. Closes #1713. - Fix broker refusing to start if only websockets listeners were defined. Closes #1740. - Change systemd unit files to create /var/log/mosquitto before starting. Closes #821. - Don't quit with an error if opening the log file isn't possible. Closes #821. - Fix bridge topic remapping when using "" as the topic. Closes #1749. - Fix messages being queued for disconnected bridges when clean start was set to true. Closes #1729. - Fix `autosave_interval` not being triggered by messages being delivered. Closes #1726. - Fix websockets clients sometimes not being disconnected promptly. Closes #1718. - Fix "slow" file based logging by switching to line based buffering. Closes #1689. Closes #1741. - Log protocol error message where appropriate from a bad UNSUBSCRIBE, rather than the generic "socket error". - Don't try to start DLT logging if DLT unavailable, to avoid a long delay when shutting down the broker. Closes #1735. - Fix potential memory leaks. Closes #1773. Closes #1774. - Fix clients not receiving messages after a previous client with the same client ID and positive will delay interval quit. Closes #1752. - Fix overly broad HAVE_PTHREAD_CANCEL compile guard. Closes #1547. Client library: - Improved documentation around connect callback return codes. Close #1730. - Fix `mosquitto_publish*()` no longer returning `MOSQ_ERR_NO_CONN` when not connected. Closes #1725. - `mosquitto_loop_start()` now sets a thread name on Linux, FreeBSD, NetBSD, and OpenBSD. Closes #1777. - Fix `mosquitto_loop_stop()` not stopping on Windows. Closes #1748. Closes #117. 1.6.10 - 2020-05-25 =================== Broker: - Report invalid bridge prefix+pattern combinations at config parsing time rather than letting the bridge fail later. Issue #1635. - Fix `mosquitto_passwd -b` not updating passwords for existing users correctly. Creating a new user with `-b` worked without problem. Closes #1664. - Fix memory leak when connecting clients rejected. - Don't disconnect clients that are already disconnected. This prevents the session expiry being extended on SIGHUP. Closes #1521. - Fix support for openssl 3.0. - Fix check when loading persistence file of a different version than the native version. Closes #1684. - Fix possible assert crash associated with bridge reconnecting when compiled without epoll support. Closes #1700. Client library: - Don't treat an unexpected PUBACK, PUBREL, or PUBCOMP as a fatal error. Issue #1629. - Fix support for openssl 3.0. - Fix memory leaks from multiple calls to `mosquitto_lib_init()`/`mosquitto_lib_cleanup()`. Closes #1691. - Fix documentation on return code of `mosquitto_lib_init()` for Windows. Closes #1690. Clients: - Fix mosquitto_sub %j or %J not working on Windows. Closes #1674. Build: - Various fixes for building with 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. - Don't reset queued messages state on CONNACK. Fixes bug with duplicate messages on connection. 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-2.0.11/snap/0000775000175000017500000000000014060132747013624 5ustar rogerrogermosquitto-2.0.11/snap/local/0000775000175000017500000000000014060132747014716 5ustar rogerrogermosquitto-2.0.11/snap/local/default_config.conf0000664000175000017500000000003414060132747020533 0ustar rogerrogerpersistence false user root mosquitto-2.0.11/snap/local/launcher.sh0000775000175000017500000000265114060132747017062 0ustar rogerroger#!/bin/sh # Wrapper to check for custom config in $SNAP_USER_COMMON or $SNAP_COMMON and # use it otherwise fall back to the included basic config which will at least # allow mosquitto to run and do something. # This script will also copy the full example config in to SNAP_USER_COMMON or # SNAP_COMMON so that people can refer to it. # # The decision about whether to use SNAP_USER_COMMON or SNAP_COMMON is taken # based on the user that runs the command. If the user is root, it is assumed # that mosquitto is being run as a system daemon, and SNAP_COMMON will be used. # If a non-root user runs the command, then SNAP_USER_COMMON will be used. case "$SNAP_USER_COMMON" in */root/snap/mosquitto/common*) COMMON=$SNAP_COMMON ;; *) COMMON=$SNAP_USER_COMMON ;; esac CONFIG_FILE="$SNAP/default_config.conf" CUSTOM_CONFIG="$COMMON/mosquitto.conf" # Copy the example config if it doesn't exist if [ ! -e "$COMMON/mosquitto_example.conf" ] then echo "Copying example config to $COMMON/mosquitto_example.conf" echo "You can create a custom config by creating a file called $CUSTOM_CONFIG" cp $SNAP/mosquitto.conf $COMMON/mosquitto_example.conf fi # Does the custom config exist? If so use it. if [ -e "$CUSTOM_CONFIG" ] then echo "Found config in $CUSTOM_CONFIG" CONFIG_FILE=$CUSTOM_CONFIG else echo "Using default config from $CONFIG_FILE" fi # Launch the snap $SNAP/usr/sbin/mosquitto -c $CONFIG_FILE $@ mosquitto-2.0.11/snap/snapcraft.yaml0000664000175000017500000000563014060132747016475 0ustar rogerrogername: mosquitto version: 2.0.11 summary: Eclipse Mosquitto MQTT broker description: This is a message broker that supports version 5.0, 3.1.1, and 3.1 of the MQTT protocol. MQTT provides a method of carrying out messaging using a publish/subscribe model. It is lightweight, both in terms of bandwidth usage and ease of implementation. This makes it particularly useful at the edge of the network where a sensor or other simple device may be implemented using an arduino for example. confinement: strict grade: stable base: core18 apps: mosquitto: command: launcher.sh daemon: simple restart-condition: always plugs: [home, network, network-bind] ctrl: command: usr/bin/mosquitto_ctrl plugs: [home, network] pub: command: usr/bin/mosquitto_pub plugs: [home, network] rr: command: usr/bin/mosquitto_rr plugs: [home, network] sub: command: usr/bin/mosquitto_sub plugs: [home, network] passwd: command: usr/bin/mosquitto_passwd plugs: [home] parts: script: plugin: dump source: snap/local/ prime: - default_config.conf - launcher.sh config: plugin: dump source: . prime: - mosquitto.conf mosquitto: after: - lws plugin: make make-parameters: ["prefix=/usr", "WITH_WEBSOCKETS=yes", "WITH_ADNS=yes", "CFLAGS=-Wall -ggdb -O2 -I$SNAPCRAFT_STAGE/include -D_GNU_SOURCE"] source: https://github.com/eclipse/mosquitto source-type: git build-packages: - libssl-dev - xsltproc - docbook-xsl - gcc - g++ stage-packages: - libssl1.0.0 - ca-certificates prime: - usr/sbin/mosquitto - usr/bin/mosquitto_ctrl - usr/bin/mosquitto_pub - usr/bin/mosquitto_rr - usr/bin/mosquitto_sub - usr/bin/mosquitto_passwd - usr/lib/libmosquitto.so* - usr/lib/mosquitto_dynamic_security.so* - lib/*-linux-gnu/libcrypto.so* - lib/*-linux-gnu/libssl.so* - usr/include/mosquitto.h - usr/include/mosquitto_broker.h - usr/include/mosquitto_plugin.h - usr/include/mqtt_protocol.h lws: after: - cjson plugin: cmake configflags: ["-DLWS_IPV6=ON", "-DLWS_WITHOUT_CLIENT=ON", "-DLWS_WITHOUT_EXTENSIONS=ON", "-DLWS_WITH_ZIP_FOPS=OFF", "-DLWS_WITH_ZLIB=OFF", "-DLWS_WITH_SHARED=OFF"] source: https://github.com/warmcat/libwebsockets/archive/v2.4.2.tar.gz source-type: tar stage: - include/libwebsockets.h - include/lws_config.h - lib/libwebsockets.a prime: [-*] cjson: plugin: cmake configflags: ["-DCMAKE_C_FLAGS=-fPIC", "-DBUILD_SHARED_AND_STATIC_LIBS=OFF", "-DBUILD_SHARED_LIBS=OFF", "-DCJSON_BUILD_SHARED_LIBS=OFF", "-DCJSON_OVERRIDE_BUILD_SHARED_LIBS=OFF"] source: https://github.com/DaveGamble/cJSON/archive/v1.7.14.tar.gz source-type: tar stage: - include/cjson/cJSON.h - lib/libcjson.a prime: [-*] mosquitto-2.0.11/examples/0000775000175000017500000000000014060132747014501 5ustar rogerrogermosquitto-2.0.11/examples/mysql_log/0000775000175000017500000000000014060132747016507 5ustar rogerrogermosquitto-2.0.11/examples/mysql_log/mysql_log.c0000664000175000017500000000527714060132747020674 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-2.0.11/examples/mysql_log/Makefile0000664000175000017500000000043714060132747020153 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-2.0.11/examples/publish/0000775000175000017500000000000014060132747016147 5ustar rogerrogermosquitto-2.0.11/examples/publish/basic-1.c0000664000175000017500000001057614060132747017543 0ustar rogerroger/* * This example shows how to publish messages from outside of the Mosquitto network loop. */ #include #include #include #include #include /* Callback called when the client receives a CONNACK message from the broker. */ void on_connect(struct mosquitto *mosq, void *obj, int reason_code) { /* Print out the connection result. mosquitto_connack_string() produces an * appropriate string for MQTT v3.x clients, the equivalent for MQTT v5.0 * clients is mosquitto_reason_string(). */ printf("on_connect: %s\n", mosquitto_connack_string(reason_code)); if(reason_code != 0){ /* If the connection fails for any reason, we don't want to keep on * retrying in this example, so disconnect. Without this, the client * will attempt to reconnect. */ mosquitto_disconnect(mosq); } /* You may wish to set a flag here to indicate to your application that the * client is now connected. */ } /* Callback called when the client knows to the best of its abilities that a * PUBLISH has been successfully sent. For QoS 0 this means the message has * been completely written to the operating system. For QoS 1 this means we * have received a PUBACK from the broker. For QoS 2 this means we have * received a PUBCOMP from the broker. */ void on_publish(struct mosquitto *mosq, void *obj, int mid) { printf("Message with mid %d has been published.\n", mid); } int get_temperature(void) { sleep(1); /* Prevent a storm of messages - this pretend sensor works at 1Hz */ return random()%100; } /* This function pretends to read some data from a sensor and publish it.*/ void publish_sensor_data(struct mosquitto *mosq) { char payload[20]; int temp; int rc; /* Get our pretend data */ temp = get_temperature(); /* Print it to a string for easy human reading - payload format is highly * application dependent. */ snprintf(payload, sizeof(payload), "%d", temp); /* Publish the message * mosq - our client instance * *mid = NULL - we don't want to know what the message id for this message is * topic = "example/temperature" - the topic on which this message will be published * payloadlen = strlen(payload) - the length of our payload in bytes * payload - the actual payload * qos = 2 - publish with QoS 2 for this example * retain = false - do not use the retained message feature for this message */ rc = mosquitto_publish(mosq, NULL, "example/temperature", strlen(payload), payload, 2, false); if(rc != MOSQ_ERR_SUCCESS){ fprintf(stderr, "Error publishing: %s\n", mosquitto_strerror(rc)); } } int main(int argc, char *argv[]) { struct mosquitto *mosq; int rc; /* Required before calling other mosquitto functions */ mosquitto_lib_init(); /* Create a new client instance. * id = NULL -> ask the broker to generate a client id for us * clean session = true -> the broker should remove old sessions when we connect * obj = NULL -> we aren't passing any of our private data for callbacks */ mosq = mosquitto_new(NULL, true, NULL); if(mosq == NULL){ fprintf(stderr, "Error: Out of memory.\n"); return 1; } /* Configure callbacks. This should be done before connecting ideally. */ mosquitto_connect_callback_set(mosq, on_connect); mosquitto_publish_callback_set(mosq, on_publish); /* Connect to test.mosquitto.org on port 1883, with a keepalive of 60 seconds. * This call makes the socket connection only, it does not complete the MQTT * CONNECT/CONNACK flow, you should use mosquitto_loop_start() or * mosquitto_loop_forever() for processing net traffic. */ rc = mosquitto_connect(mosq, "test.mosquitto.org", 1883, 60); if(rc != MOSQ_ERR_SUCCESS){ mosquitto_destroy(mosq); fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc)); return 1; } /* Run the network loop in a background thread, this call returns quickly. */ rc = mosquitto_loop_start(mosq); if(rc != MOSQ_ERR_SUCCESS){ mosquitto_destroy(mosq); fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc)); return 1; } /* At this point the client is connected to the network socket, but may not * have completed CONNECT/CONNACK. * It is fairly safe to start queuing messages at this point, but if you * want to be really sure you should wait until after a successful call to * the connect callback. * In this case we know it is 1 second before we start publishing. */ while(1){ publish_sensor_data(mosq); } mosquitto_lib_cleanup(); return 0; } mosquitto-2.0.11/examples/subscribe_simple/0000775000175000017500000000000014060132747020033 5ustar rogerrogermosquitto-2.0.11/examples/subscribe_simple/single.c0000664000175000017500000000103614060132747021460 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-2.0.11/examples/subscribe_simple/callback.c0000664000175000017500000000110514060132747021730 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-2.0.11/examples/subscribe_simple/multiple.c0000664000175000017500000000116514060132747022035 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-2.0.11/examples/temperature_conversion/temperature_conversion.cpp0000664000175000017500000000230314060132747026607 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_fahrenheit; 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_fahrenheit = temp_celsius*9.0/5.0 + 32.0; snprintf(buf, 50, "%f", temp_fahrenheit); publish(NULL, "temperature/fahrenheit", strlen(buf), buf); } } void mqtt_tempconv::on_subscribe(int mid, int qos_count, const int *granted_qos) { printf("Subscription succeeded.\n"); } mosquitto-2.0.11/examples/temperature_conversion/temperature_conversion.h0000664000175000017500000000062214060132747026256 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-2.0.11/examples/temperature_conversion/readme.txt0000664000175000017500000000046014060132747023301 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 Fahrenheit and republishes on temperature/fahrenheit. mosquitto-2.0.11/examples/temperature_conversion/Makefile0000664000175000017500000000071214060132747022743 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-2.0.11/examples/subscribe/0000775000175000017500000000000014060132747016462 5ustar rogerrogermosquitto-2.0.11/examples/subscribe/basic-1.c0000664000175000017500000001005314060132747020044 0ustar rogerroger/* * This example shows how to write a client that subscribes to a topic and does * not do anything other than handle the messages that are received. */ #include #include #include #include #include /* Callback called when the client receives a CONNACK message from the broker. */ void on_connect(struct mosquitto *mosq, void *obj, int reason_code) { int rc; /* Print out the connection result. mosquitto_connack_string() produces an * appropriate string for MQTT v3.x clients, the equivalent for MQTT v5.0 * clients is mosquitto_reason_string(). */ printf("on_connect: %s\n", mosquitto_connack_string(reason_code)); if(reason_code != 0){ /* If the connection fails for any reason, we don't want to keep on * retrying in this example, so disconnect. Without this, the client * will attempt to reconnect. */ mosquitto_disconnect(mosq); } /* Making subscriptions in the on_connect() callback means that if the * connection drops and is automatically resumed by the client, then the * subscriptions will be recreated when the client reconnects. */ rc = mosquitto_subscribe(mosq, NULL, "example/temperature", 1); if(rc != MOSQ_ERR_SUCCESS){ fprintf(stderr, "Error subscribing: %s\n", mosquitto_strerror(rc)); /* We might as well disconnect if we were unable to subscribe */ mosquitto_disconnect(mosq); } } /* Callback called when the broker sends a SUBACK in response to a SUBSCRIBE. */ void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { int i; bool have_subscription = false; /* In this example we only subscribe to a single topic at once, but a * SUBSCRIBE can contain many topics at once, so this is one way to check * them all. */ for(i=0; itopic, msg->qos, (char *)msg->payload); } int main(int argc, char *argv[]) { struct mosquitto *mosq; int rc; /* Required before calling other mosquitto functions */ mosquitto_lib_init(); /* Create a new client instance. * id = NULL -> ask the broker to generate a client id for us * clean session = true -> the broker should remove old sessions when we connect * obj = NULL -> we aren't passing any of our private data for callbacks */ mosq = mosquitto_new(NULL, true, NULL); if(mosq == NULL){ fprintf(stderr, "Error: Out of memory.\n"); return 1; } /* Configure callbacks. This should be done before connecting ideally. */ mosquitto_connect_callback_set(mosq, on_connect); mosquitto_subscribe_callback_set(mosq, on_subscribe); mosquitto_message_callback_set(mosq, on_message); /* Connect to test.mosquitto.org on port 1883, with a keepalive of 60 seconds. * This call makes the socket connection only, it does not complete the MQTT * CONNECT/CONNACK flow, you should use mosquitto_loop_start() or * mosquitto_loop_forever() for processing net traffic. */ rc = mosquitto_connect(mosq, "test.mosquitto.org", 1883, 60); if(rc != MOSQ_ERR_SUCCESS){ mosquitto_destroy(mosq); fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc)); return 1; } /* Run the network loop in a blocking call. The only thing we do in this * example is to print incoming messages, so a blocking call here is fine. * * This call will continue forever, carrying automatic reconnections if * necessary, until the user calls mosquitto_disconnect(). */ mosquitto_loop_forever(mosq, -1, 1); mosquitto_lib_cleanup(); return 0; } mosquitto-2.0.11/mosquitto.conf0000664000175000017500000011443414060132747015605 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 # 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 # Set the maximum QoS supported. Clients publishing at a QoS higher than # specified here will be disconnected. #max_qos 2 # 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 1000. Set # to 0 for no maximum (not recommended). # See also queue_qos0_messages. # See also max_queued_bytes. #max_queued_messages 1000 # # 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/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 set to "mosquitto", or left unset, and the "mosquitto" user does not exist # then it will drop privileges to the "nobody" user instead. # 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 # ================================================================= # 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. # # On systems that support Unix Domain Sockets, it is also possible # to create a # Unix socket rather than opening a TCP socket. In # this case, the port number should be set to 0 and a unix socket # path must be provided, e.g. # listener 0 /tmp/mosquitto.sock # # listener port-number [ip address/host name/unix socket path] #listener # 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 `ipv4` to force the listener to only use IPv4, or set to `ipv6` to # force the listener to only use IPv6. If you want support for both IPv4 and # IPv6, then do not use the socket_domain option. # #socket_domain # 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. If used # with the [ip address/host name] part of the listener definition, then the # bind_interface option will take priority. # Not available on Windows. # # 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, ciphers, and ciphers_tls13 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. # Both of certfile and keyfile must be defined to enable certificate based # TLS encryption. # 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. This applies to TLS 1.2 and earlier versions only. Use # ciphers_tls1.3 for TLS v1.3. #ciphers # Choose which TLS v1.3 ciphersuites are used for this listener. # Defaults to "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256" #ciphers_tls1.3 # 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 # cafile and capath define methods of accessing the PEM encoded # Certificate Authority certificates that will be considered trusted when # checking incoming client certificates. # 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 # 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. # 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 dlt # # 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. # # The dlt destination is for the automotive `Diagnostic Log and Trace` tool. # This requires that Mosquitto has been compiled with DLT support. # # 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 false, unless there are no listeners defined in the configuration # file, in which case it is set to true, but connections are only allowed from # the local machine. #allow_anonymous false # ----------------------------------------------------------------- # 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|deny] # # The access type is controlled using "read", "write", "readwrite" or "deny". # 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 "deny" option can used to explicity deny access to a topic that would # otherwise be granted by a broader read/write/readwrite statement. Any "deny" # topics are handled before topics that grant read/write access. # # 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 you need to have the bridge connect over a particular network interface, # use bridge_bind_address to tell the bridge which local IP address the socket # should bind to, e.g. `bridge_bind_address 192.168.1.10` #bridge_bind_address # 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 mqttv50, mqttv311 or mqttv31. 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 # Some MQTT brokers do not allow retained messages. MQTT v5 gives a mechanism # for brokers to tell clients that they do not support retained messages, but # this is not possible for MQTT v3.1.1 or v3.1. If you need to bridge to a # v3.1.1 or v3.1 broker that does not support retained messages, set the # bridge_outgoing_retain option to false. This will remove the retain bit on # all outgoing messages to that bridge, regardless of any other setting. #bridge_outgoing_retain true # If you wish to restrict the size of messages sent to a remote bridge, use the # bridge_max_packet_size option. This sets the maximum number of bytes for # the total message, including headers and payload. # Note that MQTT v5 brokers may provide their own maximum-packet-size property. # In this case, the smaller of the two limits will be used. # Set to 0 for "unlimited". #bridge_max_packet_size 0 # ----------------------------------------------------------------- # 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-2.0.11/man/0000775000175000017500000000000014060132747013436 5ustar rogerrogermosquitto-2.0.11/man/mosquitto_ctrl_dynsec.1.meta0000664000175000017500000000020714060132747021101 0ustar rogerroger.. title: mosquitto_ctrl dynamic security man page .. slug: mosquitto_ctrl_dynsec-1 .. category: man .. type: man .. pretty_url: False mosquitto-2.0.11/man/mosquitto.80000664000175000017500000005667314060132747015614 0ustar rogerroger'\" t .\" Title: mosquitto .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 06/09/2021 .\" Manual: System management commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO" "8" "06/09/2021" "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 5\&.0/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, then the broker will listen on port 1883 bound to the loopback interface, and the default values as described in \fBmosquitto.conf\fR(5) are used\&. .if n \{\ .sp .\} .RS 4 .it 1 an-trap .nr an-no-space-flag 1 .nr an-break-flag 1 .br .ps +1 \fBImportant\fR .ps -1 .br See the \fB\-p\fR option for a description of changes in behaviour from 1\&.6\&.x to 2\&.0\&. .sp .5v .RE .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\&. May be specified up to 10 times to open multiple sockets listening on different ports\&. .if n \{\ .sp .\} .RS 4 .it 1 an-trap .nr an-no-space-flag 1 .nr an-break-flag 1 .br .ps +1 \fBImportant\fR .ps -1 .br In version 1\&.6\&.x and earlier, the listener defined by \fB\-p\fR (or the default port of 1883) would be bound to all interfaces and so be accessible from any network\&. It could also be used in combination with \fB\-c\fR\&. .sp From version 2\&.0 onwards, the listeners defined with \fB\-p\fR are bound to the loopback interface only, and so can only be connected to from the local machine\&. If both \fB\-p\fR is used and a listener is defined in a configuration file, then the \fB\-p\fR options are IGNORED\&. .sp .5v .RE .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 "MQTT SUPPORT" .PP Mosquitto supports MQTT v5\&.0, v3\&.1\&.1, and v3\&.1\&. .SS "MQTT v5\&.0" .PP Mosquitto provides full MQTT v5\&.0 support, but some features are not used directly\&. The following sections describe the new features and explain where Mosquitto does not make use of a feature\&. .sp .it 1 an-trap .nr an-no-space-flag 1 .nr an-break-flag 1 .br .ps +1 \fBFeatures\fR .RS 4 .PP \fBEnhanced authentication\fR .RS 4 Basic MQTT authentication uses username/password checks\&. Enhanced authentication allows different authentication schemes to be integrated into MQTT, and even those schemes with multiple step processes\&. Clients request a particular type of authentication and if the broker is configured for that scheme the authentication continues\&. Mosquitto supports enhanced authentication through plugins\&. .RE .PP \fBError handling\fR .RS 4 Most MQTT packets now have the concept of a \fBreason code\fR which indicates success or failure, and what the failure was\&. Mosquitto provides full support for reason codes, but does not make use of the \fBreason string\fR feature which can be used to provide a human readable error string to explain the reason code\&. .RE .PP \fBFlow control\fR .RS 4 The number of "in flight" messages for QoS 1 and QoS 2 can be controlled by both the client and the broker\&. .RE .PP \fBRequest / response\fR .RS 4 MQTT v5\&.0 adds a request/response pattern that allows a client to publish a message and instruct the subscribers of that message where to publish a response\&. .RE .PP \fBServer redirection\fR .RS 4 Server redirection is the concept of telling a client to connect to a different MQTT broker, either on CONNECT or with a broker initiated DISCONNECT\&. Mosquitto does not currently make use of this feature\&. .RE .PP \fBShared subscriptions\fR .RS 4 When multiple clients subscribe to the same shared subscription, only one client out of the group will receive each message which allows for distributing work loads\&. .RE .RE .sp .it 1 an-trap .nr an-no-space-flag 1 .nr an-break-flag 1 .br .ps +1 \fBPacket properties\fR .RS 4 .PP MQTT v5\&.0 allows properties to be added to packets to control certain behaviour\&. Unless noted, Mosquitto support the properties listed below\&. .PP \fBCONNECT\fR .RS 4 .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Authentication data .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Authentication method .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Maximum packet size .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Receive maximum .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Request problem information \- supported but not used .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Request response information \- supported but not used .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Session expiry interval .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Topic alias maximum .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} User property .RE .RE .PP \fBLast will and testament\fR .RS 4 .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Content type .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Correlation data .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Message expiry interval .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Payload format indicator .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Response topic .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} User property .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Will delay interval .RE .RE .PP \fBCONNACK\fR .RS 4 .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Assigned client identifier .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Authentication data .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Authentication method .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Maximum packet size .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Maximum qos .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Reason string \- supported but not used .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Receive maximum .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Response information \- supported but not used .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Retain available .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Server keep alive .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Server reference \- supported but not used .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Session expiry interval .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Shared subscription available .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Subscription identifiers available .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Topic alias maximum .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} User property .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Wildcard subscription available .RE .RE .PP \fBPUBLISH\fR .RS 4 .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Content type .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Correlation data .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Message expiry interval .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Payload format indicator .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Response topic .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Subscription identifier .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Topic alias .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} User property .RE .RE .PP \fBPUBACK / PUBREC / PUBREL / PUBCOMP / SUBACK / SUBSCRIBE / SUBACK\fR .RS 4 .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Reason string \- supported but not used .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} User property .RE .RE .PP \fBSUBSCRIBE\fR .RS 4 .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Subscription identifier .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} User property .RE .RE .PP \fBDISCONNECT\fR .RS 4 .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Reason string \- supported but not used .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Server reference \- supported but not used .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Session expiry interval .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} User property .RE .RE .PP \fBAUTH\fR .RS 4 .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Authentication method .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Authentication data .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} Reason string \- supported but not used .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} User property .RE .RE .RE .SS "MQTT v3\&.1\&.1" .PP Mosquitto provides full MQTT v3\&.1\&.1 support\&. .SS "MQTT v3\&.1" .PP Mosquitto provides full MQTT v3\&.1 support\&. .SS "MQTT v3" .PP MQTT v3 is an obsolete version of the protocol that does not support username/password authentication and used the \fBclean start\fR flag in the CONNECT packet which applied only to the start of a session\&. An MQTT v3 client will be able to successfully connect to a Mosquitto instance that does not require authentication\&. .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\&. .sp If TLS certificates are in use, then mosquitto will also reload certificate on receiving a SIGHUP\&. .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_ctrl\fR(1), \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-2.0.11/man/mosquitto_ctrl_dynsec.10000664000175000017500000000450314060132747020157 0ustar rogerroger'\" t .\" Title: mosquitto_ctrl_dynsec .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 06/09/2021 .\" Manual: Commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO_CTRL_DYNSE" "1" "06/09/2021" "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_ctrl_dynsec \- mosquitto_ctrl module for controlling the Mosquitto Dynamic Security plugin\&. .SH "SYNOPSIS" .HP \w'\fBmosquitto_ctrl\fR\ 'u \fBmosquitto_ctrl\fR [connection\-options] dynsec dynsec\-command [command\-options] .SH "DESCRIPTION" .PP This page describes the \fBdynsec\fR module for \fBmosquitto_ctrl\fR(1)\&. See the mosquitto_ctrl man page for details of the options for connecting to remote brokers, in particular since this module works with authentication and access control, it is crucial that secure encrypted connections are used\&. .SH "COMMANDS" .SS "Configuration file initialisation" .PP .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} mosquitto_ctrl dynsec init config\-filename admin\-user [admin\-password] .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_pub\fR(1), \fBmosquitto_sub\fR(1), \fBmosquitto\fR(8), \fBlibmosquitto\fR(3), \fBmosquitto-tls\fR(7) .SH "AUTHOR" .PP Roger Light mosquitto-2.0.11/man/mosquitto_sub.1.meta0000664000175000017500000000015514060132747017363 0ustar rogerroger.. title: mosquitto_sub man page .. slug: mosquitto_sub-1 .. category: man .. type: man .. pretty_url: False mosquitto-2.0.11/man/mqtt.7.xml0000664000175000017500000002031614060132747015314 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-2.0.11/man/mosquitto-tls.70000664000175000017500000001022014060132747016365 0ustar rogerroger'\" t .\" Title: mosquitto-tls .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 06/09/2021 .\" Manual: Conventions and miscellaneous .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO\-TLS" "7" "06/09/2021" "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-2.0.11/man/mosquitto_pub.1.xml0000664000175000017500000011313214060132747017232 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 socket path port-number username password message-topic URL bind-address command identifier value client-id client-id-prefix keepalive-time message-QoS count seconds protocol-version session-expiry-interval file message topic payload qos file dir file file ciphers version protocol engine pem engine kpass-sha1 hex-key identity ciphers version socks-url 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 'clean session' / enable persistent client mode. When this argument is used, the broker will be instructed not to clean existing sessions for the same client id when the client connects, and sessions will never expire when the client disconnects. MQTT v5 clients can change their session expiry interval with the argument. When a session is persisted on the broker, 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 and does not clean the session, 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. Disable Nagle's algorithm for the socket. This means that latency of sent messages is reduced, which is particularly noticeable for small, reasonably infrequent messages. Using this option may result in more packets being sent than would normally be necessary. 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. Note that zero length payloads are never retained. If you send a zero length payload retained message it will clear any retained message on the topic. 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 . If used, this will load and trust the OS provided CA certificates. This can be used in conjunction with and and can be used on its own to enable TLS mode. This will be set by default if is used, or if port is 8883 and no other certificate options are used. 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. Connect to a broker through a local unix domain socket instead of a TCP socket. This is a replacement for and . For example: See the option in mosquitto.conf 5 to configure Mosquitto to listen on a unix socket. 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 . Note that zero length payloads are never retained. If you send a zero length payload retained message it will clear any retained message on the topic. The topic on which to send a Will, in the event that the client disconnects unexpectedly. Set the session-expiry-interval property on the CONNECT packet. Applies to MQTT v5 clients only. Set to 0-4294967294 to specify the session will expire in that many seconds after the client disconnects, or use -1, 4294967295, or ∞ for a session that does not expire. Defaults to -1 if -c is also given, or 0 if -c not given. If the session is set to never expire, either with -x or -c, then a client id must be provided. 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, note use instead) (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) Exit Status mosquitto_sub returns zero on success, or non-zero on error. If the connection is refused by the broker at the MQTT level, then the exit code is the CONNACK reason code. If another error occurs, the exit code is a libmosquitto return value. MQTT v3.1.1 CONNACK codes: Success Connection refused: Bad protocol version Connection refused: Identifier rejected Connection refused: Server unavailable Connection refused: Bad username/password Connection refused: Not authorized MQTT v5 CONNACK codes: Success Unspecified error Malformed packet Protocol error Implementation specific error Unsupported protocol version Client ID not valid Bad username or password Not authorized Server unavailable Server busy Banned Server shutting down Bad authentication method Keep alive timeout Session taken over Topic filter invalid Topic name invalid Receive maximum exceeded Topic alias invalid Packet too large Message rate too high Quota exceeded Administrative action Payload format invalid Retain not supported QoS not supported Use another server Server moved Shared subscriptions not supported Connection rate exceeded Maximum connect time Subscription IDs not supported Wildcard subscriptions not supported 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-2.0.11/man/CMakeLists.txt0000664000175000017500000000334714060132747016205 0ustar rogerroger# If we are building from a release tarball, the man pages should already be built, so them. # If we are building from git, then the man pages will not be built. In this # case, attempt to find xsltproc, and if found build the man pages. If xsltproc # could not be found, then the man pages will not be built or installed - # because the install is optional. if(NOT WIN32) find_program(XSLTPROC xsltproc OPTIONAL) if(XSLTPROC) function(compile_manpage page) add_custom_command(OUTPUT ${CMAKE_SOURCE_DIR}/man/${page} COMMAND xsltproc ${CMAKE_SOURCE_DIR}/man/${page}.xml -o ${CMAKE_SOURCE_DIR}/man/ MAIN_DEPENDENCY ${CMAKE_SOURCE_DIR}/man/${page}.xml) add_custom_target(${page} ALL DEPENDS ${CMAKE_SOURCE_DIR}/man/${page}) endfunction() compile_manpage("mosquitto_ctrl.1") compile_manpage("mosquitto_ctrl_dynsec.1") compile_manpage("mosquitto_passwd.1") compile_manpage("mosquitto_pub.1") compile_manpage("mosquitto_sub.1") compile_manpage("mosquitto_rr.1") compile_manpage("libmosquitto.3") compile_manpage("mosquitto.conf.5") compile_manpage("mosquitto-tls.7") compile_manpage("mqtt.7") compile_manpage("mosquitto.8") else() message(FATAL_ERROR "xsltproc not found: manpages cannot be built") endif() endif() install(FILES mosquitto_ctrl.1 mosquitto_ctrl_dynsec.1 mosquitto_passwd.1 mosquitto_pub.1 mosquitto_sub.1 mosquitto_rr.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 OPTIONAL) install(FILES libmosquitto.3 DESTINATION ${CMAKE_INSTALL_MANDIR}/man3 OPTIONAL) install(FILES mosquitto.conf.5 DESTINATION ${CMAKE_INSTALL_MANDIR}/man5 OPTIONAL) install(FILES mosquitto-tls.7 mqtt.7 DESTINATION ${CMAKE_INSTALL_MANDIR}/man7 OPTIONAL) install(FILES mosquitto.8 DESTINATION ${CMAKE_INSTALL_MANDIR}/man8 OPTIONAL) mosquitto-2.0.11/man/mosquitto.conf.5.xml0000664000175000017500000027044014060132747017322 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. An overview is also available at 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 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. Mosquitto provides the Dynamic Security plugin which handles username/password authentication and access control in a much more flexible way than a password file. See 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|deny] <topic> The access type is controlled using "read", "write", "readwrite" or "deny". 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 "deny" option can used to explicitly deny access to a topic that would otherwise be granted by a broader read/write/readwrite statement. Any "deny" topics are handled before topics that grant read/write access. 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|deny] <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. See also [ 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 false, unless no listeners are defined in the configuration file, in which case it set to true, but connections are only allowed from the local machine. If is true, this option applies to the current listener being configured only. If is false, this option applies to all listeners. In version 1.6.x and earlier, this option defaulted to true unless there was another security option set. Reloaded on reload signal. [ true | false ] This option is deprecated and will be removed in a future version. The behaviour will default to true. 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. See also [ 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 This option is deprecated and will be removed in a future version. 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. logs to the broker topic '$SYS/broker/log/<severity>', where severity is one of E, W, N, I, M which are 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. Debug messages are never logged on topics. 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. The destination is for the automotive `Diagnostic Log and Trace` tool. This requires that Mosquitto has been compiled with DLT support. 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 1000. 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 and [ 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. 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. 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/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 ] 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 set to "mosquitto" or left unset, and if the "mosquitto" user does not exist, then mosquitto will change to the "nobody" user instead. If this is set to another value and 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. 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 This option is deprecated and will be removed in a future version. Use the instead. 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. If used at the same time as the for the default listener, or the bind address/host part of the , then will take priority. This option is not available on Windows. 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/unix socket path 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. On systems that support Unix Domain Sockets, this option can also be used to create a Unix socket rather than opening a TCP socket. In this case, the port must be set to 0, and the unix socket path must be given. 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.conf. Not reloaded on reload signal. value 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 publishing 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 This option is deprecated and will be removed in a future version. Use the instead. 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 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 is used to define the path to a file containing the PEM encoded CA certificates that are trusted when checking incoming client certificates. directory path is used to define a directory that contains PEM encoded CA certificates that are trusted when checking incoming client certificates. 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. This option and must be present to enable certificate based TLS encryption. The certificate pointed to by this option will be reloaded when Mosquitto receives a SIGHUP signal. This can be used to load new certificates prior to the existing ones expiring. cipher:list The list of allowed ciphers for this listener, for TLS v1.2 and earlier only, each separated with a colon. Available ciphers can be obtained using the "openssl ciphers" command. cipher:list The list of allowed ciphersuites for this listener, for TLS v1.3, each separated with a colon. 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 server key. This option and must be present to enable certificate based TLS encryption. The private key pointed to by this option will be reloaded when Mosquitto receives a SIGHUP signal. This can be used to load new keys prior to the existing ones expiring. [ 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 minimum 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 TLS v1.3 and v1.2. In Mosquitto version 1.6.x and earlier, this option set the only TLS protocol version that was allowed, rather than the minimum. [ 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 minimum 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 TLS v1.3 and v1.2. In Mosquitto version 1.6.x and earlier, this option set the only TLS protocol version that was allowed, rather than the minimum. [ 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. ip address If you need to have the bridge connect over a particular network interface, use bridge_bind_address to tell the bridge which local IP address the socket should bind to, e.g. . value If you wish to restrict the size of messages sent to a remote bridge, use this option. This sets the maximum number of bytes for the total message, including headers and payload. Note that MQTT v5 brokers may provide their own maximum-packet-size property. In this case, the smaller of the two limits will be used. Set to 0 for "unlimited". [ true | false ] Some MQTT brokers do not allow retained messages. MQTT v5 gives a mechanism for brokers to tell clients that they do not support retained messages, but this is not possible for MQTT v3.1.1 or v3.1. If you need to bridge to a v3.1.1 or v3.1 broker that does not support retained messages, set the option to false. This will remove the retain bit on all outgoing messages to that bridge, regardless of any other setting. Defaults to true. version Set the version of the MQTT protocol to use with for this bridge. Can be one of mqttv50, mqttv311 or mqttv31. Defaults to mqttv311. [ 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. [ true | false] The regular covers both the local subscriptions and the remote subscriptions. local_cleansession allows splitting this. Setting false will mean that the local connection will preserve subscription, independent of the remote connection. Defaults to the value of bridge.cleansession unless explicitly specified. 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 true to disable the hostname verification. Setting this option to true means that a malicious third party could potentially impersonate 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-2.0.11/man/mosquitto_sub.1.xml0000664000175000017500000015277414060132747017254 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 socket path 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 chance filter-out unsub-topic protocol-version message-processing-timeout session-expiry-interval 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 'clean session' / enable persistent client mode. When this argument is used, the broker will be instructed not to clean existing sessions for the same client id when the client connects, and sessions will never expire when the client disconnects. MQTT v5 clients can change their session expiry interval with the argument. When a session is persisted on the broker, 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 and does not clean the session, 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 . Disable Nagle's algorithm for the socket. This means that latency of sent messages is reduced, which is particularly noticeable for small, reasonably infrequent messages. Using this option may result in more packets being sent than would normally be necessary. 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. When using the JSON output format %j or %J, the default is to print in an unformatted fashion. Specifying prints messages in a prettier, more human readable format. 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. This option can be used to reduce the proportion of messages that mosquitto_sub prints. The default behaviour is to print all incoming messages. Setting the chance to a floating point value between 0.1 and 100.0 will ensure that on average that percentage of messages will be printed. 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 . If used, this will load and trust the OS provided CA certificates. This can be used in conjunction with and and can be used on its own to enable TLS mode. This will be set by default if is used, or if port is 8883 and no other certificate options are used. 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. Connect to a broker through a local unix domain socket instead of a TCP socket. This is a replacement for and . For example: See the option in mosquitto.conf 5 to configure Mosquitto to listen on a unix socket. 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. Set the session-expiry-interval property on the CONNECT packet. Applies to MQTT v5 clients only. Set to 0-4294967294 to specify the session will expire in that many seconds after the client disconnects, or use -1, 4294967295, or ∞ for a session that does not expire. Defaults to -1 if -c is also given, or 0 if -c not given. If the session is set to never expire, either with -x or -c, then a client id must be provided. 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. Flag characters The parameters %A, %C, %E, %F, %I, %l, %m, %p, %R, %S, %t, %x, and %X can have optional flags immediately after the % character. The value should be zero padded. This applies to the parameters %A, %E, %F, %l, %m, %S, %X, and %x. It will be ignored for other parameters. If used with the flag, the flag will be ignored. The value will be left aligned to the field width, padded with blanks. The default is right alignment, with either 0 or blank padding. Field width Some of the MQTT related parameters can be formatted with an option to set their field width in a similar way to regular printf style formats, i.e. this sets the minimum width when printing this parameter. This applies to the options %A, %C, %E, %F, %I, %l, %m, %p, %R, %S, %t, %x, %X. For example would set the minimum topic field width to 10 characters. Maximum width Some of the MQTT related parameters can be formatted with an option to set a maximum field width in a similar way to regular printf style formats. This applies to the options %C, %I, %R, %t. For example would set the minimum topic field width to 10 characters, and the maximum topic width to 10 characters, i.e. the field will always be exactly 10 characters long. MQTT related parameters a literal %. the MQTT v5 topic-alias property, if present. the MQTT v5 content-type property, if present. the MQTT v5 correlation-data property, if present. Note that this property is specified as binary data, so may produce non-printable characters. the MQTT v5 message-expiry-interval property, if present. the MQTT v5 payload-format-indicator property, if present. the length of the payload in bytes. the message id (only relevant for messages with QoS>0). the MQTT v5 user-property property, if present. This will be printed in the form key:value. It is possible for any number of user properties to be attached to a message, and to have duplicate keys. the payload raw bytes (may produce non-printable characters depending on the payload). the message QoS. the MQTT v5 response-topic property, if present. the retained flag for the message. the MQTT v5 subscription-identifier property, if present. 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":"2020-05-06T22:12:00.000000+0100","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":"2020-05-06T22:12:00.000000+0100","topic":"foo","qos":0,"retain":0,"payload":{"temperature":27.0,"humidity":57}}. If the payload is not valid JSON, then the error message "Error: Message payload is not valid JSON on topic <topic>" will be printed to stderr. 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) (32-bit unsigned integer) (16-bit unsigned integer) (8-bit unsigned integer) (8-bit unsigned integer) (32-bit unsigned integer, note use instead) (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) Exit Status mosquitto_sub returns zero on success, or non-zero on error. If the connection is refused by the broker at the MQTT level, then the exit code is the CONNACK reason code. If another error occurs, the exit code is a libmosquitto return value. MQTT v3.1.1 CONNACK codes: Success Connection refused: Bad protocol version Connection refused: Identifier rejected Connection refused: Server unavailable Connection refused: Bad username/password Connection refused: Not authorized MQTT v5 CONNACK codes: Success Unspecified error Malformed packet Protocol error Implementation specific error Unsupported protocol version Client ID not valid Bad username or password Not authorized Server unavailable Server busy Banned Server shutting down Bad authentication method Keep alive timeout Session taken over Topic filter invalid Topic name invalid Receive maximum exceeded Topic alias invalid Packet too large Message rate too high Quota exceeded Administrative action Payload format invalid Retain not supported QoS not supported Use another server Server moved Shared subscriptions not supported Connection rate exceeded Maximum connect time Subscription IDs not supported Wildcard subscriptions not supported 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 '#' Exit Values Success Timed out waiting for message Unspecified failure 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-2.0.11/man/html.xsl0000664000175000017500000000122514060132747015132 0ustar rogerroger man.css ansi mosquitto-2.0.11/man/libmosquitto.3.meta0000664000175000017500000000015314060132747017201 0ustar rogerroger.. title: libmosquitto man page .. slug: libmosquitto-3 .. category: man .. type: man .. pretty_url: False mosquitto-2.0.11/man/mosquitto_passwd.1.xml0000664000175000017500000002262514060132747017753 0ustar rogerroger mosquitto_passwd 1 Mosquitto Project Commands mosquitto_passwd manage password files for mosquitto mosquitto_passwd hash passwordfile username mosquitto_passwd hash 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. Choose the hash to use. Can be one of sha512-pbkdf2 or sha512. Defaults to sha512-pbkdf2. The sha512 option is provided for creating password files for use with Mosquitto 1.6 and earlier. 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. Exit Status mosquitto_sub returns zero on success, or non-zero on error. If the connection is refused by the broker at the MQTT level, then the exit code is the CONNACK reason code. If another error occurs, the exit code is a libmosquitto return value. MQTT v3.1.1 CONNACK codes: Success Connection refused: Bad protocol version Connection refused: Identifier rejected Connection refused: Server unavailable Connection refused: Bad username/password Connection refused: Not authorized MQTT v5 CONNACK codes: Success Unspecified error Malformed packet Protocol error Implementation specific error Unsupported protocol version Client ID not valid Bad username or password Not authorized Server unavailable Server busy Banned Server shutting down Bad authentication method Keep alive timeout Session taken over Topic filter invalid Topic name invalid Receive maximum exceeded Topic alias invalid Packet too large Message rate too high Quota exceeded Administrative action Payload format invalid Retain not supported QoS not supported Use another server Server moved Shared subscriptions not supported Connection rate exceeded Maximum connect time Subscription IDs not supported Wildcard subscriptions not supported 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-2.0.11/man/mqtt.70000664000175000017500000002053414060132747014517 0ustar rogerroger'\" t .\" Title: mqtt .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 06/09/2021 .\" Manual: Conventions and miscellaneous .\" Source: Mosquitto Project .\" Language: English .\" .TH "MQTT" "7" "06/09/2021" "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-2.0.11/man/mosquitto.conf.5.meta0000664000175000017500000000015714060132747017444 0ustar rogerroger.. title: mosquitto.conf man page .. slug: mosquitto-conf-5 .. category: man .. type: man .. pretty_url: False mosquitto-2.0.11/man/mosquitto.8.xml0000664000175000017500000007477114060132747016412 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 5.0/3.1.1/3.1. Options Load configuration from a file. If not given, then the broker will listen on port 1883 bound to the loopback interface, and the default values as described in mosquitto.conf5 are used. See the option for a description of changes in behaviour from 1.6.x to 2.0. Run mosquitto in the background as a daemon. All other behaviour remains the same. Listen on the port specified. May be specified up to 10 times to open multiple sockets listening on different ports. In version 1.6.x and earlier, the listener defined by (or the default port of 1883) would be bound to all interfaces and so be accessible from any network. It could also be used in combination with . From version 2.0 onwards, the listeners defined with are bound to the loopback interface only, and so can only be connected to from the local machine. If both is used and a listener is defined in a configuration file, then the options are IGNORED. 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. MQTT Support Mosquitto supports MQTT v5.0, v3.1.1, and v3.1. MQTT v5.0 Mosquitto provides full MQTT v5.0 support, but some features are not used directly. The following sections describe the new features and explain where Mosquitto does not make use of a feature. Features Basic MQTT authentication uses username/password checks. Enhanced authentication allows different authentication schemes to be integrated into MQTT, and even those schemes with multiple step processes. Clients request a particular type of authentication and if the broker is configured for that scheme the authentication continues. Mosquitto supports enhanced authentication through plugins. Most MQTT packets now have the concept of a which indicates success or failure, and what the failure was. Mosquitto provides full support for reason codes, but does not make use of the feature which can be used to provide a human readable error string to explain the reason code. The number of "in flight" messages for QoS 1 and QoS 2 can be controlled by both the client and the broker. MQTT v5.0 adds a request/response pattern that allows a client to publish a message and instruct the subscribers of that message where to publish a response. Server redirection is the concept of telling a client to connect to a different MQTT broker, either on CONNECT or with a broker initiated DISCONNECT. Mosquitto does not currently make use of this feature. When multiple clients subscribe to the same shared subscription, only one client out of the group will receive each message which allows for distributing work loads. Packet properties MQTT v5.0 allows properties to be added to packets to control certain behaviour. Unless noted, Mosquitto support the properties listed below. Authentication data Authentication method Maximum packet size Receive maximum Request problem information - supported but not used Request response information - supported but not used Session expiry interval Topic alias maximum User property Content type Correlation data Message expiry interval Payload format indicator Response topic User property Will delay interval Assigned client identifier Authentication data Authentication method Maximum packet size Maximum qos Reason string - supported but not used Receive maximum Response information - supported but not used Retain available Server keep alive Server reference - supported but not used Session expiry interval Shared subscription available Subscription identifiers available Topic alias maximum User property Wildcard subscription available Content type Correlation data Message expiry interval Payload format indicator Response topic Subscription identifier Topic alias User property Reason string - supported but not used User property Subscription identifier User property Reason string - supported but not used Server reference - supported but not used Session expiry interval User property Authentication method Authentication data Reason string - supported but not used User property MQTT v3.1.1 Mosquitto provides full MQTT v3.1.1 support. MQTT v3.1 Mosquitto provides full MQTT v3.1 support. MQTT v3 MQTT v3 is an obsolete version of the protocol that does not support username/password authentication and used the flag in the CONNECT packet which applied only to the start of a session. An MQTT v3 client will be able to successfully connect to a Mosquitto instance that does not require authentication. 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. If TLS certificates are in use, then mosquitto will also reload certificate on receiving a SIGHUP. 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_ctrl 1 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-2.0.11/man/mosquitto_rr.1.meta0000664000175000017500000000015314060132747017213 0ustar rogerroger.. title: mosquitto_rr man page .. slug: mosquitto_rr-1 .. category: man .. type: man .. pretty_url: False mosquitto-2.0.11/man/mosquitto_ctrl.10000664000175000017500000005332014060132747016613 0ustar rogerroger'\" t .\" Title: mosquitto_ctrl .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 06/09/2021 .\" Manual: Commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO_CTRL" "1" "06/09/2021" "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_ctrl \- a tool for initialising/configuring a Mosquitto broker instance .SH "SYNOPSIS" .HP \w'\fBmosquitto_ctrl\fR\ 'u \fBmosquitto_ctrl\fR [connection\-options\ |\ \-o\ config\-file] module\-name module\-command [command\-options] .HP \w'\fBconnection\-options:\fR\ 'u \fBconnection\-options:\fR {[\fB\-h\fR\ \fIhostname\fR]\ [\fB\-\-unix\fR\ \fIsocket\ path\fR]\ [\fB\-p\fR\ \fIport\-number\fR]\ [\fB\-u\fR\ \fIusername\fR]\ [\fB\-P\fR\ \fIpassword\fR] | \fB\-L\fR\ \fIURL\fR} [\fB\-A\fR\ \fIbind\-address\fR] [\fB\-c\fR] [\fB\-d\fR] [\fB\-i\fR\ \fIclient\-id\fR] [\fB\-q\fR\ \fImessage\-QoS\fR] [\fB\-\-quiet\fR] [\fB\-V\fR\ \fIprotocol\-version\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] .HP \w'\fBmosquitto_ctrl\fR\ 'u \fBmosquitto_ctrl\fR [\fB\-\-help\fR] .SH "DESCRIPTION" .PP \fBmosquitto_ctrl\fR is a tool for helping configure a Mosquitto broker instance\&. .SH "ENCRYPTED CONNECTIONS" .PP \fBmosquitto_ctrl\fR supports TLS encrypted connections\&. It is strongly recommended that you use an encrypted connection for all remote use of mosquitto_ctrl\&. .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 "MODULES" .PP \fBDynamic security\fR .RS 4 Authentication, and role based access control with users and groups\&. Uses the \fBdynsec\fR module name\&. See: \fBmosquitto_ctrl_dynsec\fR(1) .RE .PP \fBExternal modules\fR .RS 4 \fBmosquitto_ctrl\fR has the ability to load external modules in the form of shared libraries\&. For example using the module name \fBexample\fR will try to load the external module \fBmosquitto_ctrl_example\&.so\fR or \fBmosquitto_ctrl_example\&.dll\fR, depending on platform\&. This allows new functionality to be added to Mosquitto by combining a plugin and mosquitto_ctrl module, without having to recompile any Mosquitto source code\&. .RE .SH "CONNECTION 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_ctrl\fR or \fB$HOME/\&.config/mosquitto_ctrl\fR\&. .PP The config file may be specified manually with the \fB\-o \fR\fB\fIconfig\-file\fR\fR option\&. .PP The config file should have 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\-\-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\-\-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\-\-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\-\-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\-\-nodelay\fR .RS 4 Disable Nagle\*(Aqs algorithm for the socket\&. This means that latency of sent messages is reduced, which is particularly noticable for small, reasonably infrequent messages\&. Using this option may result in more packets being sent than would normally be necessary\&. .RE .PP \fB\-o\fR \fIconfig\-file\fR .RS 4 Provide a path to a config file to load options from\&. The config file should have 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\&. .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 messages, from 0, 1 and 2\&. Defaults to 1\&. .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\-\-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\-\-unix\fR .RS 4 Connect to a broker through a local unix domain socket instead of a TCP socket\&. This is a replacement for \fB\-h\fR and \fB\-L\fR\&. For example: \fBmosquitto_ctrl \-\-unix /tmp/mosquitto\&.sock \&.\&.\&.\fR .sp See the \fBsocket_domain\fR option in \m[blue]\fBmosquitto\&.conf\fR\m[](5) to configure Mosquitto to listen on a unix socket\&. .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 .SH "PROPERTIES" .PP The \fB\-D\fR / \fB\-\-property\fR option allows adding properties to different stages of the mosquitto_ctrl 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_ctrl) .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, note use \fB\-x\fR instead) .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_ctrl) .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_ctrl) .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 "EXIT STATUS" .PP mosquitto_sub returns zero on success, or non\-zero on error\&. If the connection is refused by the broker at the MQTT level, then the exit code is the CONNACK reason code\&. If another error occurs, the exit code is a libmosquitto return value\&. .PP MQTT v3\&.1\&.1 CONNACK codes: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB0\fR Success .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB1\fR Connection refused: Bad protocol version .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB2\fR Connection refused: Identifier rejected .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB3\fR Connection refused: Server unavailable .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB4\fR Connection refused: Bad username/password .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB5\fR Connection refused: Not authorized .RE .PP MQTT v5 CONNACK codes: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB0\fR Success .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB128\fR Unspecified error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB129\fR Malformed packet .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB130\fR Protocol error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB131\fR Implementation specific error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB132\fR Unsupported protocol version .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB133\fR Client ID not valid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB134\fR Bad username or password .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB135\fR Not authorized .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB136\fR Server unavailable .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB137\fR Server busy .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB138\fR Banned .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB139\fR Server shutting down .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB140\fR Bad authentication method .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB141\fR Keep alive timeout .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB142\fR Session taken over .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB143\fR Topic filter invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB144\fR Topic name invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB147\fR Receive maximum exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB148\fR Topic alias invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB149\fR Packet too large .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB148\fR Message rate too high .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB151\fR Quota exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB152\fR Administrative action .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB153\fR Payload format invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB154\fR Retain not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB155\fR QoS not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB156\fR Use another server .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB157\fR Server moved .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB158\fR Shared subscriptions not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB159\fR Connection rate exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB160\fR Maximum connect time .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB161\fR Subscription IDs not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB162\fR Wildcard subscriptions not supported .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_pub\fR(1), \fBmosquitto_sub\fR(1), \fBmosquitto\fR(8), \fBlibmosquitto\fR(3), \fBmosquitto-tls\fR(7) .SH "AUTHOR" .PP Roger Light mosquitto-2.0.11/man/mosquitto_sub.10000664000175000017500000012143014060132747016436 0ustar rogerroger'\" t .\" Title: mosquitto_sub .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 06/09/2021 .\" Manual: Commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO_SUB" "1" "06/09/2021" "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\-\-unix\fR\ \fIsocket\ path\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\-\-nodelay\fR] [\fB\-\-pretty\fR] [\fB\-q\fR\ \fImessage\-QoS\fR] [\fB\-\-random\-filter\fR\ \fIchance\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\-x\fR\ \fIsession\-expiry\-interval\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\-\-tls\-use\-os\-certs\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 \*(Aqclean session\*(Aq / enable persistent client mode\&. When this argument is used, the broker will be instructed not to clean existing sessions for the same client id when the client connects, and sessions will never expire when the client disconnects\&. MQTT v5 clients can change their session expiry interval with the \fB\-x\fR argument\&. .sp When a session is persisted on the broker, 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 and does not clean the session, 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\-\-nodelay\fR .RS 4 Disable Nagle\*(Aqs algorithm for the socket\&. This means that latency of sent messages is reduced, which is particularly noticeable for small, reasonably infrequent messages\&. Using this option may result in more packets being sent than would normally be necessary\&. .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\-\-pretty\fR .RS 4 When using the JSON output format %j or %J, the default is to print in an unformatted fashion\&. Specifying \fB\-\-pretty\fR prints messages in a prettier, more human readable format\&. .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\-\-random\-filter\fR .RS 4 This option can be used to reduce the proportion of messages that mosquitto_sub prints\&. The default behaviour is to print all incoming messages\&. Setting the \fIchance\fR to a floating point value between 0\&.1 and 100\&.0 will ensure that on average that percentage of messages will be printed\&. .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\-use\-os\-certs\fR .RS 4 If used, this will load and trust the OS provided CA certificates\&. This can be used in conjunction with \fB\-\-cafile\fR and \fB\-\-capath\fR and can be used on its own to enable TLS mode\&. This will be set by default if \fB\-L mqtts://\&.\&.\&.\fR is used, or if port is 8883 and no other certificate options are used\&. .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\-\-unix\fR .RS 4 Connect to a broker through a local unix domain socket instead of a TCP socket\&. This is a replacement for \fB\-h\fR and \fB\-L\fR\&. For example: \fBmosquitto_pub \-\-unix /tmp/mosquitto\&.sock \&.\&.\&.\fR .sp See the \fBsocket_domain\fR option in \m[blue]\fBmosquitto\&.conf\fR\m[](5) to configure Mosquitto to listen on a unix socket\&. .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 .PP \fB\-x\fR .RS 4 Set the session\-expiry\-interval property on the CONNECT packet\&. Applies to MQTT v5 clients only\&. Set to 0\-4294967294 to specify the session will expire in that many seconds after the client disconnects, or use \-1, 4294967295, or ∞ for a session that does not expire\&. Defaults to \-1 if \-c is also given, or 0 if \-c not given\&. .sp If the session is set to never expire, either with \-x or \-c, then a client id must be provided\&. .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 "Flag characters" .PP The parameters %A, %C, %E, %F, %I, %l, %m, %p, %R, %S, %t, %x, and %X can have optional flags immediately after the % character\&. .PP \fB0\fR .RS 4 The value should be zero padded\&. This applies to the parameters %A, %E, %F, %l, %m, %S, %X, and %x\&. It will be ignored for other parameters\&. If used with the \fB\-\fR flag, the \fB0\fR flag will be ignored\&. .RE .PP \fB\-\fR .RS 4 The value will be left aligned to the field width, padded with blanks\&. The default is right alignment, with either 0 or blank padding\&. .RE .SS "Field width" .PP Some of the MQTT related parameters can be formatted with an option to set their field width in a similar way to regular printf style formats, i\&.e\&. this sets the minimum width when printing this parameter\&. This applies to the options %A, %C, %E, %F, %I, %l, %m, %p, %R, %S, %t, %x, %X\&. .PP For example \fB%10t\fR would set the minimum topic field width to 10 characters\&. .SS "Maximum width" .PP Some of the MQTT related parameters can be formatted with an option to set a maximum field width in a similar way to regular printf style formats\&. This applies to the options %C, %I, %R, %t\&. .PP For example \fB%10\&.10t\fR would set the minimum topic field width to 10 characters, and the maximum topic width to 10 characters, i\&.e\&. the field will always be exactly 10 characters long\&. .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%A\fR the MQTT v5 topic\-alias property, if present\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%C\fR the MQTT v5 content\-type property, if present\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%D\fR the MQTT v5 correlation\-data property, if present\&. Note that this property is specified as binary data, so may produce non\-printable characters\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%E\fR the MQTT v5 message\-expiry\-interval property, if present\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%F\fR the MQTT v5 payload\-format\-indicator property, if present\&. .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 MQTT v5 user\-property property, if present\&. This will be printed in the form key:value\&. It is possible for any number of user properties to be attached to a message, and to have duplicate keys\&. .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 MQTT v5 response\-topic property, if present\&. .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%S\fR the MQTT v5 subscription\-identifier property, if present\&. .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":"2020\-05\-06T22:12:00\&.000000+0100","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":"2020\-05\-06T22:12:00\&.000000+0100","topic":"foo","qos":0,"retain":0,"payload":{"temperature":27\&.0,"humidity":57}}\&. .sp If the payload is not valid JSON, then the error message "Error: Message payload is not valid JSON on topic " will be printed to stderr\&. .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) .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, note use \fB\-x\fR instead) .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 "EXIT STATUS" .PP mosquitto_sub returns zero on success, or non\-zero on error\&. If the connection is refused by the broker at the MQTT level, then the exit code is the CONNACK reason code\&. If another error occurs, the exit code is a libmosquitto return value\&. .PP MQTT v3\&.1\&.1 CONNACK codes: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB0\fR Success .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB1\fR Connection refused: Bad protocol version .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB2\fR Connection refused: Identifier rejected .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB3\fR Connection refused: Server unavailable .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB4\fR Connection refused: Bad username/password .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB5\fR Connection refused: Not authorized .RE .PP MQTT v5 CONNACK codes: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB0\fR Success .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB128\fR Unspecified error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB129\fR Malformed packet .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB130\fR Protocol error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB131\fR Implementation specific error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB132\fR Unsupported protocol version .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB133\fR Client ID not valid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB134\fR Bad username or password .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB135\fR Not authorized .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB136\fR Server unavailable .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB137\fR Server busy .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB138\fR Banned .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB139\fR Server shutting down .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB140\fR Bad authentication method .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB141\fR Keep alive timeout .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB142\fR Session taken over .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB143\fR Topic filter invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB144\fR Topic name invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB147\fR Receive maximum exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB148\fR Topic alias invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB149\fR Packet too large .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB148\fR Message rate too high .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB151\fR Quota exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB152\fR Administrative action .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB153\fR Payload format invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB154\fR Retain not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB155\fR QoS not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB156\fR Use another server .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB157\fR Server moved .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB158\fR Shared subscriptions not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB159\fR Connection rate exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB160\fR Maximum connect time .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB161\fR Subscription IDs not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB162\fR Wildcard subscriptions not supported .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 "EXIT VALUES" .PP \fB0\fR .RS 4 Success .RE .PP \fB27\fR .RS 4 Timed out waiting for message .RE .PP \fBOther non\-zero value\fR .RS 4 Unspecified failure .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-2.0.11/man/mosquitto_rr.1.xml0000664000175000017500000012216714060132747017077 0ustar rogerroger mosquitto_rr 1 Mosquitto Project Commands mosquitto_rr an MQTT version 5/3.1.1 client for request/response messaging mosquitto_rr response-topic hostname socket path port-number username password message-topic URL message-topic file message bind-address command identifier value client-id client-id-prefix keepalive-time message-QoS protocol-version message-processing-timeout session-expiry-interval 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. The important options are , , and one of , , , and . Example: mosquitto_rr -t request-topic -e response-topic -m message 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 'clean session' / enable persistent client mode. When this argument is used, the broker will be instructed not to clean existing sessions for the same client id when the client connects, and sessions will never expire when the client disconnects. MQTT v5 clients can change their session expiry interval with the argument. When a session is persisted on the broker, 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 and does not clean the session, 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. Response topic. The client will subscribe to this topic to wait for a response. 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. Disable Nagle's algorithm for the socket. This means that latency of sent messages is reduced, which is particularly noticeable for small, reasonably infrequent messages. Using this option may result in more packets being sent than would normally be necessary. 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. When using the JSON output format %j or %J, the default is to print in an unformatted fashion. Specifying prints messages in a prettier, more human readable format. 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 where the request message will be sent. 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 . If used, this will load and trust the OS provided CA certificates. This can be used in conjunction with and and can be used on its own to enable TLS mode. This will be set by default if is used, or if port is 8883 and no other certificate options are used. 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. Connect to a broker through a local unix domain socket instead of a TCP socket. This is a replacement for and . For example: See the option in mosquitto.conf 5 to configure Mosquitto to listen on a unix socket. 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. Set the session-expiry-interval property on the CONNECT packet. Applies to MQTT v5 clients only. Set to 0-4294967294 to specify the session will expire in that many seconds after the client disconnects, or use -1, 4294967295, or ∞ for a session that does not expire. Defaults to -1 if -c is also given, or 0 if -c not given. If the session is set to never expire, either with -x or -c, then a client id must be provided. 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 MQTT v5 topic-alias property, if present. the MQTT v5 content-type property, if present. the MQTT v5 correlation-data property, if present. Note that this property is specified as binary data, so may produce non-printable characters. the MQTT v5 message-expiry-interval property, if present. the MQTT v5 payload-format-indicator property, if present. the length of the payload in bytes. the message id (only relevant for messages with QoS>0). the MQTT v5 user-property property, if present. This will be printed in the form key:value. It is possible for any number of user properties to be attached to a message, and to have duplicate keys. the payload raw bytes (may produce non-printable characters depending on the payload). the message QoS. the MQTT v5 response-topic property, if present. the retained flag for the message. the MQTT v5 subscription-identifier property, if present. 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":"2020-05-06T22:12:00.000000+0100","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":"2020-05-06T22:12:00.000000+0100","topic":"foo","qos":0,"retain":0,"payload":{"temperature":27.0,"humidity":57}}. If the payload is not valid JSON, then the error message "Error: Message payload is not valid JSON on topic <topic>" will be printed to stderr. 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, note use instead) (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) Exit Values Success Timed out waiting for message Unspecified failure 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-2.0.11/man/mosquitto_pub.1.meta0000664000175000017500000000015514060132747017360 0ustar rogerroger.. title: mosquitto_pub man page .. slug: mosquitto_pub-1 .. category: man .. type: man .. pretty_url: False mosquitto-2.0.11/man/mosquitto_rr.10000664000175000017500000007350114060132747016275 0ustar rogerroger'\" t .\" Title: mosquitto_rr .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 06/09/2021 .\" Manual: Commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO_RR" "1" "06/09/2021" "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\-e\fR\ \fIresponse\-topic\fR {[\fB\-h\fR\ \fIhostname\fR]\ [\fB\-\-unix\fR\ \fIsocket\ path\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\-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\-\-nodelay\fR] [\fB\-\-pretty\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\-x\fR\ \fIsession\-expiry\-interval\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\-\-tls\-use\-os\-certs\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\&. .PP The important options are \fB\-t\fR, \fB\-e\fR, and one of \fB\-f\fR, \fB\-m\fR, \fB\-n\fR, and \fB\-s\fR\&. .PP Example: mosquitto_rr \-t request\-topic \-e response\-topic \-m message .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 \*(Aqclean session\*(Aq / enable persistent client mode\&. When this argument is used, the broker will be instructed not to clean existing sessions for the same client id when the client connects, and sessions will never expire when the client disconnects\&. MQTT v5 clients can change their session expiry interval with the \fB\-x\fR argument\&. .sp When a session is persisted on the broker, 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 and does not clean the session, 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\-e\fR .RS 4 Response topic\&. The client will subscribe to this topic to wait for a response\&. .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\-\-nodelay\fR .RS 4 Disable Nagle\*(Aqs algorithm for the socket\&. This means that latency of sent messages is reduced, which is particularly noticeable for small, reasonably infrequent messages\&. Using this option may result in more packets being sent than would normally be necessary\&. .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\-\-pretty\fR .RS 4 When using the JSON output format %j or %J, the default is to print in an unformatted fashion\&. Specifying \fB\-\-pretty\fR prints messages in a prettier, more human readable format\&. .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 where the request message will be sent\&. .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\-use\-os\-certs\fR .RS 4 If used, this will load and trust the OS provided CA certificates\&. This can be used in conjunction with \fB\-\-cafile\fR and \fB\-\-capath\fR and can be used on its own to enable TLS mode\&. This will be set by default if \fB\-L mqtts://\&.\&.\&.\fR is used, or if port is 8883 and no other certificate options are used\&. .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\-\-unix\fR .RS 4 Connect to a broker through a local unix domain socket instead of a TCP socket\&. This is a replacement for \fB\-h\fR and \fB\-L\fR\&. For example: \fBmosquitto_pub \-\-unix /tmp/mosquitto\&.sock \&.\&.\&.\fR .sp See the \fBsocket_domain\fR option in \m[blue]\fBmosquitto\&.conf\fR\m[](5) to configure Mosquitto to listen on a unix socket\&. .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 \fB5\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 .PP \fB\-x\fR .RS 4 Set the session\-expiry\-interval property on the CONNECT packet\&. Applies to MQTT v5 clients only\&. Set to 0\-4294967294 to specify the session will expire in that many seconds after the client disconnects, or use \-1, 4294967295, or ∞ for a session that does not expire\&. Defaults to \-1 if \-c is also given, or 0 if \-c not given\&. .sp If the session is set to never expire, either with \-x or \-c, then a client id must be provided\&. .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%A\fR the MQTT v5 topic\-alias property, if present\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%C\fR the MQTT v5 content\-type property, if present\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%D\fR the MQTT v5 correlation\-data property, if present\&. Note that this property is specified as binary data, so may produce non\-printable characters\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%E\fR the MQTT v5 message\-expiry\-interval property, if present\&. .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB%F\fR the MQTT v5 payload\-format\-indicator property, if present\&. .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 MQTT v5 user\-property property, if present\&. This will be printed in the form key:value\&. It is possible for any number of user properties to be attached to a message, and to have duplicate keys\&. .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 MQTT v5 response\-topic property, if present\&. .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%S\fR the MQTT v5 subscription\-identifier property, if present\&. .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":"2020\-05\-06T22:12:00\&.000000+0100","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":"2020\-05\-06T22:12:00\&.000000+0100","topic":"foo","qos":0,"retain":0,"payload":{"temperature":27\&.0,"humidity":57}}\&. .sp If the payload is not valid JSON, then the error message "Error: Message payload is not valid JSON on topic " will be printed to stderr\&. .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, note use \fB\-x\fR instead) .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 "EXIT VALUES" .PP \fB0\fR .RS 4 Success .RE .PP \fB27\fR .RS 4 Timed out waiting for message .RE .PP \fBOther non\-zero value\fR .RS 4 Unspecified failure .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-2.0.11/man/mosquitto_ctrl.1.meta0000664000175000017500000000015714060132747017540 0ustar rogerroger.. title: mosquitto_ctrl man page .. slug: mosquitto_ctrl-1 .. category: man .. type: man .. pretty_url: False mosquitto-2.0.11/man/mqtt.7.meta0000664000175000017500000000015714060132747015443 0ustar rogerroger.. title: MQTT man page .. slug: mqtt-7 .. category: man .. type: man .. pretty_url: False .. hide_title: True mosquitto-2.0.11/man/mosquitto_ctrl_dynsec.1.xml0000664000175000017500000000656314060132747020766 0ustar rogerroger mosquitto_ctrl_dynsec 1 Mosquitto Project Commands mosquitto_ctrl_dynsec mosquitto_ctrl module for controlling the Mosquitto Dynamic Security plugin. mosquitto_ctrl connection-options dynsec dynsec-command command-options Description This page describes the dynsec module for mosquitto_ctrl 1. See the mosquitto_ctrl man page for details of the options for connecting to remote brokers, in particular since this module works with authentication and access control, it is crucial that secure encrypted connections are used. Commands Configuration file initialisation mosquitto_ctrl dynsec init config-filename admin-user [admin-password] Bugs mosquitto bug information can be found at See Also mqtt 7 mosquitto_rr 1 mosquitto_pub 1 mosquitto_sub 1 mosquitto 8 libmosquitto 3 mosquitto-tls 7 Author Roger Light roger@atchoo.org mosquitto-2.0.11/man/mosquitto.conf.50000664000175000017500000020274514060132747016526 0ustar rogerroger'\" t .\" Title: mosquitto.conf .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 06/09/2021 .\" Manual: File formats and conventions .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO\&.CONF" "5" "06/09/2021" "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\&. An overview is also available at \m[blue]\fB\%https://mosquitto.org/documentation/authentication-methods/\fR\m[] .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 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 Mosquitto provides the Dynamic Security plugin which handles username/password authentication and access control in a much more flexible way than a password file\&. See \m[blue]\fB\%https://mosquitto.org/documentation/dynamic-security/\fR\m[] .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|deny] .sp The access type is controlled using "read", "write", "readwrite" or "deny"\&. 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\&. The "deny" option can used to explicitly deny access to a topic that would otherwise be granted by a broader read/write/readwrite statement\&. Any "deny" topics are handled before topics that grant read/write access\&. .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|deny] .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\&. .sp See also \m[blue]\fB\%https://mosquitto.org/documentation/dynamic-security/\fR\m[] .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 \fIfalse\fR, unless no listeners are defined in the configuration file, in which case it set to \fItrue\fR, but connections are only allowed from the local machine\&. .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\&. .if n \{\ .sp .\} .RS 4 .it 1 an-trap .nr an-no-space-flag 1 .nr an-break-flag 1 .br .ps +1 \fBImportant\fR .ps -1 .br In version 1\&.6\&.x and earlier, this option defaulted to \fItrue\fR unless there was another security option set\&. .sp .5v .RE Reloaded on reload signal\&. .RE .PP \fBallow_duplicate_messages\fR [ true | false ] .RS 4 This option is deprecated and will be removed in a future version\&. The behaviour will default to true\&. .sp 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\&. .sp See also \m[blue]\fB\%https://mosquitto.org/documentation/dynamic-security/\fR\m[] .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 This option is deprecated and will be removed in a future version\&. .sp 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 \fBfile\fR \fBdlt\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\&. .sp \fBtopic\fR logs to the broker topic \*(Aq$SYS/broker/log/\*(Aq, where severity is one of E, W, N, I, M which are 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\&. Debug messages are never logged on topics\&. .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 The \fBdlt\fR destination is for the automotive `Diagnostic Log and Trace` tool\&. This requires that Mosquitto has been compiled with DLT support\&. .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 1000\&. 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) and \m[blue]\fB\%https://mosquitto.org/documentation/dynamic-security/\fR\m[] .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\&. 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\&. .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/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 \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 set to "mosquitto" or left unset, and if the "mosquitto" user does not exist, then mosquitto will change to the "nobody" user instead\&. If this is set to another value and 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\&. 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 This option is deprecated and will be removed in a future version\&. Use the \fBlistener\fR instead\&. .sp 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 If used at the same time as the \fBbind_address\fR for the default listener, or the \fIbind address/host\fR part of the \fBlistener\fR, then \fBbind_interface\fR will take priority\&. .sp This option is not available on Windows\&. .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/unix socket path]\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 On systems that support Unix Domain Sockets, this option can also be used to create a Unix socket rather than opening a TCP socket\&. In this case, the port must be set to 0, and the unix socket path must be given\&. .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()\&. .sp Not reloaded on reload signal\&. .RE .PP \fBmax_qos\fR \fIvalue\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 publishing 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 This option is deprecated and will be removed in a future version\&. Use the \fBlistener\fR instead\&. .sp 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, \fBciphers\fR, and \fBciphers_tls1\&.3\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 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 \fBcafile\fR is used to define the path to a file containing the PEM encoded CA certificates that are trusted when checking incoming client certificates\&. .RE .PP \fBcapath\fR \fIdirectory path\fR .RS 4 \fBcapath\fR is used to define a directory that contains PEM encoded CA certificates that are trusted when checking incoming client certificates\&. 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\&. This option and \fBkeyfile\fR must be present to enable certificate based TLS encryption\&. .sp The certificate pointed to by this option will be reloaded when Mosquitto receives a SIGHUP signal\&. This can be used to load new certificates prior to the existing ones expiring\&. .RE .PP \fBciphers\fR \fIcipher:list\fR .RS 4 The list of allowed ciphers for this listener, for TLS v1\&.2 and earlier only, each separated with a colon\&. Available ciphers can be obtained using the "openssl ciphers" command\&. .RE .PP \fBciphers_tls1\&.3\fR \fIcipher:list\fR .RS 4 The list of allowed ciphersuites for this listener, for TLS v1\&.3, each separated with a colon\&. .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 server key\&. This option and \fBcertfile\fR must be present to enable certificate based TLS encryption\&. .sp The private key pointed to by this option will be reloaded when Mosquitto receives a SIGHUP signal\&. This can be used to load new keys prior to the existing ones expiring\&. .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 minimum 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 TLS v1\&.3 and v1\&.2\&. .sp In Mosquitto version 1\&.6\&.x and earlier, this option set the only TLS protocol version that was allowed, rather than the minimum\&. .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 minimum 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 TLS v1\&.3 and v1\&.2\&. .sp In Mosquitto version 1\&.6\&.x and earlier, this option set the only TLS protocol version that was allowed, rather than the minimum\&. .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_bind_address\fR \fIip address\fR .RS 4 If you need to have the bridge connect over a particular network interface, use bridge_bind_address to tell the bridge which local IP address the socket should bind to, e\&.g\&. \fBbridge_bind_address 192\&.168\&.1\&.10\fR\&. .RE .PP \fBbridge_max_packet_size\fR \fIvalue\fR .RS 4 If you wish to restrict the size of messages sent to a remote bridge, use this option\&. This sets the maximum number of bytes for the total message, including headers and payload\&. Note that MQTT v5 brokers may provide their own maximum\-packet\-size property\&. In this case, the smaller of the two limits will be used\&. Set to 0 for "unlimited"\&. .RE .PP \fBbridge_outgoing_retain\fR [ true | false ] .RS 4 Some MQTT brokers do not allow retained messages\&. MQTT v5 gives a mechanism for brokers to tell clients that they do not support retained messages, but this is not possible for MQTT v3\&.1\&.1 or v3\&.1\&. If you need to bridge to a v3\&.1\&.1 or v3\&.1 broker that does not support retained messages, set the \fBbridge_outgoing_retain\fR option to \fIfalse\fR\&. This will remove the retain bit on all outgoing messages to that bridge, regardless of any other setting\&. 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 \fImqttv50\fR, \fImqttv311\fR or \fImqttv31\fR\&. Defaults to \fImqttv311\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 \fBlocal_cleansession\fR [ true | false] .RS 4 The regular \fBcleansession\fR covers both the local subscriptions and the remote subscriptions\&. local_cleansession allows splitting this\&. Setting \fIfalse\fR will mean that the local connection will preserve subscription, independent of the remote connection\&. .sp Defaults to the value of bridge\&.cleansession unless explicitly specified\&. .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 \fItrue\fR to disable the hostname verification\&. .sp Setting this option to \fItrue\fR means that a malicious third party could potentially impersonate 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-2.0.11/man/libmosquitto.30000664000175000017500000000262214060132747016257 0ustar rogerroger'\" t .\" Title: libmosquitto .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 06/09/2021 .\" Manual: Library calls .\" Source: Mosquitto Project .\" Language: English .\" .TH "LIBMOSQUITTO" "3" "06/09/2021" "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-2.0.11/man/manpage.xsl0000664000175000017500000000145114060132747015577 0ustar rogerroger 0 0 https://mosquitto.org/man/ ansi mosquitto-2.0.11/man/mosquitto-tls.7.xml0000664000175000017500000000775414060132747017206 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-2.0.11/man/mosquitto-tls.7.meta0000664000175000017500000000015514060132747017320 0ustar rogerroger.. title: mosquitto-tls man page .. slug: mosquitto-tls-7 .. category: man .. type: man .. pretty_url: False mosquitto-2.0.11/man/mosquitto_pub.10000664000175000017500000006713214060132747016443 0ustar rogerroger'\" t .\" Title: mosquitto_pub .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 06/09/2021 .\" Manual: Commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO_PUB" "1" "06/09/2021" "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\-\-unix\fR\ \fIsocket\ path\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\-\-nodelay\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\-V\fR\ \fIprotocol\-version\fR] [\fB\-x\fR\ \fIsession\-expiry\-interval\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\-\-tls\-use\-os\-certs\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] .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 \*(Aqclean session\*(Aq / enable persistent client mode\&. When this argument is used, the broker will be instructed not to clean existing sessions for the same client id when the client connects, and sessions will never expire when the client disconnects\&. MQTT v5 clients can change their session expiry interval with the \fB\-x\fR argument\&. .sp When a session is persisted on the broker, 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 and does not clean the session, 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\-\-nodelay\fR .RS 4 Disable Nagle\*(Aqs algorithm for the socket\&. This means that latency of sent messages is reduced, which is particularly noticeable for small, reasonably infrequent messages\&. Using this option may result in more packets being sent than would normally be necessary\&. .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\&. Note that zero length payloads are never retained\&. If you send a zero length payload retained message it will clear any retained message on the topic\&. .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\-use\-os\-certs\fR .RS 4 If used, this will load and trust the OS provided CA certificates\&. This can be used in conjunction with \fB\-\-cafile\fR and \fB\-\-capath\fR and can be used on its own to enable TLS mode\&. This will be set by default if \fB\-L mqtts://\&.\&.\&.\fR is used, or if port is 8883 and no other certificate options are used\&. .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\-\-unix\fR .RS 4 Connect to a broker through a local unix domain socket instead of a TCP socket\&. This is a replacement for \fB\-h\fR and \fB\-L\fR\&. For example: \fBmosquitto_pub \-\-unix /tmp/mosquitto\&.sock \&.\&.\&.\fR .sp See the \fBsocket_domain\fR option in \m[blue]\fBmosquitto\&.conf\fR\m[](5) to configure Mosquitto to listen on a unix socket\&. .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\&. Note that zero length payloads are never retained\&. If you send a zero length payload retained message it will clear any retained message on the topic\&. .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 .PP \fB\-x\fR .RS 4 Set the session\-expiry\-interval property on the CONNECT packet\&. Applies to MQTT v5 clients only\&. Set to 0\-4294967294 to specify the session will expire in that many seconds after the client disconnects, or use \-1, 4294967295, or ∞ for a session that does not expire\&. Defaults to \-1 if \-c is also given, or 0 if \-c not given\&. .sp If the session is set to never expire, either with \-x or \-c, then a client id must be provided\&. .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, note use \fB\-x\fR instead) .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 "EXIT STATUS" .PP mosquitto_sub returns zero on success, or non\-zero on error\&. If the connection is refused by the broker at the MQTT level, then the exit code is the CONNACK reason code\&. If another error occurs, the exit code is a libmosquitto return value\&. .PP MQTT v3\&.1\&.1 CONNACK codes: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB0\fR Success .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB1\fR Connection refused: Bad protocol version .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB2\fR Connection refused: Identifier rejected .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB3\fR Connection refused: Server unavailable .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB4\fR Connection refused: Bad username/password .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB5\fR Connection refused: Not authorized .RE .PP MQTT v5 CONNACK codes: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB0\fR Success .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB128\fR Unspecified error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB129\fR Malformed packet .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB130\fR Protocol error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB131\fR Implementation specific error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB132\fR Unsupported protocol version .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB133\fR Client ID not valid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB134\fR Bad username or password .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB135\fR Not authorized .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB136\fR Server unavailable .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB137\fR Server busy .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB138\fR Banned .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB139\fR Server shutting down .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB140\fR Bad authentication method .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB141\fR Keep alive timeout .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB142\fR Session taken over .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB143\fR Topic filter invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB144\fR Topic name invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB147\fR Receive maximum exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB148\fR Topic alias invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB149\fR Packet too large .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB148\fR Message rate too high .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB151\fR Quota exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB152\fR Administrative action .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB153\fR Payload format invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB154\fR Retain not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB155\fR QoS not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB156\fR Use another server .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB157\fR Server moved .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB158\fR Shared subscriptions not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB159\fR Connection rate exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB160\fR Maximum connect time .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB161\fR Subscription IDs not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB162\fR Wildcard subscriptions not supported .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-2.0.11/man/libmosquitto.3.xml0000664000175000017500000000136214060132747017056 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-2.0.11/man/mosquitto_ctrl.1.xml0000664000175000017500000007030114060132747017410 0ustar rogerroger mosquitto_ctrl 1 Mosquitto Project Commands mosquitto_ctrl a tool for initialising/configuring a Mosquitto broker instance mosquitto_ctrl connection-options | -o config-file module-name module-command command-options connection-options: hostname socket path port-number username password URL bind-address client-id message-QoS protocol-version file dir file file ciphers version protocol engine pem engine kpass-sha1 hex-key identity ciphers version socks-url mosquitto_ctrl Description mosquitto_ctrl is a tool for helping configure a Mosquitto broker instance. Encrypted Connections mosquitto_ctrl supports TLS encrypted connections. It is strongly recommended that you use an encrypted connection for all remote use of mosquitto_ctrl. 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. Modules Authentication, and role based access control with users and groups. Uses the dynsec module name. See: mosquitto_ctrl_dynsec 1 mosquitto_ctrl has the ability to load external modules in the form of shared libraries. For example using the module name will try to load the external module or , depending on platform. This allows new functionality to be added to Mosquitto by combining a plugin and mosquitto_ctrl module, without having to recompile any Mosquitto source code. Connection Options The options below may be given on the command line, but may also be placed in a config file located at or . The config file may be specified manually with the option. The config file should have 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. 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. 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. 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. 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. Disable Nagle's algorithm for the socket. This means that latency of sent messages is reduced, which is particularly noticable for small, reasonably infrequent messages. Using this option may result in more packets being sent than would normally be necessary. config-file Provide a path to a config file to load options from. The config file should have 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. 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 messages, from 0, 1 and 2. Defaults to 1. 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). 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. Connect to a broker through a local unix domain socket instead of a TCP socket. This is a replacement for and . For example: See the option in mosquitto.conf 5 to configure Mosquitto to listen on a unix socket. 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 . Properties The / option allows adding properties to different stages of the mosquitto_ctrl run. The properties supported for each command are as follows: Connect (binary data - note treated as a string in mosquitto_ctrl) (UTF-8 string pair) (32-bit unsigned integer) (16-bit unsigned integer) (8-bit unsigned integer) (8-bit unsigned integer) (32-bit unsigned integer, note use instead) (16-bit unsigned integer) (UTF-8 string pair) Publish (UTF-8 string) (binary data - note treated as a string in mosquitto_ctrl) (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_ctrl) (32-bit unsigned integer) (8-bit unsigned integer) (UTF-8 string) (UTF-8 string pair) (32-bit unsigned integer) Exit Status mosquitto_sub returns zero on success, or non-zero on error. If the connection is refused by the broker at the MQTT level, then the exit code is the CONNACK reason code. If another error occurs, the exit code is a libmosquitto return value. MQTT v3.1.1 CONNACK codes: Success Connection refused: Bad protocol version Connection refused: Identifier rejected Connection refused: Server unavailable Connection refused: Bad username/password Connection refused: Not authorized MQTT v5 CONNACK codes: Success Unspecified error Malformed packet Protocol error Implementation specific error Unsupported protocol version Client ID not valid Bad username or password Not authorized Server unavailable Server busy Banned Server shutting down Bad authentication method Keep alive timeout Session taken over Topic filter invalid Topic name invalid Receive maximum exceeded Topic alias invalid Packet too large Message rate too high Quota exceeded Administrative action Payload format invalid Retain not supported QoS not supported Use another server Server moved Shared subscriptions not supported Connection rate exceeded Maximum connect time Subscription IDs not supported Wildcard subscriptions not supported Bugs mosquitto bug information can be found at See Also mqtt 7 mosquitto_rr 1 mosquitto_pub 1 mosquitto_sub 1 mosquitto 8 libmosquitto 3 mosquitto-tls 7 Author Roger Light roger@atchoo.org mosquitto-2.0.11/man/mosquitto_passwd.10000664000175000017500000002070414060132747017150 0ustar rogerroger'\" t .\" Title: mosquitto_passwd .\" Author: [see the "Author" section] .\" Generator: DocBook XSL Stylesheets vsnapshot .\" Date: 06/09/2021 .\" Manual: Commands .\" Source: Mosquitto Project .\" Language: English .\" .TH "MOSQUITTO_PASSWD" "1" "06/09/2021" "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\-H\fR\ \fIhash\fR] [\fB\-c\fR | \fB\-D\fR] \fIpasswordfile\fR \fIusername\fR .HP \w'\fBmosquitto_passwd\fR\ 'u \fBmosquitto_passwd\fR [\fB\-H\fR\ \fIhash\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\-H\fR .RS 4 Choose the hash to use\&. Can be one of \fIsha512\-pbkdf2\fR or \fIsha512\fR\&. Defaults to \fIsha512\-pbkdf2\fR\&. The \fIsha512\fR option is provided for creating password files for use with Mosquitto 1\&.6 and earlier\&. .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 "EXIT STATUS" .PP mosquitto_sub returns zero on success, or non\-zero on error\&. If the connection is refused by the broker at the MQTT level, then the exit code is the CONNACK reason code\&. If another error occurs, the exit code is a libmosquitto return value\&. .PP MQTT v3\&.1\&.1 CONNACK codes: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB0\fR Success .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB1\fR Connection refused: Bad protocol version .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB2\fR Connection refused: Identifier rejected .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB3\fR Connection refused: Server unavailable .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB4\fR Connection refused: Bad username/password .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB5\fR Connection refused: Not authorized .RE .PP MQTT v5 CONNACK codes: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB0\fR Success .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB128\fR Unspecified error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB129\fR Malformed packet .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB130\fR Protocol error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB131\fR Implementation specific error .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB132\fR Unsupported protocol version .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB133\fR Client ID not valid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB134\fR Bad username or password .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB135\fR Not authorized .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB136\fR Server unavailable .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB137\fR Server busy .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB138\fR Banned .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB139\fR Server shutting down .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB140\fR Bad authentication method .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB141\fR Keep alive timeout .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB142\fR Session taken over .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB143\fR Topic filter invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB144\fR Topic name invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB147\fR Receive maximum exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB148\fR Topic alias invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB149\fR Packet too large .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB148\fR Message rate too high .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB151\fR Quota exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB152\fR Administrative action .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB153\fR Payload format invalid .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB154\fR Retain not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB155\fR QoS not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB156\fR Use another server .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB157\fR Server moved .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB158\fR Shared subscriptions not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB159\fR Connection rate exceeded .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB160\fR Maximum connect time .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB161\fR Subscription IDs not supported .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} \fB162\fR Wildcard subscriptions not supported .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-2.0.11/man/mosquitto_passwd.1.meta0000664000175000017500000000016314060132747020072 0ustar rogerroger.. title: mosquitto_passwd man page .. slug: mosquitto_passwd-1 .. category: man .. type: man .. pretty_url: False mosquitto-2.0.11/man/Makefile0000664000175000017500000000732314060132747015103 0ustar rogerrogerinclude ../config.mk .PHONY : all clean install uninstall dist MANPAGES = \ libmosquitto.3 \ mosquitto-tls.7 \ mosquitto.8 \ mosquitto.conf.5 \ mosquitto_ctrl.1 \ mosquitto_ctrl_dynsec.1 \ 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_ctrl.1 "${DESTDIR}${mandir}/man1/mosquitto_ctrl.1" $(INSTALL) -m 644 mosquitto_ctrl_dynsec.1 "${DESTDIR}${mandir}/man1/mosquitto_ctrl_dynsec.1" $(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_ctrl.1" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_ctrl_dynsec.1" -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 manpage.xsl $(XSLTPROC) $< mosquitto.conf.5 : mosquitto.conf.5.xml manpage.xsl $(XSLTPROC) $< mosquitto_ctrl.1 : mosquitto_ctrl.1.xml manpage.xsl $(XSLTPROC) $< mosquitto_ctrl_dynsec.1 : mosquitto_ctrl_dynsec.1.xml manpage.xsl $(XSLTPROC) $< mosquitto_passwd.1 : mosquitto_passwd.1.xml manpage.xsl $(XSLTPROC) $< mosquitto_pub.1 : mosquitto_pub.1.xml manpage.xsl $(XSLTPROC) $< mosquitto_sub.1 : mosquitto_sub.1.xml manpage.xsl $(XSLTPROC) $< mosquitto_rr.1 : mosquitto_rr.1.xml manpage.xsl $(XSLTPROC) $< mqtt.7 : mqtt.7.xml manpage.xsl $(XSLTPROC) $< mosquitto-tls.7 : mosquitto-tls.7.xml manpage.xsl $(XSLTPROC) $< libmosquitto.3 : libmosquitto.3.xml manpage.xsl $(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_ctrl/mosquitto_ctrl.1.pot mosquitto_ctrl.1.xml xml2po -o po/mosquitto_ctrl/mosquitto_ctrl_dynsec.1.pot mosquitto_ctrl_dynsec.1.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-2.0.11/man/mosquitto.8.meta0000664000175000017500000000014514060132747016520 0ustar rogerroger.. title: Mosquitto man page .. slug: mosquitto-8 .. category: man .. type: man .. pretty_url: False mosquitto-2.0.11/LICENSE.txt0000664000175000017500000000023314060132747014504 0ustar rogerrogerThis project is dual licensed under the Eclipse Public License 2.0 and the Eclipse Distribution License 1.0 as described in the epl-v20 and edl-v10 files. mosquitto-2.0.11/installer/0000775000175000017500000000000014060132747014660 5ustar rogerrogermosquitto-2.0.11/installer/mosquitto.nsi0000664000175000017500000001205114060132747017436 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 2.0.11 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\apps\mosquitto_passwd\Release\mosquitto_passwd.exe" File "..\build\apps\mosquitto_ctrl\Release\mosquitto_ctrl.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 "..\build\plugins\dynamic-security\Release\mosquitto_dynamic_security.dll" File "..\aclfile.example" File "..\ChangeLog.txt" File "..\mosquitto.conf" File "..\NOTICE.md" File "..\pwfile.example" File "..\README.md" File "..\README-windows.txt" File "..\README-letsencrypt.md" ;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-v20" SetOutPath "$INSTDIR\devel" File "..\build\lib\Release\mosquitto.lib" File "..\build\lib\cpp\Release\mosquittopp.lib" File "..\include\mosquitto.h" File "..\include\mosquitto_broker.h" File "..\include\mosquitto_plugin.h" File "..\include\mqtt_protocol.h" File "..\lib\cpp\mosquittopp.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_ctrl.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\mosquitto_dynamic_security.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\README-letsencrypt.md" ;Delete "$INSTDIR\pthreadVC2.dll" Delete "$INSTDIR\libssl-1_1.dll" Delete "$INSTDIR\libcrypto-1_1.dll" Delete "$INSTDIR\edl-v10" Delete "$INSTDIR\epl-v20" Delete "$INSTDIR\devel\mosquitto.h" Delete "$INSTDIR\devel\mosquitto.lib" Delete "$INSTDIR\devel\mosquitto_broker.h" Delete "$INSTDIR\devel\mosquitto_plugin.h" Delete "$INSTDIR\devel\mosquittopp.h" Delete "$INSTDIR\devel\mosquittopp.lib" Delete "$INSTDIR\devel\mqtt_protocol.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-2.0.11/installer/mosquitto64.nsi0000664000175000017500000001225314060132747017614 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 2.0.11 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\apps\mosquitto_ctrl\Release\mosquitto_ctrl.exe" File "..\build64\apps\mosquitto_passwd\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 "..\build64\plugins\dynamic-security\Release\mosquitto_dynamic_security.dll" File "..\aclfile.example" File "..\ChangeLog.txt" File "..\mosquitto.conf" File "..\NOTICE.md" File "..\pwfile.example" File "..\README.md" File "..\README-windows.txt" File "..\README-letsencrypt.md" ;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-v20" SetOutPath "$INSTDIR\devel" File "..\build64\lib\Release\mosquitto.lib" File "..\build64\lib\cpp\Release\mosquittopp.lib" File "..\include\mosquitto.h" File "..\include\mosquitto_broker.h" File "..\include\mosquitto_plugin.h" File "..\include\mqtt_protocol.h" File "..\lib\cpp\mosquittopp.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_ctrl.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\mosquitto_dynamic_security.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\README-letsencrypt.md" ;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-v20" Delete "$INSTDIR\devel\mosquitto.h" Delete "$INSTDIR\devel\mosquitto.lib" Delete "$INSTDIR\devel\mosquitto_broker.h" Delete "$INSTDIR\devel\mosquitto_plugin.h" Delete "$INSTDIR\devel\mosquitto_plugin.h" Delete "$INSTDIR\devel\mosquittopp.h" Delete "$INSTDIR\devel\mosquittopp.lib" Delete "$INSTDIR\devel\mqtt_protocol.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-2.0.11/src/0000775000175000017500000000000014060132747013452 5ustar rogerrogermosquitto-2.0.11/src/control.c0000664000175000017500000001030714060132747015277 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include "mqtt_protocol.h" #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "send_mosq.h" #ifdef WITH_CONTROL /* Process messages coming in on $CONTROL/. These messages aren't * passed on to other clients. */ int control__process(struct mosquitto *context, struct mosquitto_msg_store *stored) { struct mosquitto__callback *cb_found; struct mosquitto_evt_control event_data; struct mosquitto__security_options *opts; mosquitto_property *properties = NULL; int rc = MOSQ_ERR_SUCCESS; if(db.config->per_listener_settings){ opts = &context->listener->security_options; }else{ opts = &db.config->security_options; } HASH_FIND(hh, opts->plugin_callbacks.control, stored->topic, strlen(stored->topic), cb_found); if(cb_found){ memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.topic = stored->topic; event_data.payload = stored->payload; event_data.payloadlen = stored->payloadlen; event_data.qos = stored->qos; event_data.retain = stored->retain; event_data.properties = stored->properties; event_data.reason_code = MQTT_RC_SUCCESS; event_data.reason_string = NULL; rc = cb_found->cb(MOSQ_EVT_CONTROL, &event_data, cb_found->userdata); if(rc){ if(context->protocol == mosq_p_mqtt5 && event_data.reason_string){ mosquitto_property_add_string(&properties, MQTT_PROP_REASON_STRING, event_data.reason_string); } } free(event_data.reason_string); event_data.reason_string = NULL; } if(stored->qos == 1){ if(send__puback(context, stored->source_mid, MQTT_RC_SUCCESS, properties)) rc = 1; }else if(stored->qos == 2){ if(send__pubrec(context, stored->source_mid, MQTT_RC_SUCCESS, properties)) rc = 1; } mosquitto_property_free_all(&properties); return rc; } #endif int control__register_callback(struct mosquitto__security_options *opts, MOSQ_FUNC_generic_callback cb_func, const char *topic, void *userdata) { #ifdef WITH_CONTROL struct mosquitto__callback *cb_found, *cb_new; size_t topic_len; if(topic == NULL || cb_func == NULL) return MOSQ_ERR_INVAL; topic_len = strlen(topic); if(topic_len == 0 || topic_len > 65535) return MOSQ_ERR_INVAL; if(strncmp(topic, "$CONTROL/", strlen("$CONTROL/")) || strlen(topic) < strlen("$CONTROL/A/v1")){ return MOSQ_ERR_INVAL; } HASH_FIND(hh, opts->plugin_callbacks.control, topic, topic_len, cb_found); if(cb_found){ return MOSQ_ERR_ALREADY_EXISTS; } cb_new = mosquitto__calloc(1, sizeof(struct mosquitto__callback)); if(cb_new == NULL){ return MOSQ_ERR_NOMEM; } cb_new->data = mosquitto__strdup(topic); if(cb_new->data == NULL){ mosquitto__free(cb_new); return MOSQ_ERR_NOMEM; } cb_new->cb = cb_func; cb_new->userdata = userdata; HASH_ADD_KEYPTR(hh, opts->plugin_callbacks.control, cb_new->data, strlen(cb_new->data), cb_new); return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } int control__unregister_callback(struct mosquitto__security_options *opts, MOSQ_FUNC_generic_callback cb_func, const char *topic) { #ifdef WITH_CONTROL struct mosquitto__callback *cb_found; size_t topic_len; if(topic == NULL) return MOSQ_ERR_INVAL; topic_len = strlen(topic); if(topic_len == 0 || topic_len > 65535) return MOSQ_ERR_INVAL; if(strncmp(topic, "$CONTROL/", strlen("$CONTROL/"))) return MOSQ_ERR_INVAL; HASH_FIND(hh, opts->plugin_callbacks.control, topic, topic_len, cb_found); if(cb_found && cb_found->cb == cb_func){ HASH_DELETE(hh, opts->plugin_callbacks.control, cb_found); mosquitto__free(cb_found->data); mosquitto__free(cb_found); return MOSQ_ERR_SUCCESS;; } return MOSQ_ERR_NOT_FOUND; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } mosquitto-2.0.11/src/mosquitto_broker_internal.h0000664000175000017500000007360014060132747021135 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 LWS_LIBRARY_VERSION_NUMBER >= 3002000 && !defined(LWS_WITH_EXTERNAL_POLL) # warning "libwebsockets is not compiled with LWS_WITH_EXTERNAL_POLL support. Websocket performance will be unusable." # endif #endif #include "mosquitto_internal.h" #include "mosquitto_broker.h" #include "mosquitto_plugin.h" #include "mosquitto.h" #include "logging_mosq.h" #include "password_mosq.h" #include "tls_mosq.h" #include "uthash.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_DLT 0x20 #define MQTT3_LOG_ALL 0xFF #define WEBSOCKET_CLIENT -2 #define CMD_PORT_LIMIT 10 #define TOPIC_HIERARCHY_LIMIT 200 typedef uint64_t dbid_t; typedef int (*FUNC_plugin_init_v5)(mosquitto_plugin_id_t *, void **, struct mosquitto_opt *, int); typedef int (*FUNC_plugin_cleanup_v5)(void *, struct mosquitto_opt *, int); 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); struct mosquitto_plugin_id_t *identifier; FUNC_plugin_init_v5 plugin_init_v5; FUNC_plugin_cleanup_v5 plugin_cleanup_v5; 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__callback{ UT_hash_handle hh; /* For callbacks that register for e.g. a specific topic */ struct mosquitto__callback *next, *prev; /* For typical callbacks */ MOSQ_FUNC_generic_callback cb; void *userdata; char *data; /* e.g. topic for control event */ }; struct plugin__callbacks{ struct mosquitto__callback *tick; struct mosquitto__callback *acl_check; struct mosquitto__callback *basic_auth; struct mosquitto__callback *control; struct mosquitto__callback *disconnect; struct mosquitto__callback *ext_auth_continue; struct mosquitto__callback *ext_auth_start; struct mosquitto__callback *message; struct mosquitto__callback *psk_key; struct mosquitto__callback *reload; }; 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__unpwd *unpwd; struct mosquitto__unpwd *psk_id; 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; uint16_t auto_id_prefix_len; struct plugin__callbacks plugin_callbacks; mosquitto_plugin_id_t *pid; /* For registering as a "plugin" */ }; #ifdef WITH_EPOLL enum struct_ident{ id_invalid = 0, id_listener = 1, id_client = 2, id_listener_ws = 3, }; #endif struct mosquitto__listener { 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 max_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 *ciphers_tls13; 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 lws_context *ws_context; bool ws_in_init; char *http_dir; struct lws_protocols *ws_protocol; #endif struct mosquitto__security_options security_options; #ifdef WITH_UNIX_SOCKETS char *unix_socket_path; #endif }; struct mosquitto__listener_sock{ #ifdef WITH_EPOLL /* This *must* be the first element in the struct. */ int ident; #endif mosq_sock_t sock; struct mosquitto__listener *listener; }; typedef struct mosquitto_plugin_id_t{ struct mosquitto__listener *listener; } mosquitto_plugin_id_t; struct mosquitto__config { bool allow_duplicate_messages; int autosave_interval; bool autosave_on_changes; bool check_retain_source; char *clientid_prefixes; bool connection_messages; uint16_t cmd_port[CMD_PORT_LIMIT]; int cmd_port_count; bool daemon; struct mosquitto__listener default_listener; struct mosquitto__listener *listeners; int listener_count; bool local_only; unsigned int log_dest; int log_facility; unsigned int log_type; bool log_timestamp; char *log_timestamp_format; char *log_file; FILE *log_fptr; size_t max_inflight_bytes; size_t max_queued_bytes; int max_queued_messages; uint32_t max_packet_size; uint32_t message_size_limit; uint16_t max_inflight_messages; uint16_t max_keepalive; uint8_t max_qos; 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; uint16_t websockets_headers_size; #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; char *topic; uint16_t topic_len; }; struct sub__token { struct sub__token *next; char *topic; uint16_t topic_len; }; struct mosquitto__retainhier { UT_hash_handle hh; struct mosquitto__retainhier *parent; struct mosquitto__retainhier *children; 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; void *payload; time_t message_expiry_time; uint32_t payloadlen; enum mosquitto_msg_origin origin; uint16_t source_mid; uint16_t mid; uint8_t qos; bool retain; }; 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{ UT_hash_handle hh; char *username; char *password; char *clientid; #ifdef WITH_TLS unsigned char *salt; unsigned int password_len; unsigned int salt_len; int iterations; #endif enum mosquitto_pwhash_type hashtype; }; 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_message_v5{ struct mosquitto_message_v5 *next, *prev; char *topic; void *payload; mosquitto_property *properties; char *clientid; /* Used only by mosquitto_broker_publish*() to indicate this message is for a specific client. */ int payloadlen; int qos; bool retain; }; struct mosquitto_db{ dbid_t last_db_id; struct mosquitto__subhier *subs; struct mosquitto__retainhier *retains; 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; time_t now_s; /* Monotonic clock, where possible */ time_t now_real_s; /* Read clock, for measuring session/message expiry */ #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 struct mosquitto_message_v5 *plugin_msgs; }; 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; char *local_prefix; char *remote_prefix; char *local_topic; /* topic prefixed with local_prefix */ char *remote_topic; /* topic prefixed with remote_prefix */ enum mosquitto__bridge_direction direction; uint8_t qos; }; struct bridge_address{ char *address; uint16_t 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; int8_t clean_start_local; uint16_t 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; char *bind_address; 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; uint32_t maximum_packet_size; bool lazy_reconnect; bool attempt_unsubscribe; bool initial_notification_done; bool outgoing_retain; #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 mosquitto__listener *listener; }; struct libws_mqtt_data { struct mosquitto *mosq; }; #endif #include extern struct mosquitto_db db; /* ============================================================ * Main functions * ============================================================ */ int mosquitto_main_loop(struct mosquitto__listener_sock *listensock, int listensock_count); /* ============================================================ * Config functions * ============================================================ */ /* Initialise config struct to default values. */ void config__init(struct mosquitto__config *config); /* Parse command line options into config. */ int config__parse_args(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__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); /* ============================================================ * Server send functions * ============================================================ */ int send__connack(struct mosquitto *context, uint8_t ack, uint8_t 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 *context, uint8_t reason_code, const void *auth_data, uint16_t auth_data_len); /* ============================================================ * Network functions * ============================================================ */ void net__broker_init(void); void net__broker_cleanup(void); struct mosquitto *net__socket_accept(struct mosquitto__listener_sock *listensock); int net__socket_listen(struct mosquitto__listener *listener); int net__socket_get_address(mosq_sock_t sock, char *buf, size_t len, uint16_t *remote_address); int net__tls_load_verify(struct mosquitto__listener *listener); int net__tls_server_ctx(struct mosquitto__listener *listener); int net__load_certificates(struct mosquitto__listener *listener); /* ============================================================ * Read handling functions * ============================================================ */ int handle__packet(struct mosquitto *context); int handle__connack(struct mosquitto *context); int handle__connect(struct mosquitto *context); int handle__disconnect(struct mosquitto *context); int handle__publish(struct mosquitto *context); int handle__subscribe(struct mosquitto *context); int handle__unsubscribe(struct mosquitto *context); int handle__auth(struct mosquitto *context); /* ============================================================ * Database handling * ============================================================ */ int db__open(struct mosquitto__config *config); int db__close(void); #ifdef WITH_PERSISTENCE int persist__backup(bool shutdown); int persist__restore(void); #endif /* Return the number of in-flight messages in count. */ int db__message_count(int *count); int db__message_delete_outgoing(struct mosquitto *context, uint16_t mid, enum mosquitto_msg_state expect_state, int qos); int db__message_insert(struct mosquitto *context, uint16_t mid, enum mosquitto_msg_direction dir, uint8_t qos, bool retain, struct mosquitto_msg_store *stored, mosquitto_property *properties, bool update); int db__message_remove_incoming(struct mosquitto* context, uint16_t mid); int db__message_release_incoming(struct mosquitto *context, uint16_t mid); int db__message_update_outgoing(struct mosquitto *context, uint16_t mid, enum mosquitto_msg_state state, int qos); void db__message_dequeue_first(struct mosquitto *context, struct mosquitto_msg_data *msg_data); int db__messages_delete(struct mosquitto *context, bool force_free); int db__messages_easy_queue(struct mosquitto *context, const char *topic, uint8_t qos, uint32_t payloadlen, const void *payload, int retain, uint32_t message_expiry_interval, mosquitto_property **properties); int db__message_store(const struct mosquitto *source, struct mosquitto_msg_store *stored, uint32_t message_expiry_interval, 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_msg_store *store); void db__msg_store_remove(struct mosquitto_msg_store *store); void db__msg_store_ref_inc(struct mosquitto_msg_store *store); void db__msg_store_ref_dec(struct mosquitto_msg_store **store); void db__msg_store_clean(void); void db__msg_store_compact(void); void db__msg_store_free(struct mosquitto_msg_store *store); int db__message_reconnect_reset(struct mosquitto *context); bool db__ready_for_flight(struct mosquitto *context, enum mosquitto_msg_direction dir, int qos); bool db__ready_for_queue(struct mosquitto *context, int qos, struct mosquitto_msg_data *msg_data); void sys_tree__init(void); void sys_tree__update(int interval, time_t start_time); int db__message_write_inflight_out_all(struct mosquitto *context); int db__message_write_inflight_out_latest(struct mosquitto *context); int db__message_write_queued_out(struct mosquitto *context); int db__message_write_queued_in(struct mosquitto *context); /* ============================================================ * Subscription functions * ============================================================ */ int sub__add(struct mosquitto *context, const char *sub, uint8_t 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, uint16_t len); int sub__remove(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 *context); int sub__messages_queue(const char *source_id, const char *topic, uint8_t qos, int retain, struct mosquitto_msg_store **stored); int sub__topic_tokenise(const char *subtopic, char **local_sub, char ***topics, const char **sharename); void sub__topic_tokens_free(struct sub__token *tokens); /* ============================================================ * Context functions * ============================================================ */ struct mosquitto *context__init(mosq_sock_t sock); void context__cleanup(struct mosquitto *context, bool force_free); void context__disconnect(struct mosquitto *context); void context__add_to_disused(struct mosquitto *context); void context__free_disused(void); void context__send_will(struct mosquitto *context); void context__remove_from_by_id(struct mosquitto *context); int connect__on_authorised(struct mosquitto *context, void *auth_data_out, uint16_t auth_data_out_len); /* ============================================================ * Control functions * ============================================================ */ #ifdef WITH_CONTROL int control__process(struct mosquitto *context, struct mosquitto_msg_store *stored); void control__cleanup(void); #endif int control__register_callback(struct mosquitto__security_options *opts, MOSQ_FUNC_generic_callback cb_func, const char *topic, void *userdata); int control__unregister_callback(struct mosquitto__security_options *opts, MOSQ_FUNC_generic_callback cb_func, const char *topic); /* ============================================================ * Logging functions * ============================================================ */ int log__init(struct mosquitto__config *config); int log__close(struct mosquitto__config *config); void log__internal(const char *fmt, ...) __attribute__((format(printf, 1, 2))); /* ============================================================ * Bridge functions * ============================================================ */ #ifdef WITH_BRIDGE void bridge__start_all(void); int bridge__new(struct mosquitto__bridge *bridge); void bridge__cleanup(struct mosquitto *context); int bridge__connect(struct mosquitto *context); int bridge__connect_step1(struct mosquitto *context); int bridge__connect_step2(struct mosquitto *context); int bridge__connect_step3(struct mosquitto *context); int bridge__on_connect(struct mosquitto *context); void bridge__packet_cleanup(struct mosquitto *context); void bridge_check(void); int bridge__register_local_connections(void); int bridge__add_topic(struct mosquitto__bridge *bridge, const char *topic, enum mosquitto__bridge_direction direction, uint8_t qos, const char *local_prefix, const char *remote_prefix); int bridge__remap_topic_in(struct mosquitto *context, char **topic); #endif /* ============================================================ * IO multiplex related functions * ============================================================ */ int mux__init(struct mosquitto__listener_sock *listensock, int listensock_count); int mux__loop_prepare(void); int mux__add_out(struct mosquitto *context); int mux__remove_out(struct mosquitto *context); int mux__add_in(struct mosquitto *context); int mux__delete(struct mosquitto *context); int mux__wait(void); int mux__handle(struct mosquitto__listener_sock *listensock, int listensock_count); int mux__cleanup(void); /* ============================================================ * Listener related functions * ============================================================ */ void listener__set_defaults(struct mosquitto__listener *listener); void listeners__reload_all_certificates(void); #ifdef WITH_WEBSOCKETS void listeners__add_websockets(struct lws_context *ws_context, mosq_sock_t fd); #endif /* ============================================================ * Plugin related functions * ============================================================ */ int plugin__load_v5(struct mosquitto__listener *listener, struct mosquitto__auth_plugin *plugin, struct mosquitto_opt *auth_options, int auth_option_count, void *lib); void plugin__handle_disconnect(struct mosquitto *context, int reason); int plugin__handle_message(struct mosquitto *context, struct mosquitto_msg_store *stored); void LIB_ERROR(void); void plugin__handle_tick(void); /* ============================================================ * Property related functions * ============================================================ */ int keepalive__add(struct mosquitto *context); void keepalive__check(void); int keepalive__remove(struct mosquitto *context); void keepalive__remove_all(void); int keepalive__update(struct mosquitto *context); /* ============================================================ * 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); /* ============================================================ * Retain tree related functions * ============================================================ */ int retain__init(void); void retain__clean(struct mosquitto__retainhier **retainhier); int retain__queue(struct mosquitto *context, const char *sub, uint8_t sub_qos, uint32_t subscription_identifier); int retain__store(const char *topic, struct mosquitto_msg_store *stored, char **split_topics); /* ============================================================ * Security related functions * ============================================================ */ int acl__find_acls(struct mosquitto *context); int mosquitto_security_module_init(void); int mosquitto_security_module_cleanup(void); int mosquitto_security_init(bool reload); int mosquitto_security_apply(void); int mosquitto_security_cleanup(bool reload); int mosquitto_acl_check(struct mosquitto *context, const char *topic, uint32_t payloadlen, void* payload, uint8_t qos, bool retain, int access); int mosquitto_unpwd_check(struct mosquitto *context); int mosquitto_psk_key_get(struct mosquitto *context, const char *hint, const char *identity, char *key, int max_key_len); int mosquitto_security_init_default(bool reload); int mosquitto_security_apply_default(void); int mosquitto_security_cleanup_default(bool reload); int mosquitto_psk_key_get_default(struct mosquitto *context, const char *hint, const char *identity, char *key, int max_key_len); int mosquitto_security_auth_start(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 *context, const void *data_in, uint16_t data_len, void **data_out, uint16_t *data_out_len); void unpwd__free_item(struct mosquitto__unpwd **unpwd, struct mosquitto__unpwd *item); /* ============================================================ * Session expiry * ============================================================ */ int session_expiry__add(struct mosquitto *context); void session_expiry__remove(struct mosquitto *context); void session_expiry__remove_all(void); void session_expiry__check(void); void session_expiry__send_all(void); /* ============================================================ * Signals * ============================================================ */ void handle_sigint(int signal); void handle_sigusr1(int signal); void handle_sigusr2(int signal); #ifdef SIGHUP void handle_sighup(int signal); #endif /* ============================================================ * 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 void mosq_websockets_init(struct mosquitto__listener *listener, const struct mosquitto__config *conf); #endif void do_disconnect(struct mosquitto *context, int reason); /* ============================================================ * Will delay * ============================================================ */ int will_delay__add(struct mosquitto *context); void will_delay__check(void); void will_delay__send_all(void); void will_delay__remove(struct mosquitto *mosq); /* ============================================================ * Other * ============================================================ */ #ifdef WITH_XTREPORT void xtreport(void); #endif #endif mosquitto-2.0.11/src/security_default.c0000664000175000017500000011101114060132747017164 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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__security_options *security_opts); static int unpwd__file_parse(struct mosquitto__unpwd **unpwd, const char *password_file); static int acl__cleanup(bool reload); static int unpwd__cleanup(struct mosquitto__unpwd **unpwd, bool reload); static int psk__file_parse(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, enum mosquitto_pwhash_type hashtype, int iterations); #endif static int mosquitto_unpwd_check_default(int event, void *event_data, void *userdata); static int mosquitto_acl_check_default(int event, void *event_data, void *userdata); int mosquitto_security_init_default(bool reload) { int rc; int i; char *pwf; char *pskf = NULL; UNUSED(reload); /* Configure plugin identifier */ if(db.config->per_listener_settings){ for(i=0; ilistener_count; i++){ db.config->listeners[i].security_options.pid = mosquitto__calloc(1, sizeof(mosquitto_plugin_id_t)); if(db.config->listeners[i].security_options.pid == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } db.config->listeners[i].security_options.pid->listener = &db.config->listeners[i]; } }else{ db.config->security_options.pid = mosquitto__calloc(1, sizeof(mosquitto_plugin_id_t)); if(db.config->security_options.pid == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } /* Load username/password data if required. */ if(db.config->per_listener_settings){ for(i=0; ilistener_count; i++){ pwf = db.config->listeners[i].security_options.password_file; if(pwf){ rc = unpwd__file_parse(&db.config->listeners[i].security_options.unpwd, pwf); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error opening password file \"%s\".", pwf); return rc; } mosquitto_callback_register(db.config->listeners[i].security_options.pid, MOSQ_EVT_BASIC_AUTH, mosquitto_unpwd_check_default, NULL, NULL); } } }else{ if(db.config->security_options.password_file){ pwf = db.config->security_options.password_file; if(pwf){ rc = unpwd__file_parse(&db.config->security_options.unpwd, pwf); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error opening password file \"%s\".", pwf); return rc; } } mosquitto_callback_register(db.config->security_options.pid, MOSQ_EVT_BASIC_AUTH, mosquitto_unpwd_check_default, NULL, NULL); } } /* Load acl data if required. */ if(db.config->per_listener_settings){ for(i=0; ilistener_count; i++){ if(db.config->listeners[i].security_options.acl_file){ rc = aclfile__parse(&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; } mosquitto_callback_register(db.config->listeners[i].security_options.pid, MOSQ_EVT_ACL_CHECK, mosquitto_acl_check_default, NULL, NULL); } } }else{ if(db.config->security_options.acl_file){ rc = aclfile__parse(&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; } mosquitto_callback_register(db.config->security_options.pid, MOSQ_EVT_ACL_CHECK, mosquitto_acl_check_default, NULL, NULL); } } /* Load psk data if required. */ if(db.config->per_listener_settings){ for(i=0; ilistener_count; i++){ pskf = db.config->listeners[i].security_options.psk_file; if(pskf){ rc = psk__file_parse(&db.config->listeners[i].security_options.psk_id, pskf); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error opening psk file \"%s\".", pskf); return rc; } } } }else{ pskf = db.config->security_options.psk_file; if(pskf){ rc = psk__file_parse(&db.config->security_options.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(bool reload) { int rc; int i; rc = acl__cleanup(reload); if(rc != MOSQ_ERR_SUCCESS) return rc; rc = unpwd__cleanup(&db.config->security_options.unpwd, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; for(i=0; ilistener_count; i++){ if(db.config->listeners[i].security_options.unpwd){ rc = unpwd__cleanup(&db.config->listeners[i].security_options.unpwd, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; } } rc = unpwd__cleanup(&db.config->security_options.psk_id, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; for(i=0; ilistener_count; i++){ if(db.config->listeners[i].security_options.psk_id){ rc = unpwd__cleanup(&db.config->listeners[i].security_options.psk_id, reload); if(rc != MOSQ_ERR_SUCCESS) return rc; } } if(db.config->per_listener_settings){ for(i=0; ilistener_count; i++){ if(db.config->listeners[i].security_options.pid){ mosquitto_callback_unregister(db.config->listeners[i].security_options.pid, MOSQ_EVT_BASIC_AUTH, mosquitto_unpwd_check_default, NULL); mosquitto_callback_unregister(db.config->listeners[i].security_options.pid, MOSQ_EVT_ACL_CHECK, mosquitto_acl_check_default, NULL); mosquitto__free(db.config->listeners[i].security_options.pid); } } }else{ if(db.config->security_options.pid){ mosquitto_callback_unregister(db.config->security_options.pid, MOSQ_EVT_BASIC_AUTH, mosquitto_unpwd_check_default, NULL); mosquitto_callback_unregister(db.config->security_options.pid, MOSQ_EVT_ACL_CHECK, mosquitto_acl_check_default, NULL); mosquitto__free(db.config->security_options.pid); } } return MOSQ_ERR_SUCCESS; } static 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; if(access == MOSQ_ACL_NONE){ /* Put "deny" acls at front of the list */ acl->next = acl_tail; acl_user->acl = acl; }else{ 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; } static 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; if(access == MOSQ_ACL_NONE){ /* Put "deny" acls at front of the list */ acl->next = acl_tail; security_opts->acl_patterns = acl; }else{ while(acl_tail->next){ acl_tail = acl_tail->next; } acl_tail->next = acl; } }else{ security_opts->acl_patterns = acl; } return MOSQ_ERR_SUCCESS; } static int mosquitto_acl_check_default(int event, void *event_data, void *userdata) { struct mosquitto_evt_acl_check *ed = event_data; char *local_acl; struct mosquitto__acl *acl_root; bool result; size_t i; size_t len, tlen, clen, ulen; char *s; struct mosquitto__security_options *security_opts = NULL; UNUSED(event); UNUSED(userdata); if(ed->client->bridge) return MOSQ_ERR_SUCCESS; if(ed->access == MOSQ_ACL_SUBSCRIBE || ed->access == MOSQ_ACL_UNSUBSCRIBE) return MOSQ_ERR_SUCCESS; /* FIXME - implement ACL subscription strings. */ if(db.config->per_listener_settings){ if(!ed->client->listener) return MOSQ_ERR_ACL_DENIED; security_opts = &ed->client->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(!ed->client->acl_list && !security_opts->acl_patterns) return MOSQ_ERR_ACL_DENIED; if(ed->client->acl_list){ acl_root = ed->client->acl_list->acl; }else{ acl_root = NULL; } /* Loop through all ACLs for this client. ACL denials are iterated over first. */ 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(ed->topic[0] == '$' && acl_root->topic[0] != '$'){ acl_root = acl_root->next; continue; } mosquitto_topic_matches_sub(acl_root->topic, ed->topic, &result); if(result){ if(acl_root->access == MOSQ_ACL_NONE){ /* Access was explicitly denied for this topic. */ return MOSQ_ERR_ACL_DENIED; } if(ed->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(ed->client->username && strpbrk(ed->client->username, "+#")){ log__printf(NULL, MOSQ_LOG_NOTICE, "ACL denying access to client with dangerous username \"%s\"", ed->client->username); return MOSQ_ERR_ACL_DENIED; } if(ed->client->id && strpbrk(ed->client->id, "+#")){ log__printf(NULL, MOSQ_LOG_NOTICE, "ACL denying access to client with dangerous client id \"%s\"", ed->client->id); return MOSQ_ERR_ACL_DENIED; } } /* Loop through all pattern ACLs. ACL denial patterns are iterated over first. */ if(!ed->client->id) return MOSQ_ERR_ACL_DENIED; clen = strlen(ed->client->id); while(acl_root){ tlen = strlen(acl_root->topic); if(acl_root->ucount && !ed->client->username){ acl_root = acl_root->next; continue; } if(ed->client->username){ ulen = strlen(ed->client->username); len = tlen + (size_t)acl_root->ccount*(clen-2) + (size_t)acl_root->ucount*(ulen-2); }else{ ulen = 0; len = tlen + (size_t)acl_root->ccount*(clen-2); } local_acl = mosquitto__malloc(len+1); if(!local_acl) return MOSQ_ERR_NOMEM; s = local_acl; for(i=0; itopic[i] == '%'){ if(acl_root->topic[i+1] == 'c'){ i++; strncpy(s, ed->client->id, clen); s+=clen; continue; }else if(ed->client->username && acl_root->topic[i+1] == 'u'){ i++; strncpy(s, ed->client->username, ulen); s+=ulen; continue; } } s[0] = acl_root->topic[i]; s++; } local_acl[len] = '\0'; mosquitto_topic_matches_sub(local_acl, ed->topic, &result); mosquitto__free(local_acl); if(result){ if(acl_root->access == MOSQ_ACL_NONE){ /* Access was explicitly denied for this topic pattern. */ return MOSQ_ERR_ACL_DENIED; } if(ed->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__security_options *security_opts) { FILE *aclfptr = NULL; char *token; char *user = NULL; char *topic; char *access_s; int access; int rc = MOSQ_ERR_SUCCESS; size_t slen; int topic_pattern; char *saveptr = NULL; char *buf = NULL; int buflen = 256; if(!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((size_t)buflen); if(buf == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } 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 MOSQ_ERR_UNKNOWN; } /* 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 if(!strcmp(access_s, "deny")){ access = MOSQ_ACL_NONE; }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(bool reload) { struct mosquitto *context, *ctxt_tmp = NULL; int i; UNUSED(reload); /* 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; ilistener_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 *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((size_t)buflen); if(buf == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } 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 MOSQ_ERR_UNKNOWN; } 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; } void unpwd__free_item(struct mosquitto__unpwd **unpwd, struct mosquitto__unpwd *item) { mosquitto__free(item->username); mosquitto__free(item->password); #ifdef WITH_TLS mosquitto__free(item->salt); #endif HASH_DEL(*unpwd, item); mosquitto__free(item); } #ifdef WITH_TLS static int unpwd__decode_passwords(struct mosquitto__unpwd **unpwd) { struct mosquitto__unpwd *u, *tmp = NULL; char *token; unsigned char *salt; unsigned int salt_len; unsigned char *password; unsigned int password_len; int rc; enum mosquitto_pwhash_type hashtype; HASH_ITER(hh, *unpwd, u, tmp){ /* Need to decode password into hashed data + salt. */ if(u->password == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Missing password hash for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); continue; } token = strtok(u->password, "$"); if(token == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid password hash for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); continue; } if(!strcmp(token, "6")){ hashtype = pw_sha512; }else if(!strcmp(token, "7")){ hashtype = pw_sha512_pbkdf2; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid password hash type for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); continue; } if(hashtype == pw_sha512_pbkdf2){ token = strtok(NULL, "$"); if(token == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid password hash for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); continue; } u->iterations = atoi(token); if(u->iterations < 1){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid hash iterations for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); continue; } } token = strtok(NULL, "$"); if(token == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid password hash for user %s, removing entry.", u->username); unpwd__free_item(unpwd, u); continue; } 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; u->hashtype = hashtype; }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); } } 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__unpwd **psk_id, const char *psk_file) { int rc; struct mosquitto__unpwd *u, *tmp = NULL; if(!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; iclient->username == NULL){ return MOSQ_ERR_PLUGIN_DEFER; } if(db.config->per_listener_settings){ if(ed->client->bridge) return MOSQ_ERR_SUCCESS; if(!ed->client->listener) return MOSQ_ERR_INVAL; unpwd_ref = ed->client->listener->security_options.unpwd; }else{ unpwd_ref = db.config->security_options.unpwd; } HASH_FIND(hh, unpwd_ref, ed->client->username, strlen(ed->client->username), u); if(u){ if(u->password){ if(ed->client->password){ #ifdef WITH_TLS rc = pw__digest(ed->client->password, u->salt, u->salt_len, hash, &hash_len, u->hashtype, u->iterations); 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, ed->client->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 = NULL; 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 *context) { if(context->protocol == mosq_p_mqtt5){ send__disconnect(context, MQTT_RC_ADMINISTRATIVE_ACTION, NULL); } mosquitto__set_state(context, mosq_cs_disconnecting); do_disconnect(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(void) { struct mosquitto *context, *ctxt_tmp = NULL; 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; BIO *subject_bio; char *data_start; size_t name_length; char *subject; #endif #ifdef WITH_TLS for(i=0; ilistener_count; i++){ listener = &db.config->listeners[i]; if(listener && listener->ssl_ctx && listener->certfile && listener->keyfile && listener->crlfile && listener->require_certificate){ if(net__tls_server_ctx(listener)){ return MOSQ_ERR_TLS; } if(net__tls_load_verify(listener)){ return MOSQ_ERR_TLS; } } } #endif HASH_ITER(hh_id, db.contexts_by_id, context, ctxt_tmp){ if(context->bridge){ continue; } /* 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(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(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(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(context); continue; } name = X509_get_subject_name(client_cert); if(!name){ X509_free(client_cert); client_cert = NULL; security__disconnect_auth(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(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(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(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(context); continue; } } } else { /* use_subject_as_username */ subject_bio = BIO_new(BIO_s_mem()); X509_NAME_print_ex(subject_bio, X509_get_subject_name(client_cert), 0, XN_FLAG_RFC2253); data_start = NULL; name_length = (size_t)BIO_get_mem_data(subject_bio, &data_start); subject = mosquitto__malloc(sizeof(char)*name_length+1); if(!subject){ BIO_free(subject_bio); X509_free(client_cert); client_cert = NULL; security__disconnect_auth(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(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(context) != MOSQ_ERR_SUCCESS){ mosquitto__set_state(context, mosq_cs_disconnecting); do_disconnect(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(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 *context, const char *hint, const char *identity, char *key, int max_key_len) { struct mosquitto__unpwd *u, *tmp = NULL; struct mosquitto__unpwd *psk_id_ref = NULL; if(!hint || !identity || !key) return MOSQ_ERR_INVAL; if(db.config->per_listener_settings){ if(!context->listener) return MOSQ_ERR_INVAL; psk_id_ref = context->listener->security_options.psk_id; }else{ psk_id_ref = db.config->security_options.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, (size_t)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, enum mosquitto_pwhash_type hashtype, int iterations) { const EVP_MD *digest; #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_MD_CTX context; #else EVP_MD_CTX *context; #endif digest = EVP_get_digestbyname("sha512"); if(!digest){ /* FIXME fprintf(stderr, "Error: Unable to create openssl digest.\n"); */ return 1; } if(hashtype == pw_sha512){ #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); /* hash is assumed to be EVP_MAX_MD_SIZE bytes long. */ 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); /* hash is assumed to be EVP_MAX_MD_SIZE bytes long. */ EVP_DigestFinal_ex(context, hash, hash_len); EVP_MD_CTX_free(context); #endif }else{ *hash_len = EVP_MAX_MD_SIZE; PKCS5_PBKDF2_HMAC(password, (int)strlen(password), salt, (int)salt_len, iterations, digest, (int)(*hash_len), hash); } return MOSQ_ERR_SUCCESS; } #endif mosquitto-2.0.11/src/handle_subscribe.c0000664000175000017500000001477614060132747017131 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *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; size_t len; uint16_t slen; char *sub_mount; mosquitto_property *properties = NULL; bool allowed; 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_MALFORMED_PACKET; } } if(packet__read_uint16(&context->in_packet, &mid)) return MOSQ_ERR_MALFORMED_PACKET; if(mid == 0) return MOSQ_ERR_MALFORMED_PACKET; if(context->protocol == mosq_p_mqtt5){ rc = property__read_all(CMD_SUBSCRIBE, &context->in_packet, &properties); if(rc){ /* FIXME - it would be better if property__read_all() returned * MOSQ_ERR_MALFORMED_PACKET, but this is would change the library * return codes so needs doc changes as well. */ if(rc == MOSQ_ERR_PROTOCOL){ return MOSQ_ERR_MALFORMED_PACKET; }else{ 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_MALFORMED_PACKET; } } 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 MOSQ_ERR_MALFORMED_PACKET; } 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 MOSQ_ERR_MALFORMED_PACKET; } 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 MOSQ_ERR_MALFORMED_PACKET; } if(packet__read_byte(&context->in_packet, &subscription_options)){ mosquitto__free(sub); mosquitto__free(payload); return MOSQ_ERR_MALFORMED_PACKET; } 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){ mosquitto__free(sub); mosquitto__free(payload); return MOSQ_ERR_MALFORMED_PACKET; } } 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 MOSQ_ERR_MALFORMED_PACKET; } if(qos > context->max_qos){ qos = context->max_qos; } 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); allowed = true; rc2 = mosquitto_acl_check(context, sub, 0, NULL, qos, false, MOSQ_ACL_SUBSCRIBE); switch(rc2){ case MOSQ_ERR_SUCCESS: break; case MOSQ_ERR_ACL_DENIED: allowed = false; if(context->protocol == mosq_p_mqtt5){ qos = MQTT_RC_NOT_AUTHORIZED; }else if(context->protocol == mosq_p_mqtt311){ qos = 0x80; } break; default: mosquitto__free(sub); return rc2; } if(allowed){ rc2 = sub__add(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(retain__queue(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(retain__queue(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_MALFORMED_PACKET; } } if(send__suback(context, mid, payloadlen, payload)) rc = 1; mosquitto__free(payload); #ifdef WITH_PERSISTENCE db.persistence_changes++; #endif if(context->current_out_packet == NULL){ rc = db__message_write_queued_out(context); if(rc) return rc; rc = db__message_write_inflight_out_latest(context); if(rc) return rc; } return rc; } mosquitto-2.0.11/src/handle_connack.c0000664000175000017500000001270714060132747016554 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *context) { int rc; uint8_t connect_acknowledge; uint8_t reason_code; mosquitto_property *properties = NULL; uint32_t maximum_packet_size; uint8_t retain_available; uint16_t server_keepalive; uint8_t max_qos = 255; if(context == NULL || context->bridge == NULL){ 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 MOSQ_ERR_MALFORMED_PACKET; if(packet__read_byte(&context->in_packet, &reason_code)) return MOSQ_ERR_MALFORMED_PACKET; if(context->protocol == mosq_p_mqtt5){ if(context->in_packet.remaining_length == 2 && reason_code == CONNACK_REFUSED_PROTOCOL_VERSION){ /* We have connected to a MQTT v3.x broker that doesn't support MQTT v5.0 * It has correctly replied with a CONNACK code of a bad protocol version. */ log__printf(NULL, MOSQ_LOG_NOTICE, "Warning: Remote bridge %s does not support MQTT v5.0, reconnecting using MQTT v3.1.1.", context->bridge->name); context->protocol = mosq_p_mqtt311; context->bridge->protocol_version = mosq_p_mqtt311; return MOSQ_ERR_PROTOCOL; } rc = property__read_all(CMD_CONNACK, &context->in_packet, &properties); if(rc) return rc; /* maximum-qos */ mosquitto_property_read_byte(properties, MQTT_PROP_MAXIMUM_QOS, &max_qos, false); /* maximum-packet-size */ if(mosquitto_property_read_int32(properties, MQTT_PROP_MAXIMUM_PACKET_SIZE, &maximum_packet_size, false)){ if(context->maximum_packet_size == 0 || context->maximum_packet_size > maximum_packet_size){ context->maximum_packet_size = maximum_packet_size; } } /* receive-maximum */ mosquitto_property_read_int16(properties, MQTT_PROP_RECEIVE_MAXIMUM, &context->msgs_out.inflight_maximum, false); context->msgs_out.inflight_quota = context->msgs_out.inflight_maximum; /* retain-available */ if(mosquitto_property_read_byte(properties, MQTT_PROP_RETAIN_AVAILABLE, &retain_available, false)){ /* Only use broker provided value if the local config is set to available==true */ if(context->retain_available){ context->retain_available = retain_available; } } /* server-keepalive */ if(mosquitto_property_read_int16(properties, MQTT_PROP_SERVER_KEEP_ALIVE, &server_keepalive, false)){ context->keepalive = server_keepalive; } mosquitto_property_free_all(&properties); } mosquitto_property_free_all(&properties); /* FIXME - TEMPORARY UNTIL PROPERTIES PROCESSED */ if(reason_code == MQTT_RC_SUCCESS){ #ifdef WITH_BRIDGE if(context->bridge){ rc = bridge__on_connect(context); if(rc) return rc; } #endif if(max_qos != 255){ context->max_qos = max_qos; } mosquitto__set_state(context, mosq_cs_active); rc = db__message_write_queued_out(context); if(rc) return rc; rc = db__message_write_inflight_out_all(context); return rc; }else{ if(context->protocol == mosq_p_mqtt5){ switch(reason_code){ case MQTT_RC_RETAIN_NOT_SUPPORTED: context->retain_available = 0; log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: retain not available (will retry)"); return MOSQ_ERR_CONN_LOST; case MQTT_RC_QOS_NOT_SUPPORTED: if(max_qos == 255){ if(context->max_qos != 0){ context->max_qos--; } }else{ context->max_qos = max_qos; } log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: QoS not supported (will retry)"); return MOSQ_ERR_CONN_LOST; default: log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: %s", mosquitto_reason_string(reason_code)); return MOSQ_ERR_CONN_LOST; } }else{ switch(reason_code){ 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 MOSQ_ERR_CONN_LOST; case CONNACK_REFUSED_IDENTIFIER_REJECTED: log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: identifier rejected"); return MOSQ_ERR_CONN_LOST; case CONNACK_REFUSED_SERVER_UNAVAILABLE: log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: broker unavailable"); return MOSQ_ERR_CONN_LOST; case CONNACK_REFUSED_BAD_USERNAME_PASSWORD: log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: broker unavailable"); return MOSQ_ERR_CONN_LOST; case CONNACK_REFUSED_NOT_AUTHORIZED: log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: not authorised"); return MOSQ_ERR_CONN_LOST; default: log__printf(NULL, MOSQ_LOG_ERR, "Connection Refused: unknown reason"); return MOSQ_ERR_CONN_LOST; } } } return MOSQ_ERR_CONN_LOST; } mosquitto-2.0.11/src/mux_poll.c0000664000175000017500000001727214060132747015466 0ustar rogerroger/* Copyright (c) 2009-2019 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifndef WITH_EPOLL #ifndef WIN32 # define _GNU_SOURCE #endif #include #ifndef WIN32 #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" #include "mux.h" static void loop_handle_reads_writes(void); static struct pollfd *pollfds = NULL; static size_t pollfd_max, pollfd_current_max; #ifndef WIN32 static sigset_t my_sigblock; #endif int mux_poll__init(struct mosquitto__listener_sock *listensock, int listensock_count) { size_t i; size_t pollfd_index = 0; #ifndef WIN32 sigemptyset(&my_sigblock); sigaddset(&my_sigblock, SIGINT); sigaddset(&my_sigblock, SIGTERM); sigaddset(&my_sigblock, SIGUSR1); sigaddset(&my_sigblock, SIGUSR2); sigaddset(&my_sigblock, SIGHUP); #endif #ifdef WIN32 pollfd_max = (size_t)_getmaxstdio(); #else pollfd_max = (size_t)sysconf(_SC_OPEN_MAX); #endif pollfds = mosquitto__calloc(pollfd_max, sizeof(struct pollfd)); if(!pollfds){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } memset(pollfds, 0, sizeof(struct pollfd)*pollfd_max); for(i=0; ievents == evt){ return MOSQ_ERR_SUCCESS; } if(context->pollfd_index != -1){ pollfds[context->pollfd_index].fd = context->sock; pollfds[context->pollfd_index].events = (short int)evt; pollfds[context->pollfd_index].revents = 0; }else{ for(i=0; isock; pollfds[i].events = POLLIN; pollfds[i].revents = 0; context->pollfd_index = (int)i; if(i > pollfd_current_max){ pollfd_current_max = i; } break; } } } context->events = evt; return MOSQ_ERR_SUCCESS; } int mux_poll__add_out(struct mosquitto *context) { return mux_poll__add(context, POLLIN | POLLOUT); } int mux_poll__remove_out(struct mosquitto *context) { if(context->events & POLLOUT) { return mux_poll__add_in(context); }else{ return MOSQ_ERR_SUCCESS; } } int mux_poll__add_in(struct mosquitto *context) { return mux_poll__add(context, POLLIN); } int mux_poll__delete(struct mosquitto *context) { size_t pollfd_index; if(context->pollfd_index != -1){ pollfds[context->pollfd_index].fd = INVALID_SOCKET; pollfds[context->pollfd_index].events = 0; pollfds[context->pollfd_index].revents = 0; pollfd_index = (size_t )context->pollfd_index; context->pollfd_index = -1; /* If this is the highest index, reduce the current max until we find * the next highest in use index. */ while(pollfd_index == pollfd_current_max && pollfd_index > 0 && pollfds[pollfd_index].fd == INVALID_SOCKET){ pollfd_index--; pollfd_current_max--; } } return MOSQ_ERR_SUCCESS; } int mux_poll__handle(struct mosquitto__listener_sock *listensock, int listensock_count) { struct mosquitto *context; int i; int fdcount; #ifndef WIN32 sigset_t origsig; #endif #ifndef WIN32 sigprocmask(SIG_SETMASK, &my_sigblock, &origsig); fdcount = poll(pollfds, pollfd_current_max+1, 100); sigprocmask(SIG_SETMASK, &origsig, NULL); #else fdcount = WSAPoll(pollfds, pollfd_current_max+1, 100); #endif db.now_s = mosquitto_time(); db.now_real_s = time(NULL); if(fdcount == -1){ # ifdef WIN32 if(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(); for(i=0; iws_context){ /* Nothing needs to happen here, because we always call lws_service in the loop. * The important point is we've been woken up for this listener. */ }else #endif { while((context = net__socket_accept(&listensock[i])) != NULL){ context->pollfd_index = -1; mux__add_in(context); } } } } } return MOSQ_ERR_SUCCESS; } int mux_poll__cleanup(void) { mosquitto__free(pollfds); pollfds = NULL; return MOSQ_ERR_SUCCESS; } static void loop_handle_reads_writes(void) { struct mosquitto *context, *ctxt_tmp; int err; socklen_t len; int rc; HASH_ITER(hh_sock, db.contexts_by_sock, context, ctxt_tmp){ if(context->pollfd_index < 0){ continue; } if(pollfds[context->pollfd_index].fd == INVALID_SOCKET){ continue; } assert(pollfds[context->pollfd_index].fd == context->sock); #ifdef WITH_WEBSOCKETS if(context->wsi){ struct lws_pollfd wspoll; wspoll.fd = pollfds[context->pollfd_index].fd; wspoll.events = pollfds[context->pollfd_index].events; wspoll.revents = pollfds[context->pollfd_index].revents; lws_service_fd(lws_get_context(context->wsi), &wspoll); continue; } #endif #ifdef WITH_TLS if(pollfds[context->pollfd_index].revents & POLLOUT || context->want_write || (context->ssl && context->state == mosq_cs_new)){ #else if(pollfds[context->pollfd_index].revents & POLLOUT){ #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(context); continue; } #endif } }else{ do_disconnect(context, MOSQ_ERR_CONN_LOST); continue; } } rc = packet__write(context); if(rc){ do_disconnect(context, rc); continue; } } } HASH_ITER(hh_sock, db.contexts_by_sock, context, ctxt_tmp){ if(context->pollfd_index < 0){ continue; } #ifdef WITH_WEBSOCKETS if(context->wsi){ // Websocket are already handled above continue; } #endif #ifdef WITH_TLS if(pollfds[context->pollfd_index].revents & POLLIN || (context->ssl && context->state == mosq_cs_new)){ #else if(pollfds[context->pollfd_index].revents & POLLIN){ #endif do{ rc = packet__read(context); if(rc){ do_disconnect(context, rc); continue; } }while(SSL_DATA_PENDING(context)); }else{ if(context->pollfd_index >= 0 && pollfds[context->pollfd_index].revents & (POLLERR | POLLNVAL | POLLHUP)){ do_disconnect(context, MOSQ_ERR_CONN_LOST); continue; } } } } #endif mosquitto-2.0.11/src/plugin_defer.c0000664000175000017500000000366614060132747016274 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 4; } 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) { printf("mosquitto_acl_check(u:%s)\n", mosquitto_client_username(client)); return MOSQ_ERR_PLUGIN_DEFER; } 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_PLUGIN_DEFER; } mosquitto-2.0.11/src/handle_disconnect.c0000664000175000017500000000440614060132747017266 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *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(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(context, MOSQ_ERR_SUCCESS); return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/src/session_expiry.c0000664000175000017500000000754114060132747016710 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *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 = db.now_real_s; 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(void) { 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(context); } } void session_expiry__check(void) { struct session_expiry_list *item, *tmp; struct mosquitto *context; if(db.now_real_s <= last_check) return; last_check = db.now_real_s; DL_FOREACH_SAFE(expiry_list, item, tmp){ if(item->context->session_expiry_time < db.now_real_s){ 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(context); context__add_to_disused(context); }else{ return; } } } mosquitto-2.0.11/src/context.c0000664000175000017500000001635714060132747015316 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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(mosq_sock_t sock) { struct mosquitto *context; char address[1024]; context = mosquitto__calloc(1, sizeof(struct mosquitto)); if(!context) return NULL; #ifdef WITH_EPOLL context->ident = id_client; #else context->pollfd_index = -1; #endif mosquitto__set_state(context, mosq_cs_new); context->sock = sock; context->last_msg_in = db.now_s; context->next_msg_out = db.now_s + 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; context->retain_available = true; /* 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->out_packet_count = 0; context->address = NULL; if((int)sock >= 0){ if(!net__socket_get_address(sock, address, 1024, &context->remote_port)){ 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->max_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 *context, bool force_free) { struct mosquitto__packet *packet; if(!context) return; if(force_free){ context->clean_start = true; } #ifdef WITH_BRIDGE if(context->bridge){ bridge__cleanup(context); } #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(context); if(force_free){ sub__clean_session(context); } db__messages_delete(context, force_free); mosquitto__free(context->address); context->address = NULL; context__send_will(context); if(context->id){ context__remove_from_by_id(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); } context->out_packet_count = 0; #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(force_free){ mosquitto__free(context); } } void context__send_will(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(ctxt, ctxt->will->msg.topic, (uint32_t)ctxt->will->msg.payloadlen, ctxt->will->msg.payload, (uint8_t)ctxt->will->msg.qos, ctxt->will->msg.retain, MOSQ_ACL_WRITE) == MOSQ_ERR_SUCCESS){ /* Unexpected disconnect, queue the client will. */ db__messages_easy_queue(ctxt, ctxt->will->msg.topic, (uint8_t)ctxt->will->msg.qos, (uint32_t)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 *context) { if(mosquitto__get_state(context) == mosq_cs_disconnected){ return; } plugin__handle_disconnect(context, -1); net__socket_close(context); context__send_will(context); if(context->session_expiry_interval == 0){ /* Client session is due to be expired now */ #ifdef WITH_BRIDGE if(context->bridge == NULL) #endif { if(context->will_delay_interval == 0){ /* This will be done later, after the will is published for delay>0. */ context__add_to_disused(context); } } }else{ session_expiry__add(context); } keepalive__remove(context); mosquitto__set_state(context, mosq_cs_disconnected); } void context__add_to_disused(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(context); mosquitto__free(context->id); context->id = NULL; } context->for_free_next = db.ll_for_free; db.ll_for_free = context; } void context__free_disused(void) { struct mosquitto *context, *next; #ifdef WITH_WEBSOCKETS struct mosquitto *last = NULL; #endif context = db.ll_for_free; db.ll_for_free = NULL; 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(context, true); context = next; } } } void context__remove_from_by_id(struct mosquitto *context) { struct mosquitto *context_found; if(context->removed_from_by_id == false && context->id){ HASH_FIND(hh_id, db.contexts_by_id, context->id, strlen(context->id), context_found); if(context_found){ HASH_DELETE(hh_id, db.contexts_by_id, context_found); } context->removed_from_by_id = true; } } mosquitto-2.0.11/src/CMakeLists.txt0000664000175000017500000001334314060132747016216 0ustar rogerrogerinclude_directories(${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/src ${mosquitto_SOURCE_DIR}/include ${mosquitto_SOURCE_DIR}/lib ${OPENSSL_INCLUDE_DIR} ${STDBOOL_H_PATH} ${STDINT_H_PATH}) set (MOSQ_SRCS ../lib/alias_mosq.c ../lib/alias_mosq.h bridge.c bridge_topic.c conf.c conf_includedir.c context.c control.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 keepalive.c lib_load.h logging.c loop.c ../lib/memory_mosq.c ../lib/memory_mosq.h memory_public.c mosquitto.c ../include/mosquitto_broker.h mosquitto_broker_internal.h ../lib/misc_mosq.c ../lib/misc_mosq.h mux.c mux.h mux_epoll.c mux_poll.c 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 password_mosq.c password_mosq.h persist_read_v234.c persist_read_v5.c persist_read.c persist_write_v5.c persist_write.c persist.h plugin.c plugin_public.c property_broker.c ../lib/property_mosq.c ../lib/property_mosq.h read_handle.c ../lib/read_handle.h retain.c 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 ../lib/strings_mosq.c subs.c sys_tree.c sys_tree.h ../lib/time_mosq.c ../lib/tls_mosq.c topic_tok.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) if (WITH_BUNDLED_DEPS) include_directories(${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/deps) endif (WITH_BUNDLED_DEPS) find_path(HAVE_SYS_EPOLL_H sys/epoll.h) if (HAVE_SYS_EPOLL_H) add_definitions("-DWITH_EPOLL") endif() 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) find_package(libwebsockets) add_definitions("-DWITH_WEBSOCKETS") endif (WITH_WEBSOCKETS) option(WITH_CONTROL "Include $CONTROL topic support?" ON) if (WITH_CONTROL) add_definitions("-DWITH_CONTROL") endif (WITH_CONTROL) 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 (${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD") set (MOSQ_LIBS ${MOSQ_LIBS} m) elseif (${CMAKE_SYSTEM_NAME} MATCHES "NetBSD") set (MOSQ_LIBS ${MOSQ_LIBS} 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 (WIN32) set_target_properties(mosquitto PROPERTIES ENABLE_EXPORTS 1) endif (WIN32) 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 ../include/mosquitto_broker.h ../include/mosquitto_plugin.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") mosquitto-2.0.11/src/handle_connect.c0000664000175000017500000007212614060132747016572 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 (char)('0'+value); }else{ return (char)(65 /*'A'*/ +value-10); } } static char *client_id_gen(uint16_t *idlen, const char *auto_id_prefix, uint16_t auto_id_prefix_len) { char *client_id; uint8_t rnd[16]; int i; int pos; if(util__random_bytes(rnd, 16)) return NULL; *idlen = (uint16_t)(auto_id_prefix_len + 36); client_id = (char *)mosquitto__calloc((size_t)(*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. */ static void connection_check_acl(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(context, msg_tail->store->topic, msg_tail->store->payloadlen, msg_tail->store->payload, msg_tail->store->qos, msg_tail->store->retain, MOSQ_ACL_READ) != MOSQ_ERR_SUCCESS){ DL_DELETE((*head), msg_tail); db__msg_store_ref_dec(&msg_tail->store); mosquitto_property_free_all(&msg_tail->properties); mosquitto__free(msg_tail); } } } } int connect__on_authorised(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; int in_quota, out_quota; uint16_t in_maximum, out_maximum; /* 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){ in_quota = context->msgs_in.inflight_quota; out_quota = context->msgs_out.inflight_quota; in_maximum = context->msgs_in.inflight_maximum; out_maximum = context->msgs_out.inflight_maximum; 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)); context->msgs_in.inflight_quota = in_quota; context->msgs_out.inflight_quota = out_quota; context->msgs_in.inflight_maximum = in_maximum; context->msgs_out.inflight_maximum = out_maximum; db__message_reconnect_reset(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(found_context); } if((found_context->protocol == mosq_p_mqtt5 && found_context->session_expiry_interval == 0) || (found_context->protocol != mosq_p_mqtt5 && found_context->clean_start == true) || (context->clean_start == true) ){ context__send_will(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(found_context, MOSQ_ERR_SUCCESS); } rc = acl__find_acls(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:%d as %s (p%d, c%d, k%d, u'%s').", context->address, context->remote_port, context->id, context->protocol, context->clean_start, context->keepalive, context->username); }else{ log__printf(NULL, MOSQ_LOG_NOTICE, "New bridge connected from %s:%d as %s (p%d, c%d, k%d).", context->address, context->remote_port, context->id, context->protocol, context->clean_start, context->keepalive); } }else{ if(context->username){ log__printf(NULL, MOSQ_LOG_NOTICE, "New client connected from %s:%d as %s (p%d, c%d, k%d, u'%s').", context->address, context->remote_port, context->id, context->protocol, context->clean_start, context->keepalive, context->username); }else{ log__printf(NULL, MOSQ_LOG_NOTICE, "New client connected from %s:%d as %s (p%d, c%d, k%d).", context->address, context->remote_port, 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(context, &context->msgs_in.inflight); connection_check_acl(context, &context->msgs_in.queued); connection_check_acl(context, &context->msgs_out.inflight); connection_check_acl(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->max_qos = context->listener->max_qos; if(context->protocol == mosq_p_mqtt5){ 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(db.config->max_keepalive && (context->keepalive > db.config->max_keepalive || context->keepalive == 0)){ 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); auth_data_out = NULL; keepalive__add(context); mosquitto__set_state(context, mosq_cs_active); rc = send__connack(context, connect_ack, CONNACK_ACCEPTED, connack_props); mosquitto_property_free_all(&connack_props); if(rc) return rc; rc = db__message_write_queued_out(context); if(rc) return rc; rc = db__message_write_inflight_out_all(context); return rc; error: free(auth_data_out); mosquitto_property_free_all(&connack_props); return rc; } static int will__read(struct mosquitto *context, const char *client_id, struct mosquitto_message_all **will, uint8_t will_qos, int will_retain) { int rc = MOSQ_ERR_SUCCESS; size_t slen; uint16_t tlen; 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, &tlen); if(rc) goto error_cleanup; if(!tlen){ 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){ if(db.config->message_size_limit && will_struct->msg.payloadlen > (int)db.config->message_size_limit){ log__printf(NULL, MOSQ_LOG_DEBUG, "Client %s connected with too large Will payload", client_id); if(context->protocol == mosq_p_mqtt5){ send__connack(context, 0, MQTT_RC_PACKET_TOO_LARGE, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_NOT_AUTHORIZED, NULL); } rc = MOSQ_ERR_PAYLOAD_SIZE; goto error_cleanup; } will_struct->msg.payload = mosquitto__malloc((size_t)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, (uint32_t)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 *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; uint16_t slen; 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; bool allow_zero_length_clientid; #ifdef WITH_TLS int i; X509 *client_cert = NULL; X509_NAME *name; X509_NAME_ENTRY *name_entry; ASN1_STRING *name_asn1 = NULL; BIO *subject_bio; char *data_start; long name_length; char *subject; #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, &slen)){ rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } 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 = MOSQ_ERR_PROTOCOL; 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(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(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 = MOSQ_ERR_PROTOCOL; 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); 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(context, 0, MQTT_RC_RETAIN_NOT_SUPPORTED, NULL); } rc = MOSQ_ERR_NOT_SUPPORTED; goto handle_connect_error; } if(packet__read_uint16(&context->in_packet, &(context->keepalive))){ rc = MOSQ_ERR_PROTOCOL; 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(will && will_qos > context->listener->max_qos){ if(protocol_version == mosq_p_mqtt5){ send__connack(context, 0, MQTT_RC_QOS_NOT_SUPPORTED, NULL); } rc = MOSQ_ERR_NOT_SUPPORTED; goto handle_connect_error; } 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 = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } if(slen == 0){ if(context->protocol == mosq_p_mqtt31){ send__connack(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; 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(context, 0, CONNACK_REFUSED_IDENTIFIER_REJECTED, NULL); }else{ send__connack(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(context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_NOT_AUTHORIZED, NULL); } rc = MOSQ_ERR_AUTH; goto handle_connect_error; } } if(will){ rc = will__read(context, client_id, &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; } /* Once context->id is set, if we return from this function with an error * we must make sure that context->id is freed and set to NULL, so that the * client isn't erroneously removed from the by_id hash table. */ context->id = client_id; client_id = NULL; #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(context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = MOSQ_ERR_AUTH; 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(context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = MOSQ_ERR_AUTH; 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(context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = MOSQ_ERR_AUTH; goto handle_connect_error; } name = X509_get_subject_name(client_cert); if(!name){ if(context->protocol == mosq_p_mqtt5){ send__connack(context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = MOSQ_ERR_AUTH; 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(context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = MOSQ_ERR_AUTH; 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(context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = MOSQ_ERR_AUTH; 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(context, 0, MQTT_RC_SERVER_UNAVAILABLE, NULL); }else{ send__connack(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(context, 0, MQTT_RC_BAD_USERNAME_OR_PASSWORD, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_BAD_USERNAME_PASSWORD, NULL); } rc = MOSQ_ERR_AUTH; goto handle_connect_error; } } } else { /* use_subject_as_username */ subject_bio = BIO_new(BIO_s_mem()); X509_NAME_print_ex(subject_bio, X509_get_subject_name(client_cert), 0, XN_FLAG_RFC2253); data_start = NULL; name_length = BIO_get_mem_data(subject_bio, &data_start); subject = mosquitto__malloc(sizeof(char)*(size_t)(name_length+1)); if(!subject){ BIO_free(subject_bio); rc = MOSQ_ERR_NOMEM; goto handle_connect_error; } memcpy(subject, data_start, (size_t)name_length); subject[name_length] = '\0'; BIO_free(subject_bio); context->username = subject; } if(!context->username){ rc = MOSQ_ERR_AUTH; 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 */ { /* FIXME - these ensure the mosquitto_client_id() and * mosquitto_client_username() functions work, but is hacky */ context->username = username; context->password = password; username = NULL; /* Avoid free() in error: below. */ password = NULL; } if(context->listener->use_username_as_clientid){ if(context->username){ mosquitto__free(context->id); context->id = mosquitto__strdup(context->username); if(!context->id){ rc = MOSQ_ERR_NOMEM; goto handle_connect_error; } }else{ if(context->protocol == mosq_p_mqtt5){ send__connack(context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_NOT_AUTHORIZED, NULL); } rc = MOSQ_ERR_AUTH; goto handle_connect_error; } } context->clean_start = clean_start; context->will = will_struct; will_struct = NULL; if(context->auth_method){ rc = mosquitto_security_auth_start(context, false, auth_data, auth_data_len, &auth_data_out, &auth_data_out_len); mosquitto__free(auth_data); auth_data = NULL; if(rc == MOSQ_ERR_SUCCESS){ return connect__on_authorised(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(context, MQTT_RC_CONTINUE_AUTHENTICATION, auth_data_out, auth_data_out_len); free(auth_data_out); return rc; }else{ free(auth_data_out); auth_data_out = NULL; will__clear(context); if(rc == MOSQ_ERR_AUTH){ send__connack(context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); mosquitto__free(context->id); context->id = NULL; goto handle_connect_error; }else if(rc == MOSQ_ERR_NOT_SUPPORTED){ /* Client has requested extended authentication, but we don't support it. */ send__connack(context, 0, MQTT_RC_BAD_AUTHENTICATION_METHOD, NULL); mosquitto__free(context->id); context->id = NULL; goto handle_connect_error; }else{ mosquitto__free(context->id); context->id = NULL; goto handle_connect_error; } } }else{ #ifdef WITH_TLS if(context->listener->ssl_ctx && (context->listener->use_identity_as_username || context->listener->use_subject_as_username)){ /* Authentication assumed to be cleared */ }else #endif { rc = mosquitto_unpwd_check(context); if(rc != MOSQ_ERR_SUCCESS){ /* We must have context->id == NULL here so we don't later try and * remove the client from the by_id hash table */ mosquitto__free(context->id); context->id = NULL; } switch(rc){ case MOSQ_ERR_SUCCESS: break; case MOSQ_ERR_AUTH: if(context->protocol == mosq_p_mqtt5){ send__connack(context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_NOT_AUTHORIZED, NULL); } rc = MOSQ_ERR_AUTH; goto handle_connect_error; break; default: rc = MOSQ_ERR_UNKNOWN; goto handle_connect_error; break; } } return connect__on_authorised(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); } context->will = NULL; #ifdef WITH_TLS if(client_cert) X509_free(client_cert); #endif /* We return an error here which means the client is freed later on. */ context->clean_start = true; context->session_expiry_interval = 0; context->will_delay_interval = 0; return rc; } mosquitto-2.0.11/src/security.c0000664000175000017500000007527314060132747015503 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "mosquitto_broker.h" #include "mosquitto_broker_internal.h" #include "mosquitto_plugin.h" #include "memory_mosq.h" #include "lib_load.h" #include "utlist.h" typedef int (*FUNC_auth_plugin_version)(void); typedef int (*FUNC_plugin_version)(int, const int *); 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_SYSTEM, NULL, GetLastError(), LANG_NEUTRAL, (LPTSTR)&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 } static 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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; } static 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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; } static 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } 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 MOSQ_ERR_UNKNOWN; } }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__listener *listener, struct mosquitto__security_options *opts) { void *lib; int (*plugin_version)(int, const int*) = NULL; int (*plugin_auth_version)(void) = NULL; int version; int i; int rc; const int plugin_versions[] = {5, 4, 3, 2}; int plugin_version_count = sizeof(plugin_versions)/sizeof(int); 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 MOSQ_ERR_UNKNOWN; } opts->auth_plugin_configs[i].plugin.lib = NULL; if((plugin_version = (FUNC_plugin_version)LIB_SYM(lib, "mosquitto_plugin_version"))){ version = plugin_version(plugin_version_count, plugin_versions); }else if((plugin_auth_version = (FUNC_auth_plugin_version)LIB_SYM(lib, "mosquitto_auth_plugin_version"))){ version = plugin_auth_version(); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load auth plugin function mosquitto_auth_plugin_version() or mosquitto_plugin_version()."); LIB_ERROR(); LIB_CLOSE(lib); return MOSQ_ERR_UNKNOWN; } opts->auth_plugin_configs[i].plugin.version = version; if(version == 5){ rc = plugin__load_v5( listener, &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 == 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: Unsupported auth plugin version (got %d, expected %d).", version, MOSQ_PLUGIN_VERSION); LIB_ERROR(); LIB_CLOSE(lib); return MOSQ_ERR_UNKNOWN; } } } return MOSQ_ERR_SUCCESS; } int mosquitto_security_module_init(void) { int rc = MOSQ_ERR_SUCCESS; int i; if(db.config->per_listener_settings){ for(i=0; ilistener_count; i++){ rc = security__module_init_single(&db.config->listeners[i], &db.config->listeners[i].security_options); if(rc) return rc; } }else{ rc = security__module_init_single(NULL, &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 == 5){ opts->auth_plugin_configs[i].plugin.plugin_cleanup_v5( opts->auth_plugin_configs[i].plugin.user_data, opts->auth_plugin_configs[i].options, opts->auth_plugin_configs[i].option_count); mosquitto__free(opts->auth_plugin_configs[i].plugin.identifier); opts->auth_plugin_configs[i].plugin.identifier = NULL; }else 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(void) { int i; mosquitto_security_cleanup(false); security__module_cleanup_single(&db.config->security_options); for(i=0; ilistener_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; struct mosquitto_evt_reload event_data; struct mosquitto__callback *cb_base; if(reload){ DL_FOREACH(opts->plugin_callbacks.reload, cb_base){ memset(&event_data, 0, sizeof(event_data)); event_data.options = NULL; event_data.option_count = 0; rc = cb_base->cb(MOSQ_EVT_RELOAD, &event_data, cb_base->userdata); if(rc != MOSQ_ERR_PLUGIN_DEFER){ return rc; } } } for(i=0; iauth_plugin_config_count; i++){ if(opts->auth_plugin_configs[i].plugin.version == 5){ continue; }else 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(bool reload) { int i; int rc; if(db.config->per_listener_settings){ for(i=0; ilistener_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(reload); } /* Apply security settings after a reload. * Includes: * - Disconnecting anonymous users if appropriate * - Disconnecting users with invalid passwords * - Reapplying ACLs */ int mosquitto_security_apply(void) { return mosquitto_security_apply_default(); } 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 == 5){ rc = MOSQ_ERR_SUCCESS; }else 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(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; ilistener_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(reload); } /* int mosquitto_acl_check(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){ if(access == MOSQ_ACL_UNSUBSCRIBE){ return MOSQ_ERR_SUCCESS; } return auth_plugin->plugin.acl_check_v4(auth_plugin->plugin.user_data, access, context, msg); }else if(auth_plugin->plugin.version == 3){ if(access == MOSQ_ACL_UNSUBSCRIBE){ return MOSQ_ERR_SUCCESS; } 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 || access == MOSQ_ACL_UNSUBSCRIBE){ 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 || 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 *context, const char *topic, uint32_t payloadlen, void* payload, uint8_t qos, bool retain, int access) { int rc; int i; struct mosquitto__security_options *opts; struct mosquitto_acl_msg msg; struct mosquitto__callback *cb_base; struct mosquitto_evt_acl_check event_data; if(!context->id){ return MOSQ_ERR_ACL_DENIED; } if(context->bridge){ return MOSQ_ERR_SUCCESS; } rc = acl__check_dollar(topic, access); if(rc) return rc; /* * 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){ if(context->listener){ opts = &context->listener->security_options; }else{ return MOSQ_ERR_ACL_DENIED; } }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; DL_FOREACH(opts->plugin_callbacks.acl_check, cb_base){ /* FIXME - username deny special chars */ memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.access = access; event_data.topic = topic; event_data.payloadlen = payloadlen; event_data.payload = payload; event_data.qos = qos; event_data.retain = retain; event_data.properties = NULL; rc = cb_base->cb(MOSQ_EVT_ACL_CHECK, &event_data, cb_base->userdata); if(rc != MOSQ_ERR_PLUGIN_DEFER){ return rc; } } for(i=0; iauth_plugin_config_count; i++){ if(opts->auth_plugin_configs[i].plugin.version < 5){ 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 *context) { int rc; int i; struct mosquitto__security_options *opts; struct mosquitto_evt_basic_auth event_data; struct mosquitto__callback *cb_base; bool plugin_used = false; rc = MOSQ_ERR_PLUGIN_DEFER; if(db.config->per_listener_settings){ if(context->listener == NULL){ return MOSQ_ERR_AUTH; } opts = &context->listener->security_options; }else{ opts = &db.config->security_options; } DL_FOREACH(opts->plugin_callbacks.basic_auth, cb_base){ memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.username = context->username; event_data.password = context->password; rc = cb_base->cb(MOSQ_EVT_BASIC_AUTH, &event_data, cb_base->userdata); if(rc != MOSQ_ERR_PLUGIN_DEFER){ return rc; } plugin_used = true; } 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, context->username, context->password); plugin_used = true; }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, context->username, context->password); plugin_used = true; }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, context->username, context->password); plugin_used = true; } } /* If all plugins deferred, this is a denial. If rc == MOSQ_ERR_SUCCESS * here, then no plugins were configured. Unless we have all deferred, and * anonymous logins are allowed. */ if(plugin_used == false){ 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)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } }else{ if(rc == MOSQ_ERR_PLUGIN_DEFER){ if(context->username == NULL && ((db.config->per_listener_settings && context->listener->security_options.allow_anonymous != false) || (!db.config->per_listener_settings && db.config->security_options.allow_anonymous != false))){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } } return rc; } int mosquitto_psk_key_get(struct mosquitto *context, const char *hint, const char *identity, char *key, int max_key_len) { int rc; int i; struct mosquitto__security_options *opts; struct mosquitto_evt_psk_key event_data; struct mosquitto__callback *cb_base; rc = mosquitto_psk_key_get_default(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; } DL_FOREACH(opts->plugin_callbacks.psk_key, cb_base){ memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.hint = hint; event_data.identity = identity; event_data.key = key; event_data.max_key_len = max_key_len; rc = cb_base->cb(MOSQ_EVT_PSK_KEY, &event_data, cb_base->userdata); if(rc != MOSQ_ERR_PLUGIN_DEFER){ return rc; } } 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 *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; struct mosquitto_evt_extended_auth event_data; struct mosquitto__callback *cb_base; 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; } DL_FOREACH(opts->plugin_callbacks.ext_auth_start, cb_base){ memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.auth_method = context->auth_method; event_data.data_in = data_in; event_data.data_out = NULL; event_data.data_in_len = data_in_len; event_data.data_out_len = 0; rc = cb_base->cb(MOSQ_EVT_EXT_AUTH_START, &event_data, cb_base->userdata); if(rc != MOSQ_ERR_PLUGIN_DEFER){ *data_out = event_data.data_out; *data_out_len = event_data.data_out_len; return rc; } } 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 *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; struct mosquitto_evt_extended_auth event_data; struct mosquitto__callback *cb_base; 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; } DL_FOREACH(opts->plugin_callbacks.ext_auth_continue, cb_base){ memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.data_in = data_in; event_data.data_out = NULL; event_data.data_in_len = data_in_len; event_data.data_out_len = 0; rc = cb_base->cb(MOSQ_EVT_EXT_AUTH_CONTINUE, &event_data, cb_base->userdata); if(rc != MOSQ_ERR_PLUGIN_DEFER){ *data_out = event_data.data_out; *data_out_len = event_data.data_out_len; return rc; } } for(i=0; iauth_plugin_config_count; i++){ if(opts->auth_plugin_configs[i].plugin.auth_continue_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-2.0.11/src/database.c0000664000175000017500000007471214060132747015375 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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" /** * 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. */ bool db__ready_for_flight(struct mosquitto *context, enum mosquitto_msg_direction dir, int qos) { struct mosquitto_msg_data *msgs; bool valid_bytes; bool valid_count; if(dir == mosq_md_out){ msgs = &context->msgs_out; }else{ msgs = &context->msgs_in; } if(msgs->inflight_maximum == 0 && db.config->max_inflight_bytes == 0){ return true; } if(qos == 0){ /* Deliver QoS 0 messages unless the queue is already full. * For QoS 0 messages the choice is either "inflight" or dropped. * There is no queueing option, unless the client is offline and * queue_qos0_messages is enabled. */ if(db.config->max_queued_messages == 0 && db.config->max_inflight_bytes == 0){ return true; } valid_bytes = ((msgs->msg_bytes - (ssize_t)db.config->max_inflight_bytes) < (ssize_t)db.config->max_queued_bytes); if(dir == mosq_md_out){ valid_count = context->out_packet_count < db.config->max_queued_messages; }else{ valid_count = msgs->msg_count - msgs->inflight_maximum < db.config->max_queued_messages; } if(db.config->max_queued_messages == 0){ return valid_bytes; } if(db.config->max_queued_bytes == 0){ return valid_count; } }else{ valid_bytes = (ssize_t)msgs->msg_bytes12 < (ssize_t)db.config->max_inflight_bytes; valid_count = msgs->inflight_quota > 0; if(msgs->inflight_maximum == 0){ return valid_bytes; } if(db.config->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 */ bool db__ready_for_queue(struct mosquitto *context, int qos, struct mosquitto_msg_data *msg_data) { int source_count; int adjust_count; long source_bytes; ssize_t adjust_bytes = (ssize_t)db.config->max_inflight_bytes; bool valid_bytes; bool valid_count; if(db.config->max_queued_messages == 0 && db.config->max_queued_bytes == 0){ return true; } if(qos == 0 && db.config->queue_qos0_messages == false){ return false; /* This case is handled in db__ready_for_flight() */ }else{ source_bytes = (ssize_t)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; } valid_bytes = (source_bytes - (ssize_t)adjust_bytes) < (ssize_t)db.config->max_queued_bytes; valid_count = source_count - adjust_count < db.config->max_queued_messages; if(db.config->max_queued_bytes == 0){ return valid_count; } if(db.config->max_queued_messages == 0){ return valid_bytes; } return valid_bytes && valid_count; } int db__open(struct mosquitto__config *config) { struct mosquitto__subhier *subhier; if(!config) 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, "", 0); if(!subhier) return MOSQ_ERR_NOMEM; subhier = sub__add_hier_entry(NULL, &db.subs, "$SYS", (uint16_t)strlen("$SYS")); if(!subhier) return MOSQ_ERR_NOMEM; retain__init(); db.config->security_options.unpwd = NULL; #ifdef WITH_PERSISTENCE if(persist__restore()) return 1; #endif return MOSQ_ERR_SUCCESS; } static void subhier_clean(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; } subhier_clean(&peer->children); mosquitto__free(peer->topic); HASH_DELETE(hh, *subhier, peer); mosquitto__free(peer); } } int db__close(void) { subhier_clean(&db.subs); retain__clean(&db.retains); db__msg_store_clean(); return MOSQ_ERR_SUCCESS; } void db__msg_store_add(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_free(struct mosquitto_msg_store *store) { int i; 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); mosquitto__free(store->payload); mosquitto__free(store); } void db__msg_store_remove(struct mosquitto_msg_store *store) { 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; db__msg_store_free(store); } void db__msg_store_clean(void) { struct mosquitto_msg_store *store, *next;; store = db.msg_store; while(store){ next = store->next; db__msg_store_remove(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_msg_store **store) { (*store)->ref_count--; if((*store)->ref_count == 0){ db__msg_store_remove(*store); *store = NULL; } } void db__msg_store_compact(void) { struct mosquitto_msg_store *store, *next; store = db.msg_store; while(store){ next = store->next; if(store->ref_count < 1){ db__msg_store_remove(store); } store = next; } } static void db__message_remove(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(&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; UNUSED(context); 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 *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(&context->msgs_out, tail); break; } } 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 = db.now_s; 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); } #ifdef WITH_PERSISTENCE db.persistence_changes++; #endif return db__message_write_inflight_out_latest(context); } int db__message_insert(struct mosquitto *context, uint16_t mid, enum mosquitto_msg_direction dir, uint8_t qos, bool retain, struct mosquitto_msg_store *stored, mosquitto_property *properties, bool update) { 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->bridge && context->bridge->clean_start_local == true){ mosquitto_property_free_all(&properties); return 2; } } if(context->sock != INVALID_SOCKET){ if(db__ready_for_flight(context, dir, 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(qos != 0 && 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 = db.now_s; msg->direction = dir; msg->state = state; msg->dup = false; if(qos > context->max_qos){ msg->qos = context->max_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 *)*(size_t)(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); } if(dir == mosq_md_out && update){ rc = db__message_write_inflight_out_latest(context); if(rc) return rc; rc = db__message_write_queued_out(context); if(rc) return rc; } return rc; } 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 = db.now_s; return MOSQ_ERR_SUCCESS; } } return MOSQ_ERR_NOT_FOUND; } static void db__messages_delete_list(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(&tail->store); mosquitto_property_free_all(&tail->properties); mosquitto__free(tail); } *head = NULL; } int db__messages_delete(struct mosquitto *context, bool force_free) { if(!context) return MOSQ_ERR_INVAL; if(force_free || context->clean_start || (context->bridge && context->bridge->clean_start)){ db__messages_delete_list(&context->msgs_in.inflight); db__messages_delete_list(&context->msgs_in.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; } if(force_free || (context->bridge && context->bridge->clean_start_local) || (context->bridge == NULL && context->clean_start)){ db__messages_delete_list(&context->msgs_out.inflight); db__messages_delete_list(&context->msgs_out.queued); 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 *context, const char *topic, uint8_t qos, uint32_t payloadlen, const void *payload, int retain, uint32_t message_expiry_interval, mosquitto_property **properties) { struct mosquitto_msg_store *stored; const char *source_id; enum mosquitto_msg_origin origin; if(!topic) return MOSQ_ERR_INVAL; stored = mosquitto__calloc(1, sizeof(struct mosquitto_msg_store)); if(stored == NULL) return MOSQ_ERR_NOMEM; stored->topic = mosquitto__strdup(topic); if(stored->topic == NULL){ db__msg_store_free(stored); return MOSQ_ERR_INVAL; } stored->qos = qos; if(db.config->retain_available == false){ stored->retain = 0; }else{ stored->retain = retain; } stored->payloadlen = payloadlen; stored->payload = mosquitto__malloc(stored->payloadlen+1); if(stored->payload == NULL){ db__msg_store_free(stored); return MOSQ_ERR_NOMEM; } /* Ensure payload is always zero terminated, this is the reason for the extra byte above */ ((uint8_t *)stored->payload)[stored->payloadlen] = 0; memcpy(stored->payload, payload, stored->payloadlen); if(context && context->id){ source_id = context->id; }else{ source_id = ""; } if(properties){ stored->properties = *properties; *properties = NULL; } if(context){ origin = mosq_mo_client; }else{ origin = mosq_mo_broker; } if(db__message_store(context, stored, message_expiry_interval, 0, origin)) return 1; return sub__messages_queue(source_id, stored->topic, stored->qos, stored->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(const struct mosquitto *source, struct mosquitto_msg_store *stored, uint32_t message_expiry_interval, dbid_t store_id, enum mosquitto_msg_origin origin) { assert(stored); if(source && source->id){ stored->source_id = mosquitto__strdup(source->id); }else{ stored->source_id = mosquitto__strdup(""); } if(!stored->source_id){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); db__msg_store_free(stored); return MOSQ_ERR_NOMEM; } if(source && source->username){ stored->source_username = mosquitto__strdup(source->username); if(!stored->source_username){ db__msg_store_free(stored); return MOSQ_ERR_NOMEM; } } if(source){ stored->source_listener = source->listener; } stored->mid = 0; stored->origin = origin; if(message_expiry_interval > 0){ stored->message_expiry_time = db.now_real_s + message_expiry_interval; }else{ stored->message_expiry_time = 0; } stored->dest_ids = NULL; stored->dest_id_count = 0; db.msg_store_count++; db.msg_store_bytes += stored->payloadlen; if(!store_id){ stored->db_id = ++db.last_db_id; }else{ stored->db_id = store_id; } db__msg_store_add(stored); return MOSQ_ERR_SUCCESS; } 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. */ static int db__message_reconnect_reset_outgoing(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_send_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, mosq_md_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. */ static int db__message_reconnect_reset_incoming(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, mosq_md_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 *context) { int rc; rc = db__message_reconnect_reset_outgoing(context); if(rc) return rc; return db__message_reconnect_reset_incoming(context); } int db__message_remove_incoming(struct mosquitto* context, uint16_t mid) { struct mosquitto_client_msg *tail, *tmp; if(!context) return MOSQ_ERR_INVAL; DL_FOREACH_SAFE(context->msgs_in.inflight, tail, tmp){ if(tail->mid == mid) { if(tail->store->qos != 2){ return MOSQ_ERR_PROTOCOL; } db__message_remove(&context->msgs_in, tail); return MOSQ_ERR_SUCCESS; } } return MOSQ_ERR_NOT_FOUND; } int db__message_release_incoming(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 == NULL){ db__message_remove(&context->msgs_in, tail); deleted = true; }else{ rc = sub__messages_queue(source_id, topic, 2, retain, &tail->store); if(rc == MOSQ_ERR_SUCCESS || rc == MOSQ_ERR_NO_SUBSCRIBERS){ db__message_remove(&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 = db.now_s; if(tail->qos == 2){ send__pubrec(context, tail->mid, 0, NULL); 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; } } static int db__message_write_inflight_out_single(struct mosquitto *context, struct mosquitto_client_msg *msg) { mosquitto_property *cmsg_props = NULL, *store_props = NULL; int rc; uint16_t mid; int retries; int retain; const char *topic; uint8_t qos; uint32_t payloadlen; const void *payload; uint32_t expiry_interval; expiry_interval = 0; if(msg->store->message_expiry_time){ if(db.now_real_s > msg->store->message_expiry_time){ /* Message is expired, must not send. */ if(msg->direction == mosq_md_out && msg->qos > 0){ util__increment_send_quota(context); } db__message_remove(&context->msgs_out, msg); return MOSQ_ERR_SUCCESS; }else{ expiry_interval = (uint32_t)(msg->store->message_expiry_time - db.now_real_s); } } mid = msg->mid; retries = msg->dup; retain = msg->retain; topic = msg->store->topic; qos = (uint8_t)msg->qos; payloadlen = msg->store->payloadlen; payload = msg->store->payload; cmsg_props = msg->properties; store_props = msg->store->properties; switch(msg->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(&context->msgs_out, msg); }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){ msg->timestamp = db.now_s; msg->dup = 1; /* Any retry attempts are a duplicate. */ msg->state = mosq_ms_wait_for_puback; }else if(rc == MOSQ_ERR_OVERSIZE_PACKET){ db__message_remove(&context->msgs_out, msg); }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){ msg->timestamp = db.now_s; msg->dup = 1; /* Any retry attempts are a duplicate. */ msg->state = mosq_ms_wait_for_pubrec; }else if(rc == MOSQ_ERR_OVERSIZE_PACKET){ db__message_remove(&context->msgs_out, msg); }else{ return rc; } break; case mosq_ms_resend_pubrel: rc = send__pubrel(context, mid, NULL); if(!rc){ msg->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; } return MOSQ_ERR_SUCCESS; } int db__message_write_inflight_out_all(struct mosquitto *context) { struct mosquitto_client_msg *tail, *tmp; int rc; if(context->state != mosq_cs_active || context->sock == INVALID_SOCKET){ return MOSQ_ERR_SUCCESS; } DL_FOREACH_SAFE(context->msgs_out.inflight, tail, tmp){ rc = db__message_write_inflight_out_single(context, tail); if(rc) return rc; } return MOSQ_ERR_SUCCESS; } int db__message_write_inflight_out_latest(struct mosquitto *context) { struct mosquitto_client_msg *tail, *next; int rc; if(context->state != mosq_cs_active || context->sock == INVALID_SOCKET || context->msgs_out.inflight == NULL){ return MOSQ_ERR_SUCCESS; } if(context->msgs_out.inflight->prev == context->msgs_out.inflight){ /* Only one message */ return db__message_write_inflight_out_single(context, context->msgs_out.inflight); } /* Start at the end of the list and work backwards looking for the first * message in a non-publish state */ tail = context->msgs_out.inflight->prev; while(tail != context->msgs_out.inflight && (tail->state == mosq_ms_publish_qos0 || tail->state == mosq_ms_publish_qos1 || tail->state == mosq_ms_publish_qos2)){ tail = tail->prev; } /* Tail is now either the head of the list, if that message is waiting for * publish, or the oldest message not waiting for a publish. In the latter * case, any pending publishes should be next after this message. */ if(tail != context->msgs_out.inflight){ tail = tail->next; } while(tail){ next = tail->next; rc = db__message_write_inflight_out_single(context, tail); if(rc) return rc; tail = next; } return MOSQ_ERR_SUCCESS; } int db__message_write_queued_in(struct mosquitto *context) { struct mosquitto_client_msg *tail, *tmp; int rc; if(context->state != mosq_cs_active){ return MOSQ_ERR_SUCCESS; } DL_FOREACH_SAFE(context->msgs_in.queued, tail, tmp){ if(context->msgs_out.inflight_maximum != 0 && context->msgs_in.inflight_quota == 0){ break; } 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, NULL); if(!rc){ tail->state = mosq_ms_wait_for_pubrel; }else{ return rc; } } } return MOSQ_ERR_SUCCESS; } int db__message_write_queued_out(struct mosquitto *context) { struct mosquitto_client_msg *tail, *tmp; if(context->state != mosq_cs_active){ return MOSQ_ERR_SUCCESS; } DL_FOREACH_SAFE(context->msgs_out.queued, tail, tmp){ if(context->msgs_out.inflight_maximum != 0 && context->msgs_out.inflight_quota == 0){ break; } 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; } mosquitto-2.0.11/src/send_auth.c0000664000175000017500000000452414060132747015575 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *context, uint8_t reason_code, const void *auth_data, uint16_t auth_data_len) { struct mosquitto__packet *packet = NULL; int rc; mosquitto_property *properties = NULL; 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; } } remaining_length += property__get_remaining_length(properties); 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-2.0.11/src/persist_write.c0000664000175000017500000002701514060132747016526 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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(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_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 = (uint16_t)strlen(context->id); chunk.F.qos = cmsg->qos; chunk.F.retain_dup = (uint8_t)((cmsg->retain&0x0F)<<4 | (cmsg->dup&0x0F)); chunk.F.direction = (uint8_t)cmsg->direction; chunk.F.state = (uint8_t)cmsg->state; chunk.client_id = context->id; chunk.properties = cmsg->properties; rc = persist__chunk_client_msg_write_v6(db_fptr, &chunk); if(rc){ return rc; } cmsg = cmsg->next; } return MOSQ_ERR_SUCCESS; } static int persist__message_store_save(FILE *db_fptr) { struct P_msg_store chunk; struct mosquitto_msg_store *stored; int rc; 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 = (uint16_t)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 = (uint16_t)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 = (uint16_t)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_v6(db_fptr, &chunk); if(rc){ return rc; } stored = stored->next; } return MOSQ_ERR_SUCCESS; } static int persist__client_save(FILE *db_fptr) { struct mosquitto *context, *ctxt_tmp; struct P_client chunk; int rc; 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 = (uint16_t)strlen(context->id); chunk.client_id = context->id; if(context->username){ chunk.F.username_len = (uint16_t)strlen(context->username); chunk.username = context->username; } if(context->listener){ chunk.F.listener_port = context->listener->port; } if(chunk.F.id_len == 0){ /* This should never happen, but in case we have a client with * zero length ID, don't persist them. */ continue; } rc = persist__chunk_client_write_v6(db_fptr, &chunk); if(rc){ return rc; } if(persist__client_messages_save(db_fptr, context, context->msgs_in.inflight)) return 1; if(persist__client_messages_save(db_fptr, context, context->msgs_in.queued)) return 1; if(persist__client_messages_save(db_fptr, context, context->msgs_out.inflight)) return 1; if(persist__client_messages_save(db_fptr, context, context->msgs_out.queued)) return 1; } } return MOSQ_ERR_SUCCESS; } static int persist__subs_save(FILE *db_fptr, struct mosquitto__subhier *node, const char *topic, int level) { struct mosquitto__subhier *subhier, *subhier_tmp; struct mosquitto__subleaf *sub; struct P_sub sub_chunk; char *thistopic; size_t slen; int rc; 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 = (uint16_t)strlen(sub->context->id); sub_chunk.F.topic_len = (uint16_t)strlen(thistopic); sub_chunk.F.qos = (uint8_t)sub->qos; sub_chunk.F.options = (uint8_t)(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_v6(db_fptr, &sub_chunk); if(rc){ mosquitto__free(thistopic); return rc; } } sub = sub->next; } HASH_ITER(hh, node->children, subhier, subhier_tmp){ persist__subs_save(db_fptr, subhier, thistopic, level+1); } mosquitto__free(thistopic); return MOSQ_ERR_SUCCESS; } static int persist__subs_save_all(FILE *db_fptr) { struct mosquitto__subhier *subhier, *subhier_tmp; HASH_ITER(hh, db.subs, subhier, subhier_tmp){ if(subhier->children){ persist__subs_save(db_fptr, subhier->children, "", 0); } } return MOSQ_ERR_SUCCESS; } static int persist__retain_save(FILE *db_fptr, struct mosquitto__retainhier *node, int level) { struct mosquitto__retainhier *retainhier, *retainhier_tmp; struct P_retain retain_chunk; int rc; memset(&retain_chunk, 0, sizeof(struct P_retain)); if(node->retained && 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_v6(db_fptr, &retain_chunk); if(rc){ return rc; } } HASH_ITER(hh, node->children, retainhier, retainhier_tmp){ persist__retain_save(db_fptr, retainhier, level+1); } return MOSQ_ERR_SUCCESS; } static int persist__retain_save_all(FILE *db_fptr) { struct mosquitto__retainhier *retainhier, *retainhier_tmp; HASH_ITER(hh, db.retains, retainhier, retainhier_tmp){ if(retainhier->children){ persist__retain_save(db_fptr, retainhier->children, 0); } } return MOSQ_ERR_SUCCESS; } int persist__backup(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; size_t len; struct PF_cfg cfg_chunk; if(db.config == NULL) return MOSQ_ERR_INVAL; if(db.config->persistence == false) return MOSQ_ERR_SUCCESS; if(db.config->persistence_filepath == NULL) return MOSQ_ERR_INVAL; 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_v6(db_fptr, &cfg_chunk)){ goto error; } if(persist__message_store_save(db_fptr)){ goto error; } persist__client_save(db_fptr); persist__subs_save_all(db_fptr); persist__retain_save_all(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-2.0.11/src/lib_load.h0000664000175000017500000000207214060132747015371 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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-2.0.11/src/persist_read_v234.c0000664000175000017500000001310314060132747017056 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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, uint32_t *chunk, uint32_t *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, uint32_t 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 = (uint8_t)((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, uint32_t 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){ chunk->payload = mosquitto_malloc(chunk->F.payloadlen+1); if(chunk->payload == NULL){ 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; } /* Ensure zero terminated regardless of contents */ ((uint8_t *)chunk->payload)[chunk->F.payloadlen] = 0; read_e(db_fptr, chunk->payload, 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-2.0.11/src/plugin_debug.c0000664000175000017500000000774214060132747016274 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 4; } 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-2.0.11/src/send_connack.c0000664000175000017500000000623314060132747016247 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *context, uint8_t ack, uint8_t reason_code, const mosquitto_property *properties) { struct mosquitto__packet *packet = NULL; int rc; mosquitto_property *connack_props = NULL; 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(reason_code < 128 && 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; } } if(reason_code < 128 && db.config->max_inflight_messages > 0){ rc = mosquitto_property_add_int16(&connack_props, MQTT_PROP_RECEIVE_MAXIMUM, db.config->max_inflight_messages); if(rc){ mosquitto_property_free_all(&connack_props); return rc; } } if(context->listener->max_qos != 2){ rc = mosquitto_property_add_byte(&connack_props, MQTT_PROP_MAXIMUM_QOS, context->listener->max_qos); if(rc){ mosquitto_property_free_all(&connack_props); return rc; } } remaining_length += property__get_remaining_length(connack_props); } if(packet__check_oversize(context, remaining_length)){ mosquitto_property_free_all(&connack_props); return MOSQ_ERR_OVERSIZE_PACKET; } packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet){ mosquitto_property_free_all(&connack_props); 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-2.0.11/src/conf.c0000664000175000017500000027244214060132747014556 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 { unsigned int log_dest; int log_dest_set; unsigned int log_type; int log_type_set; }; #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, unsigned 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__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->local_only = true; 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 | MQTT3_LOG_DLT; 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->max_queued_messages = 1000; config->max_inflight_bytes = 0; config->max_queued_bytes = 0; 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__config *config) { memset(config, 0, sizeof(struct mosquitto__config)); config__init_reload(config); config->daemon = false; memset(&config->default_listener, 0, sizeof(struct mosquitto__listener)); listener__set_defaults(&config->default_listener); } 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].ciphers_tls13); 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 #ifdef WITH_UNIX_SOCKETS mosquitto__free(config->listeners[i].unix_socket_path); #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 v5.0/v3.1.1/v3.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 https://mosquitto.org/ for more information.\n\n"); } int config__parse_args(struct mosquitto__config *config, int argc, char *argv[]) { int i; int port_tmp; for(i=1; idaemon = 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(iUINT16_MAX){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port specified (%d).", port_tmp); return MOSQ_ERR_INVAL; }else{ if(config->cmd_port_count == CMD_PORT_LIMIT){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Only %d ports can be specified on the command line.", CMD_PORT_LIMIT); return MOSQ_ERR_INVAL; } config->cmd_port[config->cmd_port_count] = (uint16_t)port_tmp; config->cmd_port_count++; } }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->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.ciphers_tls13 || 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.max_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_zero_length_clientid != true ){ config->listener_count++; config->listeners = mosquitto__realloc(config->listeners, sizeof(struct mosquitto__listener)*(size_t)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].max_qos = config->default_listener.max_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].ciphers_tls13 = config->default_listener.ciphers_tls13; 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); } static 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__config *config, bool reload) { int rc = MOSQ_ERR_SUCCESS; struct config_recurse cr; int lineno = 0; #ifdef WITH_PERSISTENCE size_t len; #endif struct mosquitto__config config_reload; int i; 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; if(!db.config_file) return 0; if(reload){ /* Re-initialise appropriate config vars to default for reload. */ config__init_reload(&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->local_only == true){ config->security_options.allow_anonymous = true; }else{ if(config->per_listener_settings){ for(i=0; ilistener_count; i++){ /* Default option if no security options set */ if(config->listeners[i].security_options.allow_anonymous == -1){ config->listeners[i].security_options.allow_anonymous = false; } } }else{ if(config->security_options.allow_anonymous == -1){ config->security_options.allow_anonymous = false; } } } #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) + 2; config->persistence_filepath = mosquitto__malloc(len); if(!config->persistence_filepath) return MOSQ_ERR_NOMEM; #ifdef WIN32 snprintf(config->persistence_filepath, len, "%s\\%s", config->persistence_location, config->persistence_file); #else snprintf(config->persistence_filepath, len, "%s/%s", config->persistence_location, config->persistence_file); #endif }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"); } #ifdef WITH_BRIDGE for(i=0; ibridge_count; i++){ if(!config->bridges[i].name){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration: bridge name not defined."); return MOSQ_ERR_INVAL; } if(config->bridges[i].addresses == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration: no remote addresses defined."); return MOSQ_ERR_INVAL; } if(config->bridges[i].topic_count == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration: no topics defined."); 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; } static 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; #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; size_t prefix_len; char **files; int file_count; #ifdef WITH_TLS char *kpass_sha = NULL, *kpass_sha_bin = NULL; char *keyform ; #endif *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)*(size_t)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 > UINT16_MAX){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } cur_bridge->addresses[i].port = (uint16_t)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")){ log__printf(NULL, MOSQ_LOG_NOTICE, "The 'allow_duplicate_messages' option is now deprecated and will be removed in a future version. The behaviour will default to true."); 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_", strlen("auth_opt_")) || !strncmp(token, "plugin_opt_", strlen("plugin_opt_"))){ 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(!strncmp(token, "auth_opt_", strlen("auth_opt_"))){ prefix_len = strlen("auth_opt_"); }else{ prefix_len = strlen("plugin_opt_"); } if(strlen(token) < prefix_len + 3){ /* 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[prefix_len]); 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 += prefix_len+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, (size_t)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") || !strcmp(token, "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, (size_t)(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 = (uint16_t)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")){ log__printf(NULL, MOSQ_LOG_NOTICE, "The 'bind_address' option is now deprecated and will be removed in a future version. The behaviour will default to true."); config->local_only = false; if(reload) continue; /* Listeners 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_bind_address")){ #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_bind_address", &cur_bridge->bind_address, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge 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_max_packet_size")){ #if defined(WITH_BRIDGE) if(reload) continue; /* Bridges not valid for reloading. */ if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_int(&token, "bridge_max_packet_size", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 0) tmp_int = 0; cur_bridge->maximum_packet_size = (uint32_t)tmp_int; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_outgoing_retain")){ #if defined(WITH_BRIDGE) 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_outgoing_retain", &cur_bridge->outgoing_retain, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge 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 if(!strcmp(token, "mqttv50")){ cur_bridge->protocol_version = mosq_p_mqtt5; }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, "ciphers_tls1.3")){ #if defined(WITH_TLS) && !defined(LIBRESSL_VERSION_NUMBER) if(reload) continue; /* Listeners not valid for reloading. */ if(conf__parse_string(&token, "ciphers_tls1.3", &cur_listener->ciphers_tls13, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: ciphers_tls1.3 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, "local_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, "local_cleansession", (bool *) &cur_bridge->clean_start_local, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "clientid_prefixes")){ log__printf(NULL, MOSQ_LOG_NOTICE, "The 'clientid_prefixes' option is now deprecated and will be removed in a future version."); 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, (size_t)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; cur_bridge->outgoing_retain = true; cur_bridge->clean_start_local = -1; }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; } 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; i UINT16_MAX){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Bridge keepalive value too high."); return MOSQ_ERR_INVAL; } if(tmp_int < 5){ log__printf(NULL, MOSQ_LOG_NOTICE, "keepalive interval too low, using 5 seconds."); tmp_int = 5; } cur_bridge->keepalive = (uint16_t)tmp_int; #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")){ config->local_only = false; token = strtok_r(NULL, " ", &saveptr); if(token){ tmp_int = atoi(token); #ifdef WITH_UNIX_SOCKETS if(tmp_int < 0 || tmp_int > UINT16_MAX){ #else if(tmp_int < 1 || tmp_int > UINT16_MAX){ #endif log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } /* Look for bind address / unix socket path */ token = strtok_r(NULL, " ", &saveptr); if (token != NULL && token[0] == '#'){ token = NULL; } if(tmp_int == 0 && token == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: A listener with port 0 must provide a Unix socket path."); return MOSQ_ERR_INVAL; } if(reload){ /* We reload listeners settings based on port number/unix socket path. * If the port number/unix path doesn't already exist, exit with a complaint. */ cur_listener = NULL; #ifdef WITH_UNIX_SOCKETS if(tmp_int == 0){ for(i=0; ilistener_count; i++){ if(config->listeners[i].unix_socket_path != NULL && strcmp(config->listeners[i].unix_socket_path, token) == 0){ cur_listener = &config->listeners[i]; break; } } }else #endif { for(i=0; ilistener_count; i++){ if(config->listeners[i].port == tmp_int){ /* Now check we have a matching bind address, if defined */ if(config->listeners[i].host){ if(token && !strcmp(config->listeners[i].host, token)){ /* They both have a bind address, and they match */ cur_listener = &config->listeners[i]; break; } }else{ if(token == NULL){ /* Neither this config nor the new config have a bind address, * so they match. */ cur_listener = &config->listeners[i]; break; } } } } } 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)*(size_t)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)); } listener__set_defaults(cur_listener); cur_listener->port = (uint16_t)tmp_int; mosquitto__free(cur_listener->host); cur_listener->host = NULL; #ifdef WITH_UNIX_SOCKETS mosquitto__free(cur_listener->unix_socket_path); cur_listener->unix_socket_path = NULL; #endif if(token){ #ifdef WITH_UNIX_SOCKETS if(cur_listener->port == 0){ cur_listener->unix_socket_path = mosquitto__strdup(token); }else #endif { cur_listener->host = mosquitto__strdup(token); } } }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, "dlt")){ cr->log_dest |= MQTT3_LOG_DLT; }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") || !strcmp(token, "max_qos")){ if(reload) continue; /* Listeners not valid for reloading. */ if(conf__parse_int(&token, token, &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 0 || tmp_int > 2){ log__printf(NULL, MOSQ_LOG_ERR, "Error: max_qos must be between 0 and 2 inclusive."); return MOSQ_ERR_INVAL; } cur_listener->max_qos = (uint8_t)tmp_int; }else if(!strcmp(token, "max_inflight_bytes")){ if(conf__parse_int(&token, "max_inflight_bytes", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 0) tmp_int = 0; config->max_inflight_bytes = (size_t)tmp_int; }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 == UINT16_MAX){ tmp_int = 0; }else if(tmp_int > UINT16_MAX){ log__printf(NULL, MOSQ_LOG_ERR, "Error: max_inflight_messages must be <= 65535."); return MOSQ_ERR_INVAL; } config->max_inflight_messages = (uint16_t)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 > UINT16_MAX){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid max_keepalive value (%d).", tmp_int); return MOSQ_ERR_INVAL; } config->max_keepalive = (uint16_t)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 = (uint32_t)tmp_int; }else if(!strcmp(token, "max_queued_bytes")){ if(conf__parse_int(&token, "max_queued_bytes", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 0) tmp_int = 0; config->max_queued_bytes = (size_t)tmp_int; }else if(!strcmp(token, "max_queued_messages")){ if(conf__parse_int(&token, "max_queued_messages", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 0) tmp_int = 0; config->max_queued_messages = tmp_int; }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((size_t)lim); }else if(!strcmp(token, "message_size_limit")){ log__printf(NULL, MOSQ_LOG_NOTICE, "Note: It is recommended to replace `message_size_limit` with `max_packet_size`."); 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")){ log__printf(NULL, MOSQ_LOG_NOTICE, "The 'port' option is now deprecated and will be removed in a future version. Please use 'listener' instead."); config->local_only = false; if(reload) continue; /* Listeners 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 > UINT16_MAX){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } config->default_listener.port = (uint16_t)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; #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, "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. */ 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. */ 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 char *topic = NULL; enum mosquitto__bridge_direction direction = bd_out; uint8_t qos = 0; char *local_prefix = NULL, *remote_prefix = NULL; 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){ topic = token; }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")){ direction = bd_out; }else if(!strcasecmp(token, "in")){ direction = bd_in; }else if(!strcasecmp(token, "both")){ 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] == '#'){ (void)strtok_r(NULL, "", &saveptr); } qos = (uint8_t)atoi(token); if(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){ if(!strcmp(token, "\"\"") || token[0] == '#'){ local_prefix = NULL; if (token[0] == '#'){ (void)strtok_r(NULL, "", &saveptr); } }else{ local_prefix = token; } token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "\"\"") || token[0] == '#'){ remote_prefix = NULL; }else{ remote_prefix = token; } } } } } if(bridge__add_topic(cur_bridge, topic, direction, qos, local_prefix, remote_prefix)){ return MOSQ_ERR_INVAL; } #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){ tmp_int = atoi(token); if(tmp_int < 0 || tmp_int > UINT16_MAX){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid max_topic_alias value in configuration."); return MOSQ_ERR_INVAL; } cur_listener->max_topic_alias = (uint16_t)tmp_int; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_topic_alias value in configuration."); return MOSQ_ERR_INVAL; } }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(conf__parse_int(&token, "websockets_headers_size", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 0 || tmp_int > UINT16_MAX){ log__printf(NULL, MOSQ_LOG_WARNING, "Error: Websockets headers size must be between 0 and 65535 inclusive."); return MOSQ_ERR_INVAL; } config->websockets_headers_size = (uint16_t)tmp_int; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Websockets support not available."); #endif }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; #ifndef WIN32 DIR *dir; #endif #ifndef WIN32 dir = opendir(file); if(dir){ closedir(dir); log__printf(NULL, MOSQ_LOG_ERR, "Error: Config file %s is a directory.", file); return 1; } #endif 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((size_t)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]; size_t 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 = (uint16_t)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 = (uint16_t)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) { size_t tlen; *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; } tlen = strlen(*token); if(tlen > UINT16_MAX){ return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(*token, (uint16_t)tlen)){ 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-2.0.11/src/send_unsuback.c0000664000175000017500000000316414060132747016446 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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; 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){ packet->remaining_length += property__get_remaining_length(properties); packet->remaining_length += (uint32_t)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, (uint32_t)reason_code_count); } return packet__queue(mosq, packet); } mosquitto-2.0.11/src/plugin_public.c0000664000175000017500000001346014060132747016456 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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" #include "mqtt_protocol.h" #include "send_mosq.h" #include "util_mosq.h" #include "utlist.h" #ifdef WITH_TLS # include #endif const char *mosquitto_client_address(const struct mosquitto *client) { if(client){ return client->address; }else{ return NULL; } } bool mosquitto_client_clean_session(const struct mosquitto *client) { if(client){ return client->clean_start; }else{ return true; } } const char *mosquitto_client_id(const struct mosquitto *client) { if(client){ return client->id; }else{ return NULL; } } int mosquitto_client_keepalive(const struct mosquitto *client) { if(client){ return client->keepalive; }else{ return -1; } } void *mosquitto_client_certificate(const struct mosquitto *client) { #ifdef WITH_TLS if(client && 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 && client->wsi){ return mp_websockets; }else #else UNUSED(client); #endif { return mp_mqtt; } } int mosquitto_client_protocol_version(const struct mosquitto *client) { if(client){ switch(client->protocol){ case mosq_p_mqtt31: return 3; case mosq_p_mqtt311: return 4; case mosq_p_mqtt5: return 5; default: return 0; } }else{ return 0; } } int mosquitto_client_sub_count(const struct mosquitto *client) { if(client){ return client->sub_count; }else{ return 0; } } const char *mosquitto_client_username(const struct mosquitto *client) { if(client){ #ifdef WITH_BRIDGE if(client->bridge){ return client->bridge->local_username; }else #endif { return client->username; } }else{ return NULL; } } int mosquitto_broker_publish( const char *clientid, const char *topic, int payloadlen, void *payload, int qos, bool retain, mosquitto_property *properties) { struct mosquitto_message_v5 *msg; if(topic == NULL || payloadlen < 0 || (payloadlen > 0 && payload == NULL) || qos < 0 || qos > 2){ return MOSQ_ERR_INVAL; } msg = mosquitto__malloc(sizeof(struct mosquitto_message_v5)); if(msg == NULL) return MOSQ_ERR_NOMEM; msg->next = NULL; msg->prev = NULL; if(clientid){ msg->clientid = mosquitto__strdup(clientid); if(msg->clientid == NULL){ mosquitto__free(msg); return MOSQ_ERR_NOMEM; } }else{ msg->clientid = NULL; } msg->topic = mosquitto__strdup(topic); if(msg->topic == NULL){ mosquitto__free(msg->clientid); mosquitto__free(msg); return MOSQ_ERR_NOMEM; } msg->payloadlen = payloadlen; msg->payload = payload; msg->qos = qos; msg->retain = retain; msg->properties = properties; DL_APPEND(db.plugin_msgs, msg); return MOSQ_ERR_SUCCESS; } int mosquitto_broker_publish_copy( const char *clientid, const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties) { void *payload_out; if(topic == NULL || payloadlen < 0 || (payloadlen > 0 && payload == NULL) || qos < 0 || qos > 2){ return MOSQ_ERR_INVAL; } payload_out = calloc(1, (size_t)(payloadlen+1)); if(payload_out == NULL){ return MOSQ_ERR_NOMEM; } memcpy(payload_out, payload, (size_t)payloadlen); return mosquitto_broker_publish( clientid, topic, payloadlen, payload_out, qos, retain, properties); } 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(client); if(rc){ client->username = old; mosquitto__free(u_dup); return rc; }else{ mosquitto__free(old); return MOSQ_ERR_SUCCESS; } } static void disconnect_client(struct mosquitto *context, bool with_will) { if(context->protocol == mosq_p_mqtt5){ send__disconnect(context, MQTT_RC_ADMINISTRATIVE_ACTION, NULL); } if(with_will == false){ mosquitto__set_state(context, mosq_cs_disconnecting); } do_disconnect(context, MOSQ_ERR_ADMINISTRATIVE_ACTION); } int mosquitto_kick_client_by_clientid(const char *clientid, bool with_will) { struct mosquitto *ctxt, *ctxt_tmp; if(clientid == NULL){ HASH_ITER(hh_sock, db.contexts_by_sock, ctxt, ctxt_tmp){ disconnect_client(ctxt, with_will); } return MOSQ_ERR_SUCCESS; }else{ HASH_FIND(hh_id, db.contexts_by_id, clientid, strlen(clientid), ctxt); if(ctxt){ disconnect_client(ctxt, with_will); return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOT_FOUND; } } } int mosquitto_kick_client_by_username(const char *username, bool with_will) { struct mosquitto *ctxt, *ctxt_tmp; if(username == NULL){ HASH_ITER(hh_sock, db.contexts_by_sock, ctxt, ctxt_tmp){ if(ctxt->username == NULL){ disconnect_client(ctxt, with_will); } } }else{ HASH_ITER(hh_sock, db.contexts_by_sock, ctxt, ctxt_tmp){ if(ctxt->username != NULL && !strcmp(ctxt->username, username)){ disconnect_client(ctxt, with_will); } } } return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/src/websockets.c0000664000175000017500000004535414060132747016002 0ustar rogerroger/* Copyright (c) 2014-2019 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #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) static int callback_mqtt( struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len); static int callback_http( struct lws *wsi, enum lws_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 lws_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 */ 0, /* id */ NULL, /* user v1.4 on */ WS_TX_BUF_SIZE /* tx_packet_size v2.3.0 */ }, { "mqtt", callback_mqtt, sizeof(struct libws_mqtt_data), 0, /* rx_buffer_size */ 1, /* id */ NULL, /* user v1.4 on */ WS_TX_BUF_SIZE /* tx_packet_size v2.3.0 */ }, { "mqttv3.1", callback_mqtt, sizeof(struct libws_mqtt_data), 0, /* rx_buffer_size */ 2, /* id */ NULL, /* user v1.4 on */ WS_TX_BUF_SIZE /* tx_packet_size v2.3.0 */ }, { NULL, NULL, 0, 0, /* rx_buffer_size */ 0, /* id */ NULL, /* user v1.4 on */ 0 /* tx_packet_size v2.3.0 */ } }; static void easy_address(int sock, struct mosquitto *mosq) { char address[1024]; if(!net__socket_get_address(sock, address, 1024, &mosq->remote_port)){ mosq->address = mosquitto__strdup(address); } } static int callback_mqtt( struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { struct mosquitto *mosq = NULL; struct mosquitto__packet *packet; int count; unsigned int ucount; const struct lws_protocols *p; struct libws_mqtt_data *u = (struct libws_mqtt_data *)user; size_t pos; uint8_t *buf; int rc; uint8_t byte; switch (reason) { case LWS_CALLBACK_ESTABLISHED: mosq = context__init(WEBSOCKET_CLIENT); if(mosq){ p = lws_get_protocol(wsi); mosq->listener = p->user; if(!mosq->listener){ mosquitto__free(mosq); return -1; } 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(lws_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 = lws_get_socket_fd(wsi); HASH_ADD(hh_sock, db.contexts_by_sock, sock, sizeof(mosq->sock), mosq); mux__add_in(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; mux__delete(mosq); } mosq->wsi = NULL; #ifdef WITH_TLS mosq->ssl = NULL; #endif do_disconnect(mosq, MOSQ_ERR_CONN_LOST); } break; case LWS_CALLBACK_SERVER_WRITEABLE: if(!u){ return -1; } mosq = u->mosq; if(!mosq){ return -1; } rc = db__message_write_inflight_out_latest(mosq); if(rc) return -1; rc = db__message_write_queued_out(mosq); if(rc) return -1; 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; } mosq->out_packet_count--; } while(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_PRE space available before the * actual data. * We've already made the payload big enough to allow this, * but need to move it into position here. */ memmove(&packet->payload[LWS_PRE], packet->payload, packet->packet_length); packet->pos += LWS_PRE; } count = lws_write(wsi, &packet->payload[packet->pos], packet->to_process, LWS_WRITE_BINARY); if(count < 0){ if (mosq->state == mosq_cs_disconnect_ws || mosq->state == mosq_cs_disconnecting || mosq->state == mosq_cs_disused){ return -1; } return 0; } ucount = (unsigned int)count; #ifdef WITH_SYS_TREE g_bytes_sent += ucount; #endif packet->to_process -= ucount; packet->pos += ucount; if(packet->to_process > 0){ if (mosq->state == mosq_cs_disconnect_ws || mosq->state == mosq_cs_disconnecting || mosq->state == mosq_cs_disused){ 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; } mosq->out_packet_count--; } packet__cleanup(packet); mosquitto__free(packet); mosq->next_msg_out = db.now_s + mosq->keepalive; } if (mosq->state == mosq_cs_disconnect_ws || mosq->state == mosq_cs_disconnecting || mosq->state == mosq_cs_disused){ return -1; } if(mosq->current_out_packet){ lws_callback_on_writable(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 = (int8_t)(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((uint32_t)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 += (uint32_t)(len-pos); mosq->in_packet.to_process -= (uint32_t)(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(mosq); /* Free data and reset values */ packet__cleanup(&mosq->in_packet); keepalive__update(mosq); if(rc && (mosq->out_packet || mosq->current_out_packet)) { if(mosq->state != mosq_cs_disconnecting){ mosquitto__set_state(mosq, mosq_cs_disconnect_ws); } lws_callback_on_writable(mosq->wsi); } else if (rc) { do_disconnect(mosq, MOSQ_ERR_CONN_LOST); return -1; } } break; default: break; } return 0; } static char *http__canonical_filename( struct lws *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){ lws_return_http_status(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){ lws_return_http_status(wsi, HTTP_STATUS_INTERNAL_SERVER_ERROR, NULL); return NULL; } #else filename_canonical = realpath(filename, NULL); mosquitto__free(filename); if(!filename_canonical){ if(errno == EACCES){ lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL); }else if(errno == EINVAL || errno == EIO || errno == ELOOP){ lws_return_http_status(wsi, HTTP_STATUS_INTERNAL_SERVER_ERROR, NULL); }else if(errno == ENAMETOOLONG){ lws_return_http_status(wsi, HTTP_STATUS_REQ_URI_TOO_LONG, NULL); }else if(errno == ENOENT || errno == ENOTDIR){ lws_return_http_status(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); lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL); return NULL; } return filename_canonical; } static int callback_http( struct lws *wsi, enum lws_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; int rc; char *filename_canonical; unsigned char buf[4096]; struct stat filestat; 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; } hack = (struct libws_mqtt_hack *)lws_context_user(lws_get_context(wsi)); 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)){ lws_return_http_status(wsi, HTTP_STATUS_METHOD_NOT_ALLOWED, NULL); return -1; } filename_canonical = http__canonical_filename(wsi, (char *)in, http_dir); if(!filename_canonical) return -1; u->fptr = fopen(filename_canonical, "rb"); if(!u->fptr){ free(filename_canonical); lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL); return -1; } if(fstat(fileno(u->fptr), &filestat) < 0){ free(filename_canonical); lws_return_http_status(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 = (size_t)snprintf((char *)buf, 4096, "HTTP/1.0 302 OK\r\n" "Location: %s/\r\n\r\n", (char *)in); return lws_write(wsi, buf, buflen, LWS_WRITE_HTTP); } if((filestat.st_mode & S_IFREG) != S_IFREG){ lws_return_http_status(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 = (size_t)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(lws_write(wsi, buf, buflen, LWS_WRITE_HTTP) < 0){ fclose(u->fptr); u->fptr = NULL; return -1; } lws_callback_on_writable(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; } rc = lws_write(wsi, buf, buflen, LWS_WRITE_HTTP); if(rc < 0){ return -1; } wlen = (size_t)rc; if(wlen < buflen){ if(fseek(u->fptr, (long)(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)); lws_callback_on_writable(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: HASH_FIND(hh_sock, db.contexts_by_sock, &pollargs->fd, sizeof(pollargs->fd), mosq); if(mosq){ if(pollargs->events & LWS_POLLOUT){ mux__add_out(mosq); mosq->ws_want_write = true; }else{ mux__remove_out(mosq); } }else{ if(pollargs->events & POLLIN){ /* Assume this is a new listener */ listeners__add_websockets(lws_get_context(wsi), pollargs->fd); } } break; case LWS_CALLBACK_DEL_POLL_FD: HASH_FIND(hh_sock, db.contexts_by_sock, &pollargs->fd, sizeof(pollargs->fd), mosq); if(mosq){ mux__delete(mosq); } break; case LWS_CALLBACK_CHANGE_MODE_POLL_FD: HASH_FIND(hh_sock, db.contexts_by_sock, &pollargs->fd, sizeof(pollargs->fd), mosq); if(mosq){ if(pollargs->events & LWS_POLLHUP){ return 1; }else if(pollargs->events & LWS_POLLOUT){ mux__add_out(mosq); mosq->ws_want_write = true; }else{ mux__remove_out(mosq); } } 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; UNUSED(level); l[strlen(line)-1] = '\0'; /* Remove \n */ log__printf(NULL, MOSQ_LOG_WEBSOCKETS, "%s", l); } void mosq_websockets_init(struct mosquitto__listener *listener, const struct mosquitto__config *conf) { struct lws_context_creation_info info; struct lws_protocols *p; size_t 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 lws_protocols)); if(!p){ log__printf(NULL, MOSQ_LOG_ERR, "Out of memory."); return; } 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 defined(WITH_WEBSOCKETS) && LWS_LIBRARY_VERSION_NUMBER>=3001000 info.tls1_3_plus_cipher_list = listener->ciphers_tls13; #endif if(listener->require_certificate){ info.options |= LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT; } #endif info.options |= LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; if(listener->socket_domain == AF_INET){ info.options |= LWS_SERVER_OPTION_DISABLE_IPV6; } info.max_http_header_data = conf->websockets_headers_size; user = mosquitto__calloc(1, sizeof(struct libws_mqtt_hack)); if(!user){ mosquitto__free(p); log__printf(NULL, MOSQ_LOG_ERR, "Out of memory."); return; } 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; } } user->listener = listener; info.user = user; info.pt_serv_buf_size = WS_SERV_BUF_SIZE; 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); listener->ws_in_init = true; listener->ws_context = lws_create_context(&info); listener->ws_in_init = false; } #endif mosquitto-2.0.11/src/property_broker.c0000664000175000017500000000645314060132747017056 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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-2.0.11/src/plugin.c0000664000175000017500000002070514060132747015120 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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" #include "mqtt_protocol.h" #include "send_mosq.h" #include "util_mosq.h" #include "utlist.h" #include "lib_load.h" static bool check_callback_exists(struct mosquitto__callback *cb_base, MOSQ_FUNC_generic_callback cb_func) { struct mosquitto__callback *tail, *tmp; DL_FOREACH_SAFE(cb_base, tail, tmp){ if(tail->cb == cb_func){ return true; } } return false; } static int remove_callback(struct mosquitto__callback **cb_base, MOSQ_FUNC_generic_callback cb_func) { struct mosquitto__callback *tail, *tmp; DL_FOREACH_SAFE(*cb_base, tail, tmp){ if(tail->cb == cb_func){ DL_DELETE(*cb_base, tail); mosquitto__free(tail); return MOSQ_ERR_SUCCESS; } } return MOSQ_ERR_NOT_FOUND; } int plugin__load_v5(struct mosquitto__listener *listener, struct mosquitto__auth_plugin *plugin, struct mosquitto_opt *options, int option_count, void *lib) { int rc; mosquitto_plugin_id_t *pid; if(!(plugin->plugin_init_v5 = (FUNC_plugin_init_v5)LIB_SYM(lib, "mosquitto_plugin_init"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load plugin function mosquitto_plugin_init()."); LIB_ERROR(); LIB_CLOSE(lib); return MOSQ_ERR_UNKNOWN; } if(!(plugin->plugin_cleanup_v5 = (FUNC_plugin_cleanup_v5)LIB_SYM(lib, "mosquitto_plugin_cleanup"))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load plugin function mosquitto_plugin_cleanup()."); LIB_ERROR(); LIB_CLOSE(lib); return MOSQ_ERR_UNKNOWN; } pid = mosquitto__calloc(1, sizeof(mosquitto_plugin_id_t)); if(pid == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); LIB_CLOSE(lib); return MOSQ_ERR_NOMEM; } pid->listener = listener; plugin->lib = lib; plugin->user_data = NULL; plugin->identifier = pid; if(plugin->plugin_init_v5){ rc = plugin->plugin_init_v5(pid, &plugin->user_data, options, option_count); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Plugin returned %d when initialising.", rc); return rc; } } return 0; } void plugin__handle_disconnect(struct mosquitto *context, int reason) { struct mosquitto_evt_disconnect event_data; struct mosquitto__callback *cb_base; struct mosquitto__security_options *opts; if(db.config->per_listener_settings){ if(context->listener == NULL){ return; } opts = &context->listener->security_options; }else{ opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); } event_data.client = context; event_data.reason = reason; DL_FOREACH(opts->plugin_callbacks.disconnect, cb_base){ cb_base->cb(MOSQ_EVT_DISCONNECT, &event_data, cb_base->userdata); } } int plugin__handle_message(struct mosquitto *context, struct mosquitto_msg_store *stored) { struct mosquitto_evt_message event_data; struct mosquitto__callback *cb_base; struct mosquitto__security_options *opts; int rc = MOSQ_ERR_SUCCESS; if(db.config->per_listener_settings){ if(context->listener == NULL){ return MOSQ_ERR_SUCCESS; } opts = &context->listener->security_options; }else{ opts = &db.config->security_options; } if(opts->plugin_callbacks.message == NULL){ return MOSQ_ERR_SUCCESS; } memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.topic = stored->topic; event_data.payloadlen = stored->payloadlen; event_data.payload = stored->payload; event_data.qos = stored->qos; event_data.retain = stored->retain; event_data.properties = stored->properties; DL_FOREACH(opts->plugin_callbacks.message, cb_base){ rc = cb_base->cb(MOSQ_EVT_MESSAGE, &event_data, cb_base->userdata); if(rc != MOSQ_ERR_SUCCESS){ break; } } stored->topic = event_data.topic; if(stored->payload != event_data.payload){ mosquitto__free(stored->payload); stored->payload = event_data.payload; stored->payloadlen = event_data.payloadlen; } stored->retain = event_data.retain; stored->properties = event_data.properties; return rc; } void plugin__handle_tick(void) { struct mosquitto_evt_tick event_data; struct mosquitto__callback *cb_base; struct mosquitto__security_options *opts; /* FIXME - set now_s and now_ns to avoid need for multiple time lookups */ if(db.config->per_listener_settings){ /* FIXME - iterate over all listeners */ }else{ opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); DL_FOREACH(opts->plugin_callbacks.tick, cb_base){ cb_base->cb(MOSQ_EVT_TICK, &event_data, cb_base->userdata); } } } int mosquitto_callback_register( mosquitto_plugin_id_t *identifier, int event, MOSQ_FUNC_generic_callback cb_func, const void *event_data, void *userdata) { struct mosquitto__callback **cb_base = NULL, *cb_new; struct mosquitto__security_options *security_options; if(cb_func == NULL) return MOSQ_ERR_INVAL; if(identifier->listener == NULL){ security_options = &db.config->security_options; }else{ security_options = &identifier->listener->security_options; } switch(event){ case MOSQ_EVT_RELOAD: cb_base = &security_options->plugin_callbacks.reload; break; case MOSQ_EVT_ACL_CHECK: cb_base = &security_options->plugin_callbacks.acl_check; break; case MOSQ_EVT_BASIC_AUTH: cb_base = &security_options->plugin_callbacks.basic_auth; break; case MOSQ_EVT_PSK_KEY: cb_base = &security_options->plugin_callbacks.psk_key; break; case MOSQ_EVT_EXT_AUTH_START: cb_base = &security_options->plugin_callbacks.ext_auth_start; break; case MOSQ_EVT_EXT_AUTH_CONTINUE: cb_base = &security_options->plugin_callbacks.ext_auth_continue; break; case MOSQ_EVT_CONTROL: return control__register_callback(security_options, cb_func, event_data, userdata); break; case MOSQ_EVT_MESSAGE: cb_base = &security_options->plugin_callbacks.message; break; case MOSQ_EVT_TICK: cb_base = &security_options->plugin_callbacks.tick; break; case MOSQ_EVT_DISCONNECT: cb_base = &security_options->plugin_callbacks.disconnect; break; default: return MOSQ_ERR_NOT_SUPPORTED; break; } if(check_callback_exists(*cb_base, cb_func)){ return MOSQ_ERR_ALREADY_EXISTS; } cb_new = mosquitto__calloc(1, sizeof(struct mosquitto__callback)); if(cb_new == NULL){ return MOSQ_ERR_NOMEM; } DL_APPEND(*cb_base, cb_new); cb_new->cb = cb_func; cb_new->userdata = userdata; return MOSQ_ERR_SUCCESS; } int mosquitto_callback_unregister( mosquitto_plugin_id_t *identifier, int event, MOSQ_FUNC_generic_callback cb_func, const void *event_data) { struct mosquitto__callback **cb_base = NULL; struct mosquitto__security_options *security_options; if(identifier == NULL || cb_func == NULL){ return MOSQ_ERR_INVAL; } if(identifier->listener == NULL){ security_options = &db.config->security_options; }else{ security_options = &identifier->listener->security_options; } switch(event){ case MOSQ_EVT_RELOAD: cb_base = &security_options->plugin_callbacks.reload; break; case MOSQ_EVT_ACL_CHECK: cb_base = &security_options->plugin_callbacks.acl_check; break; case MOSQ_EVT_BASIC_AUTH: cb_base = &security_options->plugin_callbacks.basic_auth; break; case MOSQ_EVT_PSK_KEY: cb_base = &security_options->plugin_callbacks.psk_key; break; case MOSQ_EVT_EXT_AUTH_START: cb_base = &security_options->plugin_callbacks.ext_auth_start; break; case MOSQ_EVT_EXT_AUTH_CONTINUE: cb_base = &security_options->plugin_callbacks.ext_auth_continue; break; case MOSQ_EVT_CONTROL: return control__unregister_callback(security_options, cb_func, event_data); break; case MOSQ_EVT_MESSAGE: cb_base = &security_options->plugin_callbacks.message; break; case MOSQ_EVT_TICK: cb_base = &security_options->plugin_callbacks.tick; break; case MOSQ_EVT_DISCONNECT: cb_base = &security_options->plugin_callbacks.disconnect; break; default: return MOSQ_ERR_NOT_SUPPORTED; break; } return remove_callback(cb_base, cb_func); } mosquitto-2.0.11/src/persist_read_v5.c0000664000175000017500000001655614060132747016731 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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_v56(FILE *db_fptr, uint32_t *chunk, uint32_t *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_v56(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_v56(FILE *db_fptr, struct P_client *chunk, uint32_t db_version) { int rc; if(db_version == 6){ read_e(db_fptr, &chunk->F, sizeof(struct PF_client)); chunk->F.username_len = ntohs(chunk->F.username_len); chunk->F.listener_port = ntohs(chunk->F.listener_port); }else if(db_version == 5){ read_e(db_fptr, &chunk->F, sizeof(struct PF_client_v5)); }else{ return 1; } 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){ return 1; }else if(chunk->client_id == NULL){ return -1; } if(chunk->F.username_len > 0){ rc = persist__read_string_len(db_fptr, &chunk->username, chunk->F.username_len); if(rc || !chunk->username){ mosquitto__free(chunk->client_id); return 1; } } return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } int persist__chunk_client_msg_read_v56(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 -= (uint32_t)(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_v56(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 -= (uint32_t)(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){ chunk->payload = mosquitto__malloc(chunk->F.payloadlen+1); if(chunk->payload == NULL){ 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; } /* Ensure zero terminated regardless of contents */ ((uint8_t *)chunk->payload)[chunk->F.payloadlen] = 0; read_e(db_fptr, chunk->payload, 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_v56(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_v56(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-2.0.11/src/mux.h0000664000175000017500000000261014060132747014433 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef MUX_H #define MUX_H #include "mosquitto_broker_internal.h" int mux_epoll__init(struct mosquitto__listener_sock *listensock, int listensock_count); int mux_epoll__add_out(struct mosquitto *context); int mux_epoll__remove_out(struct mosquitto *context); int mux_epoll__add_in(struct mosquitto *context); int mux_epoll__delete(struct mosquitto *context); int mux_epoll__handle(void); int mux_epoll__cleanup(void); int mux_poll__init(struct mosquitto__listener_sock *listensock, int listensock_count); int mux_poll__add_out(struct mosquitto *context); int mux_poll__remove_out(struct mosquitto *context); int mux_poll__add_in(struct mosquitto *context); int mux_poll__delete(struct mosquitto *context); int mux_poll__handle(struct mosquitto__listener_sock *listensock, int listensock_count); int mux_poll__cleanup(void); #endif mosquitto-2.0.11/src/persist_write_v5.c0000664000175000017500000001543514060132747017143 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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_v6(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_v6(FILE *db_fptr, struct P_client *chunk) { struct PF_header header; uint16_t id_len = chunk->F.id_len; uint16_t username_len = chunk->F.username_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); chunk->F.username_len = htons(chunk->F.username_len); chunk->F.listener_port = htons(chunk->F.listener_port); header.chunk = htonl(DB_CHUNK_CLIENT); header.length = htonl((uint32_t)sizeof(struct PF_client)+id_len+username_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); if(username_len > 0){ write_e(db_fptr, chunk->username, username_len); } return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } int persist__chunk_client_msg_write_v6(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_remaining_length(chunk->properties); } 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((uint32_t)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){ mosquitto__free(prop_packet.payload); 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_v6(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_remaining_length(chunk->properties); } 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((uint32_t)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, chunk->payload, (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){ mosquitto__free(prop_packet.payload); 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_v6(FILE *db_fptr, struct P_retain *chunk) { struct PF_header header; header.chunk = htonl(DB_CHUNK_RETAIN); header.length = htonl((uint32_t)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_v6(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((uint32_t)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-2.0.11/src/sys_tree.h0000664000175000017500000000422614060132747015464 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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+=(uint64_t)(A)) #define G_BYTES_SENT_INC(A) (g_bytes_sent+=(uint64_t)(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() #define G_CLIENTS_EXPIRED_INC() #define G_SOCKET_CONNECTIONS_INC() #define G_CONNECTION_COUNT_INC() #endif #endif mosquitto-2.0.11/src/memory_public.c0000664000175000017500000000200414060132747016460 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "mosquitto_broker.h" #include "memory_mosq.h" void *mosquitto_calloc(size_t nmemb, size_t size) { return mosquitto__calloc(nmemb, size); } void mosquitto_free(void *mem) { mosquitto__free(mem); } void *mosquitto_malloc(size_t size) { return mosquitto__malloc(size); } void *mosquitto_realloc(void *ptr, size_t size) { return mosquitto__realloc(ptr, size); } char *mosquitto_strdup(const char *s) { return mosquitto__strdup(s); } mosquitto-2.0.11/src/handle_auth.c0000664000175000017500000001150014060132747016067 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *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 MOSQ_ERR_MALFORMED_PACKET; 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(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(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(context, auth_data_out, auth_data_out_len); }else{ mosquitto__set_state(context, mosq_cs_active); rc = send__auth(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(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(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(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-2.0.11/src/handle_unsubscribe.c0000664000175000017500000001056614060132747017465 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *context) { uint16_t mid; char *sub; uint16_t slen; int rc; uint8_t reason = 0; int reason_code_count = 0; int reason_code_max; uint8_t *reason_codes = NULL, *reason_tmp; mosquitto_property *properties = NULL; bool allowed; 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_MALFORMED_PACKET; } } if(packet__read_uint16(&context->in_packet, &mid)) return MOSQ_ERR_MALFORMED_PACKET; if(mid == 0) return MOSQ_ERR_MALFORMED_PACKET; if(context->protocol == mosq_p_mqtt5){ rc = property__read_all(CMD_UNSUBSCRIBE, &context->in_packet, &properties); if(rc){ /* FIXME - it would be better if property__read_all() returned * MOSQ_ERR_MALFORMED_PACKET, but this is would change the library * return codes so needs doc changes as well. */ if(rc == MOSQ_ERR_PROTOCOL){ return MOSQ_ERR_MALFORMED_PACKET; }else{ 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_MALFORMED_PACKET; } } reason_code_max = 10; reason_codes = mosquitto__malloc((size_t)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 MOSQ_ERR_MALFORMED_PACKET; } if(!slen){ log__printf(NULL, MOSQ_LOG_INFO, "Empty unsubscription string from %s, disconnecting.", context->id); mosquitto__free(sub); mosquitto__free(reason_codes); return MOSQ_ERR_MALFORMED_PACKET; } 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 MOSQ_ERR_MALFORMED_PACKET; } /* ACL check */ allowed = true; rc = mosquitto_acl_check(context, sub, 0, NULL, 0, false, MOSQ_ACL_UNSUBSCRIBE); switch(rc){ case MOSQ_ERR_SUCCESS: break; case MOSQ_ERR_ACL_DENIED: allowed = false; reason = MQTT_RC_NOT_AUTHORIZED; break; default: mosquitto__free(sub); mosquitto__free(reason_codes); return rc; } log__printf(NULL, MOSQ_LOG_DEBUG, "\t%s", sub); if(allowed){ rc = sub__remove(context, sub, db.subs, &reason); }else{ rc = MOSQ_ERR_SUCCESS; } 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, (size_t)(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-2.0.11/src/topic_tok.c0000664000175000017500000000452014060132747015612 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 "util_mosq.h" #include "utlist.h" static char *strtok_hier(char *str, char **saveptr) { char *c; if(str != NULL){ *saveptr = str; } if(*saveptr == NULL){ return NULL; } c = strchr(*saveptr, '/'); if(c){ str = *saveptr; *saveptr = c+1; c[0] = '\0'; }else if(*saveptr){ /* No match, but surplus string */ str = *saveptr; *saveptr = NULL; } return str; } int sub__topic_tokenise(const char *subtopic, char **local_sub, char ***topics, const char **sharename) { char *saveptr = NULL; char *token; int count; int topic_index = 0; int i; size_t len; len = strlen(subtopic); if(len == 0){ return MOSQ_ERR_INVAL; } *local_sub = mosquitto__strdup(subtopic); if((*local_sub) == NULL) return MOSQ_ERR_NOMEM; count = 0; saveptr = *local_sub; while(saveptr){ saveptr = strchr(&saveptr[1], '/'); count++; } *topics = mosquitto__calloc((size_t)(count+3) /* 3=$shared,sharename,NULL */, sizeof(char *)); if((*topics) == NULL){ mosquitto__free(*local_sub); return MOSQ_ERR_NOMEM; } if((*local_sub)[0] != '$'){ (*topics)[topic_index] = ""; topic_index++; } token = strtok_hier((*local_sub), &saveptr); while(token){ (*topics)[topic_index] = token; topic_index++; token = strtok_hier(NULL, &saveptr); } if(!strcmp((*topics)[0], "$share")){ if(count < 2){ mosquitto__free(*local_sub); mosquitto__free(*topics); return MOSQ_ERR_PROTOCOL; } if(sharename){ (*sharename) = (*topics)[1]; } for(i=1; i All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. Tatsuzo Osawa - Add epoll. */ #include "mux.h" int mux__init(struct mosquitto__listener_sock *listensock, int listensock_count) { #ifdef WITH_EPOLL return mux_epoll__init(listensock, listensock_count); #else return mux_poll__init(listensock, listensock_count); #endif } int mux__add_out(struct mosquitto *context) { #ifdef WITH_EPOLL return mux_epoll__add_out(context); #else return mux_poll__add_out(context); #endif } int mux__remove_out(struct mosquitto *context) { #ifdef WITH_EPOLL return mux_epoll__remove_out(context); #else return mux_poll__remove_out(context); #endif } int mux__add_in(struct mosquitto *context) { #ifdef WITH_EPOLL return mux_epoll__add_in(context); #else return mux_poll__add_in(context); #endif } int mux__delete(struct mosquitto *context) { #ifdef WITH_EPOLL return mux_epoll__delete(context); #else return mux_poll__delete(context); #endif } int mux__handle(struct mosquitto__listener_sock *listensock, int listensock_count) { #ifdef WITH_EPOLL UNUSED(listensock); UNUSED(listensock_count); return mux_epoll__handle(); #else return mux_poll__handle(listensock, listensock_count); #endif } int mux__cleanup(void) { #ifdef WITH_EPOLL return mux_epoll__cleanup(); #else return mux_poll__cleanup(); #endif } mosquitto-2.0.11/src/will_delay.c0000664000175000017500000000503314060132747015744 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 (int)(i1->context->will_delay_interval - i2->context->will_delay_interval); } int will_delay__add(struct mosquitto *context) { struct will_delay_list *item; if(context->will_delay_entry){ return MOSQ_ERR_SUCCESS; } 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 = db.now_real_s + 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(void) { 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(item->context); mosquitto__free(item); } } void will_delay__check(void) { struct will_delay_list *item, *tmp; if(db.now_real_s <= last_check) return; last_check = db.now_real_s; DL_FOREACH_SAFE(delay_list, item, tmp){ if(item->context->will_delay_time < db.now_real_s){ DL_DELETE(delay_list, item); item->context->will_delay_interval = 0; item->context->will_delay_entry = NULL; context__send_will(item->context); if(item->context->session_expiry_interval == 0){ context__add_to_disused(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-2.0.11/src/conf_includedir.c0000664000175000017500000001063014060132747016745 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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" static 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) { size_t 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, (size_t)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, (size_t)l_file_count, sizeof(char *), scmp_p); } *files = l_files; *file_count = l_file_count; return 0; } #endif mosquitto-2.0.11/src/signals.c0000664000175000017500000000533614060132747015265 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. Dmitry Kaukov - windows named events implementation. */ #ifdef WIN32 # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # include #endif #include "config.h" #include #include #include #include "mosquitto_broker_internal.h" #ifdef WITH_PERSISTENCE extern bool flag_db_backup; #endif extern bool flag_reload; 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(); UNUSED(data); 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-2.0.11/src/retain.c0000664000175000017500000002022514060132747015101 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 "util_mosq.h" #include "utlist.h" static struct mosquitto__retainhier *retain__add_hier_entry(struct mosquitto__retainhier *parent, struct mosquitto__retainhier **sibling, const char *topic, uint16_t len) { struct mosquitto__retainhier *child; assert(sibling); child = mosquitto__calloc(1, sizeof(struct mosquitto__retainhier)); 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((size_t)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, (size_t)child->topic_len+1); } HASH_ADD_KEYPTR(hh, *sibling, child->topic, child->topic_len, child); return child; } int retain__init(void) { struct mosquitto__retainhier *retainhier; retainhier = retain__add_hier_entry(NULL, &db.retains, "", 0); if(!retainhier) return MOSQ_ERR_NOMEM; retainhier = retain__add_hier_entry(NULL, &db.retains, "$SYS", (uint16_t)strlen("$SYS")); if(!retainhier) return MOSQ_ERR_NOMEM; return MOSQ_ERR_SUCCESS; } int retain__store(const char *topic, struct mosquitto_msg_store *stored, char **split_topics) { struct mosquitto__retainhier *retainhier; struct mosquitto__retainhier *branch; int i; size_t slen; assert(stored); assert(split_topics); HASH_FIND(hh, db.retains, split_topics[0], strlen(split_topics[0]), retainhier); if(retainhier == NULL){ retainhier = retain__add_hier_entry(NULL, &db.retains, split_topics[0], (uint16_t)strlen(split_topics[0])); if(!retainhier) return MOSQ_ERR_NOMEM; } for(i=0; split_topics[i] != NULL; i++){ slen = strlen(split_topics[i]); HASH_FIND(hh, retainhier->children, split_topics[i], slen, branch); if(branch == NULL){ branch = retain__add_hier_entry(retainhier, &retainhier->children, split_topics[i], (uint16_t)slen); if(branch == NULL){ return MOSQ_ERR_NOMEM; } } retainhier = branch; } #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(retainhier->retained){ db__msg_store_ref_dec(&retainhier->retained); #ifdef WITH_SYS_TREE db.retained_count--; #endif } if(stored->payloadlen){ retainhier->retained = stored; db__msg_store_ref_inc(retainhier->retained); #ifdef WITH_SYS_TREE db.retained_count++; #endif }else{ retainhier->retained = NULL; } return MOSQ_ERR_SUCCESS; } static int retain__process(struct mosquitto__retainhier *branch, struct mosquitto *context, uint8_t sub_qos, uint32_t subscription_identifier) { int rc = 0; uint8_t qos; uint16_t mid; mosquitto_property *properties = NULL; struct mosquitto_msg_store *retained; if(branch->retained->message_expiry_time > 0 && db.now_real_s >= branch->retained->message_expiry_time){ db__msg_store_ref_dec(&branch->retained); branch->retained = NULL; #ifdef WITH_SYS_TREE db.retained_count--; #endif return MOSQ_ERR_SUCCESS; } retained = branch->retained; rc = mosquitto_acl_check(context, retained->topic, retained->payloadlen, retained->payload, 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(&retain_ctxt); if(rc) return rc; rc = mosquitto_acl_check(&retain_ctxt, retained->topic, retained->payloadlen, retained->payload, 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(context, mid, mosq_md_out, qos, true, retained, properties, false); } static int retain__search(struct mosquitto__retainhier *retainhier, char **split_topics, struct mosquitto *context, const char *sub, uint8_t sub_qos, uint32_t subscription_identifier, int level) { struct mosquitto__retainhier *branch, *branch_tmp; int flag = 0; if(!strcmp(split_topics[0], "#") && split_topics[1] == NULL){ HASH_ITER(hh, retainhier->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(branch, context, sub_qos, subscription_identifier); } if(branch->children){ retain__search(branch, split_topics, context, sub, sub_qos, subscription_identifier, level+1); } } }else{ if(!strcmp(split_topics[0], "+")){ HASH_ITER(hh, retainhier->children, branch, branch_tmp){ if(split_topics[1] != NULL){ if(retain__search(branch, &(split_topics[1]), context, sub, sub_qos, subscription_identifier, level+1) == -1 || (split_topics[1] != NULL && !strcmp(split_topics[1], "#") && level>0)){ if(branch->retained){ retain__process(branch, context, sub_qos, subscription_identifier); } } }else{ if(branch->retained){ retain__process(branch, context, sub_qos, subscription_identifier); } } } }else{ HASH_FIND(hh, retainhier->children, split_topics[0], strlen(split_topics[0]), branch); if(branch){ if(split_topics[1] != NULL){ if(retain__search(branch, &(split_topics[1]), context, sub, sub_qos, subscription_identifier, level+1) == -1 || (split_topics[1] != NULL && !strcmp(split_topics[1], "#") && level>0)){ if(branch->retained){ retain__process(branch, context, sub_qos, subscription_identifier); } } }else{ if(branch->retained){ retain__process(branch, context, sub_qos, subscription_identifier); } } } } } return flag; } int retain__queue(struct mosquitto *context, const char *sub, uint8_t sub_qos, uint32_t subscription_identifier) { struct mosquitto__retainhier *retainhier; char *local_sub; char **split_topics; int rc; assert(context); assert(sub); rc = sub__topic_tokenise(sub, &local_sub, &split_topics, NULL); if(rc) return rc; HASH_FIND(hh, db.retains, split_topics[0], strlen(split_topics[0]), retainhier); if(retainhier){ retain__search(retainhier, split_topics, context, sub, sub_qos, subscription_identifier, 0); } mosquitto__free(local_sub); mosquitto__free(split_topics); return MOSQ_ERR_SUCCESS; } void retain__clean(struct mosquitto__retainhier **retainhier) { struct mosquitto__retainhier *peer, *retainhier_tmp; HASH_ITER(hh, *retainhier, peer, retainhier_tmp){ if(peer->retained){ db__msg_store_ref_dec(&peer->retained); } retain__clean(&peer->children); mosquitto__free(peer->topic); HASH_DELETE(hh, *retainhier, peer); mosquitto__free(peer); } } mosquitto-2.0.11/src/subs.c0000664000175000017500000005171014060132747014576 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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" static int subs__send(struct mosquitto__subleaf *leaf, const char *topic, uint8_t qos, int retain, struct mosquitto_msg_store *stored) { bool client_retain; uint16_t mid; uint8_t client_qos, msg_qos; mosquitto_property *properties = NULL; int rc2; /* Check for ACL topic access. */ rc2 = mosquitto_acl_check(leaf->context, topic, stored->payloadlen, stored->payload, 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(leaf->context, mid, mosq_md_out, msg_qos, client_retain, stored, properties, true) == 1){ return 1; } }else{ return 1; /* Application error */ } return 0; } static int subs__shared_process(struct mosquitto__subhier *hier, const char *topic, uint8_t 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(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__subhier *hier, const char *source_id, const char *topic, uint8_t qos, int retain, struct mosquitto_msg_store *stored) { int rc = 0; int rc2; struct mosquitto__subleaf *leaf; rc = subs__shared_process(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(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 int sub__add_leaf(struct mosquitto *context, uint8_t 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 *context, uint8_t qos, uint32_t identifier, int options, struct mosquitto__subhier *subhier, const 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; size_t slen; int rc; slen = strlen(sharename); HASH_FIND(hh, subhier->shared, sharename, slen, shared); if(shared == NULL){ shared = mosquitto__calloc(1, sizeof(struct mosquitto__subshared)); if(!shared){ return MOSQ_ERR_NOMEM; } shared->name = mosquitto__strdup(sharename); if(shared->name == NULL){ mosquitto__free(shared); return MOSQ_ERR_NOMEM; } 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; shared_ref = NULL; break; } } if(shared_ref){ shared_subs = mosquitto__realloc(context->shared_subs, sizeof(struct mosquitto__subshared_ref *)*(size_t)(context->shared_sub_count + 1)); if(!shared_subs){ mosquitto__free(shared_ref); context->shared_subs[context->shared_sub_count-1] = NULL; 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 *context, uint8_t 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 *)*(size_t)(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 *context, uint8_t qos, uint32_t identifier, int options, struct mosquitto__subhier *subhier, char *const *const topics, const char *sharename) { struct mosquitto__subhier *branch; int topic_index = 0; size_t topiclen; /* Find leaf node */ while(topics && topics[topic_index] != NULL){ topiclen = strlen(topics[topic_index]); if(topiclen > UINT16_MAX){ return MOSQ_ERR_INVAL; } HASH_FIND(hh, subhier->children, topics[topic_index], topiclen, branch); if(!branch){ /* Not found */ branch = sub__add_hier_entry(subhier, &subhier->children, topics[topic_index], (uint16_t)topiclen); if(!branch) return MOSQ_ERR_NOMEM; } subhier = branch; topic_index++; } /* Add add our context */ if(context && context->id){ if(sharename){ return sub__add_shared(context, qos, identifier, options, subhier, sharename); }else{ return sub__add_normal(context, qos, identifier, options, subhier); } }else{ return MOSQ_ERR_SUCCESS; } } static int sub__remove_normal(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 *context, struct mosquitto__subhier *subhier, uint8_t *reason, const char *sharename) { struct mosquitto__subshared *shared; struct mosquitto__subleaf *leaf; int i; HASH_FIND(hh, subhier->shared, sharename, strlen(sharename), shared); 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 *context, struct mosquitto__subhier *subhier, char **topics, uint8_t *reason, const char *sharename) { struct mosquitto__subhier *branch; if(topics == NULL || topics[0] == NULL){ if(sharename){ return sub__remove_shared(context, subhier, reason, sharename); }else{ return sub__remove_normal(context, subhier, reason); } } HASH_FIND(hh, subhier->children, topics[0], strlen(topics[0]), branch); if(branch){ sub__remove_recurse(context, branch, &(topics[1]), reason, sharename); if(!branch->children && !branch->subs && !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__subhier *subhier, char **split_topics, const char *source_id, const char *topic, uint8_t qos, int retain, struct mosquitto_msg_store *stored) { /* 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(split_topics && split_topics[0]){ /* Check for literal match */ HASH_FIND(hh, subhier->children, split_topics[0], strlen(split_topics[0]), branch); if(branch){ rc = sub__search(branch, &(split_topics[1]), source_id, topic, qos, retain, stored); if(rc == MOSQ_ERR_SUCCESS){ have_subscribers = true; }else if(rc != MOSQ_ERR_NO_SUBSCRIBERS){ return rc; } if(split_topics[1] == NULL){ /* End of list */ rc = subs__process(branch, source_id, topic, qos, retain, stored); 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(branch, &(split_topics[1]), source_id, topic, qos, retain, stored); if(rc == MOSQ_ERR_SUCCESS){ have_subscribers = true; }else if(rc != MOSQ_ERR_NO_SUBSCRIBERS){ return rc; } if(split_topics[1] == NULL){ /* End of list */ rc = subs__process(branch, source_id, topic, qos, retain, stored); 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(branch, source_id, topic, qos, retain, stored); 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, uint16_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__strdup(topic); if(!child->topic){ child->topic_len = 0; mosquitto__free(child); log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return NULL; } HASH_ADD_KEYPTR(hh, *sibling, child->topic, child->topic_len, child); return child; } int sub__add(struct mosquitto *context, const char *sub, uint8_t qos, uint32_t identifier, int options, struct mosquitto__subhier **root) { int rc = 0; struct mosquitto__subhier *subhier; const char *sharename = NULL; char *local_sub; char **topics; size_t topiclen; assert(root); assert(*root); assert(sub); rc = sub__topic_tokenise(sub, &local_sub, &topics, &sharename); if(rc) return rc; topiclen = strlen(topics[0]); if(topiclen > UINT16_MAX){ mosquitto__free(local_sub); mosquitto__free(topics); return MOSQ_ERR_INVAL; } HASH_FIND(hh, *root, topics[0], topiclen, subhier); if(!subhier){ subhier = sub__add_hier_entry(NULL, root, topics[0], (uint16_t)topiclen); if(!subhier){ mosquitto__free(local_sub); mosquitto__free(topics); log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } rc = sub__add_context(context, qos, identifier, options, subhier, topics, sharename); mosquitto__free(local_sub); mosquitto__free(topics); return rc; } int sub__remove(struct mosquitto *context, const char *sub, struct mosquitto__subhier *root, uint8_t *reason) { int rc = 0; struct mosquitto__subhier *subhier; const char *sharename = NULL; char *local_sub = NULL; char **topics = NULL; assert(root); assert(sub); rc = sub__topic_tokenise(sub, &local_sub, &topics, &sharename); if(rc) return rc; HASH_FIND(hh, root, topics[0], strlen(topics[0]), subhier); if(subhier){ *reason = MQTT_RC_NO_SUBSCRIPTION_EXISTED; rc = sub__remove_recurse(context, subhier, topics, reason, sharename); } mosquitto__free(local_sub); mosquitto__free(topics); return rc; } int sub__messages_queue(const char *source_id, const char *topic, uint8_t qos, int retain, struct mosquitto_msg_store **stored) { int rc = MOSQ_ERR_SUCCESS, rc2; struct mosquitto__subhier *subhier; char **split_topics = NULL; char *local_topic = NULL; assert(topic); if(sub__topic_tokenise(topic, &local_topic, &split_topics, NULL)) 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, split_topics[0], strlen(split_topics[0]), subhier); if(subhier){ rc = sub__search(subhier, split_topics, source_id, topic, qos, retain, *stored); } if(retain){ rc2 = retain__store(topic, *stored, split_topics); if(rc2) rc = rc2; } mosquitto__free(split_topics); mosquitto__free(local_topic); /* Remove our reference and free if needed. */ db__msg_store_ref_dec(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){ 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->shared == NULL && parent->parent){ return parent; }else{ return NULL; } } static int sub__clean_session_shared(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->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 *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]->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(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; } printf("\n"); } sub__tree_print(branch->children, level+1); } } mosquitto-2.0.11/src/persist_read.c0000664000175000017500000003433014060132747016305 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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(const char *client_id, const char *sub, uint8_t qos, uint32_t identifier, int options); static struct mosquitto *persist__find_or_add_context(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(INVALID_SOCKET); 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+1U); if(!s){ 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 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; } context = persist__find_or_add_context(chunk->client_id, 0); if(!context){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Persistence file contains client message with no matching client. File may be corrupt."); return 0; } 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); 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(FILE *db_fptr) { int i, rc = 0; struct mosquitto *context; struct P_client chunk; memset(&chunk, 0, sizeof(struct P_client)); if(db_version == 6 || db_version == 5){ rc = persist__chunk_client_read_v56(db_fptr, &chunk, db_version); }else{ rc = persist__chunk_client_read_v234(db_fptr, &chunk, db_version); } if(rc > 0){ return rc; }else if(rc < 0){ /* Client not loaded, but otherwise not an error */ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Empty client entry found in persistence database, it may be corrupt."); return MOSQ_ERR_SUCCESS; } context = persist__find_or_add_context(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; if(chunk.username && !context->username){ /* username is not freed here, it is now owned by context */ context->username = chunk.username; chunk.username = NULL; } /* in per_listener_settings mode, try to find the listener by persisted port */ if(db.config->per_listener_settings && !context->listener && chunk.F.listener_port > 0){ for(i=0; i < db.config->listener_count; i++){ if(db.config->listeners[i].port == chunk.F.listener_port){ context->listener = &db.config->listeners[i]; break; } } } /* FIXME - we should expire clients here if they have exceeded their time */ }else{ rc = 1; } mosquitto__free(chunk.client_id); if(chunk.username){ mosquitto__free(chunk.username); } return rc; } static int persist__client_msg_chunk_restore(FILE *db_fptr, uint32_t length) { struct P_client_msg chunk; int rc; memset(&chunk, 0, sizeof(struct P_client_msg)); if(db_version == 6 || db_version == 5){ rc = persist__chunk_client_msg_read_v56(db_fptr, &chunk, length); }else{ rc = persist__chunk_client_msg_read_v234(db_fptr, &chunk); } if(rc){ return rc; } rc = persist__client_msg_restore(&chunk); mosquitto__free(chunk.client_id); return rc; } static int persist__msg_store_chunk_restore(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 == 6 || db_version == 5){ rc = persist__chunk_msg_store_read_v56(db_fptr, &chunk, length); }else{ rc = persist__chunk_msg_store_read_v234(db_fptr, &chunk, db_version); } if(rc){ return rc; } if(chunk.F.source_port){ for(i=0; ilistener_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){ mosquitto__free(chunk.source.id); mosquitto__free(chunk.source.username); mosquitto__free(chunk.topic); mosquitto__free(chunk.payload); 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); mosquitto__free(chunk.payload); mosquitto__free(load); return MOSQ_ERR_SUCCESS; }else{ message_expiry_interval = (uint32_t)message_expiry_interval64; } }else{ message_expiry_interval = 0; } stored = mosquitto__calloc(1, sizeof(struct mosquitto_msg_store)); if(stored == NULL){ mosquitto__free(load); mosquitto__free(chunk.source.id); mosquitto__free(chunk.source.username); mosquitto__free(chunk.topic); mosquitto__free(chunk.payload); log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } stored->source_mid = chunk.F.source_mid; stored->topic = chunk.topic; stored->qos = chunk.F.qos; stored->payloadlen = chunk.F.payloadlen; stored->retain = chunk.F.retain; stored->properties = chunk.properties; stored->payload = chunk.payload; rc = db__message_store(&chunk.source, stored, message_expiry_interval, 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); return rc; } } static int persist__retain_chunk_restore(FILE *db_fptr) { struct mosquitto_msg_store_load *load; struct P_retain chunk; int rc; char **split_topics; char *local_topic; memset(&chunk, 0, sizeof(struct P_retain)); if(db_version == 6 || db_version == 5){ rc = persist__chunk_retain_read_v56(db_fptr, &chunk); }else{ rc = persist__chunk_retain_read_v234(db_fptr, &chunk); } if(rc){ return rc; } HASH_FIND(hh, db.msg_store_load, &chunk.F.store_id, sizeof(dbid_t), load); if(load){ if(sub__topic_tokenise(load->store->topic, &local_topic, &split_topics, NULL)) return 1; retain__store(load->store->topic, load->store, split_topics); mosquitto__free(local_topic); mosquitto__free(split_topics); }else{ /* Can't find the message - probably expired */ } return MOSQ_ERR_SUCCESS; } static int persist__sub_chunk_restore(FILE *db_fptr) { struct P_sub chunk; int rc; memset(&chunk, 0, sizeof(struct P_sub)); if(db_version == 6 || db_version == 5){ rc = persist__chunk_sub_read_v56(db_fptr, &chunk); }else{ rc = persist__chunk_sub_read_v234(db_fptr, &chunk); } if(rc){ return rc; } rc = persist__restore_sub(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, uint32_t *chunk, uint32_t *length) { if(db_version == 6 || db_version == 5){ return persist__chunk_header_read_v56(db_fptr, chunk, length); }else{ return persist__chunk_header_read_v234(db_fptr, chunk, length); } } int persist__restore(void) { FILE *fptr; char header[15]; int rc = 0; uint32_t crc; uint32_t i32temp; uint32_t chunk, length; size_t rlen; char *err; struct mosquitto_msg_store_load *load, *load_tmp; struct PF_cfg cfg_chunk; 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){ if(db_version == 5){ /* Addition of username and listener_port to client chunk in v6 */ }else 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 == 6 || db_version == 5){ if(persist__chunk_cfg_read_v56(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(fptr, length)){ fclose(fptr); return 1; } break; case DB_CHUNK_CLIENT_MSG: if(persist__client_msg_chunk_restore(fptr, length)){ fclose(fptr); return 1; } break; case DB_CHUNK_RETAIN: if(persist__retain_chunk_restore(fptr)){ fclose(fptr); return 1; } break; case DB_CHUNK_SUB: if(persist__sub_chunk_restore(fptr)){ fclose(fptr); return 1; } break; case DB_CHUNK_CLIENT: if(persist__client_chunk_restore(fptr)){ fclose(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; } } }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(const char *client_id, const char *sub, uint8_t qos, uint32_t identifier, int options) { struct mosquitto *context; assert(client_id); assert(sub); context = persist__find_or_add_context(client_id, 0); if(!context) return 1; return sub__add(context, sub, qos, identifier, options, &db.subs); } #endif mosquitto-2.0.11/src/bridge.c0000664000175000017500000006463614060132747015071 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #ifndef WIN32 #include #include #else #include #include #endif #ifndef WIN32 #include #else #include #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); void bridge__start_all(void) { int i; for(i=0; ibridge_count; i++){ if(bridge__new(&(db.config->bridges[i])) > 0){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Unable to connect to bridge %s.", db.config->bridges[i].name); } } } int bridge__new(struct mosquitto__bridge *bridge) { struct mosquitto *new_context = NULL; struct mosquitto **bridges; char *local_id; 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(INVALID_SOCKET); 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; new_context->ssl_ctx_defaults = true; #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; if(bridge->clean_start_local == -1){ /* default to "regular" clean start setting */ bridge->clean_start_local = bridge->clean_start; } new_context->retain_available = bridge->outgoing_retain; new_context->protocol = bridge->protocol_version; bridges = mosquitto__realloc(db.bridges, (size_t)(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(new_context); #else return bridge__connect(new_context); #endif } #if defined(__GLIBC__) && defined(WITH_ADNS) int bridge__connect_step1(struct mosquitto *context) { int rc; char *notification_topic; size_t notification_topic_len; uint8_t notification_payload; int i; uint8_t qos; if(!context || !context->bridge) return MOSQ_ERR_INVAL; mosquitto__set_state(context, mosq_cs_new); context->sock = INVALID_SOCKET; context->last_msg_in = db.now_s; context->next_msg_out = db.now_s + 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; context->maximum_packet_size = context->bridge->maximum_packet_size; bridge__packet_cleanup(context); db__message_reconnect_reset(context); db__messages_delete(context, false); /* 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(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(context->bridge->topics[i].qos > context->max_qos){ qos = context->max_qos; }else{ qos = context->bridge->topics[i].qos; } if(sub__add(context, context->bridge->topics[i].local_topic, qos, 0, MQTT_SUB_OPT_NO_LOCAL | MQTT_SUB_OPT_RETAIN_AS_PUBLISHED, &db.subs) > 0){ return 1; } retain__queue(context, context->bridge->topics[i].local_topic, 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->max_qos == 0){ qos = 0; }else{ qos = 1; } if(context->bridge->notification_topic){ if(!context->bridge->initial_notification_done){ notification_payload = '0'; db__messages_easy_queue(context, context->bridge->notification_topic, qos, 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, qos, 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(context, notification_topic, qos, 1, ¬ification_payload, 1, 0, NULL); context->bridge->initial_notification_done = true; } notification_payload = '0'; rc = will__set(context, notification_topic, 1, ¬ification_payload, qos, 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){ mux__delete(context); net__socket_close(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 *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){ mux__delete(context); net__socket_close(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); mux__add_out(context); } return rc; } int bridge__connect_step3(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){ mux__delete(context); net__socket_close(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 = db.now_s + 5; } rc = send__connect(context, context->keepalive, context->clean_start, NULL); if(rc == MOSQ_ERR_SUCCESS){ return MOSQ_ERR_SUCCESS; }else if(rc == MOSQ_ERR_ERRNO && errno == ENOTCONN){ 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)); } mux__delete(context); net__socket_close(context); return rc; } } #else int bridge__connect(struct mosquitto *context) { int rc, rc2; int i; char *notification_topic = NULL; size_t notification_topic_len; uint8_t notification_payload; uint8_t qos; if(!context || !context->bridge) return MOSQ_ERR_INVAL; mosquitto__set_state(context, mosq_cs_new); context->sock = INVALID_SOCKET; context->last_msg_in = db.now_s; context->next_msg_out = db.now_s + 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; context->maximum_packet_size = context->bridge->maximum_packet_size; bridge__packet_cleanup(context); db__message_reconnect_reset(context); db__messages_delete(context, false); /* 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(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(context->bridge->topics[i].qos > context->max_qos){ qos = context->max_qos; }else{ qos = context->bridge->topics[i].qos; } if(sub__add(context, context->bridge->topics[i].local_topic, 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->max_qos == 0){ qos = 0; }else{ qos = 1; } if(context->bridge->notification_topic){ if(!context->bridge->initial_notification_done){ notification_payload = '0'; db__messages_easy_queue(context, context->bridge->notification_topic, qos, 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, qos, 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(context, notification_topic, qos, 1, ¬ification_payload, 1, 0, NULL); context->bridge->initial_notification_done = true; } notification_payload = '0'; rc = will__set(context, notification_topic, 1, ¬ification_payload, qos, true, NULL); if(rc != MOSQ_ERR_SUCCESS){ mosquitto__free(notification_topic); return rc; } mosquitto__free(notification_topic); } } 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, context->bridge->bind_address, false); if(rc > 0){ if(rc == MOSQ_ERR_TLS){ mux__delete(context); net__socket_close(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); mux__add_out(context); } 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){ return rc; }else if(rc2 == MOSQ_ERR_ERRNO && errno == ENOTCONN){ 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)); } mux__delete(context); net__socket_close(context); return rc2; } } #endif int bridge__on_connect(struct mosquitto *context) { int i; char *notification_topic; size_t notification_topic_len; char notification_payload; int sub_opts; bool retain = true; uint8_t qos; if(context->bridge->notifications){ if(context->max_qos == 0){ qos = 0; }else{ qos = 1; } if(!context->retain_available){ retain = false; } 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, qos, retain, 0, NULL, NULL, 0)){ return 1; } } db__messages_easy_queue(context, context->bridge->notification_topic, qos, 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, qos, retain, 0, NULL, NULL, 0)){ mosquitto__free(notification_topic); return 1; } } db__messages_easy_queue(context, notification_topic, qos, 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(context->bridge->topics[i].qos > context->max_qos){ sub_opts = context->max_qos; }else{ sub_opts = context->bridge->topics[i].qos; } if(context->bridge->protocol_version == mosq_p_mqtt5){ sub_opts = sub_opts | MQTT_SUB_OPT_NO_LOCAL | MQTT_SUB_OPT_RETAIN_AS_PUBLISHED | MQTT_SUB_OPT_SEND_RETAIN_ALWAYS; } if(send__subscribe(context, NULL, 1, &context->bridge->topics[i].remote_topic, sub_opts, 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){ if(context->bridge->topics[i].qos > context->max_qos){ qos = context->max_qos; }else{ qos = context->bridge->topics[i].qos; } retain__queue(context, context->bridge->topics[i].local_topic, qos, 0); } } bridge__backoff_reset(context); return MOSQ_ERR_SUCCESS; } int bridge__register_local_connections(void) { struct mosquitto *context, *ctxt_tmp = NULL; HASH_ITER(hh_sock, db.contexts_by_sock, context, ctxt_tmp){ if(context->bridge){ if(mux__add_in(context)){ log__printf(NULL, MOSQ_LOG_ERR, "Error in initial bridge registration: %s", strerror(errno)); return MOSQ_ERR_UNKNOWN; } mux__add_out(context); } } return MOSQ_ERR_SUCCESS; } void bridge__cleanup(struct mosquitto *context) { int i; for(i=0; ibridge->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; #ifdef WITH_TLS if(context->ssl_ctx){ SSL_CTX_free(context->ssl_ctx); context->ssl_ctx = NULL; } #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; context->out_packet_count = 0; packet__cleanup(&(context->in_packet)); } static int rand_between(int low, int high) { int r; util__random_bytes(&r, sizeof(int)); return (abs(r) % (high - low)) + low; } 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; } } static void bridge_check_pending(struct mosquitto *context) { int err; socklen_t len; 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(context); } #endif }else if(err == ECONNREFUSED){ do_disconnect(context, MOSQ_ERR_CONN_LOST); return; } }else{ do_disconnect(context, MOSQ_ERR_CONN_LOST); return; } } } void bridge_check(void) { static time_t last_check = 0; struct mosquitto *context = NULL; socklen_t len; int i; int rc; int err; if(db.now_s <= last_check) return; for(i=0; isock != INVALID_SOCKET){ mosquitto__check_keepalive(context); bridge_check_pending(context); /* Check for bridges that are not round robin and not currently * connected to their primary broker. */ if(context->bridge->round_robin == false && context->bridge->cur_address != 0 && context->bridge->primary_retry && db.now_s > 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, context->bridge->bind_address, false); if(rc == 0){ COMPAT_CLOSE(context->bridge->primary_retry_sock); context->bridge->primary_retry_sock = INVALID_SOCKET; context->bridge->primary_retry = 0; mux__delete(context); net__socket_close(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; mux__delete(context); net__socket_close(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 = db.now_s+5; } }else{ COMPAT_CLOSE(context->bridge->primary_retry_sock); context->bridge->primary_retry_sock = INVALID_SOCKET; context->bridge->primary_retry = db.now_s+5; } } } } if(context->sock == INVALID_SOCKET){ /* Want to try to restart the bridge connection */ if(!context->bridge->restart_t){ context->bridge->restart_t = db.now_s+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 && db.now_s > 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(context); if(rc == MOSQ_ERR_SUCCESS){ mux__add_in(context); if(context->current_out_packet){ mux__add_out(context); } }else if(rc == MOSQ_ERR_CONN_PENDING){ mux__add_in(context); mux__add_out(context); 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{ rc = bridge__connect_step1(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(context); context->bridge->restart_t = 0; if(rc == MOSQ_ERR_SUCCESS || rc == MOSQ_ERR_CONN_PENDING){ if(context->bridge->round_robin == false && context->bridge->cur_address != 0){ context->bridge->primary_retry = db.now_s + 5; } mux__add_in(context); if(context->current_out_packet){ mux__add_out(context); } }else{ context->bridge->cur_address++; if(context->bridge->cur_address == context->bridge->address_count){ context->bridge->cur_address = 0; } } } #endif } } } } } #endif mosquitto-2.0.11/src/xtreport.c0000664000175000017500000000645114060132747015513 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifdef WITH_XTREPORT /* This file allows reporting of internal parameters to a kcachegrind * compatible output file. It is for debugging purposes only and is most likely * of no interest to end users. */ #include "config.h" #include #include #include "mosquitto_broker_internal.h" #include "mosquitto_internal.h" #include "net_mosq.h" static void client_cost(FILE *fptr, struct mosquitto *context, int fn_index) { size_t pkt_count, pkt_bytes; size_t cmsg_count, cmsg_bytes; struct mosquitto__packet *pkt_tmp; size_t tBytes; pkt_count = 1; pkt_bytes = context->in_packet.packet_length; if(context->current_out_packet){ pkt_count++; pkt_bytes += context->current_out_packet->packet_length; } pkt_tmp = context->out_packet; while(pkt_tmp){ pkt_count++; pkt_bytes += pkt_tmp->packet_length; pkt_tmp = pkt_tmp->next; } cmsg_count = (size_t)context->msgs_in.msg_count; cmsg_bytes = context->msgs_in.msg_bytes; cmsg_count += (size_t)context->msgs_out.msg_count; cmsg_bytes += context->msgs_out.msg_bytes; tBytes = pkt_bytes + cmsg_bytes; if(context->id){ tBytes += strlen(context->id); } fprintf(fptr, "%d %ld %lu %lu %lu %lu %d\n", fn_index, tBytes, pkt_count, cmsg_count, pkt_bytes, cmsg_bytes, context->sock == INVALID_SOCKET?0:context->sock); } void xtreport(void) { pid_t pid; char filename[40]; FILE *fptr; struct mosquitto *context, *ctxt_tmp; int fn_index = 2; static int iter = 1; pid = getpid(); snprintf(filename, 40, "/tmp/xtmosquitto.kcg.%d.%d", pid, iter); iter++; fptr = fopen(filename, "wt"); if(fptr == NULL) return; fprintf(fptr, "# callgrind format\n"); fprintf(fptr, "version: 1\n"); fprintf(fptr, "creator: mosquitto\n"); fprintf(fptr, "pid: %d\n", pid); fprintf(fptr, "cmd: mosquitto\n\n"); fprintf(fptr, "positions: line\n"); fprintf(fptr, "event: tB : total bytes\n"); fprintf(fptr, "event: pkt : currently queued packets\n"); fprintf(fptr, "event: cmsg : currently pending client messages\n"); fprintf(fptr, "event: pktB : currently queued packet bytes\n"); fprintf(fptr, "event: cmsgB : currently pending client message bytes\n"); fprintf(fptr, "events: tB pkt cmsg pktB cmsgB sock\n"); fprintf(fptr, "fn=(1) clients\n"); fprintf(fptr, "1 0 0 0 0 0 0\n"); fn_index = 2; HASH_ITER(hh_id, db.contexts_by_id, context, ctxt_tmp){ if(context->id){ fprintf(fptr, "cfn=(%d) %s\n", fn_index, context->id); }else{ fprintf(fptr, "cfn=(%d) unknown\n", fn_index); } fprintf(fptr, "calls=1 %d\n", fn_index); client_cost(fptr, context, fn_index); fn_index++; } fn_index = 2; HASH_ITER(hh_id, db.contexts_by_id, context, ctxt_tmp){ fprintf(fptr, "fn=(%d)\n", fn_index); client_cost(fptr, context, fn_index); fn_index++; } fclose(fptr); } #endif mosquitto-2.0.11/src/send_suback.c0000664000175000017500000000326614060132747016106 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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; 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){ packet->remaining_length += property__get_remaining_length(properties); } 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-2.0.11/src/bridge_topic.c0000664000175000017500000001537614060132747016264 0ustar rogerroger/* Copyright (c) 2009-2019 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include "mosquitto.h" #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #ifdef WITH_BRIDGE static int bridge__create_remap_topic(const char *prefix, const char *topic, char **remap_topic) { size_t len; if(prefix){ if(topic){ len = strlen(topic) + strlen(prefix)+1; *remap_topic = mosquitto__malloc(len+1); if(!(*remap_topic)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } snprintf(*remap_topic, len+1, "%s%s", prefix, topic); (*remap_topic)[len] = '\0'; }else{ *remap_topic = mosquitto__strdup(prefix); if(!(*remap_topic)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } }else{ *remap_topic = mosquitto__strdup(topic); if(!(*remap_topic)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } return MOSQ_ERR_SUCCESS; } static int bridge__create_prefix(char **full_prefix, const char *topic, const char *prefix, const char *direction) { size_t len; if(mosquitto_pub_topic_check(prefix) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic local prefix '%s'.", prefix); return MOSQ_ERR_INVAL; } if(topic){ len = strlen(topic) + strlen(prefix) + 1; }else{ len = strlen(prefix) + 1; } *full_prefix = mosquitto__malloc(len); if(*full_prefix == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } if(topic){ /* Print full_prefix+pattern to check for validity */ snprintf(*full_prefix, len, "%s%s", prefix, topic); }else{ snprintf(*full_prefix, len, "%s", prefix); } if(mosquitto_sub_topic_check(*full_prefix) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic %s prefix and pattern combination '%s'.", direction, *full_prefix); return MOSQ_ERR_INVAL; } /* Print just the prefix for storage */ snprintf(*full_prefix, len, "%s", prefix); return MOSQ_ERR_SUCCESS; } /* topic [[[out | in | both] qos-level] local-prefix remote-prefix] */ int bridge__add_topic(struct mosquitto__bridge *bridge, const char *topic, enum mosquitto__bridge_direction direction, uint8_t qos, const char *local_prefix, const char *remote_prefix) { struct mosquitto__bridge_topic *topics; struct mosquitto__bridge_topic *cur_topic; if(bridge == NULL) return MOSQ_ERR_INVAL; if(direction != bd_out && direction != bd_in && direction != bd_both){ return MOSQ_ERR_INVAL; } if(qos > 2){ return MOSQ_ERR_INVAL; } if(local_prefix && mosquitto_pub_topic_check(local_prefix)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic local prefix '%s'.", local_prefix); return MOSQ_ERR_INVAL; } if(remote_prefix && mosquitto_pub_topic_check(remote_prefix)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic remote prefix '%s'.", remote_prefix); return MOSQ_ERR_INVAL; } if((topic == NULL || !strcmp(topic, "\"\"")) && (local_prefix == NULL || remote_prefix == NULL)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge remapping."); return MOSQ_ERR_INVAL; } bridge->topic_count++; topics = mosquitto__realloc(bridge->topics, sizeof(struct mosquitto__bridge_topic)*(size_t)bridge->topic_count); if(topics == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } bridge->topics = topics; cur_topic = &bridge->topics[bridge->topic_count-1]; cur_topic->direction = direction; cur_topic->qos = qos; cur_topic->local_prefix = NULL; cur_topic->remote_prefix = NULL; if(topic == NULL || !strcmp(topic, "\"\"")){ cur_topic->topic = NULL; }else{ cur_topic->topic = mosquitto__strdup(topic); if(cur_topic->topic == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } if(local_prefix || remote_prefix){ bridge->topic_remapping = true; if(local_prefix){ if(bridge__create_prefix(&cur_topic->local_prefix, cur_topic->topic, local_prefix, "local")){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } if(remote_prefix){ if(bridge__create_prefix(&cur_topic->remote_prefix, cur_topic->topic, remote_prefix, "local")){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } } if(bridge__create_remap_topic(cur_topic->local_prefix, cur_topic->topic, &cur_topic->local_topic)){ return MOSQ_ERR_INVAL; } if(bridge__create_remap_topic(cur_topic->remote_prefix, cur_topic->topic, &cur_topic->remote_topic)){ return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } int bridge__remap_topic_in(struct mosquitto *context, char **topic) { struct mosquitto__bridge_topic *cur_topic; char *topic_temp; int i; size_t len; int rc; bool match; 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; } } } } return MOSQ_ERR_SUCCESS; } #endif mosquitto-2.0.11/src/linker.syms0000664000175000017500000000171214060132747015654 0ustar rogerroger{ mosquitto_broker_publish; mosquitto_broker_publish_copy; mosquitto_callback_register; mosquitto_callback_unregister; mosquitto_calloc; mosquitto_client_address; mosquitto_client_certificate; mosquitto_client_clean_session; mosquitto_client_id; mosquitto_client_keepalive; mosquitto_client_protocol; mosquitto_client_protocol_version; mosquitto_client_sub_count; mosquitto_client_username; mosquitto_free; mosquitto_kick_client_by_clientid; mosquitto_kick_client_by_username; mosquitto_log_printf; mosquitto_malloc; 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_free_all; mosquitto_pub_topic_check; mosquitto_realloc; mosquitto_set_username; mosquitto_strdup; mosquitto_sub_topic_check; mosquitto_topic_matches_sub; mosquitto_validate_utf8; }; mosquitto-2.0.11/src/read_handle.c0000664000175000017500000000523614060132747016052 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *context) { int rc = MOSQ_ERR_INVAL; 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(context, "PUBACK"); case CMD_PUBCOMP: return handle__pubackcomp(context, "PUBCOMP"); case CMD_PUBLISH: rc = handle__publish(context); break; case CMD_PUBREC: return handle__pubrec(context); case CMD_PUBREL: return handle__pubrel(context); case CMD_CONNECT: return handle__connect(context); case CMD_DISCONNECT: return handle__disconnect(context); case CMD_SUBSCRIBE: rc = handle__subscribe(context); break; case CMD_UNSUBSCRIBE: rc = handle__unsubscribe(context); break; #ifdef WITH_BRIDGE case CMD_CONNACK: return handle__connack(context); case CMD_SUBACK: return handle__suback(context); case CMD_UNSUBACK: return handle__unsuback(context); #endif case CMD_AUTH: return handle__auth(context); default: rc = MOSQ_ERR_PROTOCOL; } if(context->protocol == mosq_p_mqtt5){ if(rc == MOSQ_ERR_PROTOCOL){ send__disconnect(context, MQTT_RC_PROTOCOL_ERROR, NULL); }else if(rc == MOSQ_ERR_MALFORMED_PACKET){ send__disconnect(context, MQTT_RC_MALFORMED_PACKET, NULL); }else if(rc == MOSQ_ERR_QOS_NOT_SUPPORTED){ send__disconnect(context, MQTT_RC_QOS_NOT_SUPPORTED, NULL); }else if(rc == MOSQ_ERR_RETAIN_NOT_SUPPORTED){ send__disconnect(context, MQTT_RC_RETAIN_NOT_SUPPORTED, NULL); }else if(rc == MOSQ_ERR_TOPIC_ALIAS_INVALID){ send__disconnect(context, MQTT_RC_TOPIC_ALIAS_INVALID, NULL); }else if(rc == MOSQ_ERR_UNKNOWN || rc == MOSQ_ERR_NOMEM){ send__disconnect(context, MQTT_RC_UNSPECIFIED, NULL); } } return rc; } mosquitto-2.0.11/src/password_mosq.c0000664000175000017500000001053614060132747016524 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #ifdef WITH_TLS # include # include # include # include #endif #include #include #include #include #include "mosquitto.h" #include "mosquitto_broker.h" #include "password_mosq.h" #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 #ifdef WITH_TLS int base64__encode(unsigned char *in, unsigned int in_len, char **encoded) { BIO *bmem, *b64; BUF_MEM *bptr; b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bmem = BIO_new(BIO_s_mem()); b64 = BIO_push(b64, bmem); BIO_write(b64, in, (int)in_len); if(BIO_flush(b64) != 1){ BIO_free_all(b64); return 1; } BIO_get_mem_ptr(b64, &bptr); *encoded = malloc(bptr->length+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; } int base64__decode(char *in, unsigned char **decoded, unsigned int *decoded_len) { BIO *bmem, *b64; size_t slen; int len; 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, (int)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; } len = BIO_read(b64, *decoded, (int)slen); BIO_free_all(b64); if(len <= 0){ mosquitto_free(*decoded); *decoded = NULL; *decoded_len = 0; return 1; } *decoded_len = (unsigned int)len; return 0; } int pw__hash(const char *password, struct mosquitto_pw *pw, bool new_password, int new_iterations) { int rc; unsigned int hash_len; const EVP_MD *digest; int iterations; #if OPENSSL_VERSION_NUMBER < 0x10100000L EVP_MD_CTX context; #else EVP_MD_CTX *context; #endif if(new_password){ rc = RAND_bytes(pw->salt, sizeof(pw->salt)); if(!rc){ return MOSQ_ERR_UNKNOWN; } iterations = new_iterations; }else{ iterations = pw->iterations; } if(iterations < 1){ return MOSQ_ERR_INVAL; } digest = EVP_get_digestbyname("sha512"); if(!digest){ return MOSQ_ERR_UNKNOWN; } if(pw->hashtype == pw_sha512){ #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, pw->salt, sizeof(pw->salt)); EVP_DigestFinal_ex(&context, pw->password_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, pw->salt, sizeof(pw->salt)); EVP_DigestFinal_ex(context, pw->password_hash, &hash_len); EVP_MD_CTX_free(context); #endif }else{ pw->iterations = iterations; hash_len = sizeof(pw->password_hash); PKCS5_PBKDF2_HMAC(password, (int)strlen(password), pw->salt, sizeof(pw->salt), iterations, digest, (int)hash_len, pw->password_hash); } return MOSQ_ERR_SUCCESS; } #endif int pw__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; i All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), LANG_NEUTRAL, (LPTSTR)&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; UNUSED(dwArgc); UNUSED(lpszArgv); service_handle = RegisterServiceCtrlHandler("mosquitto", service_handler); if(service_handle){ memset(conf_path, 0, sizeof(conf_path)); 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 service_string[MAX_PATH + 20]; char exe_path[MAX_PATH + 1]; SERVICE_DESCRIPTION svc_desc; memset(exe_path, 0, sizeof(exe_path)); if(GetModuleFileName(NULL, exe_path, MAX_PATH) == MAX_PATH){ fprintf(stderr, "Error: Path too long.\n"); return; } snprintf(service_string, sizeof(service_string), "\"%s\" run", exe_path); 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, service_string, NULL, NULL, NULL, NULL, NULL); if(svc_handle){ svc_desc.lpDescription = "Eclipse Mosquitto MQTT v5/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-2.0.11/src/loop.c0000664000175000017500000002366114060132747014577 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. Tatsuzo Osawa - Add epoll. */ #include "config.h" #ifndef WIN32 # define _GNU_SOURCE #endif #include #ifndef WIN32 #include #else #include #include #include #endif #include #include #include #include #ifndef WIN32 # include #endif #include #include #ifdef WITH_WEBSOCKETS # include #endif #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "mqtt_protocol.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; #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 static int single_publish(struct mosquitto *context, struct mosquitto_message_v5 *msg, uint32_t message_expiry) { struct mosquitto_msg_store *stored; uint16_t mid; stored = mosquitto__calloc(1, sizeof(struct mosquitto_msg_store)); if(stored == NULL) return MOSQ_ERR_NOMEM; stored->topic = msg->topic; msg->topic = NULL; stored->retain = 0; stored->payloadlen = (uint32_t)msg->payloadlen; stored->payload = mosquitto__malloc(stored->payloadlen+1); if(stored->payload == NULL){ db__msg_store_free(stored); return MOSQ_ERR_NOMEM; } /* Ensure payload is always zero terminated, this is the reason for the extra byte above */ ((uint8_t *)stored->payload)[stored->payloadlen] = 0; memcpy(stored->payload, msg->payload, stored->payloadlen); if(msg->properties){ stored->properties = msg->properties; msg->properties = NULL; } if(db__message_store(context, stored, message_expiry, 0, mosq_mo_broker)) return 1; if(msg->qos){ mid = mosquitto__mid_generate(context); }else{ mid = 0; } return db__message_insert(context, mid, mosq_md_out, (uint8_t)msg->qos, 0, stored, msg->properties, true); } static void read_message_expiry_interval(mosquitto_property **proplist, uint32_t *message_expiry) { mosquitto_property *p, *previous = NULL; *message_expiry = 0; if(!proplist) return; p = *proplist; while(p){ if(p->identifier == MQTT_PROP_MESSAGE_EXPIRY_INTERVAL){ *message_expiry = p->value.i32; if(p == *proplist){ *proplist = p->next; }else{ previous->next = p->next; } property__free(&p); return; } previous = p; p = p->next; } } static void queue_plugin_msgs(void) { struct mosquitto_message_v5 *msg, *tmp; struct mosquitto *context; uint32_t message_expiry; DL_FOREACH_SAFE(db.plugin_msgs, msg, tmp){ DL_DELETE(db.plugin_msgs, msg); read_message_expiry_interval(&msg->properties, &message_expiry); if(msg->clientid){ HASH_FIND(hh_id, db.contexts_by_id, msg->clientid, strlen(msg->clientid), context); if(context){ single_publish(context, msg, message_expiry); } }else{ db__messages_easy_queue(NULL, msg->topic, (uint8_t)msg->qos, (uint32_t)msg->payloadlen, msg->payload, msg->retain, message_expiry, &msg->properties); } mosquitto__free(msg->topic); mosquitto__free(msg->payload); mosquitto_property_free_all(&msg->properties); mosquitto__free(msg->clientid); mosquitto__free(msg); } } int mosquitto_main_loop(struct mosquitto__listener_sock *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 #ifdef WITH_WEBSOCKETS int i; #endif int rc; #if defined(WITH_WEBSOCKETS) && LWS_LIBRARY_VERSION_NUMBER == 3002000 memset(&sul, 0, sizeof(struct lws_sorted_usec_list)); #endif db.now_s = mosquitto_time(); db.now_real_s = time(NULL); #ifdef WITH_BRIDGE rc = bridge__register_local_connections(); if(rc) return rc; #endif while(run){ queue_plugin_msgs(); context__free_disused(); #ifdef WITH_SYS_TREE if(db.config->sys_interval > 0){ sys_tree__update(db.config->sys_interval, start_time); } #endif keepalive__check(); #ifdef WITH_BRIDGE bridge_check(); #endif rc = mux__handle(listensock, listensock_count); if(rc) return rc; session_expiry__check(); will_delay__check(); #ifdef WITH_PERSISTENCE if(db.config->persistence && db.config->autosave_interval){ if(db.config->autosave_on_changes){ if(db.persistence_changes >= db.config->autosave_interval){ persist__backup(false); db.persistence_changes = 0; } }else{ if(last_backup + db.config->autosave_interval < db.now_s){ persist__backup(false); last_backup = db.now_s; } } } #endif #ifdef WITH_PERSISTENCE if(flag_db_backup){ persist__backup(false); flag_db_backup = false; } #endif if(flag_reload){ log__printf(NULL, MOSQ_LOG_INFO, "Reloading config."); config__read(db.config, true); listeners__reload_all_certificates(); mosquitto_security_cleanup(true); mosquitto_security_init(true); mosquitto_security_apply(); 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_XTREPORT xtreport(); #endif } #ifdef WITH_WEBSOCKETS for(i=0; ilistener_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 lws_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); lws_service(db.config->listeners[i].ws_context, 0); #else lws_service(db.config->listeners[i].ws_context, 0); #endif } } #endif plugin__handle_tick(); } mux__cleanup(); return MOSQ_ERR_SUCCESS; } void do_disconnect(struct mosquitto *context, int reason) { const char *id; #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){ lws_callback_on_writable(context->wsi); } if(context->sock != INVALID_SOCKET){ HASH_DELETE(hh_sock, db.contexts_by_sock, context); mux__delete(context); context->sock = INVALID_SOCKET; } 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(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_MALFORMED_PACKET: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s disconnected due to malformed packet.", id); 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, "Client %s closed its connection.", id); break; case MOSQ_ERR_AUTH: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s disconnected, not authorised.", id); break; case MOSQ_ERR_KEEPALIVE: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s has exceeded timeout, disconnecting.", id); break; case MOSQ_ERR_OVERSIZE_PACKET: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s disconnected due to oversize packet.", id); break; case MOSQ_ERR_PAYLOAD_SIZE: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s disconnected due to oversize payload.", id); break; case MOSQ_ERR_NOMEM: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s disconnected due to out of memory.", id); break; case MOSQ_ERR_NOT_SUPPORTED: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s disconnected due to QoS too high or retain not supported.", id); break; case MOSQ_ERR_ADMINISTRATIVE_ACTION: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s been disconnected by administrative action.", id); break; case MOSQ_ERR_ERRNO: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s disconnected: %s.", id, strerror(errno)); break; default: log__printf(NULL, MOSQ_LOG_NOTICE, "Bad socket read/write on client %s: %s", id, mosquitto_strerror(reason)); break; } }else{ if(reason == MOSQ_ERR_ADMINISTRATIVE_ACTION){ log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s been disconnected by administrative action.", id); }else{ log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s disconnected.", id); } } } mux__delete(context); context__disconnect(context); } } mosquitto-2.0.11/src/mosquitto.c0000664000175000017500000003723014060132747015667 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 db; static struct mosquitto__listener_sock *listensock = NULL; static int listensock_count = 0; static int listensock_index = 0; 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 /* 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) { #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){ if(strcmp(config->user, "mosquitto")){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to drop privileges to '%s' because this user does not exist.", config->user); return 1; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Warning: Unable to drop privileges to '%s' because this user does not exist. Trying 'nobody' instead.", config->user); pwd = getpwnam("nobody"); if(!pwd){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to drop privileges to 'nobody'."); 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; } 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; } 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."); } } #else UNUSED(config); #endif return MOSQ_ERR_SUCCESS; } static 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 } void listener__set_defaults(struct mosquitto__listener *listener) { listener->security_options.allow_anonymous = -1; listener->security_options.allow_zero_length_clientid = true; listener->protocol = mp_mqtt; listener->max_connections = -1; listener->max_qos = 2; listener->max_topic_alias = 10; } void listeners__reload_all_certificates(void) { #ifdef WITH_TLS int i; int rc; struct mosquitto__listener *listener; for(i=0; ilistener_count; i++){ listener = &db.config->listeners[i]; if(listener->ssl_ctx && listener->certfile && listener->keyfile){ rc = net__load_certificates(listener); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error when reloading certificate '%s' or key '%s'.", listener->certfile, listener->keyfile); } } } #endif } static int listeners__start_single_mqtt(struct mosquitto__listener *listener) { int i; struct mosquitto__listener_sock *listensock_new; if(net__socket_listen(listener)){ return 1; } listensock_count += listener->sock_count; listensock_new = mosquitto__realloc(listensock, sizeof(struct mosquitto__listener_sock)*(size_t)listensock_count); if(!listensock_new){ return 1; } listensock = listensock_new; for(i=0; isock_count; i++){ if(listener->socks[i] == INVALID_SOCKET){ return 1; } listensock[listensock_index].sock = listener->socks[i]; listensock[listensock_index].listener = listener; #ifdef WITH_EPOLL listensock[listensock_index].ident = id_listener; #endif listensock_index++; } return MOSQ_ERR_SUCCESS; } #ifdef WITH_WEBSOCKETS void listeners__add_websockets(struct lws_context *ws_context, mosq_sock_t fd) { int i; struct mosquitto__listener *listener = NULL; struct mosquitto__listener_sock *listensock_new; /* Don't add more listeners after we've started the main loop */ if(run || ws_context == NULL) return; /* Find context */ for(i=0; ilistener_count; i++){ if(db.config->listeners[i].ws_in_init){ listener = &db.config->listeners[i]; break; } } if(listener == NULL){ return; } listensock_count++; listensock_new = mosquitto__realloc(listensock, sizeof(struct mosquitto__listener_sock)*(size_t)listensock_count); if(!listensock_new){ return; } listensock = listensock_new; listensock[listensock_index].sock = fd; listensock[listensock_index].listener = listener; #ifdef WITH_EPOLL listensock[listensock_index].ident = id_listener_ws; #endif listensock_index++; } #endif static int listeners__add_local(const char *host, uint16_t port) { struct mosquitto__listener *listeners; listeners = db.config->listeners; listener__set_defaults(&listeners[db.config->listener_count]); listeners[db.config->listener_count].security_options.allow_anonymous = true; listeners[db.config->listener_count].port = port; listeners[db.config->listener_count].host = mosquitto__strdup(host); if(listeners[db.config->listener_count].host == NULL){ return MOSQ_ERR_NOMEM; } if(listeners__start_single_mqtt(&listeners[db.config->listener_count])){ mosquitto__free(listeners[db.config->listener_count].host); listeners[db.config->listener_count].host = NULL; return MOSQ_ERR_UNKNOWN; } db.config->listener_count++; return MOSQ_ERR_SUCCESS; } static int listeners__start_local_only(void) { /* Attempt to open listeners bound to 127.0.0.1 and ::1 only */ int i; int rc; struct mosquitto__listener *listeners; listeners = mosquitto__realloc(db.config->listeners, 2*sizeof(struct mosquitto__listener)); if(listeners == NULL){ return MOSQ_ERR_NOMEM; } memset(listeners, 0, 2*sizeof(struct mosquitto__listener)); db.config->listener_count = 0; db.config->listeners = listeners; log__printf(NULL, MOSQ_LOG_WARNING, "Starting in local only mode. Connections will only be possible from clients running on this machine."); log__printf(NULL, MOSQ_LOG_WARNING, "Create a configuration file which defines a listener to allow remote access."); log__printf(NULL, MOSQ_LOG_WARNING, "For more details see https://mosquitto.org/documentation/authentication-methods/"); if(db.config->cmd_port_count == 0){ rc = listeners__add_local("127.0.0.1", 1883); if(rc == MOSQ_ERR_NOMEM) return MOSQ_ERR_NOMEM; rc = listeners__add_local("::1", 1883); if(rc == MOSQ_ERR_NOMEM) return MOSQ_ERR_NOMEM; }else{ for(i=0; icmd_port_count; i++){ rc = listeners__add_local("127.0.0.1", db.config->cmd_port[i]); if(rc == MOSQ_ERR_NOMEM) return MOSQ_ERR_NOMEM; rc = listeners__add_local("::1", db.config->cmd_port[i]); if(rc == MOSQ_ERR_NOMEM) return MOSQ_ERR_NOMEM; } } if(db.config->listener_count > 0){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_UNKNOWN; } } static int listeners__start(void) { int i; listensock_count = 0; if(db.config->listener_count == 0){ if(listeners__start_local_only()){ db__close(); if(db.config->pid_file){ (void)remove(db.config->pid_file); } return 1; } return MOSQ_ERR_SUCCESS; } for(i=0; ilistener_count; i++){ if(db.config->listeners[i].protocol == mp_mqtt){ if(listeners__start_single_mqtt(&db.config->listeners[i])){ db__close(); if(db.config->pid_file){ (void)remove(db.config->pid_file); } return 1; } }else if(db.config->listeners[i].protocol == mp_websockets){ #ifdef WITH_WEBSOCKETS mosq_websockets_init(&db.config->listeners[i], db.config); if(!db.config->listeners[i].ws_context){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to create websockets listener on port %d.", db.config->listeners[i].port); return 1; } #endif } } if(listensock == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to start any listening sockets, exiting."); return 1; } return MOSQ_ERR_SUCCESS; } static void listeners__stop(void) { int i; for(i=0; ilistener_count; i++){ #ifdef WITH_WEBSOCKETS if(db.config->listeners[i].ws_context){ lws_context_destroy(db.config->listeners[i].ws_context); } mosquitto__free(db.config->listeners[i].ws_protocol); #endif #ifdef WITH_UNIX_SOCKETS if(db.config->listeners[i].unix_socket_path != NULL){ unlink(db.config->listeners[i].unix_socket_path); } #endif } for(i=0; ipid_file){ pid = mosquitto__fopen(db.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; } } return MOSQ_ERR_SUCCESS; } int main(int argc, char *argv[]) { struct mosquitto__config config; #ifdef WITH_BRIDGE int i; #endif 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((unsigned int)(tv.tv_sec + tv.tv_usec)); #endif #ifdef WIN32 _setmaxstdio(2048); #endif memset(&db, 0, sizeof(struct mosquitto_db)); db.now_s = mosquitto_time(); db.now_real_s = time(NULL); net__broker_init(); config__init(&config); rc = config__parse_args(&config, argc, argv); if(rc != MOSQ_ERR_SUCCESS) return rc; db.config = &config; /* Drop privileges permanently immediately after the config is loaded. * This requires the user to ensure that all certificates, log locations, * etc. are accessible my the `mosquitto` or other unprivileged user. */ rc = drop_privileges(&config); if(rc != MOSQ_ERR_SUCCESS) return rc; if(config.daemon){ mosquitto__daemonise(); } if(pid__write()) return 1; rc = db__open(&config); 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(db.config_file){ log__printf(NULL, MOSQ_LOG_INFO, "Config loaded from %s.", db.config_file); }else{ log__printf(NULL, MOSQ_LOG_INFO, "Using default config."); } rc = mosquitto_security_module_init(); if(rc) return rc; rc = mosquitto_security_init(false); if(rc) return rc; /* After loading persisted clients and ACLs, try to associate them, * so persisted subscriptions can start storing messages */ HASH_ITER(hh_id, db.contexts_by_id, ctxt, ctxt_tmp){ if(ctxt && !ctxt->clean_start && ctxt->username){ rc = acl__find_acls(ctxt); if(rc){ log__printf(NULL, MOSQ_LOG_WARNING, "Failed to associate persisted user %s with ACLs, " "likely due to changed ports while using a per_listener_settings configuration.", ctxt->username); } } } #ifdef WITH_SYS_TREE sys_tree__init(); #endif if(listeners__start()) return 1; rc = mux__init(listensock, listensock_count); if(rc) return rc; signal__setup(); #ifdef WITH_BRIDGE bridge__start_all(); #endif log__printf(NULL, MOSQ_LOG_INFO, "mosquitto version %s running", VERSION); #ifdef WITH_SYSTEMD sd_notify(0, "READY=1"); #endif run = 1; rc = mosquitto_main_loop(listensock, listensock_count); log__printf(NULL, MOSQ_LOG_INFO, "mosquitto version %s terminating", VERSION); /* 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, db.contexts_by_id, ctxt, ctxt_tmp){ context__send_will(ctxt); } will_delay__send_all(); #ifdef WITH_PERSISTENCE persist__backup(true); #endif session_expiry__remove_all(); listeners__stop(); HASH_ITER(hh_id, db.contexts_by_id, ctxt, ctxt_tmp){ #ifdef WITH_WEBSOCKETS if(!ctxt->wsi) #endif { context__cleanup(ctxt, true); } } HASH_ITER(hh_sock, db.contexts_by_sock, ctxt, ctxt_tmp){ context__cleanup(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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifdef WITH_SYS_TREE #include "config.h" #include #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; unsigned int g_clients_expired = 0; unsigned int g_socket_connections = 0; unsigned int g_connection_count = 0; void sys_tree__init(void) { char buf[64]; uint32_t len; if(db.config->sys_interval == 0){ return; } /* Set static $SYS messages */ len = (uint32_t)snprintf(buf, 64, "mosquitto version %s", VERSION); db__messages_easy_queue(NULL, "$SYS/broker/version", SYS_TREE_QOS, len, buf, 1, 0, NULL); } static void sys_tree__update_clients(char *buf) { static unsigned int client_count = UINT_MAX; static unsigned int clients_expired = UINT_MAX; static unsigned int client_max = 0; static unsigned int disconnected_count = UINT_MAX; static unsigned int connected_count = UINT_MAX; uint32_t len; unsigned 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; len = (uint32_t)snprintf(buf, BUFLEN, "%d", client_count); db__messages_easy_queue(NULL, "$SYS/broker/clients/total", SYS_TREE_QOS, len, buf, 1, 60, NULL); if(client_count > client_max){ client_max = client_count; len = (uint32_t)snprintf(buf, BUFLEN, "%d", client_max); db__messages_easy_queue(NULL, "$SYS/broker/clients/maximum", SYS_TREE_QOS, len, buf, 1, 60, NULL); } } if(disconnected_count != count_total-count_by_sock){ disconnected_count = count_total-count_by_sock; len = (uint32_t)snprintf(buf, BUFLEN, "%d", disconnected_count); db__messages_easy_queue(NULL, "$SYS/broker/clients/inactive", SYS_TREE_QOS, len, buf, 1, 60, NULL); db__messages_easy_queue(NULL, "$SYS/broker/clients/disconnected", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(connected_count != count_by_sock){ connected_count = count_by_sock; len = (uint32_t)snprintf(buf, BUFLEN, "%d", connected_count); db__messages_easy_queue(NULL, "$SYS/broker/clients/active", SYS_TREE_QOS, len, buf, 1, 60, NULL); db__messages_easy_queue(NULL, "$SYS/broker/clients/connected", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(g_clients_expired != clients_expired){ clients_expired = g_clients_expired; len = (uint32_t)snprintf(buf, BUFLEN, "%d", clients_expired); db__messages_easy_queue(NULL, "$SYS/broker/clients/expired", SYS_TREE_QOS, len, buf, 1, 60, NULL); } } #ifdef REAL_WITH_MEMORY_TRACKING static void sys_tree__update_memory(char *buf) { static unsigned long current_heap = ULONG_MAX; static unsigned long max_heap = ULONG_MAX; unsigned long value_ul; uint32_t len; value_ul = mosquitto__memory_used(); if(current_heap != value_ul){ current_heap = value_ul; len = (uint32_t)snprintf(buf, BUFLEN, "%lu", current_heap); db__messages_easy_queue(NULL, "$SYS/broker/heap/current", SYS_TREE_QOS, len, buf, 1, 60, NULL); } value_ul =mosquitto__max_memory_used(); if(max_heap != value_ul){ max_heap = value_ul; len = (uint32_t)snprintf(buf, BUFLEN, "%lu", max_heap); db__messages_easy_queue(NULL, "$SYS/broker/heap/maximum", SYS_TREE_QOS, len, buf, 1, 60, NULL); } } #endif static void calc_load(char *buf, const char *topic, bool initial, double exponent, double interval, double *current) { double new_value; uint32_t len; if (initial) { new_value = *current; len = (uint32_t)snprintf(buf, BUFLEN, "%.2f", new_value); db__messages_easy_queue(NULL, topic, SYS_TREE_QOS, len, buf, 1, 60, NULL); } else { new_value = interval + exponent*((*current) - interval); if(fabs(new_value - (*current)) >= 0.01){ len = (uint32_t)snprintf(buf, BUFLEN, "%.2f", new_value); db__messages_easy_queue(NULL, topic, SYS_TREE_QOS, len, 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(int interval, time_t start_time) { static time_t last_update = 0; time_t uptime; char buf[BUFLEN]; static int msg_store_count = INT_MAX; static unsigned long msg_store_bytes = ULONG_MAX; static unsigned long msgs_received = ULONG_MAX; static unsigned long msgs_sent = ULONG_MAX; static unsigned long publish_dropped = ULONG_MAX; static unsigned long pub_msgs_received = ULONG_MAX; static unsigned long pub_msgs_sent = ULONG_MAX; static unsigned long long bytes_received = ULLONG_MAX; static unsigned long long bytes_sent = ULLONG_MAX; static unsigned long long pub_bytes_received = ULLONG_MAX; static unsigned long long pub_bytes_sent = ULLONG_MAX; static int subscription_count = INT_MAX; static int shared_subscription_count = INT_MAX; static int retained_count = INT_MAX; 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; uint32_t len; bool initial_publish; if(interval && db.now_s - interval > last_update){ uptime = db.now_s - start_time; len = (uint32_t)snprintf(buf, BUFLEN, "%d seconds", (int)uptime); db__messages_easy_queue(NULL, "$SYS/broker/uptime", SYS_TREE_QOS, len, buf, 1, 60, NULL); sys_tree__update_clients(buf); initial_publish = false; if(last_update == 0){ initial_publish = true; last_update = 1; } if(last_update > 0){ i_mult = 60.0/(double)(db.now_s-last_update); msgs_received_interval = (double)(g_msgs_received - msgs_received)*i_mult; msgs_sent_interval = (double)(g_msgs_sent - msgs_sent)*i_mult; publish_dropped_interval = (double)(g_msgs_dropped - publish_dropped)*i_mult; publish_received_interval = (double)(g_pub_msgs_received - pub_msgs_received)*i_mult; publish_sent_interval = (double)(g_pub_msgs_sent - pub_msgs_sent)*i_mult; bytes_received_interval = (double)(g_bytes_received - bytes_received)*i_mult; bytes_sent_interval = (double)(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*(double)(db.now_s-last_update)/60.0); calc_load(buf, "$SYS/broker/load/messages/received/1min", initial_publish, exponent, msgs_received_interval, &msgs_received_load1); calc_load(buf, "$SYS/broker/load/messages/sent/1min", initial_publish, exponent, msgs_sent_interval, &msgs_sent_load1); calc_load(buf, "$SYS/broker/load/publish/dropped/1min", initial_publish, exponent, publish_dropped_interval, &publish_dropped_load1); calc_load(buf, "$SYS/broker/load/publish/received/1min", initial_publish, exponent, publish_received_interval, &publish_received_load1); calc_load(buf, "$SYS/broker/load/publish/sent/1min", initial_publish, exponent, publish_sent_interval, &publish_sent_load1); calc_load(buf, "$SYS/broker/load/bytes/received/1min", initial_publish, exponent, bytes_received_interval, &bytes_received_load1); calc_load(buf, "$SYS/broker/load/bytes/sent/1min", initial_publish, exponent, bytes_sent_interval, &bytes_sent_load1); calc_load(buf, "$SYS/broker/load/sockets/1min", initial_publish, exponent, socket_interval, &socket_load1); calc_load(buf, "$SYS/broker/load/connections/1min", initial_publish, exponent, connection_interval, &connection_load1); /* 5 minute load */ exponent = exp(-1.0*(double)(db.now_s-last_update)/300.0); calc_load(buf, "$SYS/broker/load/messages/received/5min", initial_publish, exponent, msgs_received_interval, &msgs_received_load5); calc_load(buf, "$SYS/broker/load/messages/sent/5min", initial_publish, exponent, msgs_sent_interval, &msgs_sent_load5); calc_load(buf, "$SYS/broker/load/publish/dropped/5min", initial_publish, exponent, publish_dropped_interval, &publish_dropped_load5); calc_load(buf, "$SYS/broker/load/publish/received/5min", initial_publish, exponent, publish_received_interval, &publish_received_load5); calc_load(buf, "$SYS/broker/load/publish/sent/5min", initial_publish, exponent, publish_sent_interval, &publish_sent_load5); calc_load(buf, "$SYS/broker/load/bytes/received/5min", initial_publish, exponent, bytes_received_interval, &bytes_received_load5); calc_load(buf, "$SYS/broker/load/bytes/sent/5min", initial_publish, exponent, bytes_sent_interval, &bytes_sent_load5); calc_load(buf, "$SYS/broker/load/sockets/5min", initial_publish, exponent, socket_interval, &socket_load5); calc_load(buf, "$SYS/broker/load/connections/5min", initial_publish, exponent, connection_interval, &connection_load5); /* 15 minute load */ exponent = exp(-1.0*(double)(db.now_s-last_update)/900.0); calc_load(buf, "$SYS/broker/load/messages/received/15min", initial_publish, exponent, msgs_received_interval, &msgs_received_load15); calc_load(buf, "$SYS/broker/load/messages/sent/15min", initial_publish, exponent, msgs_sent_interval, &msgs_sent_load15); calc_load(buf, "$SYS/broker/load/publish/dropped/15min", initial_publish, exponent, publish_dropped_interval, &publish_dropped_load15); calc_load(buf, "$SYS/broker/load/publish/received/15min", initial_publish, exponent, publish_received_interval, &publish_received_load15); calc_load(buf, "$SYS/broker/load/publish/sent/15min", initial_publish, exponent, publish_sent_interval, &publish_sent_load15); calc_load(buf, "$SYS/broker/load/bytes/received/15min", initial_publish, exponent, bytes_received_interval, &bytes_received_load15); calc_load(buf, "$SYS/broker/load/bytes/sent/15min", initial_publish, exponent, bytes_sent_interval, &bytes_sent_load15); calc_load(buf, "$SYS/broker/load/sockets/15min", initial_publish, exponent, socket_interval, &socket_load15); calc_load(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; len = (uint32_t)snprintf(buf, BUFLEN, "%d", msg_store_count); db__messages_easy_queue(NULL, "$SYS/broker/messages/stored", SYS_TREE_QOS, len, buf, 1, 60, NULL); db__messages_easy_queue(NULL, "$SYS/broker/store/messages/count", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if (db.msg_store_bytes != msg_store_bytes){ msg_store_bytes = db.msg_store_bytes; len = (uint32_t)snprintf(buf, BUFLEN, "%lu", msg_store_bytes); db__messages_easy_queue(NULL, "$SYS/broker/store/messages/bytes", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(db.subscription_count != subscription_count){ subscription_count = db.subscription_count; len = (uint32_t)snprintf(buf, BUFLEN, "%d", subscription_count); db__messages_easy_queue(NULL, "$SYS/broker/subscriptions/count", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(db.shared_subscription_count != shared_subscription_count){ shared_subscription_count = db.shared_subscription_count; len = (uint32_t)snprintf(buf, BUFLEN, "%d", shared_subscription_count); db__messages_easy_queue(NULL, "$SYS/broker/shared_subscriptions/count", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(db.retained_count != retained_count){ retained_count = db.retained_count; len = (uint32_t)snprintf(buf, BUFLEN, "%d", retained_count); db__messages_easy_queue(NULL, "$SYS/broker/retained messages/count", SYS_TREE_QOS, len, buf, 1, 60, NULL); } #ifdef REAL_WITH_MEMORY_TRACKING sys_tree__update_memory(buf); #endif if(msgs_received != g_msgs_received){ msgs_received = g_msgs_received; len = (uint32_t)snprintf(buf, BUFLEN, "%lu", msgs_received); db__messages_easy_queue(NULL, "$SYS/broker/messages/received", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(msgs_sent != g_msgs_sent){ msgs_sent = g_msgs_sent; len = (uint32_t)snprintf(buf, BUFLEN, "%lu", msgs_sent); db__messages_easy_queue(NULL, "$SYS/broker/messages/sent", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(publish_dropped != g_msgs_dropped){ publish_dropped = g_msgs_dropped; len = (uint32_t)snprintf(buf, BUFLEN, "%lu", publish_dropped); db__messages_easy_queue(NULL, "$SYS/broker/publish/messages/dropped", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(pub_msgs_received != g_pub_msgs_received){ pub_msgs_received = g_pub_msgs_received; len = (uint32_t)snprintf(buf, BUFLEN, "%lu", pub_msgs_received); db__messages_easy_queue(NULL, "$SYS/broker/publish/messages/received", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(pub_msgs_sent != g_pub_msgs_sent){ pub_msgs_sent = g_pub_msgs_sent; len = (uint32_t)snprintf(buf, BUFLEN, "%lu", pub_msgs_sent); db__messages_easy_queue(NULL, "$SYS/broker/publish/messages/sent", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(bytes_received != g_bytes_received){ bytes_received = g_bytes_received; len = (uint32_t)snprintf(buf, BUFLEN, "%llu", bytes_received); db__messages_easy_queue(NULL, "$SYS/broker/bytes/received", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(bytes_sent != g_bytes_sent){ bytes_sent = g_bytes_sent; len = (uint32_t)snprintf(buf, BUFLEN, "%llu", bytes_sent); db__messages_easy_queue(NULL, "$SYS/broker/bytes/sent", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(pub_bytes_received != g_pub_bytes_received){ pub_bytes_received = g_pub_bytes_received; len = (uint32_t)snprintf(buf, BUFLEN, "%llu", pub_bytes_received); db__messages_easy_queue(NULL, "$SYS/broker/publish/bytes/received", SYS_TREE_QOS, len, buf, 1, 60, NULL); } if(pub_bytes_sent != g_pub_bytes_sent){ pub_bytes_sent = g_pub_bytes_sent; len = (uint32_t)snprintf(buf, BUFLEN, "%llu", pub_bytes_sent); db__messages_easy_queue(NULL, "$SYS/broker/publish/bytes/sent", SYS_TREE_QOS, len, buf, 1, 60, NULL); } last_update = db.now_s; } } #endif mosquitto-2.0.11/src/keepalive.c0000664000175000017500000000337614060132747015574 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include "mosquitto_broker_internal.h" static time_t last_keepalive_check = 0; /* FIXME - this is the prototype for the future tree/trie based keepalive check implementation. */ int keepalive__add(struct mosquitto *context) { UNUSED(context); return MOSQ_ERR_SUCCESS; } void keepalive__check(void) { struct mosquitto *context, *ctxt_tmp; if(last_keepalive_check + 5 < db.now_s){ last_keepalive_check = db.now_s; /* FIXME - this needs replacing with something more efficient */ HASH_ITER(hh_sock, db.contexts_by_sock, context, ctxt_tmp){ if(context->sock != INVALID_SOCKET){ /* Local bridges never time out in this fashion. */ if(!(context->keepalive) || context->bridge || db.now_s - context->last_msg_in <= (time_t)(context->keepalive)*3/2){ }else{ /* Client has exceeded keepalive*1.5 */ do_disconnect(context, MOSQ_ERR_KEEPALIVE); } } } } } int keepalive__remove(struct mosquitto *context) { UNUSED(context); return MOSQ_ERR_SUCCESS; } void keepalive__remove_all(void) { } int keepalive__update(struct mosquitto *context) { context->last_msg_in = db.now_s; return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/src/logging.c0000664000175000017500000002144414060132747015251 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifndef WIN32 #include #endif #include #if defined(__APPLE__) # include #endif #ifdef WITH_DLT #include #include #endif #include "logging_mosq.h" #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "misc_mosq.h" #include "util_mosq.h" #ifdef WIN32 HANDLE syslog_h; #endif static char log_fptr_buffer[BUFSIZ]; /* 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 unsigned int log_destinations = MQTT3_LOG_STDERR; static unsigned int log_priorities = MOSQ_LOG_ERR | MOSQ_LOG_WARNING | MOSQ_LOG_NOTICE | MOSQ_LOG_INFO; #ifdef WITH_DLT static DltContext dltContext; static bool dlt_allowed = false; void dlt_fifo_check(void) { struct stat statbuf; int fd; /* If we start DLT but the /tmp/dlt fifo doesn't exist, or isn't available * for writing then there is a big delay when we try and close the log * later, so check for it first. This has the side effect of not letting * people using DLT create the fifo after Mosquitto has started, but at the * benefit of not having a massive delay for everybody else. */ memset(&statbuf, 0, sizeof(statbuf)); if(stat("/tmp/dlt", &statbuf) == 0){ if(S_ISFIFO(statbuf.st_mode)){ fd = open("/tmp/dlt", O_NONBLOCK | O_WRONLY); if(fd != -1){ dlt_allowed = true; close(fd); } } } } #endif static int get_time(struct tm **ti) { time_t s; s = db.now_real_s; *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){ config->log_fptr = mosquitto__fopen(config->log_file, "at", true); if(config->log_fptr){ setvbuf(config->log_fptr, log_fptr_buffer, _IOLBF, sizeof(log_fptr_buffer)); }else{ 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); } } #ifdef WITH_DLT dlt_fifo_check(); if(dlt_allowed){ 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 if(dlt_allowed){ 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(unsigned 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 static int log__vprintf(unsigned int priority, const char *fmt, va_list va) { const char *topic; int syslog_priority; char log_line[1000]; size_t log_line_pos; #ifdef WIN32 char *sp; #endif bool log_timestamp = true; char *log_timestamp_format = NULL; FILE *log_fptr = NULL; if(db.config){ log_timestamp = db.config->log_timestamp; log_timestamp_format = db.config->log_timestamp_format; log_fptr = 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 } if(log_timestamp){ if(log_timestamp_format){ struct tm *ti = NULL; get_time(&ti); log_line_pos = strftime(log_line, sizeof(log_line), log_timestamp_format, ti); if(log_line_pos == 0){ log_line_pos = (size_t)snprintf(log_line, sizeof(log_line), "Time error"); } }else{ log_line_pos = (size_t)snprintf(log_line, sizeof(log_line), "%d", (int)db.now_real_s); } if(log_line_pos < sizeof(log_line)-3){ log_line[log_line_pos] = ':'; log_line[log_line_pos+1] = ' '; log_line[log_line_pos+2] = '\0'; log_line_pos += 2; } }else{ log_line_pos = 0; } vsnprintf(&log_line[log_line_pos], sizeof(log_line)-log_line_pos, fmt, va); log_line[sizeof(log_line)-1] = '\0'; /* Ensure string is null terminated. */ if(log_destinations & MQTT3_LOG_STDOUT){ fprintf(stdout, "%s\n", log_line); } if(log_destinations & MQTT3_LOG_STDERR){ fprintf(stderr, "%s\n", log_line); } if(log_destinations & MQTT3_LOG_FILE && log_fptr){ fprintf(log_fptr, "%s\n", log_line); #ifdef WIN32 /* Windows doesn't support line buffering, so flush. */ fflush(log_fptr); #endif } if(log_destinations & MQTT3_LOG_SYSLOG){ #ifndef WIN32 syslog(syslog_priority, "%s", log_line); #else sp = (char *)log_line; 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){ db__messages_easy_queue(NULL, topic, 2, (uint32_t)strlen(log_line), log_line, 0, 20, NULL); } #ifdef WITH_DLT if(log_destinations & MQTT3_LOG_DLT && priority != MOSQ_LOG_INTERNAL){ DLT_LOG_STRING(dltContext, get_dlt_level(priority), log_line); } #endif } return MOSQ_ERR_SUCCESS; } int log__printf(struct mosquitto *mosq, unsigned 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; } #ifdef WIN32 log__printf(NULL, MOSQ_LOG_INTERNAL, "%s", buf); #else log__printf(NULL, MOSQ_LOG_INTERNAL, "%s%s%s", "\e[32m", buf, "\e[0m"); #endif } int mosquitto_log_vprintf(int level, const char *fmt, va_list va) { return log__vprintf((unsigned int)level, fmt, va); } void mosquitto_log_printf(int level, const char *fmt, ...) { va_list va; va_start(va, fmt); log__vprintf((unsigned int)level, fmt, va); va_end(va); } mosquitto-2.0.11/src/handle_publish.c0000664000175000017500000002435114060132747016604 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *context) { uint8_t dup; int rc = 0; int rc2; uint8_t header = context->in_packet.command; int res = 0; struct mosquitto_msg_store *msg, *stored = NULL; size_t len; uint16_t slen; char *topic_mount; mosquitto_property *properties = NULL; mosquitto_property *p, *p_prev; mosquitto_property *msg_properties_last; uint32_t message_expiry_interval = 0; int topic_alias = -1; uint8_t reason_code = 0; uint16_t mid = 0; if(context->state != mosq_cs_active){ return MOSQ_ERR_PROTOCOL; } msg = mosquitto__calloc(1, sizeof(struct mosquitto_msg_store)); if(msg == NULL){ return MOSQ_ERR_NOMEM; } dup = (header & 0x08)>>3; msg->qos = (header & 0x06)>>1; if(msg->qos == 3){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid QoS in PUBLISH from %s, disconnecting.", context->id); db__msg_store_free(msg); return MOSQ_ERR_MALFORMED_PACKET; } if(msg->qos > context->max_qos){ log__printf(NULL, MOSQ_LOG_INFO, "Too high QoS in PUBLISH from %s, disconnecting.", context->id); db__msg_store_free(msg); return MOSQ_ERR_QOS_NOT_SUPPORTED; } msg->retain = (header & 0x01); if(msg->retain && db.config->retain_available == false){ db__msg_store_free(msg); return MOSQ_ERR_RETAIN_NOT_SUPPORTED; } if(packet__read_string(&context->in_packet, &msg->topic, &slen)){ db__msg_store_free(msg); return MOSQ_ERR_MALFORMED_PACKET; } if(!slen && context->protocol != mosq_p_mqtt5){ /* Invalid publish topic, disconnect client. */ db__msg_store_free(msg); return MOSQ_ERR_MALFORMED_PACKET; } if(msg->qos > 0){ if(packet__read_uint16(&context->in_packet, &mid)){ db__msg_store_free(msg); return MOSQ_ERR_MALFORMED_PACKET; } if(mid == 0){ db__msg_store_free(msg); return MOSQ_ERR_PROTOCOL; } /* It is important to have a separate copy of mid, because msg may be * freed before we want to send a PUBACK/PUBREC. */ msg->source_mid = mid; } /* Handle properties */ if(context->protocol == mosq_p_mqtt5){ rc = property__read_all(CMD_PUBLISH, &context->in_packet, &properties); if(rc){ db__msg_store_free(msg); if(rc == MOSQ_ERR_PROTOCOL){ return MOSQ_ERR_MALFORMED_PACKET; }else{ 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)){ db__msg_store_free(msg); return MOSQ_ERR_TOPIC_ALIAS_INVALID; }else if(topic_alias > 0){ if(msg->topic){ rc = alias__add(context, msg->topic, (uint16_t)topic_alias); if(rc){ db__msg_store_free(msg); return rc; } }else{ rc = alias__find(context, &msg->topic, (uint16_t)topic_alias); if(rc){ db__msg_store_free(msg); return MOSQ_ERR_PROTOCOL; } } } #ifdef WITH_BRIDGE rc = bridge__remap_topic_in(context, &msg->topic); if(rc){ db__msg_store_free(msg); return rc; } #endif if(mosquitto_pub_topic_check(msg->topic) != MOSQ_ERR_SUCCESS){ /* Invalid publish topic, just swallow it. */ db__msg_store_free(msg); return MOSQ_ERR_PROTOCOL; } msg->payloadlen = context->in_packet.remaining_length - context->in_packet.pos; G_PUB_BYTES_RECEIVED_INC(msg->payloadlen); if(context->listener && context->listener->mount_point){ len = strlen(context->listener->mount_point) + strlen(msg->topic) + 1; topic_mount = mosquitto__malloc(len+1); if(!topic_mount){ db__msg_store_free(msg); return MOSQ_ERR_NOMEM; } snprintf(topic_mount, len, "%s%s", context->listener->mount_point, msg->topic); topic_mount[len] = '\0'; mosquitto__free(msg->topic); msg->topic = topic_mount; } if(msg->payloadlen){ if(db.config->message_size_limit && msg->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, msg->qos, msg->retain, msg->source_mid, msg->topic, (long)msg->payloadlen); reason_code = MQTT_RC_PACKET_TOO_LARGE; goto process_bad_message; } msg->payload = mosquitto__malloc(msg->payloadlen+1); if(msg->payload == NULL){ db__msg_store_free(msg); return MOSQ_ERR_NOMEM; } /* Ensure payload is always zero terminated, this is the reason for the extra byte above */ ((uint8_t *)msg->payload)[msg->payloadlen] = 0; if(packet__read_bytes(&context->in_packet, msg->payload, msg->payloadlen)){ db__msg_store_free(msg); return MOSQ_ERR_MALFORMED_PACKET; } } /* Check for topic access */ rc = mosquitto_acl_check(context, msg->topic, msg->payloadlen, msg->payload, msg->qos, msg->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, msg->qos, msg->retain, msg->source_mid, msg->topic, (long)msg->payloadlen); reason_code = MQTT_RC_NOT_AUTHORIZED; goto process_bad_message; }else if(rc != MOSQ_ERR_SUCCESS){ db__msg_store_free(msg); 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, msg->qos, msg->retain, msg->source_mid, msg->topic, (long)msg->payloadlen); if(!strncmp(msg->topic, "$CONTROL/", 9)){ #ifdef WITH_CONTROL rc = control__process(context, msg); db__msg_store_free(msg); return rc; #else reason_code = MQTT_RC_IMPLEMENTATION_SPECIFIC; goto process_bad_message; #endif } { rc = plugin__handle_message(context, msg); 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, msg->qos, msg->retain, msg->source_mid, msg->topic, (long)msg->payloadlen); reason_code = MQTT_RC_NOT_AUTHORIZED; goto process_bad_message; }else if(rc != MOSQ_ERR_SUCCESS){ db__msg_store_free(msg); return rc; } } if(msg->qos > 0){ db__message_store_find(context, msg->source_mid, &stored); } if(stored && msg->source_mid != 0 && (stored->qos != msg->qos || stored->payloadlen != msg->payloadlen || strcmp(stored->topic, msg->topic) || memcmp(stored->payload, msg->payload, msg->payloadlen) )){ log__printf(NULL, MOSQ_LOG_WARNING, "Reused message ID %u from %s detected. Clearing from storage.", msg->source_mid, context->id); db__message_remove_incoming(context, msg->source_mid); stored = NULL; } if(!stored){ if(msg->qos == 0 || db__ready_for_flight(context, mosq_md_in, msg->qos) || db__ready_for_queue(context, msg->qos, &context->msgs_in)){ dup = 0; rc = db__message_store(context, msg, message_expiry_interval, 0, mosq_mo_client); if(rc) return rc; }else{ /* Client isn't allowed any more incoming messages, so fail early */ reason_code = MQTT_RC_QUOTA_EXCEEDED; goto process_bad_message; } stored = msg; msg = NULL; }else{ db__msg_store_free(msg); msg = NULL; dup = 1; } switch(stored->qos){ case 0: rc2 = sub__messages_queue(context->id, stored->topic, stored->qos, stored->retain, &stored); if(rc2 > 0) rc = 1; break; case 1: util__decrement_receive_quota(context); rc2 = sub__messages_queue(context->id, stored->topic, stored->qos, stored->retain, &stored); /* stored may now be free, so don't refer to it */ if(rc2 == MOSQ_ERR_SUCCESS || context->protocol != mosq_p_mqtt5){ if(send__puback(context, mid, 0, NULL)) rc = 1; }else if(rc2 == MOSQ_ERR_NO_SUBSCRIBERS){ if(send__puback(context, mid, MQTT_RC_NO_MATCHING_SUBSCRIBERS, NULL)) rc = 1; }else{ rc = rc2; } break; case 2: if(dup == 0){ res = db__message_insert(context, stored->source_mid, mosq_md_in, stored->qos, stored->retain, stored, NULL, false); }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. */ /* FIXME - this is no longer necessary due to failing early above */ if(!res){ if(send__pubrec(context, stored->source_mid, 0, NULL)) rc = 1; }else if(res == 1){ rc = 1; } break; } db__message_write_queued_in(context); return rc; process_bad_message: rc = 1; if(msg){ switch(msg->qos){ case 0: rc = MOSQ_ERR_SUCCESS; break; case 1: rc = send__puback(context, msg->source_mid, reason_code, NULL); break; case 2: rc = send__pubrec(context, msg->source_mid, reason_code, NULL); break; } db__msg_store_free(msg); } return rc; } mosquitto-2.0.11/src/persist.h0000664000175000017500000001170114060132747015314 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef PERSIST_H #define PERSIST_H #include "mosquitto_broker_internal.h" #define MOSQ_DB_VERSION 6 /* 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_v5{ int64_t session_expiry_time; uint32_t session_expiry_interval; uint16_t last_mid; uint16_t id_len; }; struct PF_client{ /* struct PF_client_v5; */ int64_t session_expiry_time; uint32_t session_expiry_interval; uint16_t last_mid; uint16_t id_len; uint16_t listener_port; uint16_t username_len; /* tail: 4 byte padding, because 64bit member * forces multiple of 8 for struct size */ }; struct P_client{ struct PF_client F; char *client_id; char *username; }; 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; void *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, uint32_t *chunk, uint32_t *length); int persist__chunk_header_read_v234(FILE *db_fptr, uint32_t *chunk, uint32_t *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, uint32_t 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, uint32_t 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_v56(FILE *db_fptr, uint32_t *chunk, uint32_t *length); int persist__chunk_cfg_read_v56(FILE *db_fptr, struct PF_cfg *chunk); int persist__chunk_client_read_v56(FILE *db_fptr, struct P_client *chunk, uint32_t db_version); int persist__chunk_client_msg_read_v56(FILE *db_fptr, struct P_client_msg *chunk, uint32_t length); int persist__chunk_msg_store_read_v56(FILE *db_fptr, struct P_msg_store *chunk, uint32_t length); int persist__chunk_retain_read_v56(FILE *db_fptr, struct P_retain *chunk); int persist__chunk_sub_read_v56(FILE *db_fptr, struct P_sub *chunk); int persist__chunk_cfg_write_v6(FILE *db_fptr, struct PF_cfg *chunk); int persist__chunk_client_write_v6(FILE *db_fptr, struct P_client *chunk); int persist__chunk_client_msg_write_v6(FILE *db_fptr, struct P_client_msg *chunk); int persist__chunk_message_store_write_v6(FILE *db_fptr, struct P_msg_store *chunk); int persist__chunk_retain_write_v6(FILE *db_fptr, struct P_retain *chunk); int persist__chunk_sub_write_v6(FILE *db_fptr, struct P_sub *chunk); #endif mosquitto-2.0.11/src/net.c0000664000175000017500000006522414060132747014415 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 WITH_UNIX_SOCKETS # include "sys/stat.h" # include "sys/un.h" #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(); #ifdef WITH_TLS net__init_tls(); #endif } 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(unsigned int log, const char *format_str) { char *buf; #ifdef WIN32 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), LANG_NEUTRAL, (LPTSTR)&buf, 0, NULL); log__printf(NULL, log, format_str, buf); LocalFree(buf); #else buf = strerror(errno); log__printf(NULL, log, format_str, buf); #endif } struct mosquitto *net__socket_accept(struct mosquitto__listener_sock *listensock) { 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->sock, 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->sock, 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 NULL; } G_SOCKET_CONNECTIONS_INC(); if(net__socket_nonblock(&new_sock)){ return NULL; } #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, NULL)){ log__printf(NULL, MOSQ_LOG_NOTICE, "Client connection from %s denied access by tcpd.", address); } } COMPAT_CLOSE(new_sock); return NULL; } #endif if(db.config->set_tcp_nodelay){ int flag = 1; #ifdef WIN32 if (setsockopt(new_sock, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int)) != 0) { #else if(setsockopt(new_sock, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int)) != 0){ #endif log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Unable to set TCP_NODELAY."); } } new_context = context__init(new_sock); if(!new_context){ COMPAT_CLOSE(new_sock); return NULL; } new_context->listener = listensock->listener; if(!new_context->listener){ context__cleanup(new_context, true); return NULL; } new_context->listener->client_count++; 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(new_context, true); return NULL; } #ifdef WITH_TLS /* TLS init */ if(new_context->listener->ssl_ctx){ new_context->ssl = SSL_new(new_context->listener->ssl_ctx); if(!new_context->ssl){ context__cleanup(new_context, true); return NULL; } SSL_set_ex_data(new_context->ssl, tls_ex_index_context, new_context); SSL_set_ex_data(new_context->ssl, tls_ex_index_listener, new_context->listener); 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(new_context, true); return NULL; } } } #endif if(db.config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_NOTICE, "New connection from %s:%d on port %d.", new_context->address, new_context->remote_port, new_context->listener->port); } return new_context; } #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 *context; struct mosquitto__listener *listener; char *psk_key = NULL; int len; const char *psk_hint; if(!identity) return 0; 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, (size_t)max_psk_len*2 + 1); if(!psk_key) return 0; if(mosquitto_psk_key_get(context, psk_hint, identity, psk_key, (int)max_psk_len*2) != MOSQ_ERR_SUCCESS){ mosquitto__free(psk_key); return 0; } len = mosquitto__hex2bin(psk_key, psk, (int)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 (unsigned int)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 MOSQ_ERR_TLS; } 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); }else if(!strcmp(listener->tls_version, "tlsv1.1")){ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1); #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); #endif }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unsupported tls_version \"%s\".", listener->tls_version); return MOSQ_ERR_TLS; } /* Use a new key when using temporary/ephemeral DH parameters. * This shouldn't be necessary, but we can't guarantee that `dhparam` has * been generated using strong primes. */ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_SINGLE_DH_USE); #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 #if OPENSSL_VERSION_NUMBER >= 0x10100000L SSL_CTX_set_dh_auto(listener->ssl_ctx, 1); #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, (unsigned int)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 MOSQ_ERR_TLS; } }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 MOSQ_ERR_TLS; } } #if OPENSSL_VERSION_NUMBER >= 0x10101000 && !defined(LIBRESSL_VERSION_NUMBER) if(listener->ciphers_tls13){ rc = SSL_CTX_set_ciphersuites(listener->ssl_ctx, listener->ciphers_tls13); if(rc == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to set TLS 1.3 ciphersuites. Check cipher_tls13 list \"%s\".", listener->ciphers_tls13); return MOSQ_ERR_TLS; } } #endif if(listener->dhparamfile){ dhparamfile = fopen(listener->dhparamfile, "r"); if(!dhparamfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error loading dhparamfile \"%s\".", listener->dhparamfile); return MOSQ_ERR_TLS; } 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 MOSQ_ERR_TLS; } } return MOSQ_ERR_SUCCESS; } #endif static 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 MOSQ_ERR_TLS; } 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 MOSQ_ERR_TLS; } X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK); #endif return MOSQ_ERR_SUCCESS; } int net__load_certificates(struct mosquitto__listener *listener) { #ifdef WITH_TLS int rc; 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); return MOSQ_ERR_TLS; } if(listener->tls_engine == NULL){ 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); net__print_ssl_error(NULL); return MOSQ_ERR_TLS; } } 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); return MOSQ_ERR_TLS; } /* Load CRLs if they exist. */ if(listener->crlfile){ rc = net__load_crl_file(listener); if(rc){ return rc; } } #endif return MOSQ_ERR_SUCCESS; } static int net__load_engine(struct mosquitto__listener *listener) { #if defined(WITH_TLS) && !defined(OPENSSL_NO_ENGINE) ENGINE *engine = NULL; UI_METHOD *ui_method; EVP_PKEY *pkey; if(!listener->tls_engine){ return MOSQ_ERR_SUCCESS; } 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 MOSQ_ERR_TLS; } if(!ENGINE_init(engine)){ log__printf(NULL, MOSQ_LOG_ERR, "Failed engine initialisation\n"); net__print_ssl_error(NULL); return MOSQ_ERR_TLS; } ENGINE_set_default(engine, ENGINE_METHOD_ALL); if(listener->tls_keyform == mosq_k_engine){ 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); return MOSQ_ERR_TLS; } 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); return MOSQ_ERR_TLS; } ui_method = NULL; } 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); return MOSQ_ERR_TLS; } 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); return MOSQ_ERR_TLS; } } ENGINE_free(engine); /* release the structural reference from ENGINE_by_id() */ #endif return MOSQ_ERR_SUCCESS; } int net__tls_load_verify(struct mosquitto__listener *listener) { #ifdef WITH_TLS int rc; #if OPENSSL_VERSION_NUMBER < 0x30000000L if(listener->cafile || listener->capath){ 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); } } } #else if(listener->cafile){ rc = SSL_CTX_load_verify_file(listener->ssl_ctx, listener->cafile); if(rc == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load CA certificates. Check cafile \"%s\".", listener->cafile); net__print_ssl_error(NULL); return MOSQ_ERR_TLS; } } if(listener->capath){ rc = SSL_CTX_load_verify_dir(listener->ssl_ctx, listener->capath); if(rc == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load CA certificates. Check capath \"%s\".", listener->capath); net__print_ssl_error(NULL); return MOSQ_ERR_TLS; } } #endif if(net__load_engine(listener)){ return MOSQ_ERR_TLS; } #endif return net__load_certificates(listener); } #ifndef WIN32 static int net__bind_interface(struct mosquitto__listener *listener, struct addrinfo *rp) { /* * This binds the listener sock to a network interface. * The use of SO_BINDTODEVICE requires root access, which we don't have, so instead * use getifaddrs to find the interface addresses, and use IP of the * matching interface in the later bind(). */ struct ifaddrs *ifaddr, *ifa; if(getifaddrs(&ifaddr) < 0){ net__print_error(MOSQ_LOG_ERR, "Error: %s"); return MOSQ_ERR_ERRNO; } for(ifa=ifaddr; ifa!=NULL; ifa=ifa->ifa_next){ if(ifa->ifa_addr == NULL){ continue; } if(!strcasecmp(listener->bind_interface, ifa->ifa_name) && ifa->ifa_addr->sa_family == rp->ai_addr->sa_family){ if(rp->ai_addr->sa_family == AF_INET){ if(listener->host && memcmp(&((struct sockaddr_in *)rp->ai_addr)->sin_addr, &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr, sizeof(struct in_addr))){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Interface address for %s does not match specified listener address (%s).", listener->bind_interface, listener->host); return MOSQ_ERR_INVAL; }else{ memcpy(&((struct sockaddr_in *)rp->ai_addr)->sin_addr, &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr, sizeof(struct in_addr)); freeifaddrs(ifaddr); return MOSQ_ERR_SUCCESS; } }else if(rp->ai_addr->sa_family == AF_INET6){ if(listener->host && memcmp(&((struct sockaddr_in6 *)rp->ai_addr)->sin6_addr, &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr, sizeof(struct in6_addr))){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Interface address for %s does not match specified listener address (%s).", listener->bind_interface, listener->host); return MOSQ_ERR_INVAL; }else{ memcpy(&((struct sockaddr_in6 *)rp->ai_addr)->sin6_addr, &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr, sizeof(struct in6_addr)); freeifaddrs(ifaddr); return MOSQ_ERR_SUCCESS; } } } } freeifaddrs(ifaddr); log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Interface %s does not support %s configuration.", listener->bind_interface, rp->ai_addr->sa_family == AF_INET ? "IPv4" : "IPv6"); return MOSQ_ERR_NOT_FOUND; } #endif static int net__socket_listen_tcp(struct mosquitto__listener *listener) { mosq_sock_t sock = INVALID_SOCKET; struct addrinfo hints; struct addrinfo *ainfo, *rp; char service[10]; int rc; int ss_opt = 1; #ifndef WIN32 bool interface_bound = false; #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)*(size_t)listener->sock_count); if(!listener->socks){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); freeaddrinfo(ainfo); COMPAT_CLOSE(sock); return MOSQ_ERR_NOMEM; } listener->socks[listener->sock_count-1] = sock; #ifndef WIN32 ss_opt = 1; /* Unimportant if this fails */ (void)setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &ss_opt, sizeof(ss_opt)); #endif #ifdef IPV6_V6ONLY ss_opt = 1; (void)setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &ss_opt, sizeof(ss_opt)); #endif if(net__socket_nonblock(&sock)){ freeaddrinfo(ainfo); mosquitto__free(listener->socks); return 1; } #ifndef WIN32 if(listener->bind_interface){ /* It might be possible that an interface does not support all relevant sa_families. * We should successfully find at least one. */ if(net__bind_interface(listener, rp)){ COMPAT_CLOSE(sock); listener->sock_count--; continue; } interface_bound = true; } #endif if(bind(sock, rp->ai_addr, rp->ai_addrlen) == -1){ #if defined(__linux__) if(errno == EACCES){ log__printf(NULL, MOSQ_LOG_ERR, "If you are trying to bind to a privileged port (<1024), try using setcap and do not start the broker as root:"); log__printf(NULL, MOSQ_LOG_ERR, " sudo setcap 'CAP_NET_BIND_SERVICE=+ep /usr/sbin/mosquitto'"); } #endif net__print_error(MOSQ_LOG_ERR, "Error: %s"); COMPAT_CLOSE(sock); freeaddrinfo(ainfo); mosquitto__free(listener->socks); return 1; } if(listen(sock, 100) == -1){ net__print_error(MOSQ_LOG_ERR, "Error: %s"); freeaddrinfo(ainfo); COMPAT_CLOSE(sock); mosquitto__free(listener->socks); return 1; } } freeaddrinfo(ainfo); #ifndef WIN32 if(listener->bind_interface && !interface_bound){ mosquitto__free(listener->socks); return 1; } #endif return 0; } #ifdef WITH_UNIX_SOCKETS static int net__socket_listen_unix(struct mosquitto__listener *listener) { struct sockaddr_un addr; int sock; int rc; mode_t old_mask; if(listener->unix_socket_path == NULL){ return MOSQ_ERR_INVAL; } if(strlen(listener->unix_socket_path) > sizeof(addr.sun_path)-1){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Path to unix socket is too long \"%s\".", listener->unix_socket_path); return MOSQ_ERR_INVAL; } unlink(listener->unix_socket_path); log__printf(NULL, MOSQ_LOG_INFO, "Opening unix listen socket on path %s.", listener->unix_socket_path); memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, listener->unix_socket_path, sizeof(addr.sun_path)-1); sock = socket(AF_UNIX, SOCK_STREAM, 0); if(sock == INVALID_SOCKET){ net__print_error(MOSQ_LOG_ERR, "Error creating unix socket: %s"); return 1; } listener->sock_count++; listener->socks = mosquitto__realloc(listener->socks, sizeof(mosq_sock_t)*(size_t)listener->sock_count); if(!listener->socks){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); COMPAT_CLOSE(sock); return MOSQ_ERR_NOMEM; } listener->socks[listener->sock_count-1] = sock; old_mask = umask(0007); rc = bind(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)); umask(old_mask); if(rc == -1){ net__print_error(MOSQ_LOG_ERR, "Error binding unix socket: %s"); return 1; } if(listen(sock, 10) == -1){ net__print_error(MOSQ_LOG_ERR, "Error listening to unix socket: %s"); return 1; } if(net__socket_nonblock(&sock)){ return 1; } return 0; } #endif /* Creates a socket and listens on port 'port'. * Returns 1 on failure * Returns 0 on success. */ int net__socket_listen(struct mosquitto__listener *listener) { int rc; if(!listener) return MOSQ_ERR_INVAL; #ifdef WITH_UNIX_SOCKETS if(listener->port == 0 && listener->unix_socket_path != NULL){ rc = net__socket_listen_unix(listener); }else #endif { rc = net__socket_listen_tcp(listener); } if(rc) return rc; /* We need to have at least one working socket. */ if(listener->sock_count > 0){ #ifdef WITH_TLS if(listener->certfile && listener->keyfile){ if(net__tls_server_ctx(listener)){ return 1; } if(net__tls_load_verify(listener)){ 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)){ 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); 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, size_t len, uint16_t *remote_port) { 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(remote_port){ *remote_port = ntohs(((struct sockaddr_in *)&addr)->sin_port); } if(inet_ntop(AF_INET, &((struct sockaddr_in *)&addr)->sin_addr.s_addr, buf, (socklen_t)len)){ return 0; } }else if(addr.ss_family == AF_INET6){ if(remote_port){ *remote_port = ntohs(((struct sockaddr_in6 *)&addr)->sin6_port); } if(inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&addr)->sin6_addr.s6_addr, buf, (socklen_t)len)){ return 0; } #ifdef WITH_UNIX_SOCKETS }else if(addr.ss_family == AF_UNIX){ struct sockaddr_un un; addrlen = sizeof(struct sockaddr_un); if(!getsockname(sock, (struct sockaddr *)&un, &addrlen)){ snprintf(buf, len, "%s", un.sun_path); }else{ snprintf(buf, len, "unix-socket"); } return 0; #endif } } return 1; } mosquitto-2.0.11/src/mux_epoll.c0000664000175000017500000001607514060132747015633 0ustar rogerroger/* Copyright (c) 2009-2019 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. Tatsuzo Osawa - Add epoll. */ #include "config.h" #ifdef WITH_EPOLL #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 "mux.h" #include "packet_mosq.h" #include "send_mosq.h" #include "sys_tree.h" #include "time_mosq.h" #include "util_mosq.h" #ifdef WIN32 # error "epoll not supported on WIN32" #endif static void loop_handle_reads_writes(struct mosquitto *context, uint32_t events); static sigset_t my_sigblock; static struct epoll_event ep_events[MAX_EVENTS]; int mux_epoll__init(struct mosquitto__listener_sock *listensock, int listensock_count) { struct epoll_event ev; int i; #ifndef WIN32 sigemptyset(&my_sigblock); sigaddset(&my_sigblock, SIGINT); sigaddset(&my_sigblock, SIGTERM); sigaddset(&my_sigblock, SIGUSR1); sigaddset(&my_sigblock, SIGUSR2); sigaddset(&my_sigblock, SIGHUP); #endif memset(&ep_events, 0, sizeof(struct epoll_event)*MAX_EVENTS); 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)); for(i=0; ievents & EPOLLOUT)) { memset(&ev, 0, sizeof(struct epoll_event)); ev.data.ptr = context; 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; } return MOSQ_ERR_SUCCESS; } int mux_epoll__remove_out(struct mosquitto *context) { struct epoll_event ev; if(context->events & EPOLLOUT) { memset(&ev, 0, sizeof(struct epoll_event)); ev.data.ptr = context; 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; } return MOSQ_ERR_SUCCESS; } int mux_epoll__add_in(struct mosquitto *context) { struct epoll_event ev; memset(&ev, 0, sizeof(struct epoll_event)); ev.events = EPOLLIN; ev.data.ptr = context; if (epoll_ctl(db.epollfd, EPOLL_CTL_ADD, context->sock, &ev) == -1) { if(errno != EEXIST){ log__printf(NULL, MOSQ_LOG_ERR, "Error in epoll accepting: %s", strerror(errno)); } } context->events = EPOLLIN; return MOSQ_ERR_SUCCESS; } int mux_epoll__delete(struct mosquitto *context) { struct epoll_event ev; memset(&ev, 0, sizeof(struct epoll_event)); if(context->sock != INVALID_SOCKET){ if(epoll_ctl(db.epollfd, EPOLL_CTL_DEL, context->sock, &ev) == -1){ return 1; } } return 0; } int mux_epoll__handle(void) { int i; struct epoll_event ev; sigset_t origsig; struct mosquitto *context; struct mosquitto__listener_sock *listensock; int event_count; memset(&ev, 0, sizeof(struct epoll_event)); sigprocmask(SIG_SETMASK, &my_sigblock, &origsig); event_count = epoll_wait(db.epollfd, ep_events, MAX_EVENTS, 100); sigprocmask(SIG_SETMASK, &origsig, NULL); db.now_s = mosquitto_time(); db.now_real_s = time(NULL); switch(event_count){ 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; iident == id_client){ loop_handle_reads_writes(context, ep_events[i].events); }else if(context->ident == id_listener){ listensock = ep_events[i].data.ptr; if (ep_events[i].events & (EPOLLIN | EPOLLPRI)){ while((context = net__socket_accept(listensock)) != NULL){ context->events = EPOLLIN; mux__add_in(context); } } #ifdef WITH_WEBSOCKETS }else if(context->ident == id_listener_ws){ /* Nothing needs to happen here, because we always call lws_service in the loop. * The important point is we've been woken up for this listener. */ #endif } } } return MOSQ_ERR_SUCCESS; } int mux_epoll__cleanup(void) { (void)close(db.epollfd); db.epollfd = 0; return MOSQ_ERR_SUCCESS; } static void loop_handle_reads_writes(struct mosquitto *context, uint32_t events) { int err; socklen_t len; int rc; if(context->sock == INVALID_SOCKET){ return; } #ifdef WITH_WEBSOCKETS if(context->wsi){ struct lws_pollfd wspoll; wspoll.fd = context->sock; wspoll.events = (int16_t)context->events; wspoll.revents = (int16_t)events; lws_service_fd(lws_get_context(context->wsi), &wspoll); return; } #endif if(events & EPOLLOUT #ifdef WITH_TLS || context->want_write || (context->ssl && context->state == mosq_cs_new) #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(context); } #endif } }else{ do_disconnect(context, MOSQ_ERR_CONN_LOST); return; } } rc = packet__write(context); if(rc){ do_disconnect(context, rc); return; } } if(events & EPOLLIN #ifdef WITH_TLS || (context->ssl && context->state == mosq_cs_new) #endif ){ do{ rc = packet__read(context); if(rc){ do_disconnect(context, rc); return; } }while(SSL_DATA_PENDING(context)); }else{ if(events & (EPOLLERR | EPOLLHUP)){ do_disconnect(context, MOSQ_ERR_CONN_LOST); return; } } } #endif mosquitto-2.0.11/src/linker-macosx.syms0000664000175000017500000000164314060132747017147 0ustar rogerroger_mosquitto_broker_publish _mosquitto_broker_publish_copy _mosquitto_callback_register _mosquitto_callback_unregister _mosquitto_calloc _mosquitto_client_address _mosquitto_client_certificate _mosquitto_client_clean_session _mosquitto_client_id _mosquitto_client_keepalive _mosquitto_client_protocol _mosquitto_client_protocol_version _mosquitto_client_sub_count _mosquitto_client_username _mosquitto_free _mosquitto_kick_client_by_clientid _mosquitto_kick_client_by_username _mosquitto_log_printf _mosquitto_malloc _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_free_all _mosquitto_pub_topic_check _mosquitto_realloc _mosquitto_set_username _mosquitto_strdup _mosquitto_sub_topic_check _mosquitto_topic_matches_sub _mosquitto_validate_utf8 mosquitto-2.0.11/src/password_mosq.h0000664000175000017500000000241514060132747016526 0ustar rogerroger#ifndef PASSWORD_COMMON_H #define PASSWORD_COMMON_H /* 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include enum mosquitto_pwhash_type{ pw_sha512 = 6, pw_sha512_pbkdf2 = 7, }; #define SALT_LEN 12 #define PW_DEFAULT_ITERATIONS 101 struct mosquitto_pw{ unsigned char password_hash[64]; /* For SHA512 */ unsigned char salt[SALT_LEN]; int iterations; enum mosquitto_pwhash_type hashtype; bool valid; }; int pw__hash(const char *password, struct mosquitto_pw *pw, bool new_password, int new_iterations); int pw__memcmp_const(const void *ptr1, const void *b, size_t len); int base64__encode(unsigned char *in, unsigned int in_len, char **encoded); int base64__decode(char *in, unsigned char **decoded, unsigned int *decoded_len); #endif mosquitto-2.0.11/src/Makefile0000664000175000017500000003020014060132747015105 0ustar rogerrogerinclude ../config.mk .PHONY: all install uninstall clean reallyclean all : mosquitto OBJS= mosquitto.o \ alias_mosq.o \ bridge.o \ bridge_topic.o \ conf.o \ conf_includedir.o \ context.o \ control.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 \ keepalive.o \ logging.o \ loop.o \ memory_mosq.o \ memory_public.o \ misc_mosq.o \ mux.o \ mux_epoll.o \ mux_poll.o \ net.o \ net_mosq.o \ net_mosq_ocsp.o \ packet_datatypes.o \ packet_mosq.o \ password_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 \ plugin_public.o \ read_handle.o \ retain.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 \ strings_mosq.o \ subs.o \ sys_tree.o \ time_mosq.o \ topic_tok.o \ tls_mosq.o \ utf8_mosq.o \ util_mosq.o \ util_topic.o \ websockets.o \ will_delay.o \ will_mosq.o \ xtreport.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 $@ bridge_topic.o : bridge_topic.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 $@ control.o : control.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 $@ keepalive.o : keepalive.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 $@ memory_public.o : memory_public.c mosquitto_broker_internal.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 $@ mux.o : mux.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ mux_epoll.o : mux_epoll.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ mux_poll.o : mux_poll.c mosquitto_broker_internal.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 $@ password_mosq.o : password_mosq.c password_mosq.h mosquitto_broker_internal.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 ../include/mosquitto_plugin.h mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ plugin_public.o : plugin_public.c ../include/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 $@ retain.o : retain.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 $@ strings_mosq.o : ../lib/strings_mosq.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 $@ topic_tok.o : topic_tok.c mosquitto_broker_internal.h ${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 $@ xtreport.o : xtreport.c ${CROSS_COMPILE}${CC} $(BROKER_CPPFLAGS) $(BROKER_CFLAGS) -c $< -o $@ plugin_defer.so : plugin_defer.c ../include/mosquitto_plugin.h ../include/mosquitto_broker.h mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} -I. -I../lib -fPIC -shared $< -o $@ plugin_debug.so : plugin_debug.c ../include/mosquitto_plugin.../include/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) ../include/mosquitto_broker.h "${DESTDIR}${prefix}/include/mosquitto_broker.h" $(INSTALL) ../include/mosquitto_plugin.h "${DESTDIR}${prefix}/include/mosquitto_plugin.h" uninstall : -rm -f "${DESTDIR}${prefix}/sbin/mosquitto" -rm -f "${DESTDIR}${prefix}/include/mosquitto_broker.h" -rm -f "${DESTDIR}${prefix}/include/mosquitto_plugin.h" clean : -rm -f *.o mosquitto *.gcda *.gcno reallyclean : clean -rm -rf *.orig *.db mosquitto-2.0.11/plugins/0000775000175000017500000000000014060132747014344 5ustar rogerrogermosquitto-2.0.11/plugins/CMakeLists.txt0000664000175000017500000000021614060132747017103 0ustar rogerrogeradd_subdirectory(dynamic-security) if(NOT WIN32) add_subdirectory(message-timestamp) endif(NOT WIN32) add_subdirectory(payload-modification) mosquitto-2.0.11/plugins/message-timestamp/0000775000175000017500000000000014060132747017771 5ustar rogerrogermosquitto-2.0.11/plugins/message-timestamp/CMakeLists.txt0000664000175000017500000000107114060132747022530 0ustar rogerrogerinclude_directories(${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/include ${OPENSSL_INCLUDE_DIR} ${STDBOOL_H_PATH} ${STDINT_H_PATH}) add_library(mosquitto_message_timestamp MODULE mosquitto_message_timestamp.c) set_target_properties(mosquitto_message_timestamp PROPERTIES POSITION_INDEPENDENT_CODE 1 ) set_target_properties(mosquitto_message_timestamp PROPERTIES PREFIX "") # Don't install, these are example plugins only. #install(TARGETS mosquitto_message_timestamp RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") mosquitto-2.0.11/plugins/message-timestamp/mosquitto_message_timestamp.c0000664000175000017500000000452514060132747025776 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ /* * Add an MQTT v5 user-property with key "timestamp" and value of timestamp in ISO-8601 format to all messages. * * Compile with: * gcc -I -fPIC -shared mosquitto_timestamp.c -o mosquitto_timestamp.so * * Use in config with: * * plugin /path/to/mosquitto_timestamp.so * * Note that this only works on Mosquitto 2.0 or later. */ #include "config.h" #include #include #include "mosquitto_broker.h" #include "mosquitto_plugin.h" #include "mosquitto.h" #include "mqtt_protocol.h" static mosquitto_plugin_id_t *mosq_pid = NULL; static int callback_message(int event, void *event_data, void *userdata) { struct mosquitto_evt_message *ed = event_data; struct timespec ts; struct tm *ti; char time_buf[25]; UNUSED(event); UNUSED(userdata); clock_gettime(CLOCK_REALTIME, &ts); ti = gmtime(&ts.tv_sec); strftime(time_buf, sizeof(time_buf), "%Y-%m-%dT%H:%M:%SZ", ti); return mosquitto_property_add_string_pair(&ed->properties, MQTT_PROP_USER_PROPERTY, "timestamp", time_buf); } int mosquitto_plugin_version(int supported_version_count, const int *supported_versions) { int i; for(i=0; i All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ /* * This is an example plugin showing how to use the basic authentication * callback to allow/disallow client connections based on client IP addresses. * * This is an extremely basic type of access control, password based or similar * authentication is preferred. * * Compile with: * gcc -I -fPIC -shared mosquitto_auth_by_ip.c -o mosquitto_auth_by_ip.so * * Use in config with: * * plugin /path/to/mosquitto_auth_by_ip.so * * Note that this only works on Mosquitto 2.0 or later. */ #include "config.h" #include #include #include "mosquitto_broker.h" #include "mosquitto_plugin.h" #include "mosquitto.h" #include "mqtt_protocol.h" static mosquitto_plugin_id_t *mosq_pid = NULL; static int basic_auth_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_basic_auth *ed = event_data; const char *ip_address; UNUSED(event); UNUSED(userdata); ip_address = mosquitto_client_address(ed->client); if(!strcmp(ip_address, "127.0.0.1")){ /* Only allow connections from localhost */ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } int mosquitto_plugin_version(int supported_version_count, const int *supported_versions) { int i; for(i=0; i All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ /* * This is an *example* plugin which demonstrates how to modify the payload of * a message after it is received by the broker and before it is sent on to * other clients. * * You should be very sure of what you are doing before making use of this feature. * * Compile with: * gcc -I -fPIC -shared mosquitto_payload_modification.c -o mosquitto_payload_modification.so * * Use in config with: * * plugin /path/to/mosquitto_payload_modification.so * * Note that this only works on Mosquitto 2.0 or later. */ #include #include #include "mosquitto_broker.h" #include "mosquitto_plugin.h" #include "mosquitto.h" #include "mqtt_protocol.h" #define UNUSED(A) (void)(A) static mosquitto_plugin_id_t *mosq_pid = NULL; static int callback_message(int event, void *event_data, void *userdata) { struct mosquitto_evt_message *ed = event_data; char *new_payload; uint32_t new_payloadlen; UNUSED(event); UNUSED(userdata); /* This simply adds "hello " to the front of every payload. You can of * course do much more complicated message processing if needed. */ /* Calculate the length of our new payload */ new_payloadlen = ed->payloadlen + (uint32_t)strlen("hello ")+1; /* Allocate some memory - use * mosquitto_calloc/mosquitto_malloc/mosquitto_strdup when allocating, to * allow the broker to track memory usage */ new_payload = mosquitto_calloc(1, new_payloadlen); if(new_payload == NULL){ return MOSQ_ERR_NOMEM; } /* Print "hello " to the payload */ snprintf(new_payload, new_payloadlen, "hello "); memcpy(new_payload+(uint32_t)strlen("hello "), ed->payload, ed->payloadlen); /* Assign the new payload and payloadlen to the event data structure. You * must *not* free the original payload, it will be handled by the * broker. */ ed->payload = new_payload; ed->payloadlen = new_payloadlen; return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_version(int supported_version_count, const int *supported_versions) { int i; for(i=0; i All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto.h" #include "mosquitto_broker.h" #include "json_help.h" #include "dynamic_security.h" /* ################################################################ * # * # Function declarations * # * ################################################################ */ static int dynsec__remove_client_from_all_groups(const char *username); static void client__remove_all_roles(struct dynsec__client *client); /* ################################################################ * # * # Local variables * # * ################################################################ */ static struct dynsec__client *local_clients = NULL; /* ################################################################ * # * # Utility functions * # * ################################################################ */ static int client_cmp(void *a, void *b) { struct dynsec__client *client_a = a; struct dynsec__client *client_b = b; return strcmp(client_a->username, client_b->username); } struct dynsec__client *dynsec_clients__find(const char *username) { struct dynsec__client *client = NULL; if(username){ HASH_FIND(hh, local_clients, username, strlen(username), client); } return client; } static void client__free_item(struct dynsec__client *client) { struct dynsec__client *client_found; if(client == NULL) return; client_found = dynsec_clients__find(client->username); if(client_found){ HASH_DEL(local_clients, client_found); } dynsec_rolelist__cleanup(&client->rolelist); dynsec__remove_client_from_all_groups(client->username); mosquitto_free(client->text_name); mosquitto_free(client->text_description); mosquitto_free(client->clientid); mosquitto_free(client->username); mosquitto_free(client); } void dynsec_clients__cleanup(void) { struct dynsec__client *client, *client_tmp; HASH_ITER(hh, local_clients, client, client_tmp){ client__free_item(client); } } /* ################################################################ * # * # Config file load and save * # * ################################################################ */ int dynsec_clients__config_load(cJSON *tree) { cJSON *j_clients, *j_client, *jtmp, *j_roles, *j_role; cJSON *j_salt, *j_password, *j_iterations; struct dynsec__client *client; struct dynsec__role *role; unsigned char *buf; int buf_len; int priority; int iterations; j_clients = cJSON_GetObjectItem(tree, "clients"); if(j_clients == NULL){ return 0; } if(cJSON_IsArray(j_clients) == false){ return 1; } cJSON_ArrayForEach(j_client, j_clients){ if(cJSON_IsObject(j_client) == true){ client = mosquitto_calloc(1, sizeof(struct dynsec__client)); if(client == NULL){ return MOSQ_ERR_NOMEM; } /* Username */ jtmp = cJSON_GetObjectItem(j_client, "username"); if(jtmp == NULL || !cJSON_IsString(jtmp)){ mosquitto_free(client); continue; } client->username = mosquitto_strdup(jtmp->valuestring); if(client->username == NULL){ mosquitto_free(client); continue; } jtmp = cJSON_GetObjectItem(j_client, "disabled"); if(jtmp && cJSON_IsBool(jtmp)){ client->disabled = cJSON_IsTrue(jtmp); } /* Salt */ j_salt = cJSON_GetObjectItem(j_client, "salt"); j_password = cJSON_GetObjectItem(j_client, "password"); j_iterations = cJSON_GetObjectItem(j_client, "iterations"); if(j_salt && cJSON_IsString(j_salt) && j_password && cJSON_IsString(j_password) && j_iterations && cJSON_IsNumber(j_iterations)){ iterations = (int)j_iterations->valuedouble; if(iterations < 1){ mosquitto_free(client->username); mosquitto_free(client); continue; }else{ client->pw.iterations = iterations; } if(dynsec_auth__base64_decode(j_salt->valuestring, &buf, &buf_len) != MOSQ_ERR_SUCCESS || buf_len != sizeof(client->pw.salt)){ mosquitto_free(client->username); mosquitto_free(client); continue; } memcpy(client->pw.salt, buf, (size_t)buf_len); mosquitto_free(buf); if(dynsec_auth__base64_decode(j_password->valuestring, &buf, &buf_len) != MOSQ_ERR_SUCCESS || buf_len != sizeof(client->pw.password_hash)){ mosquitto_free(client->username); mosquitto_free(client); continue; } memcpy(client->pw.password_hash, buf, (size_t)buf_len); mosquitto_free(buf); client->pw.valid = true; }else{ client->pw.valid = false; } /* Client id */ jtmp = cJSON_GetObjectItem(j_client, "clientid"); if(jtmp != NULL && cJSON_IsString(jtmp)){ client->clientid = mosquitto_strdup(jtmp->valuestring); if(client->clientid == NULL){ mosquitto_free(client->username); mosquitto_free(client); continue; } } /* Text name */ jtmp = cJSON_GetObjectItem(j_client, "textname"); if(jtmp != NULL && cJSON_IsString(jtmp)){ client->text_name = mosquitto_strdup(jtmp->valuestring); if(client->text_name == NULL){ mosquitto_free(client->clientid); mosquitto_free(client->username); mosquitto_free(client); continue; } } /* Text description */ jtmp = cJSON_GetObjectItem(j_client, "textdescription"); if(jtmp != NULL && cJSON_IsString(jtmp)){ client->text_description = mosquitto_strdup(jtmp->valuestring); if(client->text_description == NULL){ mosquitto_free(client->text_name); mosquitto_free(client->clientid); mosquitto_free(client->username); mosquitto_free(client); continue; } } /* Roles */ j_roles = cJSON_GetObjectItem(j_client, "roles"); if(j_roles && cJSON_IsArray(j_roles)){ cJSON_ArrayForEach(j_role, j_roles){ if(cJSON_IsObject(j_role)){ jtmp = cJSON_GetObjectItem(j_role, "rolename"); if(jtmp && cJSON_IsString(jtmp)){ json_get_int(j_role, "priority", &priority, true, -1); role = dynsec_roles__find(jtmp->valuestring); dynsec_rolelist__client_add(client, role, priority); } } } } HASH_ADD_KEYPTR(hh, local_clients, client->username, strlen(client->username), client); } } HASH_SORT(local_clients, client_cmp); return 0; } static int dynsec__config_add_clients(cJSON *j_clients) { struct dynsec__client *client, *client_tmp; cJSON *j_client, *j_roles, *jtmp; char *buf; HASH_ITER(hh, local_clients, client, client_tmp){ j_client = cJSON_CreateObject(); if(j_client == NULL) return 1; cJSON_AddItemToArray(j_clients, j_client); if(cJSON_AddStringToObject(j_client, "username", client->username) == NULL || (client->clientid && cJSON_AddStringToObject(j_client, "clientid", client->clientid) == NULL) || (client->text_name && cJSON_AddStringToObject(j_client, "textname", client->text_name) == NULL) || (client->text_description && cJSON_AddStringToObject(j_client, "textdescription", client->text_description) == NULL) || (client->disabled && cJSON_AddBoolToObject(j_client, "disabled", true) == NULL) ){ return 1; } j_roles = dynsec_rolelist__all_to_json(client->rolelist); if(j_roles == NULL){ return 1; } cJSON_AddItemToObject(j_client, "roles", j_roles); if(client->pw.valid){ if(dynsec_auth__base64_encode(client->pw.password_hash, sizeof(client->pw.password_hash), &buf) != MOSQ_ERR_SUCCESS){ return 1; } jtmp = cJSON_CreateString(buf); mosquitto_free(buf); if(jtmp == NULL) return 1; cJSON_AddItemToObject(j_client, "password", jtmp); if(dynsec_auth__base64_encode(client->pw.salt, sizeof(client->pw.salt), &buf) != MOSQ_ERR_SUCCESS){ return 1; } jtmp = cJSON_CreateString(buf); mosquitto_free(buf); if(jtmp == NULL) return 1; cJSON_AddItemToObject(j_client, "salt", jtmp); if(cJSON_AddIntToObject(j_client, "iterations", client->pw.iterations) == NULL){ return 1; } } } return 0; } int dynsec_clients__config_save(cJSON *tree) { cJSON *j_clients; if((j_clients = cJSON_AddArrayToObject(tree, "clients")) == NULL){ return 1; } if(dynsec__config_add_clients(j_clients)){ return 1; } return 0; } int dynsec_clients__process_create(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username, *password, *clientid = NULL; char *text_name, *text_description; struct dynsec__client *client; int rc; cJSON *j_groups, *j_group, *jtmp; int priority; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createClient", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createClient", "Username not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "password", &password, true) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createClient", "Invalid/missing password", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "clientid", &clientid, true) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createClient", "Invalid/missing client id", correlation_data); return MOSQ_ERR_INVAL; } if(clientid && mosquitto_validate_utf8(clientid, (int)strlen(clientid)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createClient", "Client ID not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "textname", &text_name, true) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createClient", "Invalid/missing textname", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "textdescription", &text_description, true) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createClient", "Invalid/missing textdescription", correlation_data); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(username); if(client){ dynsec__command_reply(j_responses, context, "createClient", "Client already exists", correlation_data); return MOSQ_ERR_SUCCESS; } client = mosquitto_calloc(1, sizeof(struct dynsec__client)); if(client == NULL){ dynsec__command_reply(j_responses, context, "createClient", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } client->username = mosquitto_strdup(username); if(client->username == NULL){ dynsec__command_reply(j_responses, context, "createClient", "Internal error", correlation_data); client__free_item(client); return MOSQ_ERR_NOMEM; } if(text_name){ client->text_name = mosquitto_strdup(text_name); if(client->text_name == NULL){ dynsec__command_reply(j_responses, context, "createClient", "Internal error", correlation_data); client__free_item(client); return MOSQ_ERR_NOMEM; } } if(text_description){ client->text_description = mosquitto_strdup(text_description); if(client->text_description == NULL){ dynsec__command_reply(j_responses, context, "createClient", "Internal error", correlation_data); client__free_item(client); return MOSQ_ERR_NOMEM; } } if(password){ if(dynsec_auth__pw_hash(client, password, client->pw.password_hash, sizeof(client->pw.password_hash), true)){ dynsec__command_reply(j_responses, context, "createClient", "Internal error", correlation_data); client__free_item(client); return MOSQ_ERR_NOMEM; } client->pw.valid = true; } if(clientid && strlen(clientid) > 0){ client->clientid = mosquitto_strdup(clientid); if(client->clientid == NULL){ dynsec__command_reply(j_responses, context, "createClient", "Internal error", correlation_data); client__free_item(client); return MOSQ_ERR_NOMEM; } } rc = dynsec_rolelist__load_from_json(command, &client->rolelist); if(rc == MOSQ_ERR_SUCCESS || rc == ERR_LIST_NOT_FOUND){ }else if(rc == MOSQ_ERR_NOT_FOUND){ dynsec__command_reply(j_responses, context, "createClient", "Role not found", correlation_data); client__free_item(client); return MOSQ_ERR_INVAL; }else{ if(rc == MOSQ_ERR_INVAL){ dynsec__command_reply(j_responses, context, "createClient", "'roles' not an array or missing/invalid rolename", correlation_data); }else{ dynsec__command_reply(j_responses, context, "createClient", "Internal error", correlation_data); } client__free_item(client); return MOSQ_ERR_INVAL; } /* Must add user before groups, otherwise adding groups will fail */ HASH_ADD_KEYPTR_INORDER(hh, local_clients, client->username, strlen(client->username), client, client_cmp); j_groups = cJSON_GetObjectItem(command, "groups"); if(j_groups && cJSON_IsArray(j_groups)){ cJSON_ArrayForEach(j_group, j_groups){ if(cJSON_IsObject(j_group)){ jtmp = cJSON_GetObjectItem(j_group, "groupname"); if(jtmp && cJSON_IsString(jtmp)){ json_get_int(j_group, "priority", &priority, true, -1); rc = dynsec_groups__add_client(username, jtmp->valuestring, priority, false); if(rc == ERR_GROUP_NOT_FOUND){ dynsec__command_reply(j_responses, context, "createClient", "Group not found", correlation_data); client__free_item(client); return MOSQ_ERR_INVAL; }else if(rc != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createClient", "Internal error", correlation_data); client__free_item(client); return MOSQ_ERR_INVAL; } } } } } dynsec__config_save(); dynsec__command_reply(j_responses, context, "createClient", NULL, correlation_data); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | createClient | username=%s | password=%s", admin_clientid, admin_username, username, password?"*****":"no password"); return MOSQ_ERR_SUCCESS; } int dynsec_clients__process_delete(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username; struct dynsec__client *client; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "deleteClient", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(username); if(client){ dynsec__remove_client_from_all_groups(username); client__remove_all_roles(client); client__free_item(client); dynsec__config_save(); dynsec__command_reply(j_responses, context, "deleteClient", NULL, correlation_data); /* Enforce any changes */ mosquitto_kick_client_by_username(username, false); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | deleteClient | username=%s", admin_clientid, admin_username, username); return MOSQ_ERR_SUCCESS; }else{ dynsec__command_reply(j_responses, context, "deleteClient", "Client not found", correlation_data); return MOSQ_ERR_SUCCESS; } } int dynsec_clients__process_disable(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username; struct dynsec__client *client; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "disableClient", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "disableClient", "Username not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(username); if(client == NULL){ dynsec__command_reply(j_responses, context, "disableClient", "Client not found", correlation_data); return MOSQ_ERR_SUCCESS; } client->disabled = true; mosquitto_kick_client_by_username(username, false); dynsec__config_save(); dynsec__command_reply(j_responses, context, "disableClient", NULL, correlation_data); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | disableClient | username=%s", admin_clientid, admin_username, username); return MOSQ_ERR_SUCCESS; } int dynsec_clients__process_enable(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username; struct dynsec__client *client; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "enableClient", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "enableClient", "Username not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(username); if(client == NULL){ dynsec__command_reply(j_responses, context, "enableClient", "Client not found", correlation_data); return MOSQ_ERR_SUCCESS; } client->disabled = false; dynsec__config_save(); dynsec__command_reply(j_responses, context, "enableClient", NULL, correlation_data); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | enableClient | username=%s", admin_clientid, admin_username, username); return MOSQ_ERR_SUCCESS; } int dynsec_clients__process_set_id(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username, *clientid, *clientid_heap = NULL; struct dynsec__client *client; size_t slen; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "setClientId", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "setClientId", "Username not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "clientid", &clientid, true) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "setClientId", "Invalid/missing client ID", correlation_data); return MOSQ_ERR_INVAL; } if(clientid){ slen = strlen(clientid); if(mosquitto_validate_utf8(clientid, (int)slen) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "setClientId", "Client ID not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(slen > 0){ clientid_heap = mosquitto_strdup(clientid); if(clientid_heap == NULL){ dynsec__command_reply(j_responses, context, "setClientId", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } }else{ clientid_heap = NULL; } } client = dynsec_clients__find(username); if(client == NULL){ mosquitto_free(clientid_heap); dynsec__command_reply(j_responses, context, "setClientId", "Client not found", correlation_data); return MOSQ_ERR_SUCCESS; } mosquitto_free(client->clientid); client->clientid = clientid_heap; dynsec__config_save(); dynsec__command_reply(j_responses, context, "setClientId", NULL, correlation_data); /* Enforce any changes */ mosquitto_kick_client_by_username(username, false); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | setClientId | username=%s | clientid=%s", admin_clientid, admin_username, username, client->clientid); return MOSQ_ERR_SUCCESS; } static int client__set_password(struct dynsec__client *client, const char *password) { if(dynsec_auth__pw_hash(client, password, client->pw.password_hash, sizeof(client->pw.password_hash), true) == MOSQ_ERR_SUCCESS){ client->pw.valid = true; return MOSQ_ERR_SUCCESS; }else{ client->pw.valid = false; /* FIXME - this should fail safe without modifying the existing password */ return MOSQ_ERR_NOMEM; } } int dynsec_clients__process_set_password(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username, *password; struct dynsec__client *client; int rc; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "setClientPassword", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "setClientPassword", "Username not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "password", &password, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "setClientPassword", "Invalid/missing password", correlation_data); return MOSQ_ERR_INVAL; } if(strlen(password) == 0){ dynsec__command_reply(j_responses, context, "setClientPassword", "Empty password is not allowed", correlation_data); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(username); if(client == NULL){ dynsec__command_reply(j_responses, context, "setClientPassword", "Client not found", correlation_data); return MOSQ_ERR_SUCCESS; } rc = client__set_password(client, password); if(rc == MOSQ_ERR_SUCCESS){ dynsec__config_save(); dynsec__command_reply(j_responses, context, "setClientPassword", NULL, correlation_data); /* Enforce any changes */ mosquitto_kick_client_by_username(username, false); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | setClientPassword | username=%s | password=******", admin_clientid, admin_username, username); }else{ dynsec__command_reply(j_responses, context, "setClientPassword", "Internal error", correlation_data); } return rc; } static void client__add_new_roles(struct dynsec__client *client, struct dynsec__rolelist *base_rolelist) { struct dynsec__rolelist *rolelist, *rolelist_tmp; HASH_ITER(hh, base_rolelist, rolelist, rolelist_tmp){ dynsec_rolelist__client_add(client, rolelist->role, rolelist->priority); } } static void client__remove_all_roles(struct dynsec__client *client) { struct dynsec__rolelist *rolelist, *rolelist_tmp; HASH_ITER(hh, client->rolelist, rolelist, rolelist_tmp){ dynsec_rolelist__client_remove(client, rolelist->role); } } int dynsec_clients__process_modify(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username; char *clientid; char *password; char *text_name, *text_description; struct dynsec__client *client; struct dynsec__rolelist *rolelist = NULL; char *str; int rc; int priority; cJSON *j_group, *j_groups, *jtmp; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "modifyClient", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "modifyClient", "Username not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(username); if(client == NULL){ dynsec__command_reply(j_responses, context, "modifyClient", "Client not found", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "clientid", &clientid, false) == MOSQ_ERR_SUCCESS){ if(clientid && strlen(clientid) > 0){ str = mosquitto_strdup(clientid); if(str == NULL){ dynsec__command_reply(j_responses, context, "modifyClient", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } }else{ str = NULL; } mosquitto_free(client->clientid); client->clientid = str; } if(json_get_string(command, "password", &password, false) == MOSQ_ERR_SUCCESS){ if(strlen(password) > 0){ /* If password == "", we just ignore it */ rc = client__set_password(client, password); if(rc != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "modifyClient", "Internal error", correlation_data); mosquitto_kick_client_by_username(username, false); return MOSQ_ERR_NOMEM; } } } if(json_get_string(command, "textname", &text_name, false) == MOSQ_ERR_SUCCESS){ str = mosquitto_strdup(text_name); if(str == NULL){ dynsec__command_reply(j_responses, context, "modifyClient", "Internal error", correlation_data); mosquitto_kick_client_by_username(username, false); return MOSQ_ERR_NOMEM; } mosquitto_free(client->text_name); client->text_name = str; } if(json_get_string(command, "textdescription", &text_description, false) == MOSQ_ERR_SUCCESS){ str = mosquitto_strdup(text_description); if(str == NULL){ dynsec__command_reply(j_responses, context, "modifyClient", "Internal error", correlation_data); mosquitto_kick_client_by_username(username, false); return MOSQ_ERR_NOMEM; } mosquitto_free(client->text_description); client->text_description = str; } rc = dynsec_rolelist__load_from_json(command, &rolelist); if(rc == MOSQ_ERR_SUCCESS){ client__remove_all_roles(client); client__add_new_roles(client, rolelist); dynsec_rolelist__cleanup(&rolelist); }else if(rc == ERR_LIST_NOT_FOUND){ /* There was no list in the JSON, so no modification */ }else if(rc == MOSQ_ERR_NOT_FOUND){ dynsec__command_reply(j_responses, context, "modifyClient", "Role not found", correlation_data); dynsec_rolelist__cleanup(&rolelist); mosquitto_kick_client_by_username(username, false); return MOSQ_ERR_INVAL; }else{ if(rc == MOSQ_ERR_INVAL){ dynsec__command_reply(j_responses, context, "modifyClient", "'roles' not an array or missing/invalid rolename", correlation_data); }else{ dynsec__command_reply(j_responses, context, "modifyClient", "Internal error", correlation_data); } dynsec_rolelist__cleanup(&rolelist); mosquitto_kick_client_by_username(username, false); return MOSQ_ERR_INVAL; } j_groups = cJSON_GetObjectItem(command, "groups"); if(j_groups && cJSON_IsArray(j_groups)){ dynsec__remove_client_from_all_groups(username); cJSON_ArrayForEach(j_group, j_groups){ if(cJSON_IsObject(j_group)){ jtmp = cJSON_GetObjectItem(j_group, "groupname"); if(jtmp && cJSON_IsString(jtmp)){ json_get_int(j_group, "priority", &priority, true, -1); dynsec_groups__add_client(username, jtmp->valuestring, priority, false); } } } } dynsec__config_save(); dynsec__command_reply(j_responses, context, "modifyClient", NULL, correlation_data); /* Enforce any changes */ mosquitto_kick_client_by_username(username, false); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | modifyClient | username=%s", admin_clientid, admin_username, username); return MOSQ_ERR_SUCCESS; } static int dynsec__remove_client_from_all_groups(const char *username) { struct dynsec__grouplist *grouplist, *grouplist_tmp; struct dynsec__client *client; client = dynsec_clients__find(username); if(client){ HASH_ITER(hh, client->grouplist, grouplist, grouplist_tmp){ dynsec_groups__remove_client(username, grouplist->group->groupname, false); } } return MOSQ_ERR_SUCCESS; } static cJSON *add_client_to_json(struct dynsec__client *client, bool verbose) { cJSON *j_client = NULL, *j_groups, *j_roles; if(verbose){ j_client = cJSON_CreateObject(); if(j_client == NULL){ return NULL; } if(cJSON_AddStringToObject(j_client, "username", client->username) == NULL || (client->clientid && cJSON_AddStringToObject(j_client, "clientid", client->clientid) == NULL) || (client->text_name && cJSON_AddStringToObject(j_client, "textname", client->text_name) == NULL) || (client->text_description && cJSON_AddStringToObject(j_client, "textdescription", client->text_description) == NULL) || (client->disabled && cJSON_AddBoolToObject(j_client, "disabled", client->disabled) == NULL) ){ cJSON_Delete(j_client); return NULL; } j_roles = dynsec_rolelist__all_to_json(client->rolelist); if(j_roles == NULL){ cJSON_Delete(j_client); return NULL; } cJSON_AddItemToObject(j_client, "roles", j_roles); j_groups = dynsec_grouplist__all_to_json(client->grouplist); if(j_groups == NULL){ cJSON_Delete(j_client); return NULL; } cJSON_AddItemToObject(j_client, "groups", j_groups); }else{ j_client = cJSON_CreateString(client->username); if(j_client == NULL){ return NULL; } } return j_client; } int dynsec_clients__process_get(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username; struct dynsec__client *client; cJSON *tree, *j_client, *j_data; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "getClient", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "getClient", "Username not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(username); if(client == NULL){ dynsec__command_reply(j_responses, context, "getClient", "Client not found", correlation_data); return MOSQ_ERR_SUCCESS; } tree = cJSON_CreateObject(); if(tree == NULL){ dynsec__command_reply(j_responses, context, "getClient", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } if(cJSON_AddStringToObject(tree, "command", "getClient") == NULL || (j_data = cJSON_AddObjectToObject(tree, "data")) == NULL || (correlation_data && cJSON_AddStringToObject(tree, "correlationData", correlation_data) == NULL) ){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "getClient", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } j_client = add_client_to_json(client, true); if(j_client == NULL){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "getClient", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(j_data, "client", j_client); cJSON_AddItemToArray(j_responses, tree); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | getClient | username=%s", admin_clientid, admin_username, username); return MOSQ_ERR_SUCCESS; } int dynsec_clients__process_list(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { bool verbose; struct dynsec__client *client, *client_tmp; cJSON *tree, *j_clients, *j_client, *j_data; int i, count, offset; const char *admin_clientid, *admin_username; json_get_bool(command, "verbose", &verbose, true, false); json_get_int(command, "count", &count, true, -1); json_get_int(command, "offset", &offset, true, 0); tree = cJSON_CreateObject(); if(tree == NULL){ dynsec__command_reply(j_responses, context, "listClients", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } if(cJSON_AddStringToObject(tree, "command", "listClients") == NULL || (j_data = cJSON_AddObjectToObject(tree, "data")) == NULL || cJSON_AddIntToObject(j_data, "totalCount", (int)HASH_CNT(hh, local_clients)) == NULL || (j_clients = cJSON_AddArrayToObject(j_data, "clients")) == NULL || (correlation_data && cJSON_AddStringToObject(tree, "correlationData", correlation_data) == NULL) ){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "listClients", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } i = 0; HASH_ITER(hh, local_clients, client, client_tmp){ if(i>=offset){ j_client = add_client_to_json(client, verbose); if(j_client == NULL){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "listClients", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_clients, j_client); if(count >= 0){ count--; if(count <= 0){ break; } } } i++; } cJSON_AddItemToArray(j_responses, tree); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | listClients | verbose=%s | count=%d | offset=%d", admin_clientid, admin_username, verbose?"true":"false", count, offset); return MOSQ_ERR_SUCCESS; } int dynsec_clients__process_add_role(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username, *rolename; struct dynsec__client *client; struct dynsec__role *role; int priority; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addClientRole", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addClientRole", "Username not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addClientRole", "Invalid/missing rolename", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addClientRole", "Role name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } json_get_int(command, "priority", &priority, true, -1); client = dynsec_clients__find(username); if(client == NULL){ dynsec__command_reply(j_responses, context, "addClientRole", "Client not found", correlation_data); return MOSQ_ERR_SUCCESS; } role = dynsec_roles__find(rolename); if(role == NULL){ dynsec__command_reply(j_responses, context, "addClientRole", "Role not found", correlation_data); return MOSQ_ERR_SUCCESS; } if(dynsec_rolelist__client_add(client, role, priority) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addClientRole", "Internal error", correlation_data); return MOSQ_ERR_UNKNOWN; } dynsec__config_save(); dynsec__command_reply(j_responses, context, "addClientRole", NULL, correlation_data); /* Enforce any changes */ mosquitto_kick_client_by_username(username, false); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | addClientRole | username=%s | rolename=%s | priority=%d", admin_clientid, admin_username, username, rolename, priority); return MOSQ_ERR_SUCCESS; } int dynsec_clients__process_remove_role(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username, *rolename; struct dynsec__client *client; struct dynsec__role *role; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeClientRole", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeClientRole", "Username not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeClientRole", "Invalid/missing rolename", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeClientRole", "Role name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(username); if(client == NULL){ dynsec__command_reply(j_responses, context, "removeClientRole", "Client not found", correlation_data); return MOSQ_ERR_SUCCESS; } role = dynsec_roles__find(rolename); if(role == NULL){ dynsec__command_reply(j_responses, context, "removeClientRole", "Role not found", correlation_data); return MOSQ_ERR_SUCCESS; } dynsec_rolelist__client_remove(client, role); dynsec__config_save(); dynsec__command_reply(j_responses, context, "removeClientRole", NULL, correlation_data); /* Enforce any changes */ mosquitto_kick_client_by_username(username, false); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | removeClientRole | username=%s | rolename=%s", admin_clientid, admin_username, username, rolename); return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/plugins/dynamic-security/json_help.h0000664000175000017500000000222514060132747021770 0ustar rogerroger#ifndef JSON_HELP_H #define JSON_HELP_H /* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include #include /* "optional==false" can also be taken to mean "only return success if the key exists and is valid" */ int json_get_bool(cJSON *json, const char *name, bool *value, bool optional, bool default_value); int json_get_int(cJSON *json, const char *name, int *value, bool optional, int default_value); int json_get_string(cJSON *json, const char *name, char **value, bool optional); cJSON *cJSON_AddIntToObject(cJSON * const object, const char * const name, int number); cJSON *cJSON_CreateInt(int num); #endif mosquitto-2.0.11/plugins/dynamic-security/CMakeLists.txt0000664000175000017500000000220114060132747022370 0ustar rogerrogerif (CJSON_FOUND AND WITH_TLS) add_definitions("-DWITH_CJSON") set( CLIENT_INC ${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/include ${STDBOOL_H_PATH} ${STDINT_H_PATH} ${PTHREAD_INCLUDE_DIR} ${OPENSSL_INCLUDE_DIR} ${mosquitto_SOURCE_DIR}/deps ${mosquitto_SOURCE_DIR}/src ${CJSON_INCLUDE_DIRS} ) set( CLIENT_DIR ${mosquitto_BINARY_DIR}/lib ${CJSON_DIR}) include_directories(${CLIENT_INC}) link_directories(${CLIENT_DIR} ${mosquitto_SOURCE_DIR}) add_library(mosquitto_dynamic_security MODULE acl.c auth.c clients.c clientlist.c dynamic_security.h groups.c grouplist.c json_help.c json_help.h plugin.c roles.c rolelist.c sub_matches_sub.c) set_target_properties(mosquitto_dynamic_security PROPERTIES POSITION_INDEPENDENT_CODE 1 ) set_target_properties(mosquitto_dynamic_security PROPERTIES PREFIX "") target_link_libraries(mosquitto_dynamic_security ${CJSON_LIBRARIES}) if(WIN32) target_link_libraries(mosquitto_dynamic_security mosquitto) endif(WIN32) install(TARGETS mosquitto_dynamic_security RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") endif() mosquitto-2.0.11/plugins/dynamic-security/auth.c0000664000175000017500000001120714060132747020743 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include "dynamic_security.h" #include "mosquitto.h" #include "mosquitto_broker.h" /* ################################################################ * # * # Base64 encoding/decoding * # * ################################################################ */ int dynsec_auth__base64_encode(unsigned char *in, int in_len, char **encoded) { BIO *bmem, *b64; BUF_MEM *bptr = NULL; if(in_len < 0) return 1; b64 = BIO_new(BIO_f_base64()); if(b64 == NULL) return 1; BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bmem = BIO_new(BIO_s_mem()); if(bmem == NULL){ BIO_free_all(b64); return 1; } b64 = BIO_push(b64, bmem); BIO_write(b64, in, in_len); if(BIO_flush(b64) != 1){ BIO_free_all(b64); return 1; } BIO_get_mem_ptr(b64, &bptr); *encoded = mosquitto_malloc(bptr->length+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; } int dynsec_auth__base64_decode(char *in, unsigned char **decoded, int *decoded_len) { BIO *bmem, *b64; size_t 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, (int)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, (int)slen); BIO_free_all(b64); if(*decoded_len <= 0){ mosquitto_free(*decoded); *decoded = NULL; *decoded_len = 0; return 1; } return 0; } /* ################################################################ * # * # Password functions * # * ################################################################ */ int dynsec_auth__pw_hash(struct dynsec__client *client, const char *password, unsigned char *password_hash, int password_hash_len, bool new_password) { const EVP_MD *digest; int iterations; if(new_password){ if(RAND_bytes(client->pw.salt, sizeof(client->pw.salt)) != 1){ return MOSQ_ERR_UNKNOWN; } iterations = PW_DEFAULT_ITERATIONS; }else{ iterations = client->pw.iterations; } if(iterations < 1){ return MOSQ_ERR_INVAL; } client->pw.iterations = iterations; digest = EVP_get_digestbyname("sha512"); if(!digest){ return MOSQ_ERR_UNKNOWN; } return !PKCS5_PBKDF2_HMAC(password, (int)strlen(password), client->pw.salt, sizeof(client->pw.salt), iterations, digest, password_hash_len, password_hash); } /* ################################################################ * # * # Username/password check * # * ################################################################ */ static int 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; iusername == NULL || ed->password == NULL) return MOSQ_ERR_PLUGIN_DEFER; client = dynsec_clients__find(ed->username); if(client){ if(client->disabled){ return MOSQ_ERR_AUTH; } if(client->clientid){ clientid = mosquitto_client_id(ed->client); if(clientid == NULL || strcmp(client->clientid, clientid)){ return MOSQ_ERR_AUTH; } } if(client->pw.valid && dynsec_auth__pw_hash(client, ed->password, password_hash, sizeof(password_hash), false) == MOSQ_ERR_SUCCESS){ if(memcmp_const(client->pw.password_hash, password_hash, sizeof(password_hash)) == 0){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } }else{ return MOSQ_ERR_PLUGIN_DEFER; } }else{ return MOSQ_ERR_PLUGIN_DEFER; } } mosquitto-2.0.11/plugins/dynamic-security/plugin.c0000664000175000017500000004756314060132747021316 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include #include "json_help.h" #include "mosquitto.h" #include "mosquitto_broker.h" #include "mosquitto_plugin.h" #include "mqtt_protocol.h" #include "dynamic_security.h" static mosquitto_plugin_id_t *plg_id = NULL; static char *config_file = NULL; struct dynsec__acl_default_access default_access = {false, false, false, false}; void dynsec__command_reply(cJSON *j_responses, struct mosquitto *context, const char *command, const char *error, const char *correlation_data) { cJSON *j_response; UNUSED(context); j_response = cJSON_CreateObject(); if(j_response == NULL) return; if(cJSON_AddStringToObject(j_response, "command", command) == NULL || (error && cJSON_AddStringToObject(j_response, "error", error) == NULL) || (correlation_data && cJSON_AddStringToObject(j_response, "correlationData", correlation_data) == NULL) ){ cJSON_Delete(j_response); return; } cJSON_AddItemToArray(j_responses, j_response); } static void send_response(cJSON *tree) { char *payload; size_t payload_len; payload = cJSON_PrintUnformatted(tree); cJSON_Delete(tree); if(payload == NULL) return; payload_len = strlen(payload); if(payload_len > MQTT_MAX_PAYLOAD){ free(payload); return; } mosquitto_broker_publish(NULL, "$CONTROL/dynamic-security/v1/response", (int)payload_len, payload, 0, 0, NULL); } static int dynsec_control_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_control *ed = event_data; cJSON *tree, *commands; cJSON *j_response_tree, *j_responses; UNUSED(event); UNUSED(userdata); /* Create object for responses */ j_response_tree = cJSON_CreateObject(); if(j_response_tree == NULL){ return MOSQ_ERR_NOMEM; } j_responses = cJSON_CreateArray(); if(j_responses == NULL){ cJSON_Delete(j_response_tree); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(j_response_tree, "responses", j_responses); /* Parse cJSON tree. * Using cJSON_ParseWithLength() is the best choice here, but Mosquitto * always adds an extra 0 to the end of the payload memory, so using * cJSON_Parse() on its own will still not overrun. */ #if CJSON_VERSION_FULL < 1007013 tree = cJSON_Parse(ed->payload); #else tree = cJSON_ParseWithLength(ed->payload, ed->payloadlen); #endif if(tree == NULL){ dynsec__command_reply(j_responses, ed->client, "Unknown command", "Payload not valid JSON", NULL); send_response(j_response_tree); return MOSQ_ERR_SUCCESS; } commands = cJSON_GetObjectItem(tree, "commands"); if(commands == NULL || !cJSON_IsArray(commands)){ cJSON_Delete(tree); dynsec__command_reply(j_responses, ed->client, "Unknown command", "Invalid/missing commands", NULL); send_response(j_response_tree); return MOSQ_ERR_SUCCESS; } /* Handle commands */ dynsec__handle_control(j_responses, ed->client, commands); cJSON_Delete(tree); send_response(j_response_tree); return MOSQ_ERR_SUCCESS; } static int dynsec__process_set_default_acl_access(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { cJSON *j_actions, *j_action, *j_acltype, *j_allow; bool allow; const char *admin_clientid, *admin_username; j_actions = cJSON_GetObjectItem(command, "acls"); if(j_actions == NULL || !cJSON_IsArray(j_actions)){ dynsec__command_reply(j_responses, context, "setDefaultACLAccess", "Missing/invalid actions array", correlation_data); return MOSQ_ERR_INVAL; } admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); cJSON_ArrayForEach(j_action, j_actions){ j_acltype = cJSON_GetObjectItem(j_action, "acltype"); j_allow = cJSON_GetObjectItem(j_action, "allow"); if(j_acltype && cJSON_IsString(j_acltype) && j_allow && cJSON_IsBool(j_allow)){ allow = cJSON_IsTrue(j_allow); if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_PUB_C_SEND)){ default_access.publish_c_send = allow; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_PUB_C_RECV)){ default_access.publish_c_recv = allow; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_SUB_GENERIC)){ default_access.subscribe = allow; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_UNSUB_GENERIC)){ default_access.unsubscribe = allow; } mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | setDefaultACLAccess | acltype=%s | allow=%s", admin_clientid, admin_username, j_acltype->valuestring, allow?"true":"false"); } } dynsec__config_save(); dynsec__command_reply(j_responses, context, "setDefaultACLAccess", NULL, correlation_data); return MOSQ_ERR_SUCCESS; } static int dynsec__process_get_default_acl_access(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { cJSON *tree, *jtmp, *j_data, *j_acls, *j_acl; const char *admin_clientid, *admin_username; UNUSED(command); tree = cJSON_CreateObject(); if(tree == NULL){ dynsec__command_reply(j_responses, context, "getDefaultACLAccess", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | getDefaultACLAccess", admin_clientid, admin_username); if(cJSON_AddStringToObject(tree, "command", "getDefaultACLAccess") == NULL || ((j_data = cJSON_AddObjectToObject(tree, "data")) == NULL) ){ goto internal_error; } j_acls = cJSON_AddArrayToObject(j_data, "acls"); if(j_acls == NULL){ goto internal_error; } /* publishClientSend */ j_acl = cJSON_CreateObject(); if(j_acl == NULL){ goto internal_error; } cJSON_AddItemToArray(j_acls, j_acl); if(cJSON_AddStringToObject(j_acl, "acltype", ACL_TYPE_PUB_C_SEND) == NULL || cJSON_AddBoolToObject(j_acl, "allow", default_access.publish_c_send) == NULL ){ goto internal_error; } /* publishClientReceive */ j_acl = cJSON_CreateObject(); if(j_acl == NULL){ goto internal_error; } cJSON_AddItemToArray(j_acls, j_acl); if(cJSON_AddStringToObject(j_acl, "acltype", ACL_TYPE_PUB_C_RECV) == NULL || cJSON_AddBoolToObject(j_acl, "allow", default_access.publish_c_recv) == NULL ){ goto internal_error; } /* subscribe */ j_acl = cJSON_CreateObject(); if(j_acl == NULL){ goto internal_error; } cJSON_AddItemToArray(j_acls, j_acl); if(cJSON_AddStringToObject(j_acl, "acltype", ACL_TYPE_SUB_GENERIC) == NULL || cJSON_AddBoolToObject(j_acl, "allow", default_access.subscribe) == NULL ){ goto internal_error; } /* unsubscribe */ j_acl = cJSON_CreateObject(); if(j_acl == NULL){ goto internal_error; } cJSON_AddItemToArray(j_acls, j_acl); if(cJSON_AddStringToObject(j_acl, "acltype", ACL_TYPE_UNSUB_GENERIC) == NULL || cJSON_AddBoolToObject(j_acl, "allow", default_access.unsubscribe) == NULL ){ goto internal_error; } cJSON_AddItemToArray(j_responses, tree); if(correlation_data){ jtmp = cJSON_AddStringToObject(tree, "correlationData", correlation_data); if(jtmp == NULL){ goto internal_error; } } return MOSQ_ERR_SUCCESS; internal_error: cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "getDefaultACLAccess", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } int mosquitto_plugin_version(int supported_version_count, const int *supported_versions) { int i; for(i=0; i All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto.h" #include "mosquitto_broker.h" #include "json_help.h" #include "dynamic_security.h" /* ################################################################ * # * # Plugin global variables * # * ################################################################ */ /* ################################################################ * # * # Function declarations * # * ################################################################ */ /* ################################################################ * # * # Local variables * # * ################################################################ */ /* ################################################################ * # * # Utility functions * # * ################################################################ */ static int dynsec_clientlist__cmp(void *a, void *b) { struct dynsec__clientlist *clientlist_a = a; struct dynsec__clientlist *clientlist_b = b; return strcmp(clientlist_a->client->username, clientlist_b->client->username); } void dynsec_clientlist__kick_all(struct dynsec__clientlist *base_clientlist) { struct dynsec__clientlist *clientlist, *clientlist_tmp; HASH_ITER(hh, base_clientlist, clientlist, clientlist_tmp){ mosquitto_kick_client_by_username(clientlist->client->username, false); } } cJSON *dynsec_clientlist__all_to_json(struct dynsec__clientlist *base_clientlist) { struct dynsec__clientlist *clientlist, *clientlist_tmp; cJSON *j_clients, *j_client; j_clients = cJSON_CreateArray(); if(j_clients == NULL) return NULL; HASH_ITER(hh, base_clientlist, clientlist, clientlist_tmp){ j_client = cJSON_CreateObject(); if(j_client == NULL){ cJSON_Delete(j_clients); return NULL; } cJSON_AddItemToArray(j_clients, j_client); if(cJSON_AddStringToObject(j_client, "username", clientlist->client->username) == NULL || (clientlist->priority != -1 && cJSON_AddIntToObject(j_client, "priority", clientlist->priority) == NULL) ){ cJSON_Delete(j_clients); return NULL; } } return j_clients; } int dynsec_clientlist__add(struct dynsec__clientlist **base_clientlist, struct dynsec__client *client, int priority) { struct dynsec__clientlist *clientlist; HASH_FIND(hh, *base_clientlist, client->username, strlen(client->username), clientlist); if(clientlist != NULL){ /* Client is already in the group */ return MOSQ_ERR_SUCCESS; } clientlist = mosquitto_malloc(sizeof(struct dynsec__clientlist)); if(clientlist == NULL){ return MOSQ_ERR_NOMEM; } clientlist->client = client; clientlist->priority = priority; HASH_ADD_KEYPTR_INORDER(hh, *base_clientlist, client->username, strlen(client->username), clientlist, dynsec_clientlist__cmp); return MOSQ_ERR_SUCCESS; } void dynsec_clientlist__cleanup(struct dynsec__clientlist **base_clientlist) { struct dynsec__clientlist *clientlist, *clientlist_tmp; HASH_ITER(hh, *base_clientlist, clientlist, clientlist_tmp){ HASH_DELETE(hh, *base_clientlist, clientlist); mosquitto_free(clientlist); } } void dynsec_clientlist__remove(struct dynsec__clientlist **base_clientlist, struct dynsec__client *client) { struct dynsec__clientlist *clientlist; HASH_FIND(hh, *base_clientlist, client->username, strlen(client->username), clientlist); if(clientlist){ HASH_DELETE(hh, *base_clientlist, clientlist); mosquitto_free(clientlist); } } mosquitto-2.0.11/plugins/dynamic-security/groups.c0000664000175000017500000010461614060132747021330 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto.h" #include "mosquitto_broker.h" #include "json_help.h" #include "dynamic_security.h" /* ################################################################ * # * # Plugin global variables * # * ################################################################ */ struct dynsec__group *dynsec_anonymous_group = NULL; /* ################################################################ * # * # Function declarations * # * ################################################################ */ static int dynsec__remove_all_clients_from_group(struct dynsec__group *group); static int dynsec__remove_all_roles_from_group(struct dynsec__group *group); static cJSON *add_group_to_json(struct dynsec__group *group); /* ################################################################ * # * # Local variables * # * ################################################################ */ static struct dynsec__group *local_groups = NULL; /* ################################################################ * # * # Utility functions * # * ################################################################ */ static void group__kick_all(struct dynsec__group *group) { if(group == dynsec_anonymous_group){ mosquitto_kick_client_by_username(NULL, false); } dynsec_clientlist__kick_all(group->clientlist); } static int group_cmp(void *a, void *b) { struct dynsec__group *group_a = a; struct dynsec__group *group_b = b; return strcmp(group_a->groupname, group_b->groupname); } struct dynsec__group *dynsec_groups__find(const char *groupname) { struct dynsec__group *group = NULL; if(groupname){ HASH_FIND(hh, local_groups, groupname, strlen(groupname), group); } return group; } static void group__free_item(struct dynsec__group *group) { struct dynsec__group *found_group = NULL; if(group == NULL) return; found_group = dynsec_groups__find(group->groupname); if(found_group){ HASH_DEL(local_groups, found_group); } dynsec__remove_all_clients_from_group(group); mosquitto_free(group->text_name); mosquitto_free(group->text_description); mosquitto_free(group->groupname); dynsec_rolelist__cleanup(&group->rolelist); mosquitto_free(group); } int dynsec_groups__process_add_role(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *groupname, *rolename; struct dynsec__group *group; struct dynsec__role *role; int priority; const char *admin_clientid, *admin_username; int rc; if(json_get_string(command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addGroupRole", "Invalid/missing groupname", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addGroupRole", "Group name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addGroupRole", "Invalid/missing rolename", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addGroupRole", "Role name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } json_get_int(command, "priority", &priority, true, -1); group = dynsec_groups__find(groupname); if(group == NULL){ dynsec__command_reply(j_responses, context, "addGroupRole", "Group not found", correlation_data); return MOSQ_ERR_SUCCESS; } role = dynsec_roles__find(rolename); if(role == NULL){ dynsec__command_reply(j_responses, context, "addGroupRole", "Role not found", correlation_data); return MOSQ_ERR_SUCCESS; } admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); rc = dynsec_rolelist__group_add(group, role, priority); if(rc == MOSQ_ERR_SUCCESS){ /* Continue */ }else if(rc == MOSQ_ERR_ALREADY_EXISTS){ dynsec__command_reply(j_responses, context, "addGroupRole", "Group is already in this role", correlation_data); return MOSQ_ERR_ALREADY_EXISTS; }else{ dynsec__command_reply(j_responses, context, "addGroupRole", "Internal error", correlation_data); return MOSQ_ERR_UNKNOWN; } mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | addGroupRole | groupname=%s | rolename=%s | priority=%d", admin_clientid, admin_username, groupname, rolename, priority); dynsec__config_save(); dynsec__command_reply(j_responses, context, "addGroupRole", NULL, correlation_data); /* Enforce any changes */ group__kick_all(group); return MOSQ_ERR_SUCCESS; } void dynsec_groups__cleanup(void) { struct dynsec__group *group, *group_tmp = NULL; HASH_ITER(hh, local_groups, group, group_tmp){ group__free_item(group); } } /* ################################################################ * # * # Config file load * # * ################################################################ */ int dynsec_groups__config_load(cJSON *tree) { cJSON *j_groups, *j_group; cJSON *j_clientlist, *j_client, *j_username; cJSON *j_roles, *j_role, *j_rolename; struct dynsec__group *group; struct dynsec__role *role; char *str; int priority; j_groups = cJSON_GetObjectItem(tree, "groups"); if(j_groups == NULL){ return 0; } if(cJSON_IsArray(j_groups) == false){ return 1; } cJSON_ArrayForEach(j_group, j_groups){ if(cJSON_IsObject(j_group) == true){ group = mosquitto_calloc(1, sizeof(struct dynsec__group)); if(group == NULL){ return MOSQ_ERR_NOMEM; } /* Group name */ if(json_get_string(j_group, "groupname", &str, false) != MOSQ_ERR_SUCCESS){ mosquitto_free(group); continue; } group->groupname = strdup(str); if(group->groupname == NULL){ mosquitto_free(group); continue; } /* Text name */ if(json_get_string(j_group, "textname", &str, false) == MOSQ_ERR_SUCCESS){ if(str){ group->text_name = strdup(str); if(group->text_name == NULL){ mosquitto_free(group->groupname); mosquitto_free(group); continue; } } } /* Text description */ if(json_get_string(j_group, "textdescription", &str, false) == MOSQ_ERR_SUCCESS){ if(str){ group->text_description = strdup(str); if(group->text_description == NULL){ mosquitto_free(group->text_name); mosquitto_free(group->groupname); mosquitto_free(group); continue; } } } /* Roles */ j_roles = cJSON_GetObjectItem(j_group, "roles"); if(j_roles && cJSON_IsArray(j_roles)){ cJSON_ArrayForEach(j_role, j_roles){ if(cJSON_IsObject(j_role)){ j_rolename = cJSON_GetObjectItem(j_role, "rolename"); if(j_rolename && cJSON_IsString(j_rolename)){ json_get_int(j_role, "priority", &priority, true, -1); role = dynsec_roles__find(j_rolename->valuestring); dynsec_rolelist__group_add(group, role, priority); } } } } /* This must go before clients are loaded, otherwise the group won't be found */ HASH_ADD_KEYPTR(hh, local_groups, group->groupname, strlen(group->groupname), group); /* Clients */ j_clientlist = cJSON_GetObjectItem(j_group, "clients"); if(j_clientlist && cJSON_IsArray(j_clientlist)){ cJSON_ArrayForEach(j_client, j_clientlist){ if(cJSON_IsObject(j_client)){ j_username = cJSON_GetObjectItem(j_client, "username"); if(j_username && cJSON_IsString(j_username)){ json_get_int(j_client, "priority", &priority, true, -1); dynsec_groups__add_client(j_username->valuestring, group->groupname, priority, false); } } } } } } HASH_SORT(local_groups, group_cmp); j_group = cJSON_GetObjectItem(tree, "anonymousGroup"); if(j_group && cJSON_IsString(j_group)){ dynsec_anonymous_group = dynsec_groups__find(j_group->valuestring); } return 0; } /* ################################################################ * # * # Config load and save * # * ################################################################ */ static int dynsec__config_add_groups(cJSON *j_groups) { struct dynsec__group *group, *group_tmp = NULL; cJSON *j_group, *j_clients, *j_roles; HASH_ITER(hh, local_groups, group, group_tmp){ j_group = cJSON_CreateObject(); if(j_group == NULL) return 1; cJSON_AddItemToArray(j_groups, j_group); if(cJSON_AddStringToObject(j_group, "groupname", group->groupname) == NULL || (group->text_name && cJSON_AddStringToObject(j_group, "textname", group->text_name) == NULL) || (group->text_description && cJSON_AddStringToObject(j_group, "textdescription", group->text_description) == NULL) ){ return 1; } j_roles = dynsec_rolelist__all_to_json(group->rolelist); if(j_roles == NULL){ return 1; } cJSON_AddItemToObject(j_group, "roles", j_roles); j_clients = dynsec_clientlist__all_to_json(group->clientlist); if(j_clients == NULL){ return 1; } cJSON_AddItemToObject(j_group, "clients", j_clients); } return 0; } int dynsec_groups__config_save(cJSON *tree) { cJSON *j_groups; j_groups = cJSON_CreateArray(); if(j_groups == NULL){ return 1; } cJSON_AddItemToObject(tree, "groups", j_groups); if(dynsec__config_add_groups(j_groups)){ return 1; } if(dynsec_anonymous_group && cJSON_AddStringToObject(tree, "anonymousGroup", dynsec_anonymous_group->groupname) == NULL){ return 1; } return 0; } int dynsec_groups__process_create(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *groupname, *text_name, *text_description; struct dynsec__group *group = NULL; int rc = MOSQ_ERR_SUCCESS; const char *admin_clientid, *admin_username; if(json_get_string(command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createGroup", "Invalid/missing groupname", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createGroup", "Group name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "textname", &text_name, true) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createGroup", "Invalid/missing textname", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "textdescription", &text_description, true) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createGroup", "Invalid/missing textdescription", correlation_data); return MOSQ_ERR_INVAL; } group = dynsec_groups__find(groupname); if(group){ dynsec__command_reply(j_responses, context, "createGroup", "Group already exists", correlation_data); return MOSQ_ERR_SUCCESS; } group = mosquitto_calloc(1, sizeof(struct dynsec__group)); if(group == NULL){ dynsec__command_reply(j_responses, context, "createGroup", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } group->groupname = strdup(groupname); if(group->groupname == NULL){ dynsec__command_reply(j_responses, context, "createGroup", "Internal error", correlation_data); group__free_item(group); return MOSQ_ERR_NOMEM; } if(text_name){ group->text_name = strdup(text_name); if(group->text_name == NULL){ dynsec__command_reply(j_responses, context, "createGroup", "Internal error", correlation_data); group__free_item(group); return MOSQ_ERR_NOMEM; } } if(text_description){ group->text_description = strdup(text_description); if(group->text_description == NULL){ dynsec__command_reply(j_responses, context, "createGroup", "Internal error", correlation_data); group__free_item(group); return MOSQ_ERR_NOMEM; } } rc = dynsec_rolelist__load_from_json(command, &group->rolelist); if(rc == MOSQ_ERR_SUCCESS || rc == ERR_LIST_NOT_FOUND){ }else if(rc == MOSQ_ERR_NOT_FOUND){ dynsec__command_reply(j_responses, context, "createGroup", "Role not found", correlation_data); group__free_item(group); return MOSQ_ERR_INVAL; }else{ dynsec__command_reply(j_responses, context, "createGroup", "Internal error", correlation_data); group__free_item(group); return MOSQ_ERR_INVAL; } HASH_ADD_KEYPTR_INORDER(hh, local_groups, group->groupname, strlen(group->groupname), group, group_cmp); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | createGroup | groupname=%s", admin_clientid, admin_username, groupname); dynsec__config_save(); dynsec__command_reply(j_responses, context, "createGroup", NULL, correlation_data); return MOSQ_ERR_SUCCESS; } int dynsec_groups__process_delete(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *groupname; struct dynsec__group *group; const char *admin_clientid, *admin_username; if(json_get_string(command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "deleteGroup", "Invalid/missing groupname", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "deleteGroup", "Group name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } group = dynsec_groups__find(groupname); if(group){ /* Enforce any changes */ group__kick_all(group); dynsec__remove_all_roles_from_group(group); group__free_item(group); dynsec__config_save(); dynsec__command_reply(j_responses, context, "deleteGroup", NULL, correlation_data); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | deleteGroup | groupname=%s", admin_clientid, admin_username, groupname); return MOSQ_ERR_SUCCESS; }else{ dynsec__command_reply(j_responses, context, "deleteGroup", "Group not found", correlation_data); return MOSQ_ERR_SUCCESS; } } int dynsec_groups__add_client(const char *username, const char *groupname, int priority, bool update_config) { struct dynsec__client *client; struct dynsec__clientlist *clientlist; struct dynsec__group *group; int rc; client = dynsec_clients__find(username); if(client == NULL){ return ERR_USER_NOT_FOUND; } group = dynsec_groups__find(groupname); if(group == NULL){ return ERR_GROUP_NOT_FOUND; } HASH_FIND(hh, group->clientlist, username, strlen(username), clientlist); if(clientlist != NULL){ /* Client is already in the group */ return MOSQ_ERR_ALREADY_EXISTS; } rc = dynsec_clientlist__add(&group->clientlist, client, priority); if(rc){ return rc; } rc = dynsec_grouplist__add(&client->grouplist, group, priority); if(rc){ dynsec_clientlist__remove(&group->clientlist, client); return rc; } if(update_config){ dynsec__config_save(); } return MOSQ_ERR_SUCCESS; } int dynsec_groups__process_add_client(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username, *groupname; int rc; int priority; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addGroupClient", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addGroupClient", "Username not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addGroupClient", "Invalid/missing groupname", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addGroupClient", "Group name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } json_get_int(command, "priority", &priority, true, -1); rc = dynsec_groups__add_client(username, groupname, priority, true); if(rc == MOSQ_ERR_SUCCESS){ admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | addGroupClient | groupname=%s | username=%s | priority=%d", admin_clientid, admin_username, groupname, username, priority); dynsec__command_reply(j_responses, context, "addGroupClient", NULL, correlation_data); }else if(rc == ERR_USER_NOT_FOUND){ dynsec__command_reply(j_responses, context, "addGroupClient", "Client not found", correlation_data); }else if(rc == ERR_GROUP_NOT_FOUND){ dynsec__command_reply(j_responses, context, "addGroupClient", "Group not found", correlation_data); }else if(rc == MOSQ_ERR_ALREADY_EXISTS){ dynsec__command_reply(j_responses, context, "addGroupClient", "Client is already in this group", correlation_data); }else{ dynsec__command_reply(j_responses, context, "addGroupClient", "Internal error", correlation_data); } /* Enforce any changes */ mosquitto_kick_client_by_username(username, false); return rc; } static int dynsec__remove_all_clients_from_group(struct dynsec__group *group) { struct dynsec__clientlist *clientlist, *clientlist_tmp = NULL; HASH_ITER(hh, group->clientlist, clientlist, clientlist_tmp){ /* Remove client stored group reference */ dynsec_grouplist__remove(&clientlist->client->grouplist, group); HASH_DELETE(hh, group->clientlist, clientlist); mosquitto_free(clientlist); } return MOSQ_ERR_SUCCESS; } static int dynsec__remove_all_roles_from_group(struct dynsec__group *group) { struct dynsec__rolelist *rolelist, *rolelist_tmp = NULL; HASH_ITER(hh, group->rolelist, rolelist, rolelist_tmp){ dynsec_rolelist__group_remove(group, rolelist->role); } return MOSQ_ERR_SUCCESS; } int dynsec_groups__remove_client(const char *username, const char *groupname, bool update_config) { struct dynsec__client *client; struct dynsec__group *group; client = dynsec_clients__find(username); if(client == NULL){ return ERR_USER_NOT_FOUND; } group = dynsec_groups__find(groupname); if(group == NULL){ return ERR_GROUP_NOT_FOUND; } dynsec_clientlist__remove(&group->clientlist, client); dynsec_grouplist__remove(&client->grouplist, group); if(update_config){ dynsec__config_save(); } return MOSQ_ERR_SUCCESS; } int dynsec_groups__process_remove_client(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *username, *groupname; int rc; const char *admin_clientid, *admin_username; if(json_get_string(command, "username", &username, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeGroupClient", "Invalid/missing username", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeGroupClient", "Username not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeGroupClient", "Invalid/missing groupname", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeGroupClient", "Group name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } rc = dynsec_groups__remove_client(username, groupname, true); if(rc == MOSQ_ERR_SUCCESS){ admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | removeGroupClient | groupname=%s | username=%s", admin_clientid, admin_username, groupname, username); dynsec__command_reply(j_responses, context, "removeGroupClient", NULL, correlation_data); }else if(rc == ERR_USER_NOT_FOUND){ dynsec__command_reply(j_responses, context, "removeGroupClient", "Client not found", correlation_data); }else if(rc == ERR_GROUP_NOT_FOUND){ dynsec__command_reply(j_responses, context, "removeGroupClient", "Group not found", correlation_data); }else{ dynsec__command_reply(j_responses, context, "removeGroupClient", "Internal error", correlation_data); } /* Enforce any changes */ mosquitto_kick_client_by_username(username, false); return rc; } static cJSON *add_group_to_json(struct dynsec__group *group) { cJSON *j_group, *jtmp, *j_clientlist, *j_client, *j_rolelist; struct dynsec__clientlist *clientlist, *clientlist_tmp = NULL; j_group = cJSON_CreateObject(); if(j_group == NULL){ return NULL; } if(cJSON_AddStringToObject(j_group, "groupname", group->groupname) == NULL || (group->text_name && cJSON_AddStringToObject(j_group, "textname", group->text_name) == NULL) || (group->text_description && cJSON_AddStringToObject(j_group, "textdescription", group->text_description) == NULL) || (j_clientlist = cJSON_AddArrayToObject(j_group, "clients")) == NULL ){ cJSON_Delete(j_group); return NULL; } HASH_ITER(hh, group->clientlist, clientlist, clientlist_tmp){ j_client = cJSON_CreateObject(); if(j_client == NULL){ cJSON_Delete(j_group); return NULL; } cJSON_AddItemToArray(j_clientlist, j_client); jtmp = cJSON_CreateStringReference(clientlist->client->username); if(jtmp == NULL){ cJSON_Delete(j_group); return NULL; } cJSON_AddItemToObject(j_client, "username", jtmp); } j_rolelist = dynsec_rolelist__all_to_json(group->rolelist); if(j_rolelist == NULL){ cJSON_Delete(j_group); return NULL; } cJSON_AddItemToObject(j_group, "roles", j_rolelist); return j_group; } int dynsec_groups__process_list(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { bool verbose; cJSON *tree, *j_groups, *j_group, *j_data; struct dynsec__group *group, *group_tmp = NULL; int i, count, offset; const char *admin_clientid, *admin_username; json_get_bool(command, "verbose", &verbose, true, false); json_get_int(command, "count", &count, true, -1); json_get_int(command, "offset", &offset, true, 0); tree = cJSON_CreateObject(); if(tree == NULL){ dynsec__command_reply(j_responses, context, "listGroups", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } if(cJSON_AddStringToObject(tree, "command", "listGroups") == NULL || (j_data = cJSON_AddObjectToObject(tree, "data")) == NULL || cJSON_AddIntToObject(j_data, "totalCount", (int)HASH_CNT(hh, local_groups)) == NULL || (j_groups = cJSON_AddArrayToObject(j_data, "groups")) == NULL || (correlation_data && cJSON_AddStringToObject(tree, "correlationData", correlation_data) == NULL) ){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "listGroups", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } i = 0; HASH_ITER(hh, local_groups, group, group_tmp){ if(i>=offset){ if(verbose){ j_group = add_group_to_json(group); if(j_group == NULL){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "listGroups", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_groups, j_group); }else{ j_group = cJSON_CreateString(group->groupname); if(j_group){ cJSON_AddItemToArray(j_groups, j_group); }else{ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "listGroups", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } } if(count >= 0){ count--; if(count <= 0){ break; } } } i++; } cJSON_AddItemToArray(j_responses, tree); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | listGroups | verbose=%s | count=%d | offset=%d", admin_clientid, admin_username, verbose?"true":"false", count, offset); return MOSQ_ERR_SUCCESS; } int dynsec_groups__process_get(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *groupname; cJSON *tree, *j_group, *j_data; struct dynsec__group *group; const char *admin_clientid, *admin_username; if(json_get_string(command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "getGroup", "Invalid/missing groupname", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "getGroup", "Group name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } tree = cJSON_CreateObject(); if(tree == NULL){ dynsec__command_reply(j_responses, context, "getGroup", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } if(cJSON_AddStringToObject(tree, "command", "getGroup") == NULL || (j_data = cJSON_AddObjectToObject(tree, "data")) == NULL || (correlation_data && cJSON_AddStringToObject(tree, "correlationData", correlation_data) == NULL) ){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "getGroup", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } group = dynsec_groups__find(groupname); if(group){ j_group = add_group_to_json(group); if(j_group == NULL){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "getGroup", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(j_data, "group", j_group); }else{ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "getGroup", "Group not found", correlation_data); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_responses, tree); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | getGroup | groupname=%s", admin_clientid, admin_username, groupname); return MOSQ_ERR_SUCCESS; } int dynsec_groups__process_remove_role(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *groupname, *rolename; struct dynsec__group *group; struct dynsec__role *role; const char *admin_clientid, *admin_username; if(json_get_string(command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeGroupRole", "Invalid/missing groupname", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeGroupRole", "Group name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeGroupRole", "Invalid/missing rolename", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeGroupRole", "Role name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } group = dynsec_groups__find(groupname); if(group == NULL){ dynsec__command_reply(j_responses, context, "removeGroupRole", "Group not found", correlation_data); return MOSQ_ERR_SUCCESS; } role = dynsec_roles__find(rolename); if(role == NULL){ dynsec__command_reply(j_responses, context, "removeGroupRole", "Role not found", correlation_data); return MOSQ_ERR_SUCCESS; } dynsec_rolelist__group_remove(group, role); dynsec__config_save(); dynsec__command_reply(j_responses, context, "removeGroupRole", NULL, correlation_data); /* Enforce any changes */ group__kick_all(group); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | removeGroupRole | groupname=%s | rolename=%s", admin_clientid, admin_username, groupname, rolename); return MOSQ_ERR_SUCCESS; } int dynsec_groups__process_modify(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *groupname; char *text_name, *text_description; struct dynsec__group *group; struct dynsec__rolelist *rolelist = NULL; char *str; int rc; int priority; cJSON *j_client, *j_clients, *jtmp; const char *admin_clientid, *admin_username; if(json_get_string(command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "modifyGroup", "Invalid/missing groupname", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "modifyGroup", "Group name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } group = dynsec_groups__find(groupname); if(group == NULL){ dynsec__command_reply(j_responses, context, "modifyGroup", "Group not found", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "textname", &text_name, false) == MOSQ_ERR_SUCCESS){ str = mosquitto_strdup(text_name); if(str == NULL){ dynsec__command_reply(j_responses, context, "modifyGroup", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } mosquitto_free(group->text_name); group->text_name = str; } if(json_get_string(command, "textdescription", &text_description, false) == MOSQ_ERR_SUCCESS){ str = mosquitto_strdup(text_description); if(str == NULL){ dynsec__command_reply(j_responses, context, "modifyGroup", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } mosquitto_free(group->text_description); group->text_description = str; } rc = dynsec_rolelist__load_from_json(command, &rolelist); if(rc == MOSQ_ERR_SUCCESS){ dynsec_rolelist__cleanup(&group->rolelist); group->rolelist = rolelist; }else if(rc == ERR_LIST_NOT_FOUND){ /* There was no list in the JSON, so no modification */ }else if(rc == MOSQ_ERR_NOT_FOUND){ dynsec__command_reply(j_responses, context, "modifyGroup", "Role not found", correlation_data); dynsec_rolelist__cleanup(&rolelist); group__kick_all(group); return MOSQ_ERR_INVAL; }else{ if(rc == MOSQ_ERR_INVAL){ dynsec__command_reply(j_responses, context, "modifyGroup", "'roles' not an array or missing/invalid rolename", correlation_data); }else{ dynsec__command_reply(j_responses, context, "modifyGroup", "Internal error", correlation_data); } dynsec_rolelist__cleanup(&rolelist); group__kick_all(group); return MOSQ_ERR_INVAL; } j_clients = cJSON_GetObjectItem(command, "clients"); if(j_clients && cJSON_IsArray(j_clients)){ dynsec__remove_all_clients_from_group(group); cJSON_ArrayForEach(j_client, j_clients){ if(cJSON_IsObject(j_client)){ jtmp = cJSON_GetObjectItem(j_client, "username"); if(jtmp && cJSON_IsString(jtmp)){ json_get_int(j_client, "priority", &priority, true, -1); dynsec_groups__add_client(jtmp->valuestring, groupname, priority, false); } } } } dynsec__config_save(); dynsec__command_reply(j_responses, context, "modifyGroup", NULL, correlation_data); /* Enforce any changes */ group__kick_all(group); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | modifyGroup | groupname=%s", admin_clientid, admin_username, groupname); return MOSQ_ERR_SUCCESS; } int dynsec_groups__process_set_anonymous_group(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *groupname; struct dynsec__group *group = NULL; const char *admin_clientid, *admin_username; if(json_get_string(command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "setAnonymousGroup", "Invalid/missing groupname", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "setAnonymousGroup", "Group name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } group = dynsec_groups__find(groupname); if(group == NULL){ dynsec__command_reply(j_responses, context, "setAnonymousGroup", "Group not found", correlation_data); return MOSQ_ERR_SUCCESS; } dynsec_anonymous_group = group; dynsec__config_save(); dynsec__command_reply(j_responses, context, "setAnonymousGroup", NULL, correlation_data); /* Enforce any changes */ mosquitto_kick_client_by_username(NULL, false); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | setAnonymousGroup | groupname=%s", admin_clientid, admin_username, groupname); return MOSQ_ERR_SUCCESS; } int dynsec_groups__process_get_anonymous_group(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { cJSON *tree, *j_data, *j_group; const char *groupname; const char *admin_clientid, *admin_username; UNUSED(command); tree = cJSON_CreateObject(); if(tree == NULL){ dynsec__command_reply(j_responses, context, "getAnonymousGroup", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } if(dynsec_anonymous_group){ groupname = dynsec_anonymous_group->groupname; }else{ groupname = ""; } if(cJSON_AddStringToObject(tree, "command", "getAnonymousGroup") == NULL || (j_data = cJSON_AddObjectToObject(tree, "data")) == NULL || (j_group = cJSON_AddObjectToObject(j_data, "group")) == NULL || cJSON_AddStringToObject(j_group, "groupname", groupname) == NULL || (correlation_data && cJSON_AddStringToObject(tree, "correlationData", correlation_data) == NULL) ){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "getAnonymousGroup", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_responses, tree); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | getAnonymousGroup", admin_clientid, admin_username); return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/plugins/dynamic-security/sub_matches_sub.c0000664000175000017500000001204314060132747023147 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include #include #include #include #include "dynamic_security.h" static char *strtok_hier(char *str, char **saveptr) { char *c; if(str != NULL){ *saveptr = str; } if(*saveptr == NULL){ return NULL; } c = strchr(*saveptr, '/'); if(c){ str = *saveptr; *saveptr = c+1; c[0] = '\0'; }else if(*saveptr){ /* No match, but surplus string */ str = *saveptr; *saveptr = NULL; } return str; } static int count_hier_levels(const char *s) { int count = 1; const char *c = s; while((c = strchr(c, '/')) && c[0]){ c++; count++; } return count; } static bool hash_check(char *s, size_t *len) { if((*len) == 1 && s[0] == '#'){ s[0] = '\0'; (*len)--; return true; }else if((*len) > 1 && s[(*len)-2] == '/' && s[(*len)-1] == '#'){ s[(*len)-2] = '\0'; s[(*len)-1] = '\0'; (*len) -= 2; return true; } return false; } bool sub_acl_check(const char *acl, const char *sub) { char *acl_local; char *sub_local; size_t acl_len, sub_len; bool acl_hash = false, sub_hash = false; int acl_levels, sub_levels; int i; char *acl_token, *sub_token; char *acl_saveptr, *sub_saveptr; acl_len = strlen(acl); if(acl_len == 1 && acl[0] == '#'){ return true; } sub_len = strlen(sub); /* mosquitto_validate_utf8(acl, acl_len); */ acl_local = strdup(acl); sub_local = strdup(sub); if(acl_local == NULL || sub_local == NULL){ free(acl_local); free(sub_local); return false; } acl_hash = hash_check(acl_local, &acl_len); sub_hash = hash_check(sub_local, &sub_len); if(sub_hash == true && acl_hash == false){ free(acl_local); free(sub_local); return false; } acl_levels = count_hier_levels(acl_local); sub_levels = count_hier_levels(sub_local); if(acl_levels > sub_levels){ free(acl_local); free(sub_local); return false; }else if(sub_levels > acl_levels){ if(acl_hash == false){ free(acl_local); free(sub_local); return false; } } acl_saveptr = acl_local; sub_saveptr = sub_local; for(i=0; i=acl_levels && acl_hash == true){ /* The sub has more levels of hierarchy than the acl, but the acl * ends in a multi level wildcard so the match is fine. */ }else{ free(acl_local); free(sub_local); return false; } } free(acl_local); free(sub_local); return true; } #ifdef TEST #define BLK "\e[0;30m" #define RED "\e[0;31m" #define GRN "\e[0;32m" #define YEL "\e[0;33m" #define BLU "\e[0;34m" #define MAG "\e[0;35m" #define CYN "\e[0;36m" #define WHT "\e[0;37m" #define RST "\e[0m" void hier_test(const char *s, int expected) { int levels; levels = count_hier_levels(s); printf("HIER %s %d:%d ", s, expected, levels); if(levels == expected){ printf(GRN "passed" RST "\n"); }else{ printf(RED "failed" RST "\n"); } } void test(const char *sub1, const char *sub2, bool expected) { bool result; printf("ACL %s : %s ", sub1, sub2); result = sub_acl_check(sub1, sub2); if(result == expected){ printf(GRN "passed\n" RST); }else{ printf(RED "failed\n" RST); } } int main(int argc, char *argv[]) { hier_test("foo/+/bar", 3); hier_test("foo/#", 2); hier_test("foo/+/ba℞/#", 4); hier_test("foo/baz/ba℞", 3); hier_test("foo/+/ba℞/#", 4); hier_test("foo/baz/ba℞/+", 4); hier_test("foo/+/ba℞/#", 4); hier_test("foo/baz/ba℞/#", 4); hier_test("foo/+/ba℞/#", 4); hier_test("foo/baz/+/#", 4); hier_test("/+//#", 4); hier_test("/foo///#", 5); hier_test("#", 1); hier_test("+", 1); hier_test("/", 2); hier_test("////////////////////////////////////////////////////////////////////////////////////////////////////", 101); test("foo/+/bar", "foo/#", false); test("foo/+/ba℞/#", "foo/baz/ba℞", true); test("foo/+/ba℞/#", "foo/baz/ba℞/+", true); test("foo/+/ba℞/#", "foo/baz/ba℞/#", true); test("foo/+/ba℞/#", "foo/baz/+/#", false); test("/+//#", "/foo///#", true); test("#", "#", true); test("#", "+", true); test("/#", "+", false); test("/#", "/+", true); test("/+", "#", false); test("/+", "+", false); test("+/+", "topic/topic", true); test("+/+", "topic/topic/", false); test("+", "#", false); test("+", "+", true); test("a/b/c/d/e", "a/b/c/d/e", true); test("a/b/ /d/e", "a/b/c/d/e", false); return 0; } #endif mosquitto-2.0.11/plugins/dynamic-security/dynamic_security.h0000664000175000017500000002625714060132747023375 0ustar rogerroger#ifndef DYNAMIC_SECURITY_H #define DYNAMIC_SECURITY_H /* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include #include #include "mosquitto.h" #include "password_mosq.h" /* ################################################################ * # * # ACL types * # * ################################################################ */ #define ACL_TYPE_PUB_C_RECV "publishClientReceive" #define ACL_TYPE_PUB_C_SEND "publishClientSend" #define ACL_TYPE_SUB_GENERIC "subscribe" #define ACL_TYPE_SUB_LITERAL "subscribeLiteral" #define ACL_TYPE_SUB_PATTERN "subscribePattern" #define ACL_TYPE_UNSUB_GENERIC "unsubscribe" #define ACL_TYPE_UNSUB_LITERAL "unsubscribeLiteral" #define ACL_TYPE_UNSUB_PATTERN "unsubscribePattern" /* ################################################################ * # * # Error codes * # * ################################################################ */ #define ERR_USER_NOT_FOUND 10000 #define ERR_GROUP_NOT_FOUND 10001 #define ERR_LIST_NOT_FOUND 10002 /* ################################################################ * # * # Datatypes * # * ################################################################ */ struct dynsec__clientlist{ UT_hash_handle hh; struct dynsec__client *client; int priority; }; struct dynsec__grouplist{ UT_hash_handle hh; struct dynsec__group *group; int priority; }; struct dynsec__rolelist{ UT_hash_handle hh; char *rolename; struct dynsec__role *role; int priority; }; struct dynsec__client{ UT_hash_handle hh; struct mosquitto_pw pw; struct dynsec__rolelist *rolelist; struct dynsec__grouplist *grouplist; char *username; char *clientid; char *text_name; char *text_description; bool disabled; }; struct dynsec__group{ UT_hash_handle hh; struct dynsec__rolelist *rolelist; struct dynsec__clientlist *clientlist; char *groupname; char *text_name; char *text_description; }; struct dynsec__acl{ UT_hash_handle hh; char *topic; int priority; bool allow; }; struct dynsec__acls{ struct dynsec__acl *publish_c_send; struct dynsec__acl *publish_c_recv; struct dynsec__acl *subscribe_literal; struct dynsec__acl *subscribe_pattern; struct dynsec__acl *unsubscribe_literal; struct dynsec__acl *unsubscribe_pattern; }; struct dynsec__role{ UT_hash_handle hh; struct dynsec__acls acls; struct dynsec__clientlist *clientlist; struct dynsec__grouplist *grouplist; char *rolename; char *text_name; char *text_description; }; struct dynsec__acl_default_access{ bool publish_c_send; bool publish_c_recv; bool subscribe; bool unsubscribe; }; extern struct dynsec__group *dynsec_anonymous_group; extern struct dynsec__acl_default_access default_access; /* ################################################################ * # * # Plugin Functions * # * ################################################################ */ void dynsec__config_save(void); int dynsec__handle_control(cJSON *j_responses, struct mosquitto *context, cJSON *commands); void dynsec__command_reply(cJSON *j_responses, struct mosquitto *context, const char *command, const char *error, const char *correlation_data); /* ################################################################ * # * # ACL Functions * # * ################################################################ */ int dynsec__acl_check_callback(int event, void *event_data, void *userdata); bool sub_acl_check(const char *acl, const char *sub); /* ################################################################ * # * # Auth Functions * # * ################################################################ */ int dynsec_auth__base64_encode(unsigned char *in, int in_len, char **encoded); int dynsec_auth__base64_decode(char *in, unsigned char **decoded, int *decoded_len); int dynsec_auth__pw_hash(struct dynsec__client *client, const char *password, unsigned char *password_hash, int password_hash_len, bool new_password); int dynsec_auth__basic_auth_callback(int event, void *event_data, void *userdata); /* ################################################################ * # * # Client Functions * # * ################################################################ */ void dynsec_clients__cleanup(void); int dynsec_clients__config_load(cJSON *tree); int dynsec_clients__config_save(cJSON *tree); int dynsec_clients__process_add_role(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_clients__process_create(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_clients__process_delete(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_clients__process_disable(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_clients__process_enable(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_clients__process_get(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_clients__process_list(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_clients__process_modify(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_clients__process_remove_role(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_clients__process_set_id(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_clients__process_set_password(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); struct dynsec__client *dynsec_clients__find(const char *username); /* ################################################################ * # * # Client List Functions * # * ################################################################ */ cJSON *dynsec_clientlist__all_to_json(struct dynsec__clientlist *base_clientlist); int dynsec_clientlist__add(struct dynsec__clientlist **base_clientlist, struct dynsec__client *client, int priority); void dynsec_clientlist__cleanup(struct dynsec__clientlist **base_clientlist); void dynsec_clientlist__remove(struct dynsec__clientlist **base_clientlist, struct dynsec__client *client); void dynsec_clientlist__kick_all(struct dynsec__clientlist *base_clientlist); /* ################################################################ * # * # Group Functions * # * ################################################################ */ void dynsec_groups__cleanup(void); int dynsec_groups__config_load(cJSON *tree); int dynsec_groups__add_client(const char *username, const char *groupname, int priority, bool update_config); int dynsec_groups__config_save(cJSON *tree); int dynsec_groups__process_add_client(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_groups__process_add_role(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_groups__process_create(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_groups__process_delete(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_groups__process_get(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_groups__process_list(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_groups__process_modify(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_groups__process_remove_client(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_groups__process_remove_role(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_groups__process_get_anonymous_group(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_groups__process_set_anonymous_group(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_groups__remove_client(const char *username, const char *groupname, bool update_config); struct dynsec__group *dynsec_groups__find(const char *groupname); /* ################################################################ * # * # Group List Functions * # * ################################################################ */ cJSON *dynsec_grouplist__all_to_json(struct dynsec__grouplist *base_grouplist); int dynsec_grouplist__add(struct dynsec__grouplist **base_grouplist, struct dynsec__group *group, int priority); void dynsec_grouplist__cleanup(struct dynsec__grouplist **base_grouplist); void dynsec_grouplist__remove(struct dynsec__grouplist **base_grouplist, struct dynsec__group *group); /* ################################################################ * # * # Role Functions * # * ################################################################ */ void dynsec_roles__cleanup(void); int dynsec_roles__config_load(cJSON *tree); int dynsec_roles__config_save(cJSON *tree); int dynsec_roles__process_add_acl(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_roles__process_create(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_roles__process_delete(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_roles__process_get(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_roles__process_list(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_roles__process_modify(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); int dynsec_roles__process_remove_acl(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data); struct dynsec__role *dynsec_roles__find(const char *rolename); /* ################################################################ * # * # Role List Functions * # * ################################################################ */ int dynsec_rolelist__client_add(struct dynsec__client *client, struct dynsec__role *role, int priority); int dynsec_rolelist__client_remove(struct dynsec__client *client, struct dynsec__role *role); int dynsec_rolelist__group_add(struct dynsec__group *group, struct dynsec__role *role, int priority); void dynsec_rolelist__group_remove(struct dynsec__group *group, struct dynsec__role *role); int dynsec_rolelist__load_from_json(cJSON *command, struct dynsec__rolelist **rolelist); void dynsec_rolelist__cleanup(struct dynsec__rolelist **base_rolelist); cJSON *dynsec_rolelist__all_to_json(struct dynsec__rolelist *base_rolelist); #endif mosquitto-2.0.11/plugins/dynamic-security/json_help.c0000664000175000017500000000410014060132747021755 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include "json_help.h" #include "mosquitto.h" int json_get_bool(cJSON *json, const char *name, bool *value, bool optional, bool default_value) { cJSON *jtmp; if(optional == true){ *value = default_value; } jtmp = cJSON_GetObjectItem(json, name); if(jtmp){ if(cJSON_IsBool(jtmp) == false){ return MOSQ_ERR_INVAL; } *value = cJSON_IsTrue(jtmp); }else{ if(optional == false){ return MOSQ_ERR_INVAL; } } return MOSQ_ERR_SUCCESS; } int json_get_int(cJSON *json, const char *name, int *value, bool optional, int default_value) { cJSON *jtmp; if(optional == true){ *value = default_value; } jtmp = cJSON_GetObjectItem(json, name); if(jtmp){ if(cJSON_IsNumber(jtmp) == false){ return MOSQ_ERR_INVAL; } *value = jtmp->valueint; }else{ if(optional == false){ return MOSQ_ERR_INVAL; } } return MOSQ_ERR_SUCCESS; } int json_get_string(cJSON *json, const char *name, char **value, bool optional) { cJSON *jtmp; *value = NULL; jtmp = cJSON_GetObjectItem(json, name); if(jtmp){ if(cJSON_IsString(jtmp) == false){ return MOSQ_ERR_INVAL; } *value = jtmp->valuestring; }else{ if(optional == false){ return MOSQ_ERR_INVAL; } } return MOSQ_ERR_SUCCESS; } cJSON *cJSON_AddIntToObject(cJSON * const object, const char * const name, int number) { char buf[30]; snprintf(buf, sizeof(buf), "%d", number); return cJSON_AddRawToObject(object, name, buf); } mosquitto-2.0.11/plugins/dynamic-security/README.md0000664000175000017500000002346314060132747021124 0ustar rogerroger# Mosquitto Dynamic Security This document describes a topic based mechanism for controlling security in Mosquitto. JSON commands are published to topics like `$CONTROL//v1` ## Clients When a client connects to Mosquitto, it can optionally provide a username. The username maps the client instance to a client on the broker, if it exists. Multiple clients can make use of the same username, and hence the same broker client. ## Groups Broker clients can be defined as belonging to zero or more broker groups. ## Roles Roles can be applied to a client or a group, and define what that client/group is allowed to do, for example what topics it may or may not publish or subscribe to. ## Commands ### Set default ACL access Sets the default access behaviour for the different ACL types, assuming there are no matching ACLs for a topic. By default, publishClientSend and subscribe default to deny, and publishClientReceive and unsubscribe default to allow. Command: ``` { "commands":[ { "command": "setDefaultACLAccess", "acls":[ { "acltype": "publishClientSend", "allow": false }, { "acltype": "publishClientReceive", "allow": true }, { "acltype": "subscribe", "allow": false }, { "acltype": "unsubscribe", "allow": true } ] } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec setDefaultACLAccess subscribe deny ``` ### Get default ACL access Gets the default access behaviour for the different ACL types. Command: ``` { "commands":[ { "command": "getDefaultACLAccess", } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec getDefaultACLAccess ``` ## Create Client Command: ``` { "commands":[ { "command": "createClient", "username": "new username", "password": "new password", "clientid": "", # Optional "textname": "", # Optional "textdescription": "", # Optional "groups": [ { "groupname": "group", "priority": 1 } ], # Optional, groups must exist "roles": [ { "rolename": "role", "priority": -1 } ] # Optional, roles must exist } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec createClient username password ``` ## Delete Client Command: ``` { "commands":[ { "command": "deleteClient", "username": "username to delete" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec deleteClient username ``` ## Enable Client Command: ``` { "commands":[ { "command": "enableClient", "username": "username to enable" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec enableClient username ``` ## Disable Client Stop a client from being able to log in, and kick any clients with matching username that are currently connected. Command: ``` { "commands":[ { "command": "disableClient", "username": "username to disable" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec disableClient username ``` ## Get Client Command: ``` { "commands":[ { "command": "getClient", "username": "required username" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec getClient username ``` ## List Clients Command: ``` { "commands":[ { "command": "listClients", "verbose": false, "count": -1, # -1 for all, or a positive integer for a limited count "offset": 0 # Where in the list to start } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec listClients 10 20 ``` ## Modify Existing Client Command: ``` { "commands":[ { "command": "modifyClient", "username": "username to modify" "clientid": "new clientid, or empty string to clear", # Optional "password": "new password", # Optional "textname": "", # Optional "textdescription": "", # Optional "roles": [ { "rolename": "role", "priority": 1 } ], # Optional "groups": [ { "groupname": "group", "priority": 1 } ], # Optional } ] } ``` Modifying clients isn't currently possible with mosquitto_ctrl. ## Set Client id Command: ``` { "commands":[ { "command": "setClientId", "username": "username to change", "clientid": "new clientid" # Optional, if blank or missing then client id will be removed. } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec setClientPassword username password ``` ## Set Client Password Command: ``` { "commands":[ { "command": "setClientPassword", "username": "username to change", "password": "new password" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec setClientPassword username password ``` ## Add Client Role Command: ``` { "commands":[ { "command": "addClientRole", "username": "client to add role to", "rolename": "role to add", "priority": -1 # Optional priority } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec addClientRole username rolename ``` ## Remove Client Role Command: ``` { "commands":[ { "command": "removeClientRole", "username": "client to remove role from", "rolename": "role to remove" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec removeClientRole username rolename ``` ## Add Client to a Group Command: ``` { "commands":[ { "command": "addGroupClient", "groupname": "group to add client to", "username": "client to add to group", "priority": -1 # Priority of the group for the client } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec addGroupClient groupname username ``` ## Create Group Command: ``` { "commands":[ { "command": "createGroup", "groupname": "new group", "roles": [ { "rolename": "role", "priority": 1 } ] # Optional, roles must exist } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec createGroup groupname ``` ## Delete Group Command: ``` { "commands":[ { "command": "deleteGroup", "groupname: "group to delete" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec deleteGroup groupname ``` ## Get Group Command: ``` { "commands":[ { "command": "getGroup", "groupname: "group to get" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec getGroup groupname ``` ## List Groups Command: ``` { "commands":[ { "command": "listGroups", "verbose": false, "count": -1, # -1 for all, or a positive integer for a limited count "offset": 0 # Where in the list to start } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec listGroups ``` ## Modify Group Command: ``` { "commands":[ { "command": "modifyGroup", "groupname": "group to modify", "textname": "", # Optional "textdescription": "", # Optional "roles": [ { "rolename": "role", "priority": 1 } ], # Optional "clients": [ { "username": "client", "priority": 1 } ] # Optional } ] } ``` Modifying groups isn't currently possible with mosquitto_ctrl. ## Remove Client from a Group Command: ``` { "commands":[ { "command": "removeGroupClient", "groupname": "group to remove client from", "username": "client to remove from group" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec removeGroupClient groupname username ``` ## Add Group Role Command: ``` { "commands":[ { "command": "addGroupRole", "groupname": "group to add role to", "rolename": "role to add", "priority": -1 # Optional priority } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec addGroupRole groupname rolename ``` ## Remove Group Role Command: ``` { "commands":[ { "command": "removeGroupRole", "groupname": "group", "rolename": "role" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec removeGroupRole groupname rolename ``` ## Set Group for Anonymous Clients Command: ``` { "commands":[ { "command": "setAnonymousGroup", "groupname": "group" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec setAnonymousGroup groupname ``` ## Get Group for Anonymous Clients Command: ``` { "commands":[ { "command": "getAnonymousGroup", } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec getAnonymousGroup ``` ## Create Role Command: ``` { "commands":[ { "command": "createRole", "rolename": "new role", "textname": "", # Optional "textdescription": "", # Optional "acls": [ { "acltype": "subscribePattern", "topic": "topic/#", "priority": -1, "allow": true} ] # Optional } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec createRole rolename ``` ## Get Role Command: ``` { "commands":[ { "command": "getRole", "rolename": "role", } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec getRole rolename ``` ## List Roles Command: ``` { "commands":[ { "command": "listRoles", "verbose": false, "count": -1, # -1 for all, or a positive integer for a limited count "offset": 0 # Where in the list to start } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec listRoles ``` ## Modify Role Command: ``` { "commands":[ { "command": "modifyRole", "rolename": "role to modify" "textname": "", # Optional "textdescription": "", # Optional "acls": [ { "acltype": "subscribePattern", "topic": "topic/#", "priority": -1, "allow": true } ] # Optional } ] } ``` Modifying roles isn't currently possible with mosquitto_ctrl. ## Delete Role Command: ``` { "commands":[ { "command": "deleteRole", "rolename": "role" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec deleteRole rolename ``` ## Add Role ACL Command: ``` { "commands":[ { "command": "addRoleACL", "rolename": "role", "acltype": "subscribePattern", "topic": "topic/#", "priority": -1, "allow": true } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec addRoleACL rolename subscribeLiteral topic/# deny ``` ## Remove Role ACL Command: ``` { "commands":[ { "command": "removeRoleACL", "rolename": "role", "acltype": "subscribePattern", "topic": "topic/#" } ] } ``` mosquitto_ctrl example: ``` mosquitto_ctrl dynsec removeRoleACL rolename subscribeLiteral topic/# ``` mosquitto-2.0.11/plugins/dynamic-security/roles.c0000664000175000017500000007255314060132747021141 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include "dynamic_security.h" #include "json_help.h" #include "mosquitto.h" #include "mosquitto_broker.h" static cJSON *add_role_to_json(struct dynsec__role *role, bool verbose); static void role__remove_all_clients(struct dynsec__role *role); /* ################################################################ * # * # Local variables * # * ################################################################ */ static struct dynsec__role *local_roles = NULL; /* ################################################################ * # * # Utility functions * # * ################################################################ */ static int role_cmp(void *a, void *b) { struct dynsec__role *role_a = a; struct dynsec__role *role_b = b; return strcmp(role_a->rolename, role_b->rolename); } static void role__free_acl(struct dynsec__acl **acl, struct dynsec__acl *item) { HASH_DELETE(hh, *acl, item); mosquitto_free(item->topic); mosquitto_free(item); } static void role__free_all_acls(struct dynsec__acl **acl) { struct dynsec__acl *iter, *tmp = NULL; HASH_ITER(hh, *acl, iter, tmp){ role__free_acl(acl, iter); } } static void role__free_item(struct dynsec__role *role, bool remove_from_hash) { if(remove_from_hash){ HASH_DEL(local_roles, role); } dynsec_clientlist__cleanup(&role->clientlist); dynsec_grouplist__cleanup(&role->grouplist); mosquitto_free(role->text_name); mosquitto_free(role->text_description); mosquitto_free(role->rolename); role__free_all_acls(&role->acls.publish_c_send); role__free_all_acls(&role->acls.publish_c_recv); role__free_all_acls(&role->acls.subscribe_literal); role__free_all_acls(&role->acls.subscribe_pattern); role__free_all_acls(&role->acls.unsubscribe_literal); role__free_all_acls(&role->acls.unsubscribe_pattern); mosquitto_free(role); } struct dynsec__role *dynsec_roles__find(const char *rolename) { struct dynsec__role *role = NULL; if(rolename){ HASH_FIND(hh, local_roles, rolename, strlen(rolename), role); } return role; } void dynsec_roles__cleanup(void) { struct dynsec__role *role, *role_tmp = NULL; HASH_ITER(hh, local_roles, role, role_tmp){ role__free_item(role, true); } } static void role__kick_all(struct dynsec__role *role) { struct dynsec__grouplist *grouplist, *grouplist_tmp = NULL; dynsec_clientlist__kick_all(role->clientlist); HASH_ITER(hh, role->grouplist, grouplist, grouplist_tmp){ if(grouplist->group == dynsec_anonymous_group){ mosquitto_kick_client_by_username(NULL, false); } dynsec_clientlist__kick_all(grouplist->group->clientlist); } } /* ################################################################ * # * # Config file load and save * # * ################################################################ */ static int add_single_acl_to_json(cJSON *j_array, const char *acl_type, struct dynsec__acl *acl) { struct dynsec__acl *iter, *tmp = NULL; cJSON *j_acl; HASH_ITER(hh, acl, iter, tmp){ j_acl = cJSON_CreateObject(); if(j_acl == NULL){ return 1; } cJSON_AddItemToArray(j_array, j_acl); if(cJSON_AddStringToObject(j_acl, "acltype", acl_type) == NULL || cJSON_AddStringToObject(j_acl, "topic", iter->topic) == NULL || cJSON_AddIntToObject(j_acl, "priority", iter->priority) == NULL || cJSON_AddBoolToObject(j_acl, "allow", iter->allow) == NULL ){ return 1; } } return 0; } static int add_acls_to_json(cJSON *j_role, struct dynsec__role *role) { cJSON *j_acls; if((j_acls = cJSON_AddArrayToObject(j_role, "acls")) == NULL){ return 1; } if(add_single_acl_to_json(j_acls, ACL_TYPE_PUB_C_SEND, role->acls.publish_c_send) != MOSQ_ERR_SUCCESS || add_single_acl_to_json(j_acls, ACL_TYPE_PUB_C_RECV, role->acls.publish_c_recv) != MOSQ_ERR_SUCCESS || add_single_acl_to_json(j_acls, ACL_TYPE_SUB_LITERAL, role->acls.subscribe_literal) != MOSQ_ERR_SUCCESS || add_single_acl_to_json(j_acls, ACL_TYPE_SUB_PATTERN, role->acls.subscribe_pattern) != MOSQ_ERR_SUCCESS || add_single_acl_to_json(j_acls, ACL_TYPE_UNSUB_LITERAL, role->acls.unsubscribe_literal) != MOSQ_ERR_SUCCESS || add_single_acl_to_json(j_acls, ACL_TYPE_UNSUB_PATTERN, role->acls.unsubscribe_pattern) != MOSQ_ERR_SUCCESS ){ return 1; } return 0; } int dynsec_roles__config_save(cJSON *tree) { cJSON *j_roles, *j_role; struct dynsec__role *role, *role_tmp = NULL; if((j_roles = cJSON_AddArrayToObject(tree, "roles")) == NULL){ return 1; } HASH_ITER(hh, local_roles, role, role_tmp){ j_role = add_role_to_json(role, true); if(j_role == NULL){ return 1; } cJSON_AddItemToArray(j_roles, j_role); } return 0; } static int insert_acl_cmp(struct dynsec__acl *a, struct dynsec__acl *b) { return b->priority - a->priority; } static int dynsec_roles__acl_load(cJSON *j_acls, const char *key, struct dynsec__acl **acllist) { cJSON *j_acl, *j_type, *jtmp; struct dynsec__acl *acl; cJSON_ArrayForEach(j_acl, j_acls){ j_type = cJSON_GetObjectItem(j_acl, "acltype"); if(j_type == NULL || !cJSON_IsString(j_type) || strcasecmp(j_type->valuestring, key) != 0){ continue; } acl = mosquitto_calloc(1, sizeof(struct dynsec__acl)); if(acl == NULL){ return 1; } json_get_int(j_acl, "priority", &acl->priority, true, 0); json_get_bool(j_acl, "allow", &acl->allow, true, false); jtmp = cJSON_GetObjectItem(j_acl, "allow"); if(jtmp && cJSON_IsBool(jtmp)){ acl->allow = cJSON_IsTrue(jtmp); } jtmp = cJSON_GetObjectItem(j_acl, "topic"); if(jtmp && cJSON_IsString(jtmp)){ acl->topic = mosquitto_strdup(jtmp->valuestring); } if(acl->topic == NULL){ mosquitto_free(acl); continue; } HASH_ADD_KEYPTR_INORDER(hh, *acllist, acl->topic, strlen(acl->topic), acl, insert_acl_cmp); } return 0; } int dynsec_roles__config_load(cJSON *tree) { cJSON *j_roles, *j_role, *jtmp, *j_acls; struct dynsec__role *role; j_roles = cJSON_GetObjectItem(tree, "roles"); if(j_roles == NULL){ return 0; } if(cJSON_IsArray(j_roles) == false){ return 1; } cJSON_ArrayForEach(j_role, j_roles){ if(cJSON_IsObject(j_role) == true){ role = mosquitto_calloc(1, sizeof(struct dynsec__role)); if(role == NULL){ return MOSQ_ERR_NOMEM; } /* Role name */ jtmp = cJSON_GetObjectItem(j_role, "rolename"); if(jtmp == NULL){ mosquitto_free(role); continue; } role->rolename = mosquitto_strdup(jtmp->valuestring); if(role->rolename == NULL){ mosquitto_free(role); continue; } /* Text name */ jtmp = cJSON_GetObjectItem(j_role, "textname"); if(jtmp != NULL){ role->text_name = mosquitto_strdup(jtmp->valuestring); if(role->text_name == NULL){ mosquitto_free(role->rolename); mosquitto_free(role); continue; } } /* Text description */ jtmp = cJSON_GetObjectItem(j_role, "textdescription"); if(jtmp != NULL){ role->text_description = mosquitto_strdup(jtmp->valuestring); if(role->text_description == NULL){ mosquitto_free(role->text_name); mosquitto_free(role->rolename); mosquitto_free(role); continue; } } /* ACLs */ j_acls = cJSON_GetObjectItem(j_role, "acls"); if(j_acls && cJSON_IsArray(j_acls)){ if(dynsec_roles__acl_load(j_acls, ACL_TYPE_PUB_C_SEND, &role->acls.publish_c_send) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_PUB_C_RECV, &role->acls.publish_c_recv) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_SUB_LITERAL, &role->acls.subscribe_literal) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_SUB_PATTERN, &role->acls.subscribe_pattern) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_UNSUB_LITERAL, &role->acls.unsubscribe_literal) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_UNSUB_PATTERN, &role->acls.unsubscribe_pattern) != 0 ){ mosquitto_free(role->rolename); mosquitto_free(role); continue; } } HASH_ADD_KEYPTR(hh, local_roles, role->rolename, strlen(role->rolename), role); } } HASH_SORT(local_roles, role_cmp); return 0; } int dynsec_roles__process_create(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *rolename; char *text_name, *text_description; struct dynsec__role *role; int rc = MOSQ_ERR_SUCCESS; cJSON *j_acls; const char *admin_clientid, *admin_username; if(json_get_string(command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createRole", "Invalid/missing rolename", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createRole", "Role name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "textname", &text_name, true) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createRole", "Invalid/missing textname", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "textdescription", &text_description, true) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "createRole", "Invalid/missing textdescription", correlation_data); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(rolename); if(role){ dynsec__command_reply(j_responses, context, "createRole", "Role already exists", correlation_data); return MOSQ_ERR_SUCCESS; } role = mosquitto_calloc(1, sizeof(struct dynsec__role)); if(role == NULL){ dynsec__command_reply(j_responses, context, "createRole", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } role->rolename = mosquitto_strdup(rolename); if(role->rolename == NULL){ dynsec__command_reply(j_responses, context, "createRole", "Internal error", correlation_data); rc = MOSQ_ERR_NOMEM; goto error; } if(text_name){ role->text_name = mosquitto_strdup(text_name); if(role->text_name == NULL){ dynsec__command_reply(j_responses, context, "createRole", "Internal error", correlation_data); rc = MOSQ_ERR_NOMEM; goto error; } } if(text_description){ role->text_description = mosquitto_strdup(text_description); if(role->text_description == NULL){ dynsec__command_reply(j_responses, context, "createRole", "Internal error", correlation_data); rc = MOSQ_ERR_NOMEM; goto error; } } /* ACLs */ j_acls = cJSON_GetObjectItem(command, "acls"); if(j_acls && cJSON_IsArray(j_acls)){ if(dynsec_roles__acl_load(j_acls, ACL_TYPE_PUB_C_SEND, &role->acls.publish_c_send) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_PUB_C_RECV, &role->acls.publish_c_recv) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_SUB_LITERAL, &role->acls.subscribe_literal) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_SUB_PATTERN, &role->acls.subscribe_pattern) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_UNSUB_LITERAL, &role->acls.unsubscribe_literal) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_UNSUB_PATTERN, &role->acls.unsubscribe_pattern) != 0 ){ dynsec__command_reply(j_responses, context, "createRole", "Internal error", correlation_data); rc = MOSQ_ERR_NOMEM; goto error; } } HASH_ADD_KEYPTR_INORDER(hh, local_roles, role->rolename, strlen(role->rolename), role, role_cmp); dynsec__config_save(); dynsec__command_reply(j_responses, context, "createRole", NULL, correlation_data); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | createRole | rolename=%s", admin_clientid, admin_username, rolename); return MOSQ_ERR_SUCCESS; error: if(role){ role__free_item(role, false); } return rc; } static void role__remove_all_clients(struct dynsec__role *role) { struct dynsec__clientlist *clientlist, *clientlist_tmp = NULL; HASH_ITER(hh, role->clientlist, clientlist, clientlist_tmp){ mosquitto_kick_client_by_username(clientlist->client->username, false); dynsec_rolelist__client_remove(clientlist->client, role); } } static void role__remove_all_groups(struct dynsec__role *role) { struct dynsec__grouplist *grouplist, *grouplist_tmp = NULL; HASH_ITER(hh, role->grouplist, grouplist, grouplist_tmp){ if(grouplist->group == dynsec_anonymous_group){ mosquitto_kick_client_by_username(NULL, false); } dynsec_clientlist__kick_all(grouplist->group->clientlist); dynsec_rolelist__group_remove(grouplist->group, role); } } int dynsec_roles__process_delete(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *rolename; struct dynsec__role *role; const char *admin_clientid, *admin_username; if(json_get_string(command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "deleteRole", "Invalid/missing rolename", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "deleteRole", "Role name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(rolename); if(role){ role__remove_all_clients(role); role__remove_all_groups(role); role__free_item(role, true); dynsec__config_save(); dynsec__command_reply(j_responses, context, "deleteRole", NULL, correlation_data); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | deleteRole | rolename=%s", admin_clientid, admin_username, rolename); return MOSQ_ERR_SUCCESS; }else{ dynsec__command_reply(j_responses, context, "deleteRole", "Role not found", correlation_data); return MOSQ_ERR_SUCCESS; } } static cJSON *add_role_to_json(struct dynsec__role *role, bool verbose) { cJSON *j_role = NULL; if(verbose){ j_role = cJSON_CreateObject(); if(j_role == NULL){ return NULL; } if(cJSON_AddStringToObject(j_role, "rolename", role->rolename) == NULL || (role->text_name && cJSON_AddStringToObject(j_role, "textname", role->text_name) == NULL) || (role->text_description && cJSON_AddStringToObject(j_role, "textdescription", role->text_description) == NULL) ){ cJSON_Delete(j_role); return NULL; } if(add_acls_to_json(j_role, role)){ cJSON_Delete(j_role); return NULL; } }else{ j_role = cJSON_CreateString(role->rolename); if(j_role == NULL){ return NULL; } } return j_role; } int dynsec_roles__process_list(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { bool verbose; struct dynsec__role *role, *role_tmp = NULL; cJSON *tree, *j_roles, *j_role, *j_data; int i, count, offset; const char *admin_clientid, *admin_username; json_get_bool(command, "verbose", &verbose, true, false); json_get_int(command, "count", &count, true, -1); json_get_int(command, "offset", &offset, true, 0); tree = cJSON_CreateObject(); if(tree == NULL){ dynsec__command_reply(j_responses, context, "listRoles", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } if(cJSON_AddStringToObject(tree, "command", "listRoles") == NULL || (j_data = cJSON_AddObjectToObject(tree, "data")) == NULL || cJSON_AddIntToObject(j_data, "totalCount", (int)HASH_CNT(hh, local_roles)) == NULL || (j_roles = cJSON_AddArrayToObject(j_data, "roles")) == NULL || (correlation_data && cJSON_AddStringToObject(tree, "correlationData", correlation_data) == NULL) ){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "listRoles", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } i = 0; HASH_ITER(hh, local_roles, role, role_tmp){ if(i>=offset){ j_role = add_role_to_json(role, verbose); if(j_role == NULL){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "listRoles", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_roles, j_role); if(count >= 0){ count--; if(count <= 0){ break; } } } i++; } cJSON_AddItemToArray(j_responses, tree); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | listRoles | verbose=%s | count=%d | offset=%d", admin_clientid, admin_username, verbose?"true":"false", count, offset); return MOSQ_ERR_SUCCESS; } int dynsec_roles__process_add_acl(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *rolename; char *topic; struct dynsec__role *role; cJSON *jtmp, *j_acltype; struct dynsec__acl **acllist, *acl; int rc; const char *admin_clientid, *admin_username; if(json_get_string(command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addRoleACL", "Invalid/missing rolename", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addRoleACL", "Role name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(rolename); if(role == NULL){ dynsec__command_reply(j_responses, context, "addRoleACL", "Role not found", correlation_data); return MOSQ_ERR_SUCCESS; } j_acltype = cJSON_GetObjectItem(command, "acltype"); if(j_acltype == NULL || !cJSON_IsString(j_acltype)){ dynsec__command_reply(j_responses, context, "addRoleACL", "Invalid/missing acltype", correlation_data); return MOSQ_ERR_SUCCESS; } if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_PUB_C_SEND)){ acllist = &role->acls.publish_c_send; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_PUB_C_RECV)){ acllist = &role->acls.publish_c_recv; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_SUB_LITERAL)){ acllist = &role->acls.subscribe_literal; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_SUB_PATTERN)){ acllist = &role->acls.subscribe_pattern; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_UNSUB_LITERAL)){ acllist = &role->acls.unsubscribe_literal; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_UNSUB_PATTERN)){ acllist = &role->acls.unsubscribe_pattern; }else{ dynsec__command_reply(j_responses, context, "addRoleACL", "Unknown acltype", correlation_data); return MOSQ_ERR_SUCCESS; } jtmp = cJSON_GetObjectItem(command, "topic"); if(jtmp && cJSON_IsString(jtmp)){ if(mosquitto_validate_utf8(jtmp->valuestring, (int)strlen(jtmp->valuestring)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addRoleACL", "Topic not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } rc = mosquitto_sub_topic_check(jtmp->valuestring); if(rc != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "addRoleACL", "Invalid ACL topic", correlation_data); return MOSQ_ERR_INVAL; } topic = mosquitto_strdup(jtmp->valuestring); if(topic == NULL){ dynsec__command_reply(j_responses, context, "addRoleACL", "Internal error", correlation_data); return MOSQ_ERR_SUCCESS; } }else{ dynsec__command_reply(j_responses, context, "addRoleACL", "Invalid/missing topic", correlation_data); return MOSQ_ERR_SUCCESS; } HASH_FIND(hh, *acllist, topic, strlen(topic), acl); if(acl){ mosquitto_free(topic); dynsec__command_reply(j_responses, context, "addRoleACL", "ACL with this topic already exists", correlation_data); return MOSQ_ERR_SUCCESS; } acl = mosquitto_calloc(1, sizeof(struct dynsec__acl)); if(acl == NULL){ mosquitto_free(topic); dynsec__command_reply(j_responses, context, "addRoleACL", "Internal error", correlation_data); return MOSQ_ERR_SUCCESS; } acl->topic = topic; json_get_int(command, "priority", &acl->priority, true, 0); json_get_bool(command, "allow", &acl->allow, true, false); HASH_ADD_KEYPTR_INORDER(hh, *acllist, acl->topic, strlen(acl->topic), acl, insert_acl_cmp); dynsec__config_save(); dynsec__command_reply(j_responses, context, "addRoleACL", NULL, correlation_data); role__kick_all(role); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | addRoleACL | rolename=%s | acltype=%s | topic=%s | priority=%d | allow=%s", admin_clientid, admin_username, rolename, j_acltype->valuestring, topic, acl->priority, acl->allow?"true":"false"); return MOSQ_ERR_SUCCESS; } int dynsec_roles__process_remove_acl(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *rolename; struct dynsec__role *role; struct dynsec__acl **acllist, *acl; char *topic; cJSON *j_acltype; int rc; const char *admin_clientid, *admin_username; if(json_get_string(command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeRoleACL", "Invalid/missing rolename", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeRoleACL", "Role name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(rolename); if(role == NULL){ dynsec__command_reply(j_responses, context, "removeRoleACL", "Role not found", correlation_data); return MOSQ_ERR_SUCCESS; } j_acltype = cJSON_GetObjectItem(command, "acltype"); if(j_acltype == NULL || !cJSON_IsString(j_acltype)){ dynsec__command_reply(j_responses, context, "removeRoleACL", "Invalid/missing acltype", correlation_data); return MOSQ_ERR_SUCCESS; } if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_PUB_C_SEND)){ acllist = &role->acls.publish_c_send; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_PUB_C_RECV)){ acllist = &role->acls.publish_c_recv; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_SUB_LITERAL)){ acllist = &role->acls.subscribe_literal; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_SUB_PATTERN)){ acllist = &role->acls.subscribe_pattern; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_UNSUB_LITERAL)){ acllist = &role->acls.unsubscribe_literal; }else if(!strcasecmp(j_acltype->valuestring, ACL_TYPE_UNSUB_PATTERN)){ acllist = &role->acls.unsubscribe_pattern; }else{ dynsec__command_reply(j_responses, context, "removeRoleACL", "Unknown acltype", correlation_data); return MOSQ_ERR_SUCCESS; } if(json_get_string(command, "topic", &topic, false)){ dynsec__command_reply(j_responses, context, "removeRoleACL", "Invalid/missing topic", correlation_data); return MOSQ_ERR_SUCCESS; } if(mosquitto_validate_utf8(topic, (int)strlen(topic)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeRoleACL", "Topic not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } rc = mosquitto_sub_topic_check(topic); if(rc != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "removeRoleACL", "Invalid ACL topic", correlation_data); return MOSQ_ERR_INVAL; } HASH_FIND(hh, *acllist, topic, strlen(topic), acl); if(acl){ role__free_acl(acllist, acl); dynsec__config_save(); dynsec__command_reply(j_responses, context, "removeRoleACL", NULL, correlation_data); role__kick_all(role); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | removeRoleACL | rolename=%s | acltype=%s | topic=%s", admin_clientid, admin_username, rolename, j_acltype->valuestring, topic); }else{ dynsec__command_reply(j_responses, context, "removeRoleACL", "ACL not found", correlation_data); } return MOSQ_ERR_SUCCESS; } int dynsec_roles__process_get(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *rolename; struct dynsec__role *role; cJSON *tree, *j_role, *j_data; if(json_get_string(command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "getRole", "Invalid/missing rolename", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "getRole", "Role name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(rolename); if(role == NULL){ dynsec__command_reply(j_responses, context, "getRole", "Role not found", correlation_data); return MOSQ_ERR_SUCCESS; } tree = cJSON_CreateObject(); if(tree == NULL){ dynsec__command_reply(j_responses, context, "getRole", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } if(cJSON_AddStringToObject(tree, "command", "getRole") == NULL || (j_data = cJSON_AddObjectToObject(tree, "data")) == NULL || (correlation_data && cJSON_AddStringToObject(tree, "correlationData", correlation_data) == NULL) ){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "getRole", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } j_role = add_role_to_json(role, true); if(j_role == NULL){ cJSON_Delete(tree); dynsec__command_reply(j_responses, context, "getRole", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(j_data, "role", j_role); cJSON_AddItemToArray(j_responses, tree); return MOSQ_ERR_SUCCESS; } int dynsec_roles__process_modify(cJSON *j_responses, struct mosquitto *context, cJSON *command, char *correlation_data) { char *rolename; char *text_name, *text_description; struct dynsec__role *role; char *str; cJSON *j_acls; struct dynsec__acl *tmp_publish_c_send = NULL, *tmp_publish_c_recv = NULL; struct dynsec__acl *tmp_subscribe_literal = NULL, *tmp_subscribe_pattern = NULL; struct dynsec__acl *tmp_unsubscribe_literal = NULL, *tmp_unsubscribe_pattern = NULL; const char *admin_clientid, *admin_username; if(json_get_string(command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "modifyRole", "Invalid/missing rolename", correlation_data); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ dynsec__command_reply(j_responses, context, "modifyRole", "Role name not valid UTF-8", correlation_data); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(rolename); if(role == NULL){ dynsec__command_reply(j_responses, context, "modifyRole", "Role does not exist", correlation_data); return MOSQ_ERR_INVAL; } if(json_get_string(command, "textname", &text_name, false) == MOSQ_ERR_SUCCESS){ str = mosquitto_strdup(text_name); if(str == NULL){ dynsec__command_reply(j_responses, context, "modifyRole", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } mosquitto_free(role->text_name); role->text_name = str; } if(json_get_string(command, "textdescription", &text_description, false) == MOSQ_ERR_SUCCESS){ str = mosquitto_strdup(text_description); if(str == NULL){ dynsec__command_reply(j_responses, context, "modifyRole", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } mosquitto_free(role->text_description); role->text_description = str; } j_acls = cJSON_GetObjectItem(command, "acls"); if(j_acls && cJSON_IsArray(j_acls)){ if(dynsec_roles__acl_load(j_acls, ACL_TYPE_PUB_C_SEND, &tmp_publish_c_send) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_PUB_C_RECV, &tmp_publish_c_recv) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_SUB_LITERAL, &tmp_subscribe_literal) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_SUB_PATTERN, &tmp_subscribe_pattern) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_UNSUB_LITERAL, &tmp_unsubscribe_literal) != 0 || dynsec_roles__acl_load(j_acls, ACL_TYPE_UNSUB_PATTERN, &tmp_unsubscribe_pattern) != 0 ){ /* Free any that were successful */ role__free_all_acls(&tmp_publish_c_send); role__free_all_acls(&tmp_publish_c_recv); role__free_all_acls(&tmp_subscribe_literal); role__free_all_acls(&tmp_subscribe_pattern); role__free_all_acls(&tmp_unsubscribe_literal); role__free_all_acls(&tmp_unsubscribe_pattern); dynsec__command_reply(j_responses, context, "modifyRole", "Internal error", correlation_data); return MOSQ_ERR_NOMEM; } role__free_all_acls(&role->acls.publish_c_send); role__free_all_acls(&role->acls.publish_c_recv); role__free_all_acls(&role->acls.subscribe_literal); role__free_all_acls(&role->acls.subscribe_pattern); role__free_all_acls(&role->acls.unsubscribe_literal); role__free_all_acls(&role->acls.unsubscribe_pattern); role->acls.publish_c_send = tmp_publish_c_send; role->acls.publish_c_recv = tmp_publish_c_recv; role->acls.subscribe_literal = tmp_subscribe_literal; role->acls.subscribe_pattern = tmp_subscribe_pattern; role->acls.unsubscribe_literal = tmp_unsubscribe_literal; role->acls.unsubscribe_pattern = tmp_unsubscribe_pattern; } dynsec__config_save(); dynsec__command_reply(j_responses, context, "modifyRole", NULL, correlation_data); admin_clientid = mosquitto_client_id(context); admin_username = mosquitto_client_username(context); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | modifyRole | rolename=%s", admin_clientid, admin_username, rolename); return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/plugins/dynamic-security/acl.c0000664000175000017500000001556614060132747020555 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include "dynamic_security.h" #include "mosquitto.h" #include "mosquitto_broker.h" #include "mosquitto_plugin.h" typedef int (*MOSQ_FUNC_acl_check)(struct mosquitto_evt_acl_check *, struct dynsec__rolelist *); /* FIXME - CACHE! */ /* ################################################################ * # * # ACL check - publish broker to client * # * ################################################################ */ static int acl_check_publish_c_recv(struct mosquitto_evt_acl_check *ed, struct dynsec__rolelist *base_rolelist) { struct dynsec__rolelist *rolelist, *rolelist_tmp = NULL; struct dynsec__acl *acl, *acl_tmp = NULL; bool result; HASH_ITER(hh, base_rolelist, rolelist, rolelist_tmp){ HASH_ITER(hh, rolelist->role->acls.publish_c_recv, acl, acl_tmp){ mosquitto_topic_matches_sub(acl->topic, ed->topic, &result); if(result){ if(acl->allow){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } } } } return MOSQ_ERR_NOT_FOUND; } /* ################################################################ * # * # ACL check - publish client to broker * # * ################################################################ */ static int acl_check_publish_c_send(struct mosquitto_evt_acl_check *ed, struct dynsec__rolelist *base_rolelist) { struct dynsec__rolelist *rolelist, *rolelist_tmp = NULL; struct dynsec__acl *acl, *acl_tmp = NULL; bool result; HASH_ITER(hh, base_rolelist, rolelist, rolelist_tmp){ HASH_ITER(hh, rolelist->role->acls.publish_c_send, acl, acl_tmp){ mosquitto_topic_matches_sub(acl->topic, ed->topic, &result); if(result){ if(acl->allow){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } } } } return MOSQ_ERR_NOT_FOUND; } /* ################################################################ * # * # ACL check - subscribe * # * ################################################################ */ static int acl_check_subscribe(struct mosquitto_evt_acl_check *ed, struct dynsec__rolelist *base_rolelist) { struct dynsec__rolelist *rolelist, *rolelist_tmp = NULL; struct dynsec__acl *acl, *acl_tmp = NULL; size_t len; len = strlen(ed->topic); HASH_ITER(hh, base_rolelist, rolelist, rolelist_tmp){ HASH_FIND(hh, rolelist->role->acls.subscribe_literal, ed->topic, len, acl); if(acl){ if(acl->allow){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } } HASH_ITER(hh, rolelist->role->acls.subscribe_pattern, acl, acl_tmp){ if(sub_acl_check(acl->topic, ed->topic)){ if(acl->allow){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } } } } return MOSQ_ERR_NOT_FOUND; } /* ################################################################ * # * # ACL check - unsubscribe * # * ################################################################ */ static int acl_check_unsubscribe(struct mosquitto_evt_acl_check *ed, struct dynsec__rolelist *base_rolelist) { struct dynsec__rolelist *rolelist, *rolelist_tmp = NULL; struct dynsec__acl *acl, *acl_tmp = NULL; size_t len; len = strlen(ed->topic); HASH_ITER(hh, base_rolelist, rolelist, rolelist_tmp){ HASH_FIND(hh, rolelist->role->acls.unsubscribe_literal, ed->topic, len, acl); if(acl){ if(acl->allow){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } } HASH_ITER(hh, rolelist->role->acls.unsubscribe_pattern, acl, acl_tmp){ if(sub_acl_check(acl->topic, ed->topic)){ if(acl->allow){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } } } } return MOSQ_ERR_NOT_FOUND; } /* ################################################################ * # * # ACL check - generic check * # * ################################################################ */ static int acl_check(struct mosquitto_evt_acl_check *ed, MOSQ_FUNC_acl_check check, bool acl_default_access) { struct dynsec__client *client; struct dynsec__grouplist *grouplist, *grouplist_tmp = NULL; const char *username; int rc; username = mosquitto_client_username(ed->client); if(username){ client = dynsec_clients__find(username); if(client == NULL) return MOSQ_ERR_PLUGIN_DEFER; /* Client roles */ rc = check(ed, client->rolelist); if(rc != MOSQ_ERR_NOT_FOUND){ return rc; } HASH_ITER(hh, client->grouplist, grouplist, grouplist_tmp){ rc = check(ed, grouplist->group->rolelist); if(rc != MOSQ_ERR_NOT_FOUND){ return rc; } } }else if(dynsec_anonymous_group){ /* If we have a group for anonymous users, use that for checking. */ rc = check(ed, dynsec_anonymous_group->rolelist); if(rc != MOSQ_ERR_NOT_FOUND){ return rc; } } if(acl_default_access == false){ return MOSQ_ERR_PLUGIN_DEFER; }else{ if(!strncmp(ed->topic, "$CONTROL", strlen("$CONTROL"))){ /* We never give fall through access to $CONTROL topics, they must * be granted explicitly. */ return MOSQ_ERR_PLUGIN_DEFER; }else{ return MOSQ_ERR_SUCCESS; } } } /* ################################################################ * # * # ACL check - plugin callback * # * ################################################################ */ int dynsec__acl_check_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_acl_check *ed = event_data; UNUSED(event); UNUSED(userdata); /* ACL checks are made in the order below until a match occurs, at which * point the decision is made. * * User roles in priority order highest to lowest. * Roles have their ACLs checked in priority order, highest to lowest * Groups are processed in priority order highest to lowest * Group roles are processed in priority order, highest to lowest * Roles have their ACLs checked in priority order, highest to lowest */ switch(ed->access){ case MOSQ_ACL_SUBSCRIBE: return acl_check(event_data, acl_check_subscribe, default_access.subscribe); break; case MOSQ_ACL_UNSUBSCRIBE: return acl_check(event_data, acl_check_unsubscribe, default_access.unsubscribe); break; case MOSQ_ACL_WRITE: /* Client to broker */ return acl_check(event_data, acl_check_publish_c_send, default_access.publish_c_send); break; case MOSQ_ACL_READ: return acl_check(event_data, acl_check_publish_c_recv, default_access.publish_c_recv); break; default: return MOSQ_ERR_PLUGIN_DEFER; } return MOSQ_ERR_PLUGIN_DEFER; } mosquitto-2.0.11/plugins/dynamic-security/grouplist.c0000664000175000017500000000734514060132747022042 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include "mosquitto.h" #include "mosquitto_broker.h" #include "json_help.h" #include "dynamic_security.h" /* ################################################################ * # * # Plugin global variables * # * ################################################################ */ /* ################################################################ * # * # Function declarations * # * ################################################################ */ /* ################################################################ * # * # Local variables * # * ################################################################ */ /* ################################################################ * # * # Utility functions * # * ################################################################ */ static int dynsec_grouplist__cmp(void *a, void *b) { int prio; struct dynsec__grouplist *grouplist_a = a; struct dynsec__grouplist *grouplist_b = b; prio = grouplist_b->priority - grouplist_a->priority; if(prio == 0){ return strcmp(grouplist_a->group->groupname, grouplist_b->group->groupname); }else{ return prio; } } cJSON *dynsec_grouplist__all_to_json(struct dynsec__grouplist *base_grouplist) { struct dynsec__grouplist *grouplist, *grouplist_tmp; cJSON *j_groups, *j_group; j_groups = cJSON_CreateArray(); if(j_groups == NULL) return NULL; HASH_ITER(hh, base_grouplist, grouplist, grouplist_tmp){ j_group = cJSON_CreateObject(); if(j_group == NULL){ cJSON_Delete(j_groups); return NULL; } cJSON_AddItemToArray(j_groups, j_group); if(cJSON_AddStringToObject(j_group, "groupname", grouplist->group->groupname) == NULL || (grouplist->priority != -1 && cJSON_AddIntToObject(j_group, "priority", grouplist->priority) == NULL) ){ cJSON_Delete(j_groups); return NULL; } } return j_groups; } int dynsec_grouplist__add(struct dynsec__grouplist **base_grouplist, struct dynsec__group *group, int priority) { struct dynsec__grouplist *grouplist; HASH_FIND(hh, *base_grouplist, group->groupname, strlen(group->groupname), grouplist); if(grouplist != NULL){ /* Group is already in the list */ return MOSQ_ERR_SUCCESS; } grouplist = mosquitto_malloc(sizeof(struct dynsec__grouplist)); if(grouplist == NULL){ return MOSQ_ERR_NOMEM; } grouplist->group = group; grouplist->priority = priority; HASH_ADD_KEYPTR_INORDER(hh, *base_grouplist, grouplist->group->groupname, strlen(grouplist->group->groupname), grouplist, dynsec_grouplist__cmp); return MOSQ_ERR_SUCCESS; } void dynsec_grouplist__cleanup(struct dynsec__grouplist **base_grouplist) { struct dynsec__grouplist *grouplist, *grouplist_tmp; HASH_ITER(hh, *base_grouplist, grouplist, grouplist_tmp){ HASH_DELETE(hh, *base_grouplist, grouplist); mosquitto_free(grouplist); } } void dynsec_grouplist__remove(struct dynsec__grouplist **base_grouplist, struct dynsec__group *group) { struct dynsec__grouplist *grouplist; HASH_FIND(hh, *base_grouplist, group->groupname, strlen(group->groupname), grouplist); if(grouplist){ HASH_DELETE(hh, *base_grouplist, grouplist); mosquitto_free(grouplist); } } mosquitto-2.0.11/plugins/dynamic-security/rolelist.c0000664000175000017500000001355714060132747021651 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include "dynamic_security.h" #include "json_help.h" #include "mosquitto.h" #include "mosquitto_broker.h" /* ################################################################ * # * # Utility functions * # * ################################################################ */ static int rolelist_cmp(void *a, void *b) { int prio; struct dynsec__rolelist *rolelist_a = a; struct dynsec__rolelist *rolelist_b = b; prio = rolelist_b->priority - rolelist_a->priority; if(prio == 0){ return strcmp(rolelist_a->rolename, rolelist_b->rolename); }else{ return prio; } } static void dynsec_rolelist__free_item(struct dynsec__rolelist **base_rolelist, struct dynsec__rolelist *rolelist) { HASH_DELETE(hh, *base_rolelist, rolelist); mosquitto_free(rolelist->rolename); mosquitto_free(rolelist); } void dynsec_rolelist__cleanup(struct dynsec__rolelist **base_rolelist) { struct dynsec__rolelist *rolelist, *rolelist_tmp; HASH_ITER(hh, *base_rolelist, rolelist, rolelist_tmp){ dynsec_rolelist__free_item(base_rolelist, rolelist); } } static int dynsec_rolelist__remove_role(struct dynsec__rolelist **base_rolelist, const struct dynsec__role *role) { struct dynsec__rolelist *found_rolelist; HASH_FIND(hh, *base_rolelist, role->rolename, strlen(role->rolename), found_rolelist); if(found_rolelist){ dynsec_rolelist__free_item(base_rolelist, found_rolelist); return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOT_FOUND; } } int dynsec_rolelist__client_remove(struct dynsec__client *client, struct dynsec__role *role) { int rc; struct dynsec__clientlist *found_clientlist; rc = dynsec_rolelist__remove_role(&client->rolelist, role); if(rc) return rc; HASH_FIND(hh, role->clientlist, client->username, strlen(client->username), found_clientlist); if(found_clientlist){ HASH_DELETE(hh, role->clientlist, found_clientlist); mosquitto_free(found_clientlist); return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOT_FOUND; } } void dynsec_rolelist__group_remove(struct dynsec__group *group, struct dynsec__role *role) { dynsec_rolelist__remove_role(&group->rolelist, role); dynsec_grouplist__remove(&role->grouplist, group); } static int dynsec_rolelist__add(struct dynsec__rolelist **base_rolelist, struct dynsec__role *role, int priority) { struct dynsec__rolelist *rolelist; if(role == NULL) return MOSQ_ERR_INVAL; HASH_FIND(hh, *base_rolelist, role->rolename, strlen(role->rolename), rolelist); if(rolelist){ return MOSQ_ERR_ALREADY_EXISTS; }else{ rolelist = mosquitto_calloc(1, sizeof(struct dynsec__rolelist)); if(rolelist == NULL) return MOSQ_ERR_NOMEM; rolelist->role = role; rolelist->priority = priority; rolelist->rolename = mosquitto_strdup(role->rolename); if(rolelist->rolename == NULL){ mosquitto_free(rolelist); return MOSQ_ERR_NOMEM; } HASH_ADD_KEYPTR_INORDER(hh, *base_rolelist, role->rolename, strlen(role->rolename), rolelist, rolelist_cmp); return MOSQ_ERR_SUCCESS; } } int dynsec_rolelist__client_add(struct dynsec__client *client, struct dynsec__role *role, int priority) { struct dynsec__rolelist *rolelist; int rc; rc = dynsec_rolelist__add(&client->rolelist, role, priority); if(rc) return rc; HASH_FIND(hh, client->rolelist, role->rolename, strlen(role->rolename), rolelist); if(rolelist == NULL){ /* This should never happen because the above add_role succeeded. */ return MOSQ_ERR_UNKNOWN; } return dynsec_clientlist__add(&role->clientlist, client, priority); } int dynsec_rolelist__group_add(struct dynsec__group *group, struct dynsec__role *role, int priority) { int rc; rc = dynsec_rolelist__add(&group->rolelist, role, priority); if(rc) return rc; return dynsec_grouplist__add(&role->grouplist, group, priority); } int dynsec_rolelist__load_from_json(cJSON *command, struct dynsec__rolelist **rolelist) { cJSON *j_roles, *j_role, *j_rolename; int priority; struct dynsec__role *role; j_roles = cJSON_GetObjectItem(command, "roles"); if(j_roles){ if(cJSON_IsArray(j_roles)){ cJSON_ArrayForEach(j_role, j_roles){ j_rolename = cJSON_GetObjectItem(j_role, "rolename"); if(j_rolename && cJSON_IsString(j_rolename)){ json_get_int(j_role, "priority", &priority, true, -1); role = dynsec_roles__find(j_rolename->valuestring); if(role){ dynsec_rolelist__add(rolelist, role, priority); }else{ dynsec_rolelist__cleanup(rolelist); return MOSQ_ERR_NOT_FOUND; } }else{ return MOSQ_ERR_INVAL; } } return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_INVAL; } }else{ return ERR_LIST_NOT_FOUND; } } cJSON *dynsec_rolelist__all_to_json(struct dynsec__rolelist *base_rolelist) { struct dynsec__rolelist *rolelist, *rolelist_tmp; cJSON *j_roles, *j_role; j_roles = cJSON_CreateArray(); if(j_roles == NULL) return NULL; HASH_ITER(hh, base_rolelist, rolelist, rolelist_tmp){ j_role = cJSON_CreateObject(); if(j_role == NULL){ cJSON_Delete(j_roles); return NULL; } cJSON_AddItemToArray(j_roles, j_role); if(cJSON_AddStringToObject(j_role, "rolename", rolelist->role->rolename) == NULL || (rolelist->priority != -1 && cJSON_AddIntToObject(j_role, "priority", rolelist->priority) == NULL) ){ cJSON_Delete(j_roles); return NULL; } } return j_roles; } mosquitto-2.0.11/plugins/dynamic-security/Makefile0000664000175000017500000000453314060132747021302 0ustar rogerrogerinclude ../../config.mk .PHONY : all binary check clean reallyclean test install uninstall PLUGIN_NAME=mosquitto_dynamic_security LOCAL_CPPFLAGS=-I../../src/ -DWITH_CJSON OBJS= \ acl.o \ auth.o \ clients.o \ clientlist.o \ groups.o \ grouplist.o \ json_help.o \ plugin.o \ roles.o \ rolelist.o \ sub_matches_sub.o ifeq ($(WITH_CJSON),yes) ifeq ($(WITH_TLS),yes) ALL_DEPS:= binary else ALL_DEPS:= endif else ALL_DEPS:= endif all : ${ALL_DEPS} binary : ${PLUGIN_NAME}.so ${PLUGIN_NAME}.so : ${OBJS} ${CROSS_COMPILE}${CC} $(PLUGIN_LDFLAGS) -fPIC -shared $^ -o $@ -lcjson acl.o : acl.c dynamic_security.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ auth.o : auth.c dynamic_security.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ clients.o : clients.c dynamic_security.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ clientlist.o : clientlist.c dynamic_security.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ groups.o : groups.c dynamic_security.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ grouplist.o : grouplist.c dynamic_security.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ json_help.o : json_help.c dynamic_security.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ plugin.o : plugin.c dynamic_security.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ roles.o : roles.c dynamic_security.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ rolelist.o : rolelist.c dynamic_security.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ sub_matches_sub.o : sub_matches_sub.c dynamic_security.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ reallyclean : clean clean: -rm -f *.o ${PLUGIN_NAME}.so *.gcda *.gcno check: test test: install: all ifeq ($(WITH_CJSON),yes) ifeq ($(WITH_TLS),yes) $(INSTALL) -d "${DESTDIR}$(libdir)" $(INSTALL) ${STRIP_OPTS} ${PLUGIN_NAME}.so "${DESTDIR}${libdir}/${PLUGIN_NAME}.so" endif endif uninstall : -rm -f "${DESTDIR}${libdir}/${PLUGIN_NAME}.so" mosquitto-2.0.11/plugins/Makefile0000664000175000017500000000117014060132747016003 0ustar rogerrogerDIRS= \ auth-by-ip \ dynamic-security \ message-timestamp \ payload-modification .PHONY : all binary check clean reallyclean test install uninstall all : set -e; for d in ${DIRS}; do $(MAKE) -C $${d}; done binary : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done clean : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done reallyclean : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done check : test test : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done install : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done uninstall : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done mosquitto-2.0.11/lib/0000775000175000017500000000000014060132747013431 5ustar rogerrogermosquitto-2.0.11/lib/socks_mosq.h0000664000175000017500000000132014060132747015757 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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-2.0.11/lib/actions.c0000664000175000017500000002072514060132747015243 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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; size_t 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->max_qos) return MOSQ_ERR_QOS_NOT_SUPPORTED; if(!mosq->retain_available){ retain = false; } 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, (int)tlen)) return MOSQ_ERR_MALFORMED_UTF8; if(payloadlen < 0 || payloadlen > (int)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+(uint32_t)tlen + (uint32_t)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, (uint32_t)payloadlen, payload, (uint8_t)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((unsigned int)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, (uint32_t)payloadlen*sizeof(uint8_t)); }else{ message->msg.payloadlen = 0; message->msg.payload = NULL; } message->msg.qos = (uint8_t)qos; message->msg.retain = retain; message->dup = false; message->properties = properties_copy; pthread_mutex_lock(&mosq->msgs_out.mutex); message->state = mosq_ms_invalid; rc = message__queue(mosq, message, mosq_md_out); pthread_mutex_unlock(&mosq->msgs_out.mutex); return rc; } } 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 += 2U + 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-2.0.11/lib/handle_connack.c0000664000175000017500000000773114060132747016534 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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_RETAIN_AVAILABLE, &mosq->retain_available, false); mosquitto_property_read_byte(properties, MQTT_PROP_MAXIMUM_QOS, &mosq->max_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; message__reconnect_reset(mosq, true); 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-2.0.11/lib/linker.version0000664000175000017500000000665514060132747016340 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_copy_all; 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; MOSQ_1.7 { global: mosquitto_property_identifier; mosquitto_property_identifier_to_string; mosquitto_property_next; mosquitto_ssl_get; } MOSQ_1.6; mosquitto-2.0.11/lib/handle_disconnect.c0000664000175000017500000000304114060132747017237 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 "read_handle.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-2.0.11/lib/CMakeLists.txt0000664000175000017500000000575514060132747016205 0ustar rogerrogeroption(WITH_LIB_CPP "Build C++ library?" ON) if (WITH_LIB_CPP) add_subdirectory(cpp) endif (WITH_LIB_CPP) include_directories(${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/lib ${mosquitto_SOURCE_DIR}/include ${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}/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 ../include/mosquitto.h mosquitto_internal.h ../include/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 strings_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 AND NOT ANDROID) find_library(LIBRT rt) if (LIBRT) set (LIBRARIES ${LIBRARIES} rt) endif (LIBRT) endif (UNIX AND NOT APPLE AND NOT ANDROID) 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 ../include/mosquitto.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") install(FILES ../include/mqtt_protocol.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") mosquitto-2.0.11/lib/handle_pubackcomp.c0000664000175000017500000000637514060132747017247 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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__pubackcomp(struct mosquitto *mosq, const char *type) { uint8_t reason_code = 0; uint16_t mid; int rc; mosquitto_property *properties = NULL; int qos; assert(mosq); if(mosquitto__get_state(mosq) != 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(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 == MOSQ_ERR_SUCCESS){ /* 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); }else if(rc != MOSQ_ERR_NOT_FOUND){ return rc; } 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-2.0.11/lib/socks_mosq.c0000664000175000017500000003222314060132747015760 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifdef WIN32 # include #elif defined(__QNX__) # include # include # include #else # include #endif #if defined(__FreeBSD__) || defined(__OpenBSD__) # include # include #endif #include "mosquitto_internal.h" #include "memory_mosq.h" #include "net_mosq.h" #include "packet_mosq.h" #include "send_mosq.h" #include "socks_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 > UINT16_MAX) 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 = (uint16_t)port; mosquitto__free(mosq->socks5_username); mosq->socks5_username = NULL; mosquitto__free(mosq->socks5_password); mosq->socks5_password = NULL; if(username){ if(strlen(username) > UINT8_MAX){ return MOSQ_ERR_INVAL; } mosq->socks5_username = mosquitto__strdup(username); if(!mosq->socks5_username){ return MOSQ_ERR_NOMEM; } if(password){ if(strlen(password) > UINT8_MAX){ return MOSQ_ERR_INVAL; } 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; size_t slen; uint8_t ulen, plen; struct in_addr addr_ipv4; struct in6_addr addr_ipv6; int ipv4_pton_result; int ipv6_pton_result; enum mosquitto_client_state 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 = 7U + (uint32_t)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 = (uint8_t)strlen(mosq->socks5_username); plen = (uint8_t)strlen(mosq->socks5_password); packet->packet_length = 3U + 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; enum mosquitto_client_state 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 += (uint32_t)len; mosq->in_packet.to_process -= (uint32_t)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 += (uint32_t)len; mosq->in_packet.to_process -= (uint32_t)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 += (uint32_t)len; mosq->in_packet.to_process -= (uint32_t)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-2.0.11/lib/tls_mosq.c0000664000175000017500000001151714060132747015443 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef WITH_TLS #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 #ifndef WITH_BROKER && mosq->port != 0 /* no hostname checking for unix sockets */ #endif ){ 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; } } static int mosquitto__cmp_hostname_wildcard(char *certname, const char *hostname) { size_t i; size_t 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-2.0.11/lib/will_mosq.h0000664000175000017500000000156214060132747015614 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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-2.0.11/lib/handle_suback.c0000664000175000017500000000546014060132747016365 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 "read_handle.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; assert(mosq); if(mosquitto__get_state(mosq) != 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 = (int)(mosq->in_packet.remaining_length - mosq->in_packet.pos); granted_qos = mosquitto__malloc((size_t)qos_count*sizeof(int)); if(!granted_qos){ #ifdef WITH_BROKER mosquitto_property_free_all(&properties); #endif 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); #ifdef WITH_BROKER mosquitto_property_free_all(&properties); #endif 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-2.0.11/lib/util_mosq.h0000664000175000017500000000277014060132747015624 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 int mosquitto__check_keepalive(struct mosquitto *mosq); 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-2.0.11/lib/misc_mosq.h0000664000175000017500000000152514060132747015577 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef MISC_MOSQ_H #define MISC_MOSQ_H #include #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-2.0.11/lib/misc_mosq.c0000664000175000017500000000713214060132747015572 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 #include "misc_mosq.h" FILE *mosquitto__fopen(const char *path, const char *mode, bool restrict_read) { #ifdef WIN32 char buf[4096]; int rc; rc = ExpandEnvironmentStringsA(path, buf, 4096); if(rc == 0 || rc > 4096){ return NULL; }else{ if (restrict_read) { HANDLE hfile; SECURITY_ATTRIBUTES sec; EXPLICIT_ACCESS_A ea; PACL pacl = NULL; char username[UNLEN + 1]; DWORD ulen = UNLEN; SECURITY_DESCRIPTOR sd; DWORD dwCreationDisposition; int fd; FILE *fptr; switch(mode[0]){ case 'a': dwCreationDisposition = OPEN_ALWAYS; break; case 'r': dwCreationDisposition = OPEN_EXISTING; break; case 'w': dwCreationDisposition = CREATE_ALWAYS; break; default: return NULL; } GetUserNameA(username, &ulen); if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) { return NULL; } BuildExplicitAccessWithNameA(&ea, username, GENERIC_ALL, SET_ACCESS, NO_INHERITANCE); if (SetEntriesInAclA(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 = CreateFileA(buf, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, &sec, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL); LocalFree(pacl); fd = _open_osfhandle((intptr_t)hfile, 0); if (fd < 0) { return NULL; } 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, (size_t)*buflen); if(!newbuf){ return NULL; } *buf = newbuf; }while(1); } mosquitto-2.0.11/lib/will_mosq.c0000664000175000017500000000636114060132747015611 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 > (int)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, (uint16_t)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)*(unsigned int)mosq->will->msg.payloadlen); if(!mosq->will->msg.payload){ rc = MOSQ_ERR_NOMEM; goto cleanup; } memcpy(mosq->will->msg.payload, payload, (unsigned int)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; mosq->will_delay_interval = 0; return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/lib/logging_mosq.c0000664000175000017500000000267214060132747016271 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include "logging_mosq.h" #include "mosquitto_internal.h" #include "mosquitto.h" #include "memory_mosq.h" int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { va_list va; char *s; size_t 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, (int)priority, s); mosquitto__free(s); } pthread_mutex_unlock(&mosq->log_callback_mutex); return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/lib/dummypthread.h0000664000175000017500000000045714060132747016313 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_testcancel() #define pthread_mutex_init(A, B) #define pthread_mutex_destroy(A) #define pthread_mutex_lock(A) #define pthread_mutex_unlock(A) #endif mosquitto-2.0.11/lib/handle_ping.c0000664000175000017500000000333714060132747016053 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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) { assert(mosq); if(mosquitto__get_state(mosq) != 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) { assert(mosq); if(mosquitto__get_state(mosq) != 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-2.0.11/lib/util_mosq.c0000664000175000017500000001523614060132747015620 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 int mosquitto__check_keepalive(struct mosquitto *mosq) { time_t next_msg_out; time_t last_msg_in; time_t now; #ifndef WITH_BROKER int rc; #endif enum mosquitto_client_state state; assert(mosq); #ifdef WITH_BROKER now = db.now_s; #else now = mosquitto_time(); #endif #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(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(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, (size_t)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-2.0.11/lib/send_connect.c0000664000175000017500000001367614060132747016254 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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" #include "send_mosq.h" int send__connect(struct mosquitto *mosq, uint16_t keepalive, bool clean_session, const mosquitto_property *properties) { struct mosquitto__packet *packet = NULL; uint32_t payloadlen; uint8_t will = 0; uint8_t byte; int rc; uint8_t version; char *clientid, *username, *password; uint32_t headerlen; uint32_t proplen = 0, 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 = (uint32_t)(2U+strlen(clientid)); }else{ payloadlen = 2U; } #ifdef WITH_BROKER if(mosq->will && (mosq->bridge == NULL || mosq->bridge->notifications_local_only == false)){ #else if(mosq->will){ #endif will = 1; assert(mosq->will->msg.topic); payloadlen += (uint32_t)(2+strlen(mosq->will->msg.topic) + 2+(uint32_t)mosq->will->msg.payloadlen); if(mosq->protocol == mosq_p_mqtt5){ payloadlen += property__get_remaining_length(mosq->will->properties); } } /* 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){ mosquitto__free(packet); return MOSQ_ERR_INVAL; } } if(username){ payloadlen += (uint32_t)(2+strlen(username)); } if(password){ payloadlen += (uint32_t)(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, (uint16_t)strlen(PROTOCOL_NAME_v31)); }else{ packet__write_string(packet, PROTOCOL_NAME, (uint16_t)strlen(PROTOCOL_NAME)); } #if defined(WITH_BROKER) && defined(WITH_BRIDGE) if(mosq->bridge && mosq->bridge->protocol_version != mosq_p_mqtt5 && mosq->bridge->try_private && mosq->bridge->try_private_accepted){ version |= 0x80; }else{ } #endif packet__write_byte(packet, version); byte = (uint8_t)((clean_session&0x1)<<1); if(will){ byte = byte | (uint8_t)(((mosq->will->msg.qos&0x3)<<3) | ((will&0x1)<<2)); if(mosq->retain_available){ byte |= (uint8_t)((mosq->will->msg.retain&0x1)<<5); } } 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, (uint16_t)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, (uint16_t)strlen(mosq->will->msg.topic)); packet__write_string(packet, (const char *)mosq->will->msg.payload, (uint16_t)mosq->will->msg.payloadlen); } if(username){ packet__write_string(packet, username, (uint16_t)strlen(username)); } if(password){ packet__write_string(packet, password, (uint16_t)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-2.0.11/lib/handle_pubrel.c0000664000175000017500000000655414060132747016413 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *mosq) { uint8_t reason_code; uint16_t mid; #ifndef WITH_BROKER struct mosquitto_message_all *message = NULL; #endif int rc; mosquitto_property *properties = NULL; assert(mosq); if(mosquitto__get_state(mosq) != 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(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, NULL); if(rc) return rc; #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received PUBREL (Mid: %d)", mosq->id, mid); rc = send__pubcomp(mosq, mid, NULL); 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 == MOSQ_ERR_SUCCESS){ /* 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); }else if(rc == MOSQ_ERR_NOT_FOUND){ return MOSQ_ERR_SUCCESS; }else{ return rc; } #endif return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/lib/time_mosq.h0000664000175000017500000000123114060132747015574 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef TIME_MOSQ_H #define TIME_MOSQ_H time_t mosquitto_time(void); #endif mosquitto-2.0.11/lib/send_mosq.c0000664000175000017500000001222714060132747015571 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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, const mosquitto_property *properties) { #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, properties); } int send__pubcomp(struct mosquitto *mosq, uint16_t mid, const mosquitto_property *properties) { #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, properties); } int send__pubrec(struct mosquitto *mosq, uint16_t mid, uint8_t reason_code, const mosquitto_property *properties) { #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, properties); } int send__pubrel(struct mosquitto *mosq, uint16_t mid, const mosquitto_property *properties) { #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, properties); } /* 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; 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){ packet->remaining_length += property__get_remaining_length(properties); } } 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-2.0.11/lib/memory_mosq.c0000664000175000017500000000562714060132747016156 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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) { void *mem; #ifdef REAL_WITH_MEMORY_TRACKING if(mem_limit && memcount + size > mem_limit){ return NULL; } #endif 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) { void *mem; #ifdef REAL_WITH_MEMORY_TRACKING if(mem_limit && memcount + size > mem_limit){ return NULL; } #endif 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) { void *mem; #ifdef REAL_WITH_MEMORY_TRACKING if(mem_limit && memcount + size > mem_limit){ return NULL; } 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) { char *str; #ifdef REAL_WITH_MEMORY_TRACKING if(mem_limit && memcount + strlen(s) > mem_limit){ return NULL; } #endif 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-2.0.11/lib/send_publish.c0000664000175000017500000001511614060132747016260 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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, uint8_t qos, bool retain, bool dup, const mosquitto_property *cmsg_props, const mosquitto_property *store_props, uint32_t expiry_interval) { #ifdef WITH_BROKER #ifdef WITH_BRIDGE size_t len; 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 if(!mosq->retain_available){ retain = false; } #ifdef WITH_BROKER #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, uint8_t qos, bool retain, bool dup, const mosquitto_property *cmsg_props, const mosquitto_property *store_props, uint32_t expiry_interval) { struct mosquitto__packet *packet = NULL; unsigned int packetlen; unsigned int proplen = 0, varbytes; int rc; mosquitto_property expiry_prop; assert(mosq); if(topic){ packetlen = 2+(unsigned int)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 = (uint8_t)(CMD_PUBLISH | (uint8_t)((dup&0x1)<<3) | (uint8_t)(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, (uint16_t)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-2.0.11/lib/logging_mosq.h0000664000175000017500000000151114060132747016265 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef LOGGING_MOSQ_H #define LOGGING_MOSQ_H #include "mosquitto.h" #ifndef __GNUC__ #define __attribute__(attrib) #endif int log__printf(struct mosquitto *mosq, unsigned int level, const char *fmt, ...) __attribute__((format(printf, 3, 4))); #endif mosquitto-2.0.11/lib/handle_auth.c0000664000175000017500000000254514060132747016057 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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" #include "read_handle.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-2.0.11/lib/packet_mosq.h0000664000175000017500000000435114060132747016113 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef PACKET_MOSQ_H #define PACKET_MOSQ_H #include "mosquitto_internal.h" #include "mosquitto.h" int packet__alloc(struct mosquitto__packet *packet); void packet__cleanup(struct mosquitto__packet *packet); void packet__cleanup_all(struct mosquitto *mosq); void packet__cleanup_all_no_locks(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, uint16_t *length); int packet__read_string(struct mosquitto__packet *packet, char **str, uint16_t *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, uint32_t *word, uint8_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, uint32_t word); unsigned int packet__varint_bytes(uint32_t word); int packet__write(struct mosquitto *mosq); int packet__read(struct mosquitto *mosq); #endif mosquitto-2.0.11/lib/net_mosq_ocsp.c0000664000175000017500000001204714060132747016452 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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. */ #include "config.h" #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; UNUSED(ssl); 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-2.0.11/lib/send_subscribe.c0000664000175000017500000000516714060132747016600 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 "send_mosq.h" #include "util_mosq.h" int send__subscribe(struct mosquitto *mosq, int *mid, int topic_count, char *const *const topic, int topic_qos, const mosquitto_property *properties) { struct mosquitto__packet *packet = NULL; uint32_t packetlen; uint16_t local_mid; int rc; int i; size_t tlen; assert(mosq); assert(topic); packetlen = 2; if(mosq->protocol == mosq_p_mqtt5){ packetlen += property__get_remaining_length(properties); } for(i=0; i UINT16_MAX){ return MOSQ_ERR_INVAL; } packetlen += 2U+(uint16_t)tlen + 1U; } packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; packet->command = 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-2.0.11/lib/net_mosq.c0000664000175000017500000007004214060132747015425 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 #include #else #include #include #endif #ifdef __ANDROID__ #include #include #include #endif #ifdef HAVE_NETINET_IN_H # include #endif #ifdef WITH_UNIX_SOCKETS # 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; static bool is_tls_initialized = false; /* 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 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 is_tls_initialized = false; # endif CONF_modules_unload(1); cleanup_ui_method(); #endif #ifdef WITH_SRV ares_library_cleanup(); #endif #ifdef WIN32 WSACleanup(); #endif } #ifdef WITH_TLS void net__init_tls(void) { if(is_tls_initialized) return; # 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); } is_tls_initialized = true; } #endif /* Close a socket associated with a context and set it to -1. * Returns 1 on failure (context is NULL) * Returns 0 on success. */ int net__socket_close(struct mosquitto *mosq) { int rc = 0; #ifdef WITH_BROKER struct mosquitto *mosq_found; #endif 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); } lws_callback_on_writable(mosq->wsi); }else #endif { if(mosq->sock != INVALID_SOCKET){ #ifdef WITH_BROKER HASH_FIND(hh_sock, db.contexts_by_sock, &mosq->sock, sizeof(mosq->sock), mosq_found); if(mosq_found){ HASH_DELETE(hh_sock, db.contexts_by_sock, mosq_found); } #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, (int)max_psk_len); if (len < 0) return 0; return (unsigned int)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 static int net__try_connect_tcp(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; ainfo_bind = NULL; *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_UNIX_SOCKETS static int net__try_connect_unix(const char *host, mosq_sock_t *sock) { struct sockaddr_un addr; int s; int rc; if(host == NULL || strlen(host) == 0 || strlen(host) > sizeof(addr.sun_path)-1){ return MOSQ_ERR_INVAL; } memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, host, sizeof(addr.sun_path)-1); s = socket(AF_UNIX, SOCK_STREAM, 0); if(s < 0){ return MOSQ_ERR_ERRNO; } rc = net__socket_nonblock(&s); if(rc) return rc; rc = connect(s, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)); if(rc < 0){ close(s); return MOSQ_ERR_ERRNO; } *sock = s; return 0; } #endif int net__try_connect(const char *host, uint16_t port, mosq_sock_t *sock, const char *bind_address, bool blocking) { if(port == 0){ #ifdef WITH_UNIX_SOCKETS return net__try_connect_unix(host, sock); #else return MOSQ_ERR_NOT_SUPPORTED; #endif }else{ return net__try_connect_tcp(host, port, sock, bind_address, blocking); } } #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; long res; ERR_clear_error(); 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__tls_load_ca(struct mosquitto *mosq) { int ret; if(mosq->tls_use_os_certs){ SSL_CTX_set_default_verify_paths(mosq->ssl_ctx); } #if OPENSSL_VERSION_NUMBER < 0x30000000L 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 return MOSQ_ERR_TLS; } } #else if(mosq->tls_cafile){ ret = SSL_CTX_load_verify_file(mosq->ssl_ctx, mosq->tls_cafile); if(ret == 0){ # ifdef WITH_BROKER 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 cafile \"%s\".", mosq->tls_cafile); # endif return MOSQ_ERR_TLS; } } if(mosq->tls_capath){ ret = SSL_CTX_load_verify_dir(mosq->ssl_ctx, mosq->tls_capath); if(ret == 0){ # ifdef WITH_BROKER log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load CA certificates, check bridge_capath \"%s\".", mosq->tls_capath); # else log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to load CA certificates, check capath \"%s\".", mosq->tls_capath); # endif return MOSQ_ERR_TLS; } } #endif return MOSQ_ERR_SUCCESS; } 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 !defined(OPENSSL_NO_ENGINE) EVP_PKEY *pkey; #endif 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 || mosq->tls_use_os_certs){ if(!mosq->ssl_ctx){ net__init_tls(); #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."); 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 | SSL_OP_NO_TLSv1_1); #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); #endif }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); }else{ log__printf(mosq, MOSQ_LOG_ERR, "Error: Protocol %s not supported.", mosq->tls_version); return MOSQ_ERR_INVAL; } #if OPENSSL_VERSION_NUMBER >= 0x10100000L /* Allow use of DHE ciphers */ SSL_CTX_set_dh_auto(mosq->ssl_ctx, 1); #endif /* 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 + 1U); } #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); return MOSQ_ERR_TLS; } if(!ENGINE_init(engine)){ log__printf(mosq, MOSQ_LOG_ERR, "Failed engine initialisation\n"); ENGINE_free(engine); 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 net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } } if(mosq->tls_cafile || mosq->tls_capath || mosq->tls_use_os_certs){ ret = net__tls_load_ca(mosq); if(ret != MOSQ_ERR_SUCCESS){ # if !defined(OPENSSL_NO_ENGINE) ENGINE_FINISH(engine); # endif 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 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); 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); net__print_ssl_error(mosq); return MOSQ_ERR_TLS; } ui_method = NULL; } 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); 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); 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 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 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){ net__socket_close(mosq); return rc; } if(mosq->ssl_ctx){ if(mosq->ssl){ SSL_free(mosq->ssl); } mosq->ssl = SSL_new(mosq->ssl_ctx); if(!mosq->ssl){ net__socket_close(mosq); 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){ net__socket_close(mosq); 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) { net__socket_close(mosq); return MOSQ_ERR_TLS; } if(net__socket_connect_tls(mosq)){ net__socket_close(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) { int rc, rc2; if(!mosq || !host) return MOSQ_ERR_INVAL; rc = net__try_connect(host, port, &mosq->sock, bind_address, blocking); if(rc > 0) return rc; if(mosq->tcp_nodelay){ int flag = 1; if(setsockopt(mosq->sock, IPPROTO_TCP, TCP_NODELAY, (const void*)&flag, sizeof(int)) != 0){ log__printf(mosq, MOSQ_LOG_WARNING, "Warning: Unable to set TCP_NODELAY."); } } #if defined(WITH_SOCKS) && !defined(WITH_BROKER) if(!mosq->socks5_host) #endif { rc2 = net__socket_connect_step3(mosq, host); if(rc2) return rc2; } return rc; } #ifdef WITH_TLS static int net__handle_ssl(struct mosquitto* mosq, int ret) { int err; 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; #ifdef WITH_BROKER mux__add_out(mosq); #else mosq->want_write = true; #endif errno = EAGAIN; } else { net__print_ssl_error(mosq); errno = EPROTO; } ERR_clear_error(); #ifdef WIN32 WSASetLastError(errno); #endif return ret; } #endif ssize_t net__read(struct mosquitto *mosq, void *buf, size_t count) { #ifdef WITH_TLS int ret; #endif assert(mosq); errno = 0; #ifdef WITH_TLS if(mosq->ssl){ ret = SSL_read(mosq->ssl, buf, (int)count); if(ret <= 0){ ret = net__handle_ssl(mosq, ret); } 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, const void *buf, size_t count) { #ifdef WITH_TLS int ret; #endif assert(mosq); errno = 0; #ifdef WITH_TLS if(mosq->ssl){ mosq->want_write = false; ret = SSL_write(mosq->ssl, buf, (int)count); if(ret < 0){ ret = net__handle_ssl(mosq, ret); } 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]; *pairR = INVALID_SOCKET; *pairW = INVALID_SOCKET; 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 #ifndef WITH_BROKER void *mosquitto_ssl_get(struct mosquitto *mosq) { #ifdef WITH_TLS return mosq->ssl; #else return NULL; #endif } #endif mosquitto-2.0.11/lib/messages_mosq.h0000664000175000017500000000273414060132747016456 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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, bool update_quota_only); 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-2.0.11/lib/send_unsubscribe.c0000664000175000017500000000475714060132747017147 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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) { struct mosquitto__packet *packet = NULL; uint32_t packetlen; uint16_t local_mid; int rc; int i; size_t tlen; assert(mosq); assert(topic); packetlen = 2; for(i=0; i UINT16_MAX){ return MOSQ_ERR_INVAL; } packetlen += 2U+(uint16_t)tlen; } packet = mosquitto__calloc(1, sizeof(struct mosquitto__packet)); if(!packet) return MOSQ_ERR_NOMEM; if(mosq->protocol == mosq_p_mqtt5){ packetlen += property__get_remaining_length(properties); } 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-2.0.11/lib/alias_mosq.c0000664000175000017500000000403614060132747015730 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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, uint16_t 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)*(size_t)(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, uint16_t 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-2.0.11/lib/property_mosq.c0000664000175000017500000010440714060132747016526 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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" static int property__read(struct mosquitto__packet *packet, uint32_t *len, mosquitto_property *property) { int rc; uint32_t property_identifier; uint8_t byte; uint8_t byte_count; uint16_t uint16; uint32_t uint32; uint32_t varint; char *str1, *str2; uint16_t 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 = (int32_t)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; uint32_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; } unsigned 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 3U + 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 3U + property->value.s.len; /* 1 + 2 bytes (len) + X bytes (string) */ /* string pair */ case MQTT_PROP_USER_PROPERTY: return 5U + property->value.s.len + property->name.len; /* 1 + 2*(2 bytes (len) + X bytes (string))*/ default: return 0; } return 0; } unsigned int property__get_length_all(const mosquitto_property *property) { const mosquitto_property *p; unsigned int len = 0; p = property; while(p){ len += property__get_length(p); p = p->next; } return len; } /* Return the number of bytes we need to add on to the remaining length when * encoding these properties. */ unsigned int property__get_remaining_length(const mosquitto_property *props) { unsigned int proplen, varbytes; proplen = property__get_length_all(props); varbytes = packet__varint_bytes(proplen); return proplen + varbytes; } static int property__write(struct mosquitto__packet *packet, const mosquitto_property *property) { int rc; rc = packet__write_varint(packet, (uint32_t)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; } const char *mosquitto_property_identifier_to_string(int identifier) { switch(identifier){ case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: return "payload-format-indicator"; case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: return "message-expiry-interval"; case MQTT_PROP_CONTENT_TYPE: return "content-type"; case MQTT_PROP_RESPONSE_TOPIC: return "response-topic"; case MQTT_PROP_CORRELATION_DATA: return "correlation-data"; case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: return "subscription-identifier"; case MQTT_PROP_SESSION_EXPIRY_INTERVAL: return "session-expiry-interval"; case MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER: return "assigned-client-identifier"; case MQTT_PROP_SERVER_KEEP_ALIVE: return "server-keep-alive"; case MQTT_PROP_AUTHENTICATION_METHOD: return "authentication-method"; case MQTT_PROP_AUTHENTICATION_DATA: return "authentication-data"; case MQTT_PROP_REQUEST_PROBLEM_INFORMATION: return "request-problem-information"; case MQTT_PROP_WILL_DELAY_INTERVAL: return "will-delay-interval"; case MQTT_PROP_REQUEST_RESPONSE_INFORMATION: return "request-response-information"; case MQTT_PROP_RESPONSE_INFORMATION: return "response-information"; case MQTT_PROP_SERVER_REFERENCE: return "server-reference"; case MQTT_PROP_REASON_STRING: return "reason-string"; case MQTT_PROP_RECEIVE_MAXIMUM: return "receive-maximum"; case MQTT_PROP_TOPIC_ALIAS_MAXIMUM: return "topic-alias-maximum"; case MQTT_PROP_TOPIC_ALIAS: return "topic-alias"; case MQTT_PROP_MAXIMUM_QOS: return "maximum-qos"; case MQTT_PROP_RETAIN_AVAILABLE: return "retain-available"; case MQTT_PROP_USER_PROPERTY: return "user-property"; case MQTT_PROP_MAXIMUM_PACKET_SIZE: return "maximum-packet-size"; case MQTT_PROP_WILDCARD_SUB_AVAILABLE: return "wildcard-subscription-available"; case MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE: return "subscription-identifier-available"; case MQTT_PROP_SHARED_SUB_AVAILABLE: return "shared-subscription-available"; default: return NULL; } } 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; size_t slen = 0; if(!proplist) return MOSQ_ERR_INVAL; if(value){ slen = strlen(value); if(mosquitto_validate_utf8(value, (int)slen)) 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 && slen > 0){ prop->value.s.v = mosquitto__strdup(value); if(!prop->value.s.v){ mosquitto__free(prop); return MOSQ_ERR_NOMEM; } prop->value.s.len = (uint16_t)slen; } 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; size_t slen_name = 0, slen_value = 0; if(!proplist) return MOSQ_ERR_INVAL; if(identifier != MQTT_PROP_USER_PROPERTY) return MOSQ_ERR_INVAL; if(name){ slen_name = strlen(name); if(mosquitto_validate_utf8(name, (int)slen_name)) return MOSQ_ERR_MALFORMED_UTF8; } if(value){ if(mosquitto_validate_utf8(value, (int)slen_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){ prop->name.v = mosquitto__strdup(name); if(!prop->name.v){ mosquitto__free(prop); return MOSQ_ERR_NOMEM; } prop->name.len = (uint16_t)strlen(name); } if(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 = (uint16_t)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; } static 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; } int mosquitto_property_identifier(const mosquitto_property *property) { if(property == NULL) return 0; return property->identifier; } const mosquitto_property *mosquitto_property_next(const mosquitto_property *proplist) { if(proplist == NULL) return NULL; return proplist->next; } 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; if(value) *value = 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 = calloc(1, *len + 1U); 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, (size_t)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; if(name) *name = NULL; if(value) *value = 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, (size_t)p->name.len+1); if(!(*name)) return NULL; memcpy(*name, p->name.v, p->name.len); } if(value){ *value = calloc(1, (size_t)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-2.0.11/lib/utf8_mosq.c0000664000175000017500000000574414060132747015534 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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-2.0.11/lib/srv_mosq.c0000664000175000017500000000566214060132747015457 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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; if(keepalive < 0 || keepalive > UINT16_MAX){ 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 = (uint16_t)keepalive; return MOSQ_ERR_SUCCESS; #else UNUSED(mosq); UNUSED(host); UNUSED(keepalive); UNUSED(bind_address); return MOSQ_ERR_NOT_SUPPORTED; #endif } mosquitto-2.0.11/lib/util_topic.c0000664000175000017500000001551714060132747015761 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 if(str == NULL){ return MOSQ_ERR_INVAL; } 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(str == NULL || 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 if(str == NULL){ return MOSQ_ERR_INVAL; } while(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(str == NULL || 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-2.0.11/lib/mosquitto_internal.h0000664000175000017500000002233314060132747017545 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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_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; long msg_bytes; 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 { #if defined(WITH_BROKER) && defined(WITH_EPOLL) /* This *must* be the first element in the struct. */ int ident; #endif mosq_sock_t sock; #ifndef WITH_BROKER mosq_sock_t sockpairR, sockpairW; #endif uint32_t maximum_packet_size; #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; int alias_count; int out_packet_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; char *tls_engine; char *tls_engine_kpass_sha1; char *tls_alpn; int tls_cert_reqs; bool tls_insecure; bool ssl_ctx_defaults; bool tls_ocsp_required; bool tls_use_os_certs; enum mosquitto__keyform tls_keyform; #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; time_t session_expiry_time; uint32_t session_expiry_interval; #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; # ifndef WITH_EPOLL int pollfd_index; # endif # ifdef WITH_WEBSOCKETS struct lws *wsi; # endif bool ws_want_write; bool assigned_id; #else # ifdef WITH_SOCKS char *socks5_host; uint16_t 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; uint16_t 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; mosquitto_property *connect_properties; # ifdef WITH_SRV ares_channel achan; # endif #endif uint8_t max_qos; uint8_t retain_available; bool tcp_nodelay; #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; uint16_t remote_port; #endif uint32_t events; }; #define STREMPTY(str) (str[0] == '\0') void do_client_disconnect(struct mosquitto *mosq, int reason_code, const mosquitto_property *properties); #endif mosquitto-2.0.11/lib/time_mosq.c0000664000175000017500000000257714060132747015605 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef __APPLE__ #include #include #endif #ifdef WIN32 #if !(defined(_MSC_VER) && _MSC_VER <= 1500) # define _WIN32_WINNT _WIN32_WINNT_VISTA #endif # 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-2.0.11/lib/thread_mosq.c0000664000175000017500000000633114060132747016106 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifndef WIN32 #include #endif #if defined(WITH_THREADING) #if defined(__linux__) || defined(__NetBSD__) # include #elif defined(__FreeBSD__) || defined(__OpenBSD__) # include #endif #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) 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)){ #if defined(__linux__) pthread_setname_np(mosq->thread_id, "mosquitto loop"); #elif defined(__NetBSD__) pthread_setname_np(mosq->thread_id, "%s", "mosquitto loop"); #elif defined(__FreeBSD__) || defined(__OpenBSD__) pthread_set_name_np(mosq->thread_id, "mosquitto loop"); #endif return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ERRNO; } #else UNUSED(mosq); return MOSQ_ERR_NOT_SUPPORTED; #endif } int mosquitto_loop_stop(struct mosquitto *mosq, bool force) { #if defined(WITH_THREADING) # 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 } #ifdef HAVE_PTHREAD_CANCEL if(force){ pthread_cancel(mosq->thread_id); } #endif pthread_join(mosq->thread_id, NULL); mosq->thread_id = pthread_self(); mosq->threaded = mosq_ts_none; return MOSQ_ERR_SUCCESS; #else UNUSED(mosq); UNUSED(force); return MOSQ_ERR_NOT_SUPPORTED; #endif } #ifdef WITH_THREADING void *mosquitto__thread_main(void *obj) { struct mosquitto *mosq = obj; #ifndef WIN32 struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 10000000; #endif if(!mosq) return NULL; do{ if(mosquitto__get_state(mosq) == 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-2.0.11/lib/options.c0000664000175000017500000002701714060132747015277 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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) { size_t slen; 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){ slen = strlen(username); if(slen > UINT16_MAX){ return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)slen)){ 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: #if defined(WITH_TLS) && !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; #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; case MOSQ_OPT_BIND_ADDRESS: mosquitto__free(mosq->bind_address); if(value){ mosq->bind_address = mosquitto__strdup(value); if(mosq->bind_address){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOMEM; } }else{ return MOSQ_ERR_SUCCESS; } 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 > UINT16_MAX){ return MOSQ_ERR_INVAL; } if(value == 0){ mosq->msgs_in.inflight_maximum = UINT16_MAX; }else{ mosq->msgs_in.inflight_maximum = (uint16_t)value; } break; case MOSQ_OPT_SEND_MAXIMUM: if(value < 0 || value > UINT16_MAX){ return MOSQ_ERR_INVAL; } if(value == 0){ mosq->msgs_out.inflight_maximum = UINT16_MAX; }else{ mosq->msgs_out.inflight_maximum = (uint16_t)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_USE_OS_CERTS: #ifdef WITH_TLS if(value){ mosq->tls_use_os_certs = true; }else{ mosq->tls_use_os_certs = 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; case MOSQ_OPT_TCP_NODELAY: mosq->tcp_nodelay = (bool)value; 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-2.0.11/lib/handle_pubrec.c0000664000175000017500000000617314060132747016377 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *mosq) { uint8_t reason_code = 0; uint16_t mid; int rc; mosquitto_property *properties = NULL; assert(mosq); if(mosquitto__get_state(mosq) != 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(mosq, mid, mosq_ms_wait_for_pubrec, 2); } #else 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, NULL); if(rc) return rc; return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/lib/handle_unsuback.c0000664000175000017500000000434414060132747016730 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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; assert(mosq); if(mosquitto__get_state(mosq) != 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-2.0.11/lib/connect.c0000664000175000017500000002022614060132747015230 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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); static int mosquitto__connect_init(struct mosquitto *mosq, const char *host, int port, int keepalive); static int mosquitto__connect_init(struct mosquitto *mosq, const char *host, int port, int keepalive) { int i; int rc; if(!mosq) return MOSQ_ERR_INVAL; if(!host || port < 0 || port > UINT16_MAX) return MOSQ_ERR_INVAL; if(keepalive != 0 && (keepalive < 5 || keepalive > UINT16_MAX)) return MOSQ_ERR_INVAL; /* Only MQTT v3.1 requires a client id to be sent */ if(mosq->id == NULL && (mosq->protocol == mosq_p_mqtt31)){ 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 = (uint16_t)port; mosq->keepalive = (uint16_t)keepalive; mosq->msgs_in.inflight_quota = mosq->msgs_in.inflight_maximum; mosq->msgs_out.inflight_quota = mosq->msgs_out.inflight_maximum; mosq->retain_available = 1; 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(bind_address){ rc = mosquitto_string_option(mosq, MOSQ_OPT_BIND_ADDRESS, bind_address); if(rc) return rc; } mosquitto_property_free_all(&mosq->connect_properties); if(properties){ rc = mosquitto_property_check_all(CMD_CONNECT, properties); if(rc) return rc; rc = mosquitto_property_copy_all(&mosq->connect_properties, properties); if(rc) return rc; mosq->connect_properties->client_generated = true; } rc = mosquitto__connect_init(mosq, host, port, keepalive); if(rc) return rc; mosquitto__set_state(mosq, mosq_cs_new); return mosquitto__reconnect(mosq, true); } 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; if(bind_address){ rc = mosquitto_string_option(mosq, MOSQ_OPT_BIND_ADDRESS, bind_address); if(rc) return rc; } rc = mosquitto__connect_init(mosq, host, port, keepalive); if(rc) return rc; return mosquitto__reconnect(mosq, false); } int mosquitto_reconnect_async(struct mosquitto *mosq) { return mosquitto__reconnect(mosq, false); } int mosquitto_reconnect(struct mosquitto *mosq) { return mosquitto__reconnect(mosq, true); } static int mosquitto__reconnect(struct mosquitto *mosq, bool blocking) { const mosquitto_property *outgoing_properties = NULL; mosquitto_property local_property; int rc; if(!mosq) return MOSQ_ERR_INVAL; if(!mosq->host) return MOSQ_ERR_INVAL; if(mosq->connect_properties){ if(mosq->protocol != mosq_p_mqtt5) return MOSQ_ERR_NOT_SUPPORTED; if(mosq->connect_properties->client_generated){ outgoing_properties = mosq->connect_properties; }else{ memcpy(&local_property, mosq->connect_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, false); if(mosq->sock != INVALID_SOCKET){ net__socket_close(mosq); } #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(reason_code < 0 || reason_code > UINT8_MAX) return MOSQ_ERR_INVAL; 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, (uint8_t)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; } mosq->out_packet_count--; } 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-2.0.11/lib/read_handle.h0000664000175000017500000000247614060132747016041 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 *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 *mosq); int handle__pubrel(struct mosquitto *mosq); int handle__suback(struct mosquitto *mosq); int handle__unsuback(struct mosquitto *mosq); #endif mosquitto-2.0.11/lib/helpers.c0000664000175000017500000001155114060132747015242 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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), (size_t)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-2.0.11/lib/cpp/0000775000175000017500000000000014060132747014213 5ustar rogerrogermosquitto-2.0.11/lib/cpp/CMakeLists.txt0000664000175000017500000000235414060132747016757 0ustar rogerrogerinclude_directories(${mosquitto_SOURCE_DIR}/lib ${mosquitto_SOURCE_DIR}/lib/cpp ${mosquitto_SOURCE_DIR}/include ${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-2.0.11/lib/cpp/mosquittopp.cpp0000664000175000017500000002334714060132747017334 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ 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-2.0.11/lib/cpp/mosquittopp.h0000664000175000017500000001233214060132747016771 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ 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 #include #include #include namespace mosqpp { mosqpp_EXPORT const char * strerror(int mosq_errno); mosqpp_EXPORT const char * connack_string(int connack_code); mosqpp_EXPORT int sub_topic_tokenise(const char *subtopic, char ***topics, int *count); mosqpp_EXPORT int sub_topic_tokens_free(char ***topics, int count); mosqpp_EXPORT int lib_version(int *major, int *minor, int *revision); mosqpp_EXPORT int lib_init(); mosqpp_EXPORT int lib_cleanup(); mosqpp_EXPORT int topic_matches_sub(const char *sub, const char *topic, bool *result); mosqpp_EXPORT int validate_utf8(const char *str, int len); mosqpp_EXPORT int 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 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 mosquittopp { private: struct mosquitto *m_mosq; public: mosquittopp(const char *id=NULL, bool clean_session=true); virtual ~mosquittopp(); int reinitialise(const char *id, bool clean_session); int socket(); int will_set(const char *topic, int payloadlen=0, const void *payload=NULL, int qos=0, bool retain=false); int will_clear(); int username_pw_set(const char *username, const char *password=NULL); int connect(const char *host, int port=1883, int keepalive=60); int connect_async(const char *host, int port=1883, int keepalive=60); int connect(const char *host, int port, int keepalive, const char *bind_address); int connect_async(const char *host, int port, int keepalive, const char *bind_address); int reconnect(); int reconnect_async(); int disconnect(); int publish(int *mid, const char *topic, int payloadlen=0, const void *payload=NULL, int qos=0, bool retain=false); int subscribe(int *mid, const char *sub, int qos=0); int unsubscribe(int *mid, const char *sub); void reconnect_delay_set(unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff); int max_inflight_messages_set(unsigned int max_inflight_messages); void message_retry_set(unsigned int message_retry); void user_data_set(void *userdata); int 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 tls_opts_set(int cert_reqs, const char *tls_version=NULL, const char *ciphers=NULL); int tls_insecure_set(bool value); int tls_psk_set(const char *psk, const char *identity, const char *ciphers=NULL); int opts_set(enum mosq_opt_t option, void *value); int loop(int timeout=-1, int max_packets=1); int loop_misc(); int loop_read(int max_packets=1); int loop_write(int max_packets=1); int loop_forever(int timeout=-1, int max_packets=1); int loop_start(); int loop_stop(bool force=false); bool want_write(); int threaded_set(bool threaded=true); int 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-2.0.11/lib/cpp/Makefile0000664000175000017500000000326114060132747015655 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 ${SEDINPLACE} -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-2.0.11/lib/net_mosq.h0000664000175000017500000000534414060132747015435 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 WIN32 # define COMPAT_CLOSE(a) closesocket(a) # define COMPAT_ECONNRESET WSAECONNRESET # define COMPAT_EINTR WSAEINTR # define COMPAT_EWOULDBLOCK WSAEWOULDBLOCK # ifndef EINPROGRESS # define EINPROGRESS WSAEINPROGRESS # endif #else # define COMPAT_CLOSE(a) close(a) # define COMPAT_ECONNRESET ECONNRESET # define COMPAT_EINTR EINTR # 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); #ifdef WITH_TLS void net__init_tls(void); #endif int net__socket_connect(struct mosquitto *mosq, const char *host, uint16_t port, const char *bind_address, bool blocking); int net__socket_close(struct mosquitto *mosq); 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, const 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-2.0.11/lib/tls_mosq.h0000664000175000017500000000176714060132747015456 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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-2.0.11/lib/property_mosq.h0000664000175000017500000000274614060132747016536 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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; uint16_t 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); unsigned int property__get_length(const mosquitto_property *property); unsigned int property__get_length_all(const mosquitto_property *property); unsigned int property__get_remaining_length(const mosquitto_property *props); #endif mosquitto-2.0.11/lib/read_handle.c0000664000175000017500000000360514060132747016027 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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(mosq); case CMD_PUBREL: return handle__pubrel(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-2.0.11/lib/callbacks.c0000664000175000017500000001055214060132747015517 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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-2.0.11/lib/send_disconnect.c0000664000175000017500000000414014060132747016736 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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; 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){ packet->remaining_length += property__get_remaining_length(properties); } }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-2.0.11/lib/strings_mosq.c0000664000175000017500000001572214060132747016334 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include "mosquitto.h" #include "mqtt_protocol.h" 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; } mosquitto-2.0.11/lib/loop.c0000664000175000017500000002421014060132747014545 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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__) && !defined(__QNX__) #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; time_t timeout_ms; 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){ if(mosquitto__get_state(mosq) == 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((int)mosq->sockpairR > maxfd){ maxfd = mosq->sockpairR; } } timeout_ms = timeout; if(timeout_ms < 0){ timeout_ms = 1000; } now = mosquitto_time(); if(mosq->next_msg_out && now + timeout_ms/1000 > mosq->next_msg_out){ timeout_ms = (mosq->next_msg_out - now)*1000; } if(timeout_ms < 0){ /* There has been a delay somewhere which means we should have already * sent a message. */ timeout_ms = 0; } local_timeout.tv_sec = timeout_ms/1000; #ifdef HAVE_PSELECT local_timeout.tv_nsec = (timeout_ms-local_timeout.tv_sec*1000)*1000000; #else local_timeout.tv_usec = (timeout_ms-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); } static int interruptible_sleep(struct mosquitto *mosq, time_t reconnect_delay) { #ifdef HAVE_PSELECT struct timespec local_timeout; #else struct timeval local_timeout; #endif fd_set readfds; int fdcount; char pairbuf; int maxfd = 0; #ifndef WIN32 while(mosq->sockpairR != INVALID_SOCKET && read(mosq->sockpairR, &pairbuf, 1) > 0); #else while(mosq->sockpairR != INVALID_SOCKET && recv(mosq->sockpairR, &pairbuf, 1, 0) > 0); #endif local_timeout.tv_sec = reconnect_delay; #ifdef HAVE_PSELECT local_timeout.tv_nsec = 0; #else local_timeout.tv_usec = 0; #endif FD_ZERO(&readfds); maxfd = 0; if(mosq->sockpairR != INVALID_SOCKET){ /* sockpairR is used to break out of select() before the * timeout, when mosquitto_loop_stop() is called */ FD_SET(mosq->sockpairR, &readfds); maxfd = mosq->sockpairR; } #ifdef HAVE_PSELECT fdcount = pselect(maxfd+1, &readfds, NULL, NULL, &local_timeout, NULL); #else fdcount = select(maxfd+1, &readfds, NULL, 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->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 } return MOSQ_ERR_SUCCESS; } int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets) { int run = 1; int rc = MOSQ_ERR_SUCCESS; unsigned long reconnect_delay; enum mosquitto_client_state state; if(!mosq) return MOSQ_ERR_INVAL; mosq->reconnects = 0; while(run){ do{ #ifdef HAVE_PTHREAD_CANCEL pthread_testcancel(); #endif 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{ #ifdef HAVE_PTHREAD_CANCEL pthread_testcancel(); #endif 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++; } rc = interruptible_sleep(mosq, (time_t)reconnect_delay); if(rc) return rc; 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) { enum mosquitto_client_state 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 = MOSQ_ERR_SUCCESS; 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 = MOSQ_ERR_SUCCESS; int i; if(max_packets < 1) return MOSQ_ERR_INVAL; for(i=0; i All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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, uint16_t alias); int alias__find(struct mosquitto *mosq, char **topic, uint16_t alias); void alias__free_all(struct mosquitto *mosq); #endif mosquitto-2.0.11/lib/mosquitto.c0000664000175000017500000002270614060132747015650 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #ifndef WIN32 #include #include #endif #if defined(__APPLE__) # include #endif #include "logging_mosq.h" #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" static unsigned int init_refcount = 0; 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) { int rc; if (init_refcount == 0) { #ifdef WIN32 srand((unsigned int)GetTickCount64()); #elif _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK) struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); srand((unsigned int)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 rc = net__init(); if (rc != MOSQ_ERR_SUCCESS) { return rc; } } init_refcount++; return MOSQ_ERR_SUCCESS; } int mosquitto_lib_cleanup(void) { if (init_refcount == 1) { net__cleanup(); } if (init_refcount > 0) { --init_refcount; } 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; #ifdef WITH_THREADING mosq->thread_id = pthread_self(); #endif mosq->sockpairR = INVALID_SOCKET; mosq->sockpairW = INVALID_SOCKET; 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->keepalive = 60; mosq->clean_start = clean_start; if(id){ if(STREMPTY(id)){ return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(id, (int)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->out_packet_count = 0; 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->max_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->ssl_ctx_defaults = true; 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 /* This must be after pthread_mutex_init(), otherwise the log mutex may be * used before being initialised. */ 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; } void mosquitto__destroy(struct mosquitto *mosq) { 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; mosquitto_property_free_all(&mosq->connect_properties); packet__cleanup_all_no_locks(mosq); 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; } int mosquitto_sub_topic_tokenise(const char *subtopic, char ***topics, int *count) { size_t len; size_t hier_count = 1; size_t start, stop; size_t hier; size_t tlen; size_t 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 + (uint8_t)packet->remaining_count; #ifdef WITH_WEBSOCKETS packet->payload = mosquitto__malloc(sizeof(uint8_t)*packet->packet_length + LWS_PRE); #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 = 1U + (uint8_t)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_no_locks(struct mosquitto *mosq) { struct mosquitto__packet *packet; /* 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); } mosq->out_packet_count = 0; packet__cleanup(&mosq->in_packet); } void packet__cleanup_all(struct mosquitto *mosq) { pthread_mutex_lock(&mosq->current_out_packet_mutex); pthread_mutex_lock(&mosq->out_packet_mutex); packet__cleanup_all_no_locks(mosq); 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; mosq->out_packet_count++; pthread_mutex_unlock(&mosq->out_packet_mutex); #ifdef WITH_BROKER # ifdef WITH_WEBSOCKETS if(mosq->wsi){ lws_callback_on_writable(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; enum mosquitto_client_state 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; } mosq->out_packet_count--; } pthread_mutex_unlock(&mosq->out_packet_mutex); #ifdef WITH_BROKER if(mosq->current_out_packet){ mux__add_out(mosq); } #endif 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 -= (uint32_t)write_length; packet->pos += (uint32_t)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; case COMPAT_EINTR: return MOSQ_ERR_SUCCESS; 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 }else if(((packet->command)&0xF0) == CMD_PUBLISH){ G_PUB_MSGS_SENT_INC(1); } /* 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; } mosq->out_packet_count--; } pthread_mutex_unlock(&mosq->out_packet_mutex); packet__cleanup(packet); mosquitto__free(packet); #ifdef WITH_BROKER mosq->next_msg_out = db.now_s + mosq->keepalive; #else pthread_mutex_lock(&mosq->msgtime_mutex); mosq->next_msg_out = mosquitto_time() + mosq->keepalive; pthread_mutex_unlock(&mosq->msgtime_mutex); #endif } #ifdef WITH_BROKER if (mosq->current_out_packet == NULL) { mux__remove_out(mosq); } #endif pthread_mutex_unlock(&mosq->current_out_packet_mutex); return MOSQ_ERR_SUCCESS; } int packet__read(struct mosquitto *mosq) { uint8_t byte; ssize_t read_length; int rc = 0; enum mosquitto_client_state 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) && 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; case COMPAT_EINTR: return MOSQ_ERR_SUCCESS; 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; case COMPAT_EINTR: return MOSQ_ERR_SUCCESS; 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 = (int8_t)(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){ 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 -= (uint32_t)read_length; mosq->in_packet.pos += (uint32_t)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. */ #ifdef WITH_BROKER keepalive__update(mosq); #else pthread_mutex_lock(&mosq->msgtime_mutex); mosq->last_msg_in = mosquitto_time(); pthread_mutex_unlock(&mosq->msgtime_mutex); #endif } return MOSQ_ERR_SUCCESS; }else{ switch(errno){ case COMPAT_ECONNRESET: return MOSQ_ERR_CONN_LOST; case COMPAT_EINTR: return MOSQ_ERR_SUCCESS; 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); } #endif rc = handle__packet(mosq); /* Free data and reset values */ packet__cleanup(&mosq->in_packet); #ifdef WITH_BROKER keepalive__update(mosq); #else pthread_mutex_lock(&mosq->msgtime_mutex); mosq->last_msg_in = mosquitto_time(); pthread_mutex_unlock(&mosq->msgtime_mutex); #endif return rc; } mosquitto-2.0.11/lib/send_mosq.h0000664000175000017500000000461614060132747015601 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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, uint8_t 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, const mosquitto_property *properties); int send__pubcomp(struct mosquitto *mosq, uint16_t mid, const mosquitto_property *properties); int send__publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, uint8_t 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, const mosquitto_property *properties); int send__pubrel(struct mosquitto *mosq, uint16_t mid, const mosquitto_property *properties); 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-2.0.11/lib/handle_publish.c0000664000175000017500000001126014060132747016556 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 "read_handle.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 = 0; uint16_t slen; mosquitto_property *properties = NULL; assert(mosq); if(mosquitto__get_state(mosq) != 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){ message__cleanup(&message); return rc; } } message->msg.payloadlen = (int)(mosq->in_packet.remaining_length - mosq->in_packet.pos); if(message->msg.payloadlen){ message->msg.payload = mosquitto__calloc((size_t)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, (uint32_t)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, mid, 0, NULL); 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, mid, 0, NULL); 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-2.0.11/lib/packet_datatypes.c0000664000175000017500000001341214060132747017123 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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, uint16_t *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+1U); 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, uint16_t *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 = 0; 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 = (uint16_t)((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, (uint8_t)((word & 0xFF000000) >> 24)); packet__write_byte(packet, (uint8_t)((word & 0x00FF0000) >> 16)); packet__write_byte(packet, (uint8_t)((word & 0x0000FF00) >> 8)); packet__write_byte(packet, (uint8_t)((word & 0x000000FF))); } int packet__read_varint(struct mosquitto__packet *packet, uint32_t *word, uint8_t *bytes) { int i; uint8_t byte; unsigned int remaining_mult = 1; uint32_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, uint32_t word) { uint8_t byte; int count = 0; do{ byte = (uint8_t)(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; } unsigned int packet__varint_bytes(uint32_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-2.0.11/lib/memory_mosq.h0000664000175000017500000000237314060132747016156 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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) # if defined(__APPLE__) || defined(__FreeBSD__) || defined(__GLIBC__) # define REAL_WITH_MEMORY_TRACKING # endif #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-2.0.11/lib/messages_mosq.c0000664000175000017500000002175214060132747016452 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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((unsigned int)src->payloadlen+1, sizeof(uint8_t)); if(!dst->payload){ mosquitto__free(dst->topic); return MOSQ_ERR_NOMEM; } memcpy(dst->payload, src->payload, (unsigned int)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, bool update_quota_only) { 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 (update_quota_only == false){ 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, (uint16_t)cur->msg.mid, cur->msg.topic, (uint32_t)cur->msg.payloadlen, cur->msg.payload, (uint8_t)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, (uint16_t)msg->msg.mid, msg->msg.topic, (uint32_t)msg->msg.payloadlen, msg->msg.payload, (uint8_t)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, (uint16_t)msg->msg.mid, 0, NULL); break; case mosq_ms_resend_pubrel: case mosq_ms_wait_for_pubcomp: msg->timestamp = now; msg->dup = true; send__pubrel(mosq, (uint16_t)msg->msg.mid, NULL); 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, (int)max_inflight_messages); } mosquitto-2.0.11/lib/Makefile0000664000175000017500000001633514060132747015101 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 \ strings_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) ../include/mosquitto.h "${DESTDIR}${incdir}/mosquitto.h" $(INSTALL) ../include/mqtt_protocol.h "${DESTDIR}${incdir}/mqtt_protocol.h" $(INSTALL) -d "${DESTDIR}${libdir}/pkgconfig" $(INSTALL) -m644 ../libmosquitto.pc.in "${DESTDIR}${libdir}/pkgconfig/libmosquitto.pc" sed ${SEDINPLACE} -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 ../include/mosquitto.h mosquitto_internal.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ actions.o : actions.c ../include/mosquitto.h mosquitto_internal.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ callbacks.o : callbacks.c ../include/mosquitto.h mosquitto_internal.h ${CROSS_COMPILE}$(CC) $(LIB_CPPFLAGS) $(LIB_CFLAGS) -c $< -o $@ connect.o : connect.c ../include/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 ../include/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 ../include/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 $@ strings_mosq.o : strings_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-2.0.11/cmake/0000775000175000017500000000000014060132747013743 5ustar rogerrogermosquitto-2.0.11/cmake/FindcJSON.cmake0000664000175000017500000000132514060132747016463 0ustar rogerrogerINCLUDE( FindPackageHandleStandardArgs ) # Checks an environment variable; note that the first check # does not require the usual CMake $-sign. IF( DEFINED ENV{CJSON_DIR} ) SET( CJSON_DIR "$ENV{CJSON_DIR}" ) ENDIF() FIND_PATH( CJSON_INCLUDE_DIR cjson/cJSON.h HINTS CJSON_DIR ) FIND_LIBRARY( CJSON_LIBRARY NAMES cjson HINTS ${CJSON_DIR} ) FIND_PACKAGE_HANDLE_STANDARD_ARGS( cJSON DEFAULT_MSG CJSON_INCLUDE_DIR CJSON_LIBRARY ) IF( CJSON_FOUND ) SET( CJSON_INCLUDE_DIRS ${CJSON_INCLUDE_DIR} ) SET( CJSON_LIBRARIES ${CJSON_LIBRARY} ) MARK_AS_ADVANCED( CJSON_LIBRARY CJSON_INCLUDE_DIR CJSON_DIR ) ELSE() SET( CJSON_DIR "" CACHE STRING "An optional hint to a directory for finding `cJSON`" ) ENDIF() mosquitto-2.0.11/README-windows.txt0000664000175000017500000000374414060132747016061 0ustar rogerrogerMosquitto for Windows ===================== Mosquitto for Windows comes in 64-bit and 32-bit flavours. All dependencies are provided in the installer. Capabilities ------------ Some versions of Windows have limitations on the number of concurrent connections due to the Windows API being used. In modern versions of Windows, e.g. Windows 10 or Windows Server 2019, this is approximately 8192 connections. In earlier versions of Windows, t his limit is 2048 connections. 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. 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. 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-2.0.11/client/0000775000175000017500000000000014060132747014141 5ustar rogerrogermosquitto-2.0.11/client/sub_test_fixed_width0000775000175000017500000000275614060132747020307 0ustar rogerrogerLD_LIBRARY_PATH=../lib ./mosquitto_sub \ -h test.mosquitto.org \ --retained-only \ --remove-retained \ -t FW/# \ -W 1>/dev/null 2>/dev/null LD_LIBRARY_PATH=../lib ./mosquitto_pub \ -h test.mosquitto.org \ -D publish content-type "application/json" \ -D publish message-expiry-interval 360000 \ -D publish payload-format-indicator 1 \ -D publish response-topic response-topic \ -m ABCDEFGHIJKLMNOPQRSTUVWXYZ \ -q 2 \ -r \ -t FW/truncate \ -V 5 LD_LIBRARY_PATH=../lib ./mosquitto_pub \ -h test.mosquitto.org \ -D publish content-type "null" \ -D publish message-expiry-interval 3600 \ -D publish payload-format-indicator 1 \ -D publish response-topic r-t \ -m Off \ -q 2 \ -r \ -t FW/expire \ -V 5 LD_LIBRARY_PATH=../lib ./mosquitto_pub \ -h test.mosquitto.org \ -D publish payload-format-indicator 1 \ -D publish response-topic rt \ -m Offline \ -q 2 \ -r \ -t FW/1 \ -V 5 LD_LIBRARY_PATH=../lib ./mosquitto_sub \ -h test.mosquitto.org \ -C 3 \ -F "| %10t | %-10t | %7x | %-7x | %08x | %7X | %-7X | %08X | %8p | %-8p | %3m | %-3m | %03m | %3l | %-3l | %03l | %2F | %-2F | %02F | %5C | %-5C | %5E | %-5E | %05E | %5A | %5R | %-5R |" \ -q 2 \ -t 'FW/#' \ -V 5 echo LD_LIBRARY_PATH=../lib ./mosquitto_sub \ -h test.mosquitto.org \ -C 3 \ -F "| %10.10t | %.5t | %-10.10t | %7x | %-7x | %08x | %7X | %-7X | %08X | %8p | %-8p | %3m | %-3m | %03m | %3l | %-3l | %03l | %2F | %-2F | %02F | %5C | %-5C | %5E | %-5E | %05E | %5.5A | %5.5R | %-5.5R |" \ -q 2 \ -t 'FW/#' \ -V 5 mosquitto-2.0.11/client/sub_client.c0000664000175000017500000003626014060132747016443 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 "sub_client_output.h" struct mosq_config cfg; bool process_messages = true; int msg_count = 0; struct mosquitto *g_mosq = NULL; int last_mid = 0; static bool timed_out = false; static int connack_result = 0; bool connack_received = false; #ifndef WIN32 static void my_signal_handler(int signum) { if(signum == SIGALRM || signum == SIGTERM || signum == SIGINT){ if(connack_received){ process_messages = false; mosquitto_disconnect_v5(g_mosq, MQTT_RC_DISCONNECT_WITH_WILL_MSG, cfg.disconnect_props); }else{ exit(-1); } } if(signum == SIGALRM){ timed_out = true; } } #endif static 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, properties); if(ferror(stdout)){ mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props); } 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); } } } } static 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); connack_received = true; connack_result = result; 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(timed_out){ err_printf(&cfg, "Timed out\n"); return MOSQ_ERR_TIMEOUT; }else if(rc){ err_printf(&cfg, "Error: %s\n", mosquitto_strerror(rc)); } if(connack_result){ return connack_result; }else{ return rc; } cleanup: mosquitto_destroy(g_mosq); mosquitto_lib_cleanup(); client_config_cleanup(&cfg); return 1; } mosquitto-2.0.11/client/CMakeLists.txt0000664000175000017500000000335714060132747016711 0ustar rogerrogerset(shared_src client_shared.c client_shared.h client_props.c) if (WITH_SRV) add_definitions("-DWITH_SRV") endif (WITH_SRV) set( CLIENT_INC ${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/include ${STDBOOL_H_PATH} ${STDINT_H_PATH} ${PTHREAD_INCLUDE_DIR} ${OPENSSL_INCLUDE_DIR}) set( CLIENT_DIR ${mosquitto_BINARY_DIR}/lib) if (CJSON_FOUND) add_definitions("-DWITH_CJSON") set( CLIENT_DIR "${CLIENT_DIR};${CJSON_DIR}" ) set( CLIENT_INC "${CLIENT_INC};${CJSON_INCLUDE_DIRS}" ) endif() include_directories(${CLIENT_INC}) link_directories(${CLIENT_DIR}) 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 (CJSON_FOUND) target_link_libraries(mosquitto_pub ${CJSON_LIBRARIES}) target_link_libraries(mosquitto_sub ${CJSON_LIBRARIES}) target_link_libraries(mosquitto_rr ${CJSON_LIBRARIES}) endif() 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-2.0.11/client/client_shared.c0000664000175000017500000012723614060132747017124 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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) { size_t i; size_t len; len = strlen(str); for(i=0; i= '0' && str[i+1] <= '9'){ i++; if(i == len-1){ /* error */ fprintf(stderr, "Error: Incomplete format specifier.\n"); return 1; } } if(str[i+1] == '.'){ /* Precision specifier */ i++; if(i == len-1){ /* error */ fprintf(stderr, "Error: Incomplete format specifier.\n"); return 1; } /* Precision */ while(str[i+1] >= '0' && str[i+1] <= '9'){ i++; if(i == len-1){ /* error */ fprintf(stderr, "Error: Incomplete format specifier.\n"); return 1; } } } if(str[i+1] == '%'){ /* Print %, ignore */ }else if(str[i+1] == 'A'){ /* MQTT v5 property topic-alias */ }else if(str[i+1] == 'C'){ /* MQTT v5 property content-type */ }else if(str[i+1] == 'D'){ /* MQTT v5 property correlation-data */ }else if(str[i+1] == 'E'){ /* MQTT v5 property message-expiry-interval */ }else if(str[i+1] == 'F'){ /* MQTT v5 property payload-format-indicator */ }else if(str[i+1] == 'I'){ /* ISO 8601 date+time */ }else if(str[i+1] == 'l'){ /* payload length */ }else if(str[i+1] == 'm'){ /* mid */ }else if(str[i+1] == 'P'){ /* MQTT v5 property user-property */ }else if(str[i+1] == 'p'){ /* payload */ }else if(str[i+1] == 'q'){ /* qos */ }else if(str[i+1] == 'R'){ /* MQTT v5 property response-topic */ }else if(str[i+1] == 'S'){ /* MQTT v5 property subscription-identifier */ }else if(str[i+1] == 'r'){ /* retain */ }else if(str[i+1] == 't'){ /* topic */ }else if(str[i+1] == 'j'){ /* JSON output, escaped payload */ }else if(str[i+1] == 'J'){ /* JSON output, assuming JSON payload */ }else if(str[i+1] == 'U'){ /* Unix time+nanoseconds */ #ifdef WIN32 fprintf(stderr, "Error: The %%U format option is not supported on Windows.\n"); return 1; #endif }else if(str[i+1] == 'x' || str[i+1] == 'X'){ /* payload in hex */ }else{ fprintf(stderr, "Error: Invalid format specifier '%c'.\n", str[i+1]); return 1; } i++; } }else if(str[i] == '@'){ if(i == len-1){ /* error */ fprintf(stderr, "Error: Incomplete format specifier.\n"); return 1; } i++; }else if(str[i] == '\\'){ if(i == len-1){ /* error */ fprintf(stderr, "Error: Incomplete escape specifier.\n"); return 1; }else{ switch(str[i+1]){ case '\\': /* '\' */ case '0': /* 0 (NULL) */ case 'a': /* alert */ case 'e': /* escape */ case 'n': /* new line */ case 'r': /* carriage return */ case 't': /* horizontal tab */ case 'v': /* vertical tab */ break; default: fprintf(stderr, "Error: Invalid escape specifier '%c'.\n", str[i+1]); return 1; } i++; } } } return 0; } static void init_config(struct mosq_config *cfg, int pub_or_sub) { memset(cfg, 0, sizeof(*cfg)); cfg->port = PORT_UNDEFINED; 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; cfg->random_filter = 10000; 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; size_t 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, (uint32_t )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; } static int cfg_add_topic(struct mosq_config *cfg, int type, char *topic, const char *arg) { if(mosquitto_validate_utf8(topic, (int )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, (size_t )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; int tmpi; float f; size_t szt; 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<5 || cfg->keepalive>UINT16_MAX){ fprintf(stderr, "Error: Invalid keepalive given, it must be between 5 and 65535 inclusive.\n\n"); 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)) { #ifdef WITH_TLS url += 8; cfg->port = 8883; cfg->tls_use_os_certs = true; #else fprintf(stderr, "Error: TLS support not available.\n\n"); return 1; #endif } 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) { char *colon; *tmp++ = 0; 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]); if(cfg->message == NULL){ fprintf(stderr, "Error: Out of memory.\n\n"); return 1; } szt = strlen(cfg->message); if(szt > MQTT_MAX_PAYLOAD){ fprintf(stderr, "Error: Message length must be less than %u bytes.\n\n", MQTT_MAX_PAYLOAD); return 1; } cfg->msglen = (int )szt; 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{ tmpi = atoi(argv[i+1]); if(tmpi < 1){ fprintf(stderr, "Error: Maximum inflight messages must be greater than 0.\n\n"); return 1; } cfg->max_inflight = (unsigned int )tmpi; } i++; }else if(!strcmp(argv[i], "--nodelay")){ cfg->tcp_nodelay = true; }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<0 || cfg->port>65535){ fprintf(stderr, "Error: Invalid port given: %d\n", cfg->port); return 1; } } i++; }else if(!strcmp(argv[i], "--pretty")){ if(pub_or_sub == CLIENT_PUB){ goto unknown_option; } cfg->pretty = true; }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], "--random-filter")){ if(pub_or_sub != CLIENT_SUB){ goto unknown_option; } if(i==argc-1){ fprintf(stderr, "Error: --random-filter argument given but no chance specified.\n\n"); return 1; }else{ cfg->random_filter = (int)(10.0*atof(argv[i+1])); if(cfg->random_filter > 10000 || cfg->random_filter < 1){ fprintf(stderr, "Error: --random-filter chance must be between 0.1-100.0\n\n"); return 1; } } i++; }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 = (float )atof(argv[i+1]); if(f < 0.0f){ fprintf(stderr, "Error: --repeat-delay argument must be >=0.0.\n\n"); return 1; } f *= 1.0e6f; cfg->repeat_delay.tv_sec = (int)f/1000000; 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], (int )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, (size_t )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-use-os-certs")){ cfg->tls_use_os_certs = true; }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], (int )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, (size_t )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], "--unix")){ if(i==argc-1){ fprintf(stderr, "Error: --unix argument given but no socket path specified.\n\n"); return 1; }else{ cfg->host = strdup(argv[i+1]); cfg->port = 0; } 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], "--version")){ return 3; }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{ tmpi = atoi(argv[i+1]); if(tmpi < 1){ fprintf(stderr, "Error: Invalid timeout \"%d\".\n\n", tmpi); return 1; } cfg->timeout = (unsigned int )tmpi; } 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 = (int )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], (int )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 if(!strcmp(argv[i], "-x")){ if(i==argc-1){ fprintf(stderr, "Error: -x argument given but no session expiry interval specified.\n\n"); return 1; }else{ if(!strcmp(argv[i+1], "∞")){ cfg->session_expiry_interval = UINT32_MAX; }else{ char *endptr = NULL; cfg->session_expiry_interval = strtol(argv[i+1], &endptr, 0); if(endptr == argv[i+1] || endptr[0] != '\0'){ /* Entirety of argument wasn't a number */ fprintf(stderr, "Error: session-expiry-interval not a number.\n\n"); return 1; } if(cfg->session_expiry_interval > UINT32_MAX || cfg->session_expiry_interval < -1){ fprintf(stderr, "Error: session-expiry-interval out of range.\n\n"); return 1; } if(cfg->session_expiry_interval == -1){ /* Convenience value for infinity. */ cfg->session_expiry_interval = UINT32_MAX; } } } 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; } # ifdef FINAL_WITH_TLS_PSK }else if(cfg->psk){ if(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 }else if(cfg->port == 8883){ mosquitto_int_option(mosq, MOSQ_OPT_TLS_USE_OS_CERTS, 1); } if(cfg->tls_use_os_certs){ mosquitto_int_option(mosq, MOSQ_OPT_TLS_USE_OS_CERTS, 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; } 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 if(cfg->tcp_nodelay){ mosquitto_int_option(mosq, MOSQ_OPT_TCP_NODELAY, 1); } if(cfg->msg_count > 0 && cfg->msg_count < 20){ /* 20 is the default "receive maximum" * If we don't set this, then we can receive > msg_count messages * before we quit.*/ mosquitto_int_option(mosq, MOSQ_OPT_RECEIVE_MAXIMUM, cfg->msg_count); } 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 == PORT_UNDEFINED){ #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) { size_t i, j; size_t 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-2.0.11/client/client_shared.h0000664000175000017500000000674014060132747017125 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef CLIENT_CONFIG_H #define CLIENT_CONFIG_H #include #ifdef WIN32 # include #else # include #endif #ifndef __GNUC__ #define __attribute__(attrib) #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 #define PORT_UNDEFINED -1 #define PORT_UNIX 0 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 */ int 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; int 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; bool tls_use_os_certs; # ifdef FINAL_WITH_TLS_PSK char *psk; char *psk_identity; # endif #endif bool clean_session; char **topics; /* sub, rr */ int topic_count; /* sub, rr */ 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, rr */ bool pretty; /* sub, rr */ unsigned int timeout; /* sub */ int sub_opts; /* sub */ long session_expiry_interval; int random_filter; /* sub */ #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 */ bool tcp_nodelay; }; 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, ...) __attribute__((format(printf, 2, 3))); #endif mosquitto-2.0.11/client/sub_test_properties0000775000175000017500000000202114060132747020166 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-2.0.11/client/args.txt0000664000175000017500000000225514060132747015642 0ustar rogerrogerA - PUB,RR,SUB (bind to address) a B b C - SUB (message count) c - PUB,RR,SUB (clean session) D - PUB,RR,SUB (properties) d - PUB,RR,SUB (debug log) E - SUB (exit after subscribe) e - RR (response topic) F - RR,SUB (output format) f - PUB,RR (file input) G g H h - PUB,RR,SUB (host) I - PUB,RR,SUB (client id prefix) i - PUB,RR,SUB (client id) J j K k - PUB,RR,SUB (keepalive) L - PUB,RR,SUB (connect url) l - PUB (stdin input) M - PUB,RR,SUB (max inflight) m - PUB,RR (message input) N - RR,SUB (no end of line) n - PUB,RR (null message) O o - CTRL (options file) P - PUB,RR,SUB (password) p - PUB,RR,SUB (port) Q q - PUB,RR,SUB (qos) R - RR,SUB (don't show retained) r - PUB,RR (retain) S - PUB,RR,SUB (SRV lookups) s - PUB,RR (stdin input) T - SUB (filter out topic) t - PUB,RR,SUB (topic) U - SUB (unsubscribe) u - PUB,RR,SUB (username) V - PUB,RR,SUB (version output) v - RR,SUB (verbose) W - SUB (timeout) w X x - PUB,RR,SUB (session-expiry-interval) Y y Z z mosquitto-2.0.11/client/client_props.c0000664000175000017500000001372314060132747017014 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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; long tmpl; size_t szt; /* 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 allowed 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: tmpl = atol(value); if(tmpl < 0 || tmpl > UINT8_MAX){ fprintf(stderr, "Error: Property value (%ld) out of range for property %s.\n\n", tmpl, propname); return MOSQ_ERR_INVAL; } rc = mosquitto_property_add_byte(proplist, identifier, (uint8_t )tmpl); break; case MQTT_PROP_TYPE_INT16: tmpl = atol(value); if(tmpl < 0 || tmpl > UINT16_MAX){ fprintf(stderr, "Error: Property value (%ld) out of range for property %s.\n\n", tmpl, propname); return MOSQ_ERR_INVAL; } rc = mosquitto_property_add_int16(proplist, identifier, (uint16_t )tmpl); break; case MQTT_PROP_TYPE_INT32: tmpl = atol(value); if(tmpl < 0 || tmpl > UINT32_MAX){ fprintf(stderr, "Error: Property value (%ld) out of range for property %s.\n\n", tmpl, propname); return MOSQ_ERR_INVAL; } rc = mosquitto_property_add_int32(proplist, identifier, (uint32_t )tmpl); break; case MQTT_PROP_TYPE_VARINT: tmpl = atol(value); if(tmpl < 0 || tmpl > UINT32_MAX){ fprintf(stderr, "Error: Property value (%ld) out of range for property %s.\n\n", tmpl, propname); return MOSQ_ERR_INVAL; } rc = mosquitto_property_add_varint(proplist, identifier, (uint32_t )tmpl); break; case MQTT_PROP_TYPE_BINARY: szt = strlen(value); if(szt > UINT16_MAX){ fprintf(stderr, "Error: Property value too long for property %s.\n\n", propname); return MOSQ_ERR_INVAL; } rc = mosquitto_property_add_binary(proplist, identifier, value, (uint16_t )szt); 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-2.0.11/client/rr_client.c0000664000175000017500000003512314060132747016272 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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" #include "sub_client_output.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; bool process_messages = true; int msg_count = 0; struct mosquitto *g_mosq = NULL; static bool timed_out = false; static int connack_result = 0; #ifndef WIN32 static void my_signal_handler(int signum) { if(signum == SIGALRM){ process_messages = false; mosquitto_disconnect_v5(g_mosq, MQTT_RC_DISCONNECT_WITH_WILL_MSG, cfg.disconnect_props); timed_out = true; } } #endif int my_publish(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, void *payload, int qos, bool retain) { if(cfg.protocol_version < MQTT_PROTOCOL_V5){ return mosquitto_publish_v5(mosq, mid, topic, payloadlen, payload, qos, retain, NULL); }else{ return mosquitto_publish_v5(mosq, mid, topic, payloadlen, payload, qos, retain, cfg.publish_props); } } static void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(obj); UNUSED(properties); print_message(&cfg, message, properties); 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) { UNUSED(obj); UNUSED(flags); UNUSED(properties); connack_result = result; 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); } } static void my_subscribe_callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { UNUSED(obj); UNUSED(mid); UNUSED(qos_count); 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) { UNUSED(mosq); UNUSED(obj); UNUSED(mid); UNUSED(reason_code); UNUSED(properties); client_state = rr_s_wait_for_response; } static void print_version(void) { int major, minor, revision; mosquitto_lib_version(&major, &minor, &revision); printf("mosquitto_rr version %s running on libmosquitto %d.%d.%d.\n", VERSION, major, minor, revision); } static 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] [--unix path] [-p port] [-u username] [-P password] -t topic | -L URL} -e response-topic\n"); printf(" [-c] [-k keepalive] [-q qos] [-R] [-x session-expiry-interval\n"); printf(" [-F format]\n"); #ifndef WIN32 printf(" [-W timeout_secs]\n"); #endif #ifdef WITH_SRV printf(" [-A bind_address] [--nodelay] [-S]\n"); #else printf(" [-A bind_address] [--nodelay]\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"); printf(" [--tls-use-os-certs]\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/enable persistent client mode\n"); printf(" When this argument is used, the broker will be instructed not to clean existing sessions\n"); printf(" for the same client id when the client connects, and sessions will never expire when the\n"); printf(" client disconnects. MQTT v5 clients can change their session expiry interval with the -x\n"); printf(" argument.\n"); printf(" -d : enable debug messages.\n"); printf(" -D : Define MQTT v5 properties. See the documentation for more details.\n"); printf(" -e : Response topic. The client will subscribe to this topic to wait for a response.\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 : topic where the request message will be sent.\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(" -x : Set the session-expiry-interval property on the CONNECT packet. Applies to MQTT v5\n"); printf(" clients only. Set to 0-4294967294 to specify the session will expire in that many\n"); printf(" seconds after the client disconnects, or use -1, 4294967295, or ∞ for a session\n"); printf(" that does not expire. Defaults to -1 if -c is also given, or 0 if -c not given.\n"); printf(" --help : display this message.\n"); printf(" --nodelay : disable Nagle's algorithm, to reduce socket sending latency at the possible\n"); printf(" expense of more packets being sent.\n"); printf(" --pretty : print formatted output rather than minimised output when using the\n"); printf(" JSON output format option.\n"); printf(" --quiet : don't print error messages.\n"); printf(" --unix : connect to a broker through a unix domain socket instead of a TCP socket,\n"); printf(" e.g. /tmp/mosquitto.sock\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-use-os-certs : Load and trust OS provided CA certificates.\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"); #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 if(rc == 3){ /* --version */ print_version(); }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; } g_mosq = mosquitto_new(cfg.id, cfg.clean_session, &cfg); if(!g_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(g_mosq, &cfg)){ goto cleanup; } if(cfg.debug){ mosquitto_log_callback_set(g_mosq, my_log_callback); } mosquitto_connect_v5_callback_set(g_mosq, my_connect_callback); mosquitto_subscribe_callback_set(g_mosq, my_subscribe_callback); mosquitto_message_v5_callback_set(g_mosq, my_message_callback); rc = client_connect(g_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(g_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(g_mosq, &mid_sent, cfg.topic, cfg.msglen, cfg.message, cfg.qos, cfg.retain); break; case MSGMODE_NULL: rc = my_publish(g_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(g_mosq); mosquitto_lib_cleanup(); if(cfg.msg_count>0 && rc == MOSQ_ERR_NO_CONN){ rc = 0; } client_config_cleanup(&cfg); if(timed_out){ err_printf(&cfg, "Timed out\n"); return MOSQ_ERR_TIMEOUT; }else if(rc){ err_printf(&cfg, "Error: %s\n", mosquitto_strerror(rc)); } if(connack_result){ return connack_result; }else{ return rc; } cleanup: mosquitto_lib_cleanup(); client_config_cleanup(&cfg); return 1; } mosquitto-2.0.11/client/pub_client.c0000664000175000017500000004660014060132747016437 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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; static int connack_result = 0; #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/1000000; 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); connack_result = result; 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)); } /* let the loop know that this is an unrecoverable connection */ status = STATUS_NOHOPE; } } } void my_publish_callback(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { char *reason_string = NULL; 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)); mosquitto_property_read_string(properties, MQTT_PROP_REASON_STRING, &reason_string, false); if(reason_string){ err_printf(&cfg, "%s\n", reason_string); free(reason_string); } } 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((size_t )line_buf_len); if(!line_buf){ err_printf(&cfg, "Error: Out of memory.\n"); return 1; } return 0; } static 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_CONNECTING){ #ifdef WIN32 Sleep(100); #else struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 100000000; nanosleep(&ts, NULL); #endif } if(status == STATUS_NOHOPE){ return MOSQ_ERR_CONN_REFUSED; } 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 = (int )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 != MOSQ_ERR_SUCCESS && rc != MOSQ_ERR_NO_CONN){ return rc; } break; }else{ line_buf_len += 1024; pos += read_len-1; read_len = 1024; buf2 = realloc(line_buf, (size_t )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){ if(cfg.qos>0) return rc; } } 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; } } static 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 = (int )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 != MOSQ_ERR_SUCCESS && rc != MOSQ_ERR_NO_CONN){ 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); } static void print_version(void) { int major, minor, revision; mosquitto_lib_version(&major, &minor, &revision); printf("mosquitto_pub version %s running on libmosquitto %d.%d.%d.\n", VERSION, major, minor, revision); } static 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] [--unix path] [-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] [-x session-expiry]\n"); #ifdef WITH_SRV printf(" [-A bind_address] [--nodelay] [-S]\n"); #else printf(" [-A bind_address] [--nodelay]\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"); printf(" [--tls-use-os-certs]\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(" -c : disable clean session/enable persistent client mode\n"); printf(" When this argument is used, the broker will be instructed not to clean existing sessions\n"); printf(" for the same client id when the client connects, and sessions will never expire when the\n"); printf(" client disconnects. MQTT v5 clients can change their session expiry interval with the -x\n"); printf(" argument.\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(" -x : Set the session-expiry-interval property on the CONNECT packet. Applies to MQTT v5\n"); printf(" clients only. Set to 0-4294967294 to specify the session will expire in that many\n"); printf(" seconds after the client disconnects, or use -1, 4294967295, or ∞ for a session\n"); printf(" that does not expire. Defaults to -1 if -c is also given, or 0 if -c not given.\n"); printf(" --help : display this message.\n"); printf(" --nodelay : disable Nagle's algorithm, to reduce socket sending latency at the possible\n"); printf(" expense of more packets being sent.\n"); printf(" --quiet : don't print error messages.\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(" --unix : connect to a broker through a unix domain socket instead of a TCP socket,\n"); printf(" e.g. /tmp/mosquitto.sock\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"); printf(" --tls-use-os-certs : Load and trust OS provided CA certificates.\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 if(rc == 3){ print_version(); }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)); } if(connack_result){ return connack_result; }else{ return rc; } cleanup: mosquitto_lib_cleanup(); client_config_cleanup(&cfg); pub_shared_cleanup(); return 1; } mosquitto-2.0.11/client/sub_client_output.c0000664000175000017500000004434614060132747020067 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef WIN32 /* For rand_s on Windows */ # define _CRT_RAND_S #endif #include #include #include #include #include #include #ifndef WIN32 #include #else #include #include #define snprintf sprintf_s #endif #ifdef WITH_CJSON # include #endif #ifdef __APPLE__ # include #endif #include #include #include "client_shared.h" #include "sub_client_output.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, char align, char pad, int field_width, int precision) { int i; int padlen; UNUSED(precision); /* FIXME - use or remove */ if(field_width > 0){ if(payloadlen > field_width){ payloadlen = field_width; } if(hex > 0){ payloadlen /= 2; padlen = field_width - payloadlen*2; }else{ padlen = field_width - payloadlen; } }else{ padlen = field_width - payloadlen; } if(align != '-'){ for(i=0; i=0 && payload[i] < 32)){ printf("\\u%04x", payload[i]); }else{ fputc(payload[i], stdout); } } } #endif #ifdef WITH_CJSON static int json_print_properties(cJSON *root, const mosquitto_property *properties) { int identifier; uint8_t i8value = 0; uint16_t i16value = 0; uint32_t i32value = 0; char *strname = NULL, *strvalue = NULL; char *binvalue = NULL; cJSON *tmp, *prop_json, *user_json = NULL; const mosquitto_property *prop = NULL; prop_json = cJSON_CreateObject(); if(prop_json == NULL){ cJSON_Delete(prop_json); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(root, "properties", prop_json); for(prop=properties; prop != NULL; prop = mosquitto_property_next(prop)){ tmp = NULL; identifier = mosquitto_property_identifier(prop); switch(identifier){ case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: mosquitto_property_read_byte(prop, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, &i8value, false); tmp = cJSON_CreateNumber(i8value); break; case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: mosquitto_property_read_int32(prop, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, &i32value, false); tmp = cJSON_CreateNumber(i32value); break; case MQTT_PROP_CONTENT_TYPE: case MQTT_PROP_RESPONSE_TOPIC: mosquitto_property_read_string(prop, identifier, &strvalue, false); if(strvalue == NULL) return MOSQ_ERR_NOMEM; tmp = cJSON_CreateString(strvalue); free(strvalue); strvalue = NULL; break; case MQTT_PROP_CORRELATION_DATA: mosquitto_property_read_binary(prop, MQTT_PROP_CORRELATION_DATA, (void **)&binvalue, &i16value, false); if(binvalue == NULL) return MOSQ_ERR_NOMEM; tmp = cJSON_CreateString(binvalue); free(binvalue); binvalue = NULL; break; case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: mosquitto_property_read_varint(prop, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, &i32value, false); tmp = cJSON_CreateNumber(i32value); break; case MQTT_PROP_TOPIC_ALIAS: mosquitto_property_read_int16(prop, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, &i16value, false); tmp = cJSON_CreateNumber(i16value); break; case MQTT_PROP_USER_PROPERTY: if(user_json == NULL){ user_json = cJSON_CreateObject(); if(user_json == NULL){ return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(prop_json, "user-properties", user_json); } mosquitto_property_read_string_pair(prop, MQTT_PROP_USER_PROPERTY, &strname, &strvalue, false); if(strname == NULL || strvalue == NULL) return MOSQ_ERR_NOMEM; tmp = cJSON_CreateString(strvalue); free(strvalue); if(tmp == NULL){ free(strname); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(user_json, strname, tmp); free(strname); strname = NULL; strvalue = NULL; tmp = NULL; /* Don't add this to prop_json below */ break; } if(tmp != NULL){ cJSON_AddItemToObject(prop_json, mosquitto_property_identifier_to_string(identifier), tmp); } } return MOSQ_ERR_SUCCESS; } #endif static int json_print(const struct mosquitto_message *message, const mosquitto_property *properties, const struct tm *ti, int ns, bool escaped, bool pretty) { char buf[100]; #ifdef WITH_CJSON cJSON *root; cJSON *tmp; char *json_str; const char *return_parse_end; root = cJSON_CreateObject(); if(root == NULL){ return MOSQ_ERR_NOMEM; } strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S.000000Z%z", ti); snprintf(&buf[strlen("2020-05-06T21:48:00.")], 9, "%06d", ns/1000); buf[strlen("2020-05-06T21:48:00.000000")] = 'Z'; tmp = cJSON_CreateStringReference(buf); if(tmp == NULL){ cJSON_Delete(root); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(root, "tst", tmp); tmp = cJSON_CreateString(message->topic); if(tmp == NULL){ cJSON_Delete(root); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(root, "topic", tmp); tmp = cJSON_CreateNumber(message->qos); if(tmp == NULL){ cJSON_Delete(root); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(root, "qos", tmp); tmp = cJSON_CreateNumber(message->retain); if(tmp == NULL){ cJSON_Delete(root); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(root, "retain", tmp); tmp = cJSON_CreateNumber(message->payloadlen); if(tmp == NULL){ cJSON_Delete(root); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(root, "payloadlen", tmp); if(message->qos > 0){ tmp = cJSON_CreateNumber(message->mid); if(tmp == NULL){ cJSON_Delete(root); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(root, "mid", tmp); } /* Properties */ if(properties){ if(json_print_properties(root, properties)){ cJSON_Delete(root); return MOSQ_ERR_NOMEM; } } /* Payload */ if(escaped){ if(message->payload){ tmp = cJSON_CreateString(message->payload); }else{ tmp = cJSON_CreateNull(); } if(tmp == NULL){ cJSON_Delete(root); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(root, "payload", tmp); }else{ return_parse_end = NULL; if(message->payload){ tmp = cJSON_ParseWithOpts(message->payload, &return_parse_end, true); if(tmp == NULL || return_parse_end != (char *)message->payload + message->payloadlen){ cJSON_Delete(root); return MOSQ_ERR_INVAL; } }else{ tmp = cJSON_CreateNull(); if(tmp == NULL){ cJSON_Delete(root); return MOSQ_ERR_INVAL; } } cJSON_AddItemToObject(root, "payload", tmp); } if(pretty){ json_str = cJSON_Print(root); }else{ json_str = cJSON_PrintUnformatted(root); } cJSON_Delete(root); if(json_str == NULL){ return MOSQ_ERR_NOMEM; } fputs(json_str, stdout); free(json_str); return MOSQ_ERR_SUCCESS; #else UNUSED(properties); UNUSED(pretty); strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S.000000Z%z", ti); snprintf(&buf[strlen("2020-05-06T21:48:00.")], 9, "%06d", ns/1000); buf[strlen("2020-05-06T21:48:00.000000")] = 'Z'; 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, 0, 0, 0, 0); fputs("}", stdout); } return MOSQ_ERR_SUCCESS; #endif } static void formatted_print_blank(char pad, int field_width) { int i; for(i=0; ipretty) != MOSQ_ERR_SUCCESS){ err_printf(lcfg, "Error: Out of memory.\n"); return; } break; case 'J': if(!ti){ if(get_time(&ti, &ns)){ err_printf(lcfg, "Error obtaining system time.\n"); return; } } rc = json_print(message, properties, ti, (int)ns, false, lcfg->pretty); if(rc == MOSQ_ERR_NOMEM){ err_printf(lcfg, "Error: Out of memory.\n"); return; }else if(rc == MOSQ_ERR_INVAL){ err_printf(lcfg, "Error: Message payload is not valid JSON on topic %s.\n", message->topic); return; } break; case 'l': formatted_print_int(message->payloadlen, align, pad, field_width); break; case 'm': formatted_print_int(message->mid, align, pad, field_width); break; case 'P': strname = NULL; strvalue = NULL; prop = mosquitto_property_read_string_pair(properties, MQTT_PROP_USER_PROPERTY, &strname, &strvalue, false); while(prop){ printf("%s:%s", strname, strvalue); free(strname); free(strvalue); strname = NULL; strvalue = NULL; prop = mosquitto_property_read_string_pair(prop, MQTT_PROP_USER_PROPERTY, &strname, &strvalue, true); if(prop){ fputc(' ', stdout); } } free(strname); free(strvalue); break; case 'p': write_payload(message->payload, message->payloadlen, 0, align, pad, field_width, precision); break; case 'q': fputc(message->qos + 48, stdout); break; case 'R': if(mosquitto_property_read_string(properties, MQTT_PROP_RESPONSE_TOPIC, &strvalue, false)){ formatted_print_str(strvalue, align, field_width, precision); free(strvalue); } break; case 'r': if(message->retain){ fputc('1', stdout); }else{ fputc('0', stdout); } break; case 'S': if(mosquitto_property_read_varint(properties, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, &i32value, false)){ formatted_print_int((int)i32value, align, pad, field_width); }else{ formatted_print_blank(pad, field_width); } break; case 't': formatted_print_str(message->topic, align, field_width, precision); 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, align, pad, field_width, precision); break; case 'X': write_payload(message->payload, message->payloadlen, 2, align, pad, field_width, precision); break; } } static void formatted_print(const struct mosq_config *lcfg, const struct mosquitto_message *message, const mosquitto_property *properties) { size_t len; size_t i; struct tm *ti = NULL; long ns = 0; char strf[3] = {0, 0 ,0}; char buf[100]; char align, pad; int field_width, precision; len = strlen(lcfg->format); for(i=0; iformat[i] == '%'){ align = 0; pad = ' '; field_width = 0; precision = -1; if(i < len-1){ i++; /* Optional alignment */ if(lcfg->format[i] == '-'){ align = lcfg->format[i]; if(i < len-1){ i++; } } /* "%-040p" is allowed by this combination of checks, but isn't * a valid format specifier, the '0' will be ignored. */ /* Optional zero padding */ if(lcfg->format[i] == '0'){ pad = '0'; if(i < len-1){ i++; } } /* Optional field width */ while(i < len-1 && lcfg->format[i] >= '0' && lcfg->format[i] <= '9'){ field_width *= 10; field_width += lcfg->format[i]-'0'; i++; } /* Optional precision */ if(lcfg->format[i] == '.'){ if(i < len-1){ i++; precision = 0; while(i < len-1 && lcfg->format[i] >= '0' && lcfg->format[i] <= '9'){ precision *= 10; precision += lcfg->format[i]-'0'; i++; } } } if(i < len){ formatted_print_percent(lcfg, message, properties, lcfg->format[i], align, pad, field_width, precision); } } }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 rand_init(void) { #ifndef WIN32 struct tm *ti = NULL; long ns; if(!get_time(&ti, &ns)){ srandom((unsigned int)ns); } #endif } void print_message(struct mosq_config *lcfg, const struct mosquitto_message *message, const mosquitto_property *properties) { #ifdef WIN32 unsigned int r = 0; #else long r = 0; #endif if(lcfg->random_filter < 10000){ #ifdef WIN32 rand_s(&r); #else r = random(); #endif if((long)(r%10000) >= lcfg->random_filter){ return; } } if(lcfg->format){ formatted_print(lcfg, message, properties); }else if(lcfg->verbose){ if(message->payloadlen){ printf("%s ", message->topic); write_payload(message->payload, message->payloadlen, false, 0, 0, 0, 0); if(lcfg->eol){ printf("\n"); } }else{ if(lcfg->eol){ printf("%s (null)\n", message->topic); } } fflush(stdout); }else{ if(message->payloadlen){ write_payload(message->payload, message->payloadlen, false, 0, 0, 0, 0); if(lcfg->eol){ printf("\n"); } fflush(stdout); } } } mosquitto-2.0.11/client/pub_shared.c0000664000175000017500000000574514060132747016434 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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) { size_t 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; } if(pos > MQTT_MAX_PAYLOAD){ err_printf(&cfg, "Error: Message length must be less than %u bytes.\n\n", MQTT_MAX_PAYLOAD); free(cfg.message); return 1; } cfg.msglen = (int )pos; if(!cfg.msglen){ err_printf(&cfg, "Error: Zero length input.\n"); return 1; } return 0; } int load_file(const char *filename) { size_t pos, rlen; FILE *fptr = NULL; long flen; 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); flen = ftell(fptr); if(flen > MQTT_MAX_PAYLOAD){ fclose(fptr); err_printf(&cfg, "Error: File must be less than %u bytes.\n\n", MQTT_MAX_PAYLOAD); free(cfg.message); return 1; }else if(flen == 0){ fclose(fptr); cfg.message = NULL; cfg.msglen = 0; return 0; }else if(flen < 0){ fclose(fptr); err_printf(&cfg, "Error: Unable to determine size of file \"%s\".\n", filename); return 1; } cfg.msglen = (int )flen; fseek(fptr, 0, SEEK_SET); cfg.message = malloc((size_t )cfg.msglen); if(!cfg.message){ fclose(fptr); err_printf(&cfg, "Error: Out of memory.\n"); return 1; } pos = 0; while(pos < (size_t)cfg.msglen){ rlen = fread(&(cfg.message[pos]), sizeof(char), (size_t )cfg.msglen-pos, fptr); pos += rlen; } fclose(fptr); return 0; } mosquitto-2.0.11/client/Makefile0000664000175000017500000000660014060132747015603 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 sub_client_output.h ${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-2.0.11/client/sub_client_output.h0000664000175000017500000000151414060132747020062 0ustar rogerroger/* Copyright (c) 2019 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef SUB_CLIENT_OUTPUT_H #define SUB_CLIENT_OUTPUT_H #include "mosquitto.h" #include "client_shared.h" void rand_init(void); void print_message(struct mosq_config *cfg, const struct mosquitto_message *message, const mosquitto_property *properties); #endif mosquitto-2.0.11/client/pub_shared.h0000664000175000017500000000306514060132747016432 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 #define STATUS_NOHOPE 5 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-2.0.11/client/pub_test_properties0000775000175000017500000000154214060132747020172 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-2.0.11/libmosquitto.pc.in0000664000175000017500000000036614060132747016354 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-2.0.11/README.md0000664000175000017500000000727014060132747014150 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.md`. 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` * cJSON - for client JSON output support. Disable with `make WITH_CJSON=no` Auto detected with CMake. * libwebsockets (libwebsockets-dev) - enable with `make WITH_WEBSOCKETS=yes` * openssl (libssl-dev on Debian based systems) - disable with `make WITH_TLS=no` * pthreads - for client library thread support. This is required to support the `mosquitto_loop_start()` and `mosquitto_loop_stop()` functions. If compiled without pthread support, the library isn't guaranteed to be thread safe. * uthash / utlist - bundled versions of these headers are provided, disable their use with `make WITH_BUNDLED_DEPS=no` * xsltproc (xsltproc and docbook-xsl on Debian based systems) - only needed when building from git sources - disable with `make WITH_DOCS=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-2.0.11/deps/0000775000175000017500000000000014060132747013616 5ustar rogerrogermosquitto-2.0.11/deps/uthash.h0000664000175000017500000023116514060132747015273 0ustar rogerroger/* Copyright (c) 2003-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 UTHASH_H #define UTHASH_H #define UTHASH_VERSION 2.1.0 #include /* memcmp, memset, 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. */ #if !defined(DECLTYPE) && !defined(NO_DECLTYPE) #if defined(_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 #endif #elif defined(__BORLANDC__) || defined(__ICCARM__) || defined(__LCC__) || defined(__WATCOMC__) #define NO_DECLTYPE #else /* GNU, Sun and other compilers */ #define DECLTYPE(x) (__typeof(x)) #endif #endif #ifdef NO_DECLTYPE #define DECLTYPE(x) #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 Pre VS2010 */ #if defined(_WIN32) #if defined(_MSC_VER) && _MSC_VER >= 1600 #include #elif defined(__WATCOMC__) || defined(__MINGW32__) || defined(__CYGWIN__) #include #else typedef unsigned int uint32_t; typedef unsigned char uint8_t; #endif #elif defined(__GNUC__) && !defined(__VXWORKS__) #include #else typedef unsigned int uint32_t; typedef unsigned char uint8_t; #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_bzero #define uthash_bzero(a,n) memset(a,'\0',n) #endif #ifndef uthash_strlen #define uthash_strlen(s) strlen(s) #endif #ifdef uthash_memcmp /* This warning will not catch programs that define uthash_memcmp AFTER including uthash.h. */ #warning "uthash_memcmp is deprecated; please use HASH_KEYCMP instead" #else #define uthash_memcmp(a,b,n) memcmp(a,b,n) #endif #ifndef HASH_KEYCMP #define HASH_KEYCMP(a,b,n) uthash_memcmp(a,b,n) #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 #ifndef HASH_NONFATAL_OOM #define HASH_NONFATAL_OOM 0 #endif #if HASH_NONFATAL_OOM /* malloc failures can be recovered from */ #ifndef uthash_nonfatal_oom #define uthash_nonfatal_oom(obj) do {} while (0) /* non-fatal OOM error */ #endif #define HASH_RECORD_OOM(oomed) do { (oomed) = 1; } while (0) #define IF_HASH_NONFATAL_OOM(x) x #else /* malloc failures result in lost memory, hash tables are unusable */ #ifndef uthash_fatal #define uthash_fatal(msg) exit(-1) /* fatal OOM error */ #endif #define HASH_RECORD_OOM(oomed) uthash_fatal("out of memory") #define IF_HASH_NONFATAL_OOM(x) #endif /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */ #define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */ /* calculate the element whose hash handle address is hhp */ #define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) /* calculate the hash handle from element address elp */ #define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle *)(((char*)(elp)) + ((tbl)->hho))) #define HASH_ROLLBACK_BKT(hh, head, itemptrhh) \ do { \ struct UT_hash_handle *_hd_hh_item = (itemptrhh); \ unsigned _hd_bkt; \ HASH_TO_BKT(_hd_hh_item->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ (head)->hh.tbl->buckets[_hd_bkt].count++; \ _hd_hh_item->hh_next = NULL; \ _hd_hh_item->hh_prev = NULL; \ } while (0) #define HASH_VALUE(keyptr,keylen,hashv) \ do { \ HASH_FCN(keyptr, keylen, hashv); \ } while (0) #define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out) \ do { \ (out) = NULL; \ if (head) { \ unsigned _hf_bkt; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \ if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) { \ HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \ } \ } \ } while (0) #define HASH_FIND(hh,head,keyptr,keylen,out) \ do { \ unsigned _hf_hashv; \ HASH_VALUE(keyptr, keylen, _hf_hashv); \ HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \ } while (0) #ifdef HASH_BLOOM #define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM) #define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL) #define HASH_BLOOM_MAKE(tbl,oomed) \ do { \ (tbl)->bloom_nbits = HASH_BLOOM; \ (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ if (!(tbl)->bloom_bv) { \ HASH_RECORD_OOM(oomed); \ } else { \ uthash_bzero((tbl)->bloom_bv, 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)/8U] |= (1U << ((idx)%8U))) #define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8U] & (1U << ((idx)%8U))) #define HASH_BLOOM_ADD(tbl,hashv) \ HASH_BLOOM_BITSET((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) #define HASH_BLOOM_TEST(tbl,hashv) \ HASH_BLOOM_BITTEST((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) #else #define HASH_BLOOM_MAKE(tbl,oomed) #define HASH_BLOOM_FREE(tbl) #define HASH_BLOOM_ADD(tbl,hashv) #define HASH_BLOOM_TEST(tbl,hashv) (1) #define HASH_BLOOM_BYTELEN 0U #endif #define HASH_MAKE_TABLE(hh,head,oomed) \ do { \ (head)->hh.tbl = (UT_hash_table*)uthash_malloc(sizeof(UT_hash_table)); \ if (!(head)->hh.tbl) { \ HASH_RECORD_OOM(oomed); \ } else { \ uthash_bzero((head)->hh.tbl, 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)); \ (head)->hh.tbl->signature = HASH_SIGNATURE; \ if (!(head)->hh.tbl->buckets) { \ HASH_RECORD_OOM(oomed); \ uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ } else { \ uthash_bzero((head)->hh.tbl->buckets, \ HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ HASH_BLOOM_MAKE((head)->hh.tbl, oomed); \ IF_HASH_NONFATAL_OOM( \ if (oomed) { \ uthash_free((head)->hh.tbl->buckets, \ HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ } \ ) \ } \ } \ } while (0) #define HASH_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \ do { \ (replaced) = NULL; \ HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ if (replaced) { \ HASH_DELETE(hh, head, replaced); \ } \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \ } while (0) #define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \ do { \ (replaced) = NULL; \ HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ if (replaced) { \ HASH_DELETE(hh, head, replaced); \ } \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \ } while (0) #define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ do { \ unsigned _hr_hashv; \ HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \ } while (0) #define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn) \ do { \ unsigned _hr_hashv; \ HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \ } while (0) #define HASH_APPEND_LIST(hh, head, add) \ do { \ (add)->hh.next = NULL; \ (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ (head)->hh.tbl->tail->next = (add); \ (head)->hh.tbl->tail = &((add)->hh); \ } while (0) #define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \ do { \ do { \ if (cmpfcn(DECLTYPE(head)(_hs_iter), add) > 0) { \ break; \ } \ } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ } while (0) #ifdef NO_DECLTYPE #undef HASH_AKBI_INNER_LOOP #define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \ do { \ char *_hs_saved_head = (char*)(head); \ do { \ DECLTYPE_ASSIGN(head, _hs_iter); \ if (cmpfcn(head, add) > 0) { \ DECLTYPE_ASSIGN(head, _hs_saved_head); \ break; \ } \ DECLTYPE_ASSIGN(head, _hs_saved_head); \ } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ } while (0) #endif #if HASH_NONFATAL_OOM #define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed) \ do { \ if (!(oomed)) { \ unsigned _ha_bkt; \ (head)->hh.tbl->num_items++; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \ if (oomed) { \ HASH_ROLLBACK_BKT(hh, head, &(add)->hh); \ HASH_DELETE_HH(hh, head, &(add)->hh); \ (add)->hh.tbl = NULL; \ uthash_nonfatal_oom(add); \ } else { \ HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ } \ } else { \ (add)->hh.tbl = NULL; \ uthash_nonfatal_oom(add); \ } \ } while (0) #else #define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed) \ do { \ unsigned _ha_bkt; \ (head)->hh.tbl->num_items++; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \ HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ } while (0) #endif #define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \ do { \ IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; ) \ (add)->hh.hashv = (hashval); \ (add)->hh.key = (char*) (keyptr); \ (add)->hh.keylen = (unsigned) (keylen_in); \ if (!(head)) { \ (add)->hh.next = NULL; \ (add)->hh.prev = NULL; \ HASH_MAKE_TABLE(hh, add, _ha_oomed); \ IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { ) \ (head) = (add); \ IF_HASH_NONFATAL_OOM( } ) \ } else { \ void *_hs_iter = (head); \ (add)->hh.tbl = (head)->hh.tbl; \ HASH_AKBI_INNER_LOOP(hh, head, add, cmpfcn); \ if (_hs_iter) { \ (add)->hh.next = _hs_iter; \ if (((add)->hh.prev = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev)) { \ HH_FROM_ELMT((head)->hh.tbl, (add)->hh.prev)->next = (add); \ } else { \ (head) = (add); \ } \ HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev = (add); \ } else { \ HASH_APPEND_LIST(hh, head, add); \ } \ } \ HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \ HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE_INORDER"); \ } while (0) #define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn) \ do { \ unsigned _hs_hashv; \ HASH_VALUE(keyptr, keylen_in, _hs_hashv); \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \ } while (0) #define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn) #define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn) \ HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn) #define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add) \ do { \ IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; ) \ (add)->hh.hashv = (hashval); \ (add)->hh.key = (char*) (keyptr); \ (add)->hh.keylen = (unsigned) (keylen_in); \ if (!(head)) { \ (add)->hh.next = NULL; \ (add)->hh.prev = NULL; \ HASH_MAKE_TABLE(hh, add, _ha_oomed); \ IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { ) \ (head) = (add); \ IF_HASH_NONFATAL_OOM( } ) \ } else { \ (add)->hh.tbl = (head)->hh.tbl; \ HASH_APPEND_LIST(hh, head, add); \ } \ HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \ HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE"); \ } while (0) #define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ do { \ unsigned _ha_hashv; \ HASH_VALUE(keyptr, keylen_in, _ha_hashv); \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \ } while (0) #define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add) \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add) #define HASH_ADD(hh,head,fieldname,keylen_in,add) \ HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add) #define HASH_TO_BKT(hashv,num_bkts,bkt) \ do { \ bkt = ((hashv) & ((num_bkts) - 1U)); \ } 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) \ HASH_DELETE_HH(hh, head, &(delptr)->hh) #define HASH_DELETE_HH(hh,head,delptrhh) \ do { \ struct UT_hash_handle *_hd_hh_del = (delptrhh); \ if ((_hd_hh_del->prev == NULL) && (_hd_hh_del->next == NULL)) { \ HASH_BLOOM_FREE((head)->hh.tbl); \ uthash_free((head)->hh.tbl->buckets, \ (head)->hh.tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ (head) = NULL; \ } else { \ unsigned _hd_bkt; \ if (_hd_hh_del == (head)->hh.tbl->tail) { \ (head)->hh.tbl->tail = HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev); \ } \ if (_hd_hh_del->prev != NULL) { \ HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev)->next = _hd_hh_del->next; \ } else { \ DECLTYPE_ASSIGN(head, _hd_hh_del->next); \ } \ if (_hd_hh_del->next != NULL) { \ HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->next)->prev = _hd_hh_del->prev; \ } \ HASH_TO_BKT(_hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ HASH_DEL_IN_BKT((head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ (head)->hh.tbl->num_items--; \ } \ HASH_FSCK(hh, head, "HASH_DELETE_HH"); \ } while (0) /* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ #define HASH_FIND_STR(head,findstr,out) \ do { \ unsigned _uthash_hfstr_keylen = (unsigned)uthash_strlen(findstr); \ HASH_FIND(hh, head, findstr, _uthash_hfstr_keylen, out); \ } while (0) #define HASH_ADD_STR(head,strfield,add) \ do { \ unsigned _uthash_hastr_keylen = (unsigned)uthash_strlen((add)->strfield); \ HASH_ADD(hh, head, strfield[0], _uthash_hastr_keylen, add); \ } while (0) #define HASH_REPLACE_STR(head,strfield,add,replaced) \ do { \ unsigned _uthash_hrstr_keylen = (unsigned)uthash_strlen((add)->strfield); \ HASH_REPLACE(hh, head, strfield[0], _uthash_hrstr_keylen, add, replaced); \ } while (0) #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,replaced) \ 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,where) \ do { \ struct UT_hash_handle *_thh; \ if (head) { \ unsigned _bkt_i; \ unsigned _count = 0; \ char *_prev; \ for (_bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; ++_bkt_i) { \ unsigned _bkt_count = 0; \ _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ _prev = NULL; \ while (_thh) { \ if (_prev != (char*)(_thh->hh_prev)) { \ HASH_OOPS("%s: invalid hh_prev %p, actual %p\n", \ (where), (void*)_thh->hh_prev, (void*)_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("%s: invalid bucket count %u, actual %u\n", \ (where), (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ } \ } \ if (_count != (head)->hh.tbl->num_items) { \ HASH_OOPS("%s: invalid hh item count %u, actual %u\n", \ (where), (head)->hh.tbl->num_items, _count); \ } \ _count = 0; \ _prev = NULL; \ _thh = &(head)->hh; \ while (_thh) { \ _count++; \ if (_prev != (char*)_thh->prev) { \ HASH_OOPS("%s: invalid prev %p, actual %p\n", \ (where), (void*)_thh->prev, (void*)_prev); \ } \ _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ _thh = (_thh->next ? HH_FROM_ELMT((head)->hh.tbl, _thh->next) : NULL); \ } \ if (_count != (head)->hh.tbl->num_items) { \ HASH_OOPS("%s: invalid app item count %u, actual %u\n", \ (where), (head)->hh.tbl->num_items, _count); \ } \ } \ } while (0) #else #define HASH_FSCK(hh,head,where) #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, (unsigned long)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. Note (x<<5+x)=x*33. */ #define HASH_BER(key,keylen,hashv) \ do { \ unsigned _hb_keylen = (unsigned)keylen; \ const unsigned char *_hb_key = (const unsigned char*)(key); \ (hashv) = 0; \ while (_hb_keylen-- != 0U) { \ (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \ } \ } 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,hashv) \ do { \ unsigned _sx_i; \ const unsigned char *_hs_key = (const unsigned char*)(key); \ hashv = 0; \ for (_sx_i=0; _sx_i < keylen; _sx_i++) { \ hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ } \ } while (0) /* FNV-1a variation */ #define HASH_FNV(key,keylen,hashv) \ do { \ unsigned _fn_i; \ const unsigned char *_hf_key = (const unsigned char*)(key); \ (hashv) = 2166136261U; \ for (_fn_i=0; _fn_i < keylen; _fn_i++) { \ hashv = hashv ^ _hf_key[_fn_i]; \ hashv = hashv * 16777619U; \ } \ } while (0) #define HASH_OAT(key,keylen,hashv) \ do { \ unsigned _ho_i; \ const unsigned char *_ho_key=(const unsigned 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); \ } 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,hashv) \ do { \ unsigned _hj_i,_hj_j,_hj_k; \ unsigned const char *_hj_key=(unsigned const char*)(key); \ hashv = 0xfeedbeefu; \ _hj_i = _hj_j = 0x9e3779b9u; \ _hj_k = (unsigned)(keylen); \ while (_hj_k >= 12U) { \ _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 -= 12U; \ } \ hashv += (unsigned)(keylen); \ switch ( _hj_k ) { \ case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \ case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \ case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \ case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \ case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \ case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \ case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \ case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \ case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \ case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \ case 1: _hj_i += _hj_key[0]; \ } \ HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ } 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,hashv) \ do { \ unsigned const char *_sfh_key=(unsigned const char*)(key); \ uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \ \ unsigned _sfh_rem = _sfh_len & 3U; \ _sfh_len >>= 2; \ hashv = 0xcafebabeu; \ \ /* Main loop */ \ for (;_sfh_len > 0U; _sfh_len--) { \ hashv += get16bits (_sfh_key); \ _sfh_tmp = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv; \ hashv = (hashv << 16) ^ _sfh_tmp; \ _sfh_key += 2U*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; \ } 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 & 3UL) == 0UL) #define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 3UL) == 1UL) #define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 3UL) == 2UL) #define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 3UL) == 3UL) #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 *= 0x85ebca6bu; \ _h ^= _h >> 13; \ _h *= 0xc2b2ae35u; \ _h ^= _h >> 16; \ } while (0) #define HASH_MUR(key,keylen,hashv) \ do { \ const uint8_t *_mur_data = (const uint8_t*)(key); \ const int _mur_nblocks = (int)(keylen) / 4; \ uint32_t _mur_h1 = 0xf88D5353u; \ uint32_t _mur_c1 = 0xcc9e2d51u; \ uint32_t _mur_c2 = 0x1b873593u; \ 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 != 0; _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*5U) + 0xe6546b64u; \ } \ _mur_tail = (const uint8_t*)(_mur_data + (_mur_nblocks*4)); \ _mur_k1=0; \ switch ((keylen) & 3U) { \ case 0: break; \ case 3: _mur_k1 ^= (uint32_t)_mur_tail[2] << 16; /* FALLTHROUGH */ \ case 2: _mur_k1 ^= (uint32_t)_mur_tail[1] << 8; /* FALLTHROUGH */ \ case 1: _mur_k1 ^= (uint32_t)_mur_tail[0]; \ _mur_k1 *= _mur_c1; \ _mur_k1 = MUR_ROTL32(_mur_k1,15); \ _mur_k1 *= _mur_c2; \ _mur_h1 ^= _mur_k1; \ } \ _mur_h1 ^= (uint32_t)(keylen); \ MUR_FMIX(_mur_h1); \ hashv = _mur_h1; \ } while (0) #endif /* HASH_USING_NO_STRICT_ALIASING */ /* iterate over items in a known bucket to find desired item */ #define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out) \ do { \ if ((head).hh_head != NULL) { \ DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \ } else { \ (out) = NULL; \ } \ while ((out) != NULL) { \ if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \ if (HASH_KEYCMP((out)->hh.key, keyptr, keylen_in) == 0) { \ break; \ } \ } \ if ((out)->hh.hh_next != NULL) { \ 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,hh,addhh,oomed) \ do { \ UT_hash_bucket *_ha_head = &(head); \ _ha_head->count++; \ (addhh)->hh_next = _ha_head->hh_head; \ (addhh)->hh_prev = NULL; \ if (_ha_head->hh_head != NULL) { \ _ha_head->hh_head->hh_prev = (addhh); \ } \ _ha_head->hh_head = (addhh); \ if ((_ha_head->count >= ((_ha_head->expand_mult + 1U) * HASH_BKT_CAPACITY_THRESH)) \ && !(addhh)->tbl->noexpand) { \ HASH_EXPAND_BUCKETS(addhh,(addhh)->tbl, oomed); \ IF_HASH_NONFATAL_OOM( \ if (oomed) { \ HASH_DEL_IN_BKT(head,addhh); \ } \ ) \ } \ } while (0) /* remove an item from a given bucket */ #define HASH_DEL_IN_BKT(head,delhh) \ do { \ UT_hash_bucket *_hd_head = &(head); \ _hd_head->count--; \ if (_hd_head->hh_head == (delhh)) { \ _hd_head->hh_head = (delhh)->hh_next; \ } \ if ((delhh)->hh_prev) { \ (delhh)->hh_prev->hh_next = (delhh)->hh_next; \ } \ if ((delhh)->hh_next) { \ (delhh)->hh_next->hh_prev = (delhh)->hh_prev; \ } \ } while (0) /* 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(hh,tbl,oomed) \ 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( \ 2UL * (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \ if (!_he_new_buckets) { \ HASH_RECORD_OOM(oomed); \ } else { \ uthash_bzero(_he_new_buckets, \ 2UL * (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \ (tbl)->ideal_chain_maxlen = \ ((tbl)->num_items >> ((tbl)->log2_num_buckets+1U)) + \ ((((tbl)->num_items & (((tbl)->num_buckets*2U)-1U)) != 0U) ? 1U : 0U); \ (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 != NULL) { \ _he_hh_nxt = _he_thh->hh_next; \ HASH_TO_BKT(_he_thh->hashv, (tbl)->num_buckets * 2U, _he_bkt); \ _he_newbkt = &(_he_new_buckets[_he_bkt]); \ if (++(_he_newbkt->count) > (tbl)->ideal_chain_maxlen) { \ (tbl)->nonideal_items++; \ if (_he_newbkt->count > _he_newbkt->expand_mult * (tbl)->ideal_chain_maxlen) { \ _he_newbkt->expand_mult++; \ } \ } \ _he_thh->hh_prev = NULL; \ _he_thh->hh_next = _he_newbkt->hh_head; \ if (_he_newbkt->hh_head != NULL) { \ _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 *= 2U; \ (tbl)->log2_num_buckets++; \ (tbl)->buckets = _he_new_buckets; \ (tbl)->ineff_expands = ((tbl)->nonideal_items > ((tbl)->num_items >> 1)) ? \ ((tbl)->ineff_expands+1U) : 0U; \ if ((tbl)->ineff_expands > 1U) { \ (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 != NULL) { \ _hs_insize = 1; \ _hs_looping = 1; \ _hs_list = &((head)->hh); \ while (_hs_looping != 0U) { \ _hs_p = _hs_list; \ _hs_list = NULL; \ _hs_tail = NULL; \ _hs_nmerges = 0; \ while (_hs_p != NULL) { \ _hs_nmerges++; \ _hs_q = _hs_p; \ _hs_psize = 0; \ for (_hs_i = 0; _hs_i < _hs_insize; ++_hs_i) { \ _hs_psize++; \ _hs_q = ((_hs_q->next != NULL) ? \ HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ if (_hs_q == NULL) { \ break; \ } \ } \ _hs_qsize = _hs_insize; \ while ((_hs_psize != 0U) || ((_hs_qsize != 0U) && (_hs_q != NULL))) { \ if (_hs_psize == 0U) { \ _hs_e = _hs_q; \ _hs_q = ((_hs_q->next != NULL) ? \ HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ _hs_qsize--; \ } else if ((_hs_qsize == 0U) || (_hs_q == NULL)) { \ _hs_e = _hs_p; \ if (_hs_p != NULL) { \ _hs_p = ((_hs_p->next != NULL) ? \ HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : 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 != NULL) { \ _hs_p = ((_hs_p->next != NULL) ? \ HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \ } \ _hs_psize--; \ } else { \ _hs_e = _hs_q; \ _hs_q = ((_hs_q->next != NULL) ? \ HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ _hs_qsize--; \ } \ if ( _hs_tail != NULL ) { \ _hs_tail->next = ((_hs_e != NULL) ? \ ELMT_FROM_HH((head)->hh.tbl, _hs_e) : NULL); \ } else { \ _hs_list = _hs_e; \ } \ if (_hs_e != NULL) { \ _hs_e->prev = ((_hs_tail != NULL) ? \ ELMT_FROM_HH((head)->hh.tbl, _hs_tail) : NULL); \ } \ _hs_tail = _hs_e; \ } \ _hs_p = _hs_q; \ } \ if (_hs_tail != NULL) { \ _hs_tail->next = NULL; \ } \ if (_hs_nmerges <= 1U) { \ _hs_looping = 0; \ (head)->hh.tbl->tail = _hs_tail; \ DECLTYPE_ASSIGN(head, ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ } \ _hs_insize *= 2U; \ } \ HASH_FSCK(hh, head, "HASH_SRT"); \ } \ } 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) != NULL) { \ 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 != NULL; \ _src_hh = _src_hh->hh_next) { \ _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ if (cond(_elt)) { \ IF_HASH_NONFATAL_OOM( int _hs_oomed = 0; ) \ _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 != NULL) { \ _last_elt_hh->next = _elt; \ } \ if ((dst) == NULL) { \ DECLTYPE_ASSIGN(dst, _elt); \ HASH_MAKE_TABLE(hh_dst, dst, _hs_oomed); \ IF_HASH_NONFATAL_OOM( \ if (_hs_oomed) { \ uthash_nonfatal_oom(_elt); \ (dst) = NULL; \ continue; \ } \ ) \ } 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], hh_dst, _dst_hh, _hs_oomed); \ (dst)->hh_dst.tbl->num_items++; \ IF_HASH_NONFATAL_OOM( \ if (_hs_oomed) { \ HASH_ROLLBACK_BKT(hh_dst, dst, _dst_hh); \ HASH_DELETE_HH(hh_dst, dst, _dst_hh); \ _dst_hh->tbl = NULL; \ uthash_nonfatal_oom(_elt); \ continue; \ } \ ) \ HASH_BLOOM_ADD(_dst_hh->tbl, _dst_hh->hashv); \ _last_elt = _elt; \ _last_elt_hh = _dst_hh; \ } \ } \ } \ } \ HASH_FSCK(hh_dst, dst, "HASH_SELECT"); \ } while (0) #define HASH_CLEAR(hh,head) \ do { \ if ((head) != NULL) { \ HASH_BLOOM_FREE((head)->hh.tbl); \ uthash_free((head)->hh.tbl->buckets, \ (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ (head) = NULL; \ } \ } while (0) #define HASH_OVERHEAD(hh,head) \ (((head) != NULL) ? ( \ (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))) : 0U) #ifdef NO_DECLTYPE #define HASH_ITER(hh,head,el,tmp) \ for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \ (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL))) #else #define HASH_ITER(hh,head,el,tmp) \ for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \ (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(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 != NULL)?((head)->hh.tbl->num_items):0U) 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 0xa0111fe1u #define HASH_BLOOM_SIGNATURE 0xb12220f2u 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; uint8_t 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-2.0.11/deps/utlist.h0000664000175000017500000023714014060132747015322 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-2.0.11/test/0000775000175000017500000000000014060132747013642 5ustar rogerrogermosquitto-2.0.11/test/mqtt5_rc.py0000664000175000017500000000273114060132747015755 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-2.0.11/test/ptest.py0000775000175000017500000000436714060132747015370 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:") failed_tests.sort() for f in failed_tests: print(f) sys.exit(1) mosquitto-2.0.11/test/mosq_test.py0000664000175000017500000006232114060132747016236 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 = [] class TestError(Exception): def __init__(self, message="Mismatched packets"): self.message = message 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: outs, errs = broker.communicate(timeout=1) print("FAIL: unable to start broker: %s" % errs) 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) if packet_matches(name, packet_recvd, expected): return True else: raise TestError 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)) try: print("Expected: "+to_string(expected)) except struct.error: print("Expected (not decoded, len=%d): %s" % (len(expected), expected)) return False else: return True def receive_unordered(sock, recv1_packet, recv2_packet, error_string): expected1 = recv1_packet + recv2_packet expected2 = recv2_packet + recv1_packet recvd = b'' while len(recvd) < len(expected1): r = sock.recv(1) if len(r) == 0: raise ValueError(error_string) recvd += r if recvd == expected1 or recvd == expected2: return else: packet_matches(error_string, recvd, expected2) raise ValueError(error_string) 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 # Useful for mocking a client receiving (with ack) a qos1 publish def do_receive_send(sock, receive_packet, send_packet, error_string="receive send error"): if expect_packet(sock, error_string, receive_packet): 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 return sock else: sock.close() raise ValueError def do_client_connect(connect_packet, connack_packet, hostname="localhost", port=1888, timeout=10, 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%ds" % (len(packet)-1), bytes(packet)) 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="+str(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="+str(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="+str(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="+str(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="+str(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="+str(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="+str(packet) return s elif cmd == 0x40: # PUBACK if len(packet) == 5: (cmd, rl, mid, reason_code) = struct.unpack('!BBHB', packet) return "PUBACK, rl="+str(rl)+", mid="+str(mid)+", reason_code="+str(reason_code) else: (cmd, rl, mid) = struct.unpack('!BBH', packet) return "PUBACK, rl="+str(rl)+", mid="+str(mid) elif cmd == 0x50: # PUBREC if len(packet) == 5: (cmd, rl, mid, reason_code) = struct.unpack('!BBHB', packet) return "PUBREC, rl="+str(rl)+", mid="+str(mid)+", reason_code="+str(reason_code) else: (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)+"="+str(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)+"="+str(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 if len(packet) == 3: (cmd, rl, reason_code) = struct.unpack('!BBB', packet) return "DISCONNECT, rl="+str(rl)+", reason_code="+str(reason_code) else: (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 read_varint(sock, rl): varint = 0 multiplier = 1 while True: byte = sock.recv(1) byte, = struct.unpack("!B", byte) varint += (byte & 127)*multiplier multiplier *= 128 rl -= 1 if byte & 128 == 0x00: return (varint, rl) def mqtt_read_string(sock, rl): slen = sock.recv(2) slen, = struct.unpack("!H", slen) payload = sock.recv(slen) payload, = struct.unpack("!%ds" % (slen), payload) rl -= (2 + slen) return (payload, rl) def read_publish(sock, proto_ver=4): cmd, = struct.unpack("!B", sock.recv(1)) if cmd & 0xF0 != 0x30: raise ValueError qos = (cmd & 0x06) >> 1 rl, t = read_varint(sock, 0) topic, rl = mqtt_read_string(sock, rl) if qos > 0: sock.recv(2) rl -= 1 if proto_ver == 5: proplen, rl = read_varint(sock, rl) sock.recv(proplen) rl -= proplen payload = sock.recv(rl).decode('utf-8') return payload 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"", session_expiry=-1): 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) if session_expiry != -1: properties += mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, session_expiry) 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"", property_helper=True): if proto_ver == 5: if property_helper == True: if properties is not None: properties = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS_MAXIMUM, 10) \ + properties + mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 20) 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, cmd=130, proto_ver=4, properties=b""): topic = topic.encode("utf-8") packet = struct.pack("!B", cmd) 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, cmd=162, proto_ver=4, properties=b""): topic = topic.encode("utf-8") if proto_ver == 5: if properties == b"": pack_format = "!BBHBH"+str(len(topic))+"s" return struct.pack(pack_format, cmd, 2+2+len(topic)+1, mid, 0, len(topic), topic) else: properties = mqtt5_props.prop_finalise(properties) packet = struct.pack("!B", cmd) l = 2+2+len(topic)+1+len(properties) packet += pack_remaining_length(l) pack_format = "!HB"+str(len(properties))+"sH"+str(len(topic))+"s" packet += struct.pack(pack_format, mid, len(properties), properties, len(topic), topic) return packet else: pack_format = "!BBHH"+str(len(topic))+"s" return struct.pack(pack_format, cmd, 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, reason_code=0, proto_ver=4): 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-2.0.11/test/random/0000775000175000017500000000000014060132747015122 5ustar rogerrogermosquitto-2.0.11/test/random/random_client.py0000775000175000017500000001200114060132747020307 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-2.0.11/test/random/auth_plugin.c0000664000175000017500000000257414060132747017615 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-2.0.11/test/random/pwfile0000664000175000017500000000016214060132747016332 0ustar rogerrogertest:$6$cBP7e6sUriMSh8yf$+Z3E9P1g+Hui8zDJA+XJpTHl6+0eym0MtWokmOY4j1svAR5RtjZoXB4OQuHYzrGrdp1e8gXoqcKlcP+1lmepmg== mosquitto-2.0.11/test/random/test.py0000775000175000017500000000203514060132747016456 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-2.0.11/test/random/random.conf0000664000175000017500000000312514060132747017252 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-2.0.11/test/random/Makefile0000664000175000017500000000074614060132747016571 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-2.0.11/test/old/0000775000175000017500000000000014060132747014420 5ustar rogerrogermosquitto-2.0.11/test/old/msgsps_sub.c0000664000175000017500000000161214060132747016751 0ustar rogerroger/* This provides a crude manner of testing the performance of a broker in messages/s. */ #include #include #include #include #include #include #include #include static atomic_int message_count = 0; void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { message_count++; } int main(int argc, char *argv[]) { struct mosquitto *mosq; int c; mosquitto_lib_init(); mosq = mosquitto_new(NULL, true, NULL); mosquitto_message_callback_set(mosq, my_message_callback); mosquitto_connect(mosq, HOST, PORT, 600); mosquitto_subscribe(mosq, NULL, "perf/test", SUB_QOS); mosquitto_loop_start(mosq); while(1){ sleep(1); c = message_count; message_count = 0; printf("%d\n", c); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return 0; } mosquitto-2.0.11/test/old/msgsps_common.h0000664000175000017500000000015414060132747017455 0ustar rogerroger#define HOST "127.0.0.1" #define PORT 1883 #define PUB_QOS 1 #define SUB_QOS 1 #define MESSAGE_SIZE 1024L mosquitto-2.0.11/test/old/msgsps_pub.c0000664000175000017500000000203714060132747016750 0ustar rogerroger/* This provides a crude manner of testing the performance of a broker in messages/s. */ #include #include #include #include #include #include #include #include static atomic_int message_count = 0; void my_publish_callback(struct mosquitto *mosq, void *obj, int mid) { message_count++; } int main(int argc, char *argv[]) { struct mosquitto *mosq; int i; uint8_t buf[MESSAGE_SIZE]; mosquitto_lib_init(); mosq = mosquitto_new(NULL, true, NULL); mosquitto_publish_callback_set(mosq, my_publish_callback); mosquitto_connect(mosq, HOST, PORT, 600); mosquitto_loop_start(mosq); i=0; while(1){ mosquitto_publish(mosq, NULL, "perf/test", sizeof(buf), buf, PUB_QOS, false); usleep(100); i++; if(i == 10000){ /* Crude "messages per second" count */ i = message_count; message_count = 0; printf("%d\n", i); i = 0; } } mosquitto_loop_stop(mosq, false); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return 0; } mosquitto-2.0.11/test/old/Makefile0000664000175000017500000000103514060132747016057 0ustar rogerrogerinclude ../../config.mk CC=cc CFLAGS=-I../../src -I../../include -I. -I../.. -Wall -ggdb -DDEBUG -DWITH_CLIENT LDFLAGS= SOVERSION=1 .PHONY: all test clean all : msgsps_pub msgsps_sub msgsps_pub : msgsps_pub.o ${CC} $^ -o $@ ../../lib/libmosquitto.so.${SOVERSION} msgsps_pub.o : msgsps_pub.c msgsps_common.h ${CC} $(CFLAGS) -c $< -o $@ msgsps_sub : msgsps_sub.o ${CC} $^ -o $@ ../../lib/libmosquitto.so.${SOVERSION} msgsps_sub.o : msgsps_sub.c msgsps_common.h ${CC} $(CFLAGS) -c $< -o $@ clean : -rm -f *.o msgsps_pub msgsps_sub mosquitto-2.0.11/test/lib/0000775000175000017500000000000014060132747014410 5ustar rogerrogermosquitto-2.0.11/test/lib/01-keepalive-pingreq.py0000775000175000017500000000305614060132747020617 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a pingreq after the keepalive time # The client should connect to port 1888 with keepalive=4, clean session set, # and client id 01-keepalive-pingreq # The client should send a PINGREQ message after the appropriate amount of time # (4 seconds after no traffic). from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 5 connect_packet = mosq_test.gen_connect("01-keepalive-pingreq", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) pingreq_packet = mosq_test.gen_pingreq() pingresp_packet = mosq_test.gen_pingresp() 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(keepalive+10) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "pingreq", pingreq_packet) time.sleep(1.0) conn.send(pingresp_packet) mosq_test.expect_packet(conn, "pingreq", pingreq_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/03-request-response-correlation.py0000775000175000017500000000605414060132747023055 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) props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_CORRELATION_DATA, "corridor") publish1_packet_incoming = mosq_test.gen_publish(pub_topic, qos=0, payload="action", proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_RESPONSE_TOPIC, resp_topic) props += mqtt5_props.gen_string_prop(mqtt5_props.PROP_CORRELATION_DATA, "corridor") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.PROP_USER_PROPERTY, "user", "data") publish1_packet_outgoing = mosq_test.gen_publish(pub_topic, qos=0, payload="action", proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.PROP_CORRELATION_DATA, "corridor") publish2_packet = mosq_test.gen_publish(resp_topic, qos=0, payload="a response", proto_ver=5, properties=props) 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-correlation-1.log", cmd=["c/03-request-response-correlation-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) mosq_test.do_receive_send(conn1, connect1_packet, connack_packet, "connect1") mosq_test.do_receive_send(conn2, connect2_packet, connack_packet, "connect2") mosq_test.do_receive_send(conn1, subscribe1_packet, suback_packet, "subscribe1") mosq_test.do_receive_send(conn2, subscribe2_packet, suback_packet, "subscribe2") mosq_test.expect_packet(conn1, "publish1", publish1_packet_incoming) conn2.send(publish1_packet_outgoing) mosq_test.expect_packet(conn2, "publish2", publish2_packet) rc = 0 conn1.close() conn2.close() except mosq_test.TestError: pass 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-2.0.11/test/lib/03-publish-b2c-qos2-unexpected-pubrel.py0000775000175000017500000000401714060132747023634 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("publish-qos2-test", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() pubrel_unexpected = mosq_test.gen_pubrel(1000) pubcomp_unexpected = mosq_test.gen_pubcomp(1000) 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) publish_quit_packet = mosq_test.gen_publish("quit", qos=0, payload="quit") 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(pubrel_unexpected) if mosq_test.expect_packet(conn, "pubcomp", pubcomp_unexpected): 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): conn.send(publish_quit_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-2.0.11/test/lib/01-server-keepalive-pingreq.py0000775000175000017500000000313514060132747022121 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client sends a pingreq after the keepalive time # Client sets a keepalive of 60 seconds, but receives a server keepalive to set # it back to 4 seconds. from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 60 server_keepalive = 4 connect_packet = mosq_test.gen_connect("01-server-keepalive-pingreq", keepalive=keepalive, proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_SERVER_KEEP_ALIVE, server_keepalive) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) pingreq_packet = mosq_test.gen_pingreq() pingresp_packet = mosq_test.gen_pingresp() 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(server_keepalive+10) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "pingreq", pingreq_packet) time.sleep(1.0) conn.send(pingresp_packet) mosq_test.expect_packet(conn, "pingreq", pingreq_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-c2b-qos2-len.py0000775000175000017500000000562514060132747020765 0ustar rogerroger#!/usr/bin/env python3 # Check whether a v5 client 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_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) mid = 1 publish_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message", proto_ver=5) pubrel_packet = mosq_test.gen_pubrel(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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, publish_packet, pubrec_packet, "publish") mosq_test.do_receive_send(conn, pubrel_packet, pubcomp_packet, "pubrel") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() 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-2.0.11/test/lib/11-prop-recv-qos0.py0000775000175000017500000000315414060132747020004 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_send_receive(conn, publish_packet, ok_packet, "ok") rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-2.0.11/test/lib/08-ssl-connect-no-auth.py0000775000175000017500000000352014060132747021013 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() ssock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-c2b-qos1-timeout.py0000775000175000017500000000470714060132747021674 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish", publish_packet) # Delay for > 3 seconds (message retry time) mosq_test.do_receive_send(conn, publish_packet_dup, puback_packet, "dup publish") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-c2b-qos2-receive-maximum-2.py0000775000175000017500000000744714060132747023447 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, property_helper=False) 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish 1", publish_1_packet) mosq_test.expect_packet(conn, "publish 2", publish_2_packet) conn.send(pubrec_1_packet) conn.send(pubrec_2_packet) mosq_test.expect_packet(conn, "pubrel 1", pubrel_1_packet) mosq_test.expect_packet(conn, "pubrel 2", pubrel_2_packet) conn.send(pubcomp_1_packet) conn.send(pubcomp_2_packet) mosq_test.expect_packet(conn, "publish 3", publish_3_packet) mosq_test.expect_packet(conn, "publish 4", publish_4_packet) conn.send(pubrec_3_packet) conn.send(pubrec_4_packet) mosq_test.expect_packet(conn, "pubrel 3", pubrel_3_packet) mosq_test.expect_packet(conn, "pubrel 4", pubrel_4_packet) conn.send(pubcomp_3_packet) conn.send(pubcomp_4_packet) mosq_test.expect_packet(conn, "publish 5", publish_5_packet) conn.send(pubrec_5_packet) mosq_test.expect_packet(conn, "pubrel 5", pubrel_5_packet) conn.send(pubcomp_5_packet) rc = 0 conn.close() except mosq_test.TestError: pass 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-2.0.11/test/lib/03-publish-qos0-no-payload.py0000775000175000017500000000345714060132747021605 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish", publish_packet) mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-b2c-qos2.py0000775000175000017500000000504714060132747020207 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_send_receive(conn, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(conn, pubrel_packet, pubcomp_packet, "pubcomp") rc = 0 conn.close() except mosq_test.TestError: pass 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-2.0.11/test/lib/08-ssl-bad-cacert.py0000775000175000017500000000077314060132747020005 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-2.0.11/test/lib/03-request-response.py0000775000175000017500000000471414060132747020537 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) mosq_test.do_receive_send(conn1, connect1_packet, connack_packet, "connect1") mosq_test.do_receive_send(conn2, connect2_packet, connack_packet, "connect2") mosq_test.do_receive_send(conn1, subscribe1_packet, suback_packet, "subscribe1") mosq_test.do_receive_send(conn2, subscribe2_packet, suback_packet, "subscribe2") mosq_test.expect_packet(conn1, "publish1", publish1_packet) conn2.send(publish1_packet) mosq_test.expect_packet(conn2, "publish2", publish2_packet) rc = 0 conn1.close() conn2.close() except mosq_test.TestError: pass 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-2.0.11/test/lib/09-util-topic-tokenise.py0000775000175000017500000000062614060132747021127 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-2.0.11/test/lib/03-publish-c2b-qos2.py0000775000175000017500000000537614060132747020214 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, publish_packet, pubrec_packet, "publish") mosq_test.do_receive_send(conn, pubrel_packet, pubcomp_packet, "pubrel") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/11-prop-send-content-type.py0000775000175000017500000000272514060132747021550 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish", publish_packet) mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-2.0.11/test/lib/02-subscribe-qos1.py0000775000175000017500000000370114060132747020047 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, subscribe_packet, suback_packet, "subscribe") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/02-subscribe-qos2.py0000775000175000017500000000370114060132747020050 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, subscribe_packet, suback_packet, "subscribe") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/08-ssl-connect-cert-auth-enc.py0000775000175000017500000000365314060132747022106 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() ssock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-c2b-qos1-len.py0000775000175000017500000000446114060132747020761 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, publish_packet, puback_packet, "publish") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass 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-2.0.11/test/lib/02-unsubscribe-v5.py0000775000175000017500000000272214060132747020063 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, unsubscribe_packet, unsuback_packet, "unsubscribe") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/01-con-discon-success.py0000775000175000017500000000301314060132747020702 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: #client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/08-ssl-connect-cert-auth.py0000775000175000017500000000364714060132747021346 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() ssock.close() exit(rc) mosquitto-2.0.11/test/lib/c/0000775000175000017500000000000014060132747014632 5ustar rogerrogermosquitto-2.0.11/test/lib/c/02-unsubscribe-v5.c0000664000175000017500000000204714060132747020074 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-b2c-qos1-unexpected-puback.c0000664000175000017500000000126514060132747023622 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ printf("Connect error: %d\n", 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("publish-qos1-test", true, &run); if(mosq == NULL){ return 1; } mosquitto_connect_callback_set(mosq, on_connect); rc = mosquitto_connect(mosq, "localhost", port, 5); while(run == -1){ rc = mosquitto_loop(mosq, 300, 1); if(rc){ exit(0); } } mosquitto_lib_cleanup(); return 0; } mosquitto-2.0.11/test/lib/c/03-publish-c2b-qos2-len.c0000664000175000017500000000226214060132747020770 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-b2c-qos2.c0000664000175000017500000000257514060132747020223 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-c2b-qos2.c0000664000175000017500000000200714060132747020211 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/01-keepalive-pingreq.c0000664000175000017500000000125514060132747020627 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); if(mosq == NULL){ return 1; } mosquitto_connect_callback_set(mosq, on_connect); rc = mosquitto_connect(mosq, "localhost", port, 5); if(rc != 0) return rc; while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); if(rc != 0) break; } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-c2b-qos2-pubrec-error.c0000664000175000017500000000230714060132747022621 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-c2b-qos1-disconnect.c0000664000175000017500000000227414060132747022345 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/02-subscribe-qos1-async2.c0000664000175000017500000000276014060132747021261 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/02-unsubscribe.c0000664000175000017500000000173514060132747017547 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/01-unpwd-set.c0000664000175000017500000000106514060132747017144 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); if(mosq == NULL){ return 1; } mosquitto_username_pw_set(mosq, "uname", ";'[08gn=#"); rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-b2c-qos2-len.c0000664000175000017500000000306314060132747020770 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/01-no-clean-session.c0000664000175000017500000000100514060132747020365 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); if(mosq == NULL){ return 1; } rc = mosquitto_connect(mosq, "localhost", port, 60); while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-c2b-qos2-maximum-qos-1.c0000664000175000017500000000271114060132747022624 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-b2c-qos2-unexpected-pubcomp.c0000664000175000017500000000126514060132747024023 0ustar rogerroger#include #include #include #include #include static int run = -1; void on_connect(struct mosquitto *mosq, void *obj, int rc) { if(rc){ printf("Connect error: %d\n", 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("publish-qos2-test", true, &run); if(mosq == NULL){ return 1; } mosquitto_connect_callback_set(mosq, on_connect); rc = mosquitto_connect(mosq, "localhost", port, 5); while(run == -1){ rc = mosquitto_loop(mosq, 300, 1); if(rc){ exit(0); } } mosquitto_lib_cleanup(); return 0; } mosquitto-2.0.11/test/lib/c/11-prop-recv-qos0.c0000664000175000017500000000316114060132747020013 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); if(mosq == NULL){ return 1; } 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-2.0.11/test/lib/c/01-con-discon-success.c0000664000175000017500000000145314060132747020721 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); if(mosq == NULL){ return 1; } 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-2.0.11/test/lib/c/11-prop-recv-qos1.c0000664000175000017500000000316114060132747020014 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); if(mosq == NULL){ return 1; } 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-2.0.11/test/lib/c/03-publish-c2b-qos1-len.c0000664000175000017500000000217014060132747020765 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/02-subscribe-qos0.c0000664000175000017500000000177314060132747020066 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/08-ssl-bad-cacert.c0000664000175000017500000000072414060132747020012 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(mosq == NULL){ return 1; } if(mosquitto_tls_set(mosq, "this/file/doesnt/exist", NULL, NULL, NULL, NULL) == MOSQ_ERR_INVAL){ rc = 0; } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return rc; } mosquitto-2.0.11/test/lib/c/11-prop-send-content-type.c0000664000175000017500000000242014060132747021551 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); mosquitto_property_free_all(&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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/08-ssl-fake-cacert.c0000664000175000017500000000145714060132747020176 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); if(mosq == NULL){ return 1; } 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); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); if(rc == MOSQ_ERR_ERRNO && errno == EPROTO){ return 0; }else{ return 1; } } mosquitto-2.0.11/test/lib/c/03-publish-c2b-qos1-receive-maximum.c0000664000175000017500000000223014060132747023301 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/08-ssl-connect-no-auth.c0000664000175000017500000000160514060132747021026 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/11-prop-oversize-packet.c0000664000175000017500000000325214060132747021310 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-c2b-qos2-receive-maximum-1.c0000664000175000017500000000223014060132747023440 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-request-response-2.c0000664000175000017500000000316114060132747020702 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/08-ssl-connect-cert-auth.c0000664000175000017500000000166414060132747021354 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/11-prop-recv-qos2.c0000664000175000017500000000316114060132747020015 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); if(mosq == NULL){ return 1; } 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-2.0.11/test/lib/c/03-publish-c2b-qos2-receive-maximum-2.c0000664000175000017500000000223014060132747023441 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/04-retain-qos0.c0000664000175000017500000000140214060132747017356 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); if(mosq == NULL){ return 1; } 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-2.0.11/test/lib/c/02-subscribe-qos1-async1.c0000664000175000017500000000301314060132747021250 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-c2b-qos2-disconnect.c0000664000175000017500000000227414060132747022346 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/02-unsubscribe-multiple-v5.c0000664000175000017500000000246414060132747021730 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-qos0-no-payload.c0000664000175000017500000000172014060132747021605 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-request-response-1.c0000664000175000017500000000270514060132747020704 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/01-will-unpwd-set.c0000664000175000017500000000123714060132747020112 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/01-server-keepalive-pingreq.c0000664000175000017500000000131514060132747022130 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); if(mosq == NULL){ return 1; } 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-2.0.11/test/lib/c/02-subscribe-qos1.c0000664000175000017500000000177314060132747020067 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/01-will-set.c0000664000175000017500000000115214060132747016753 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-b2c-qos2-unexpected-pubrel.c0000664000175000017500000000277614060132747023657 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(!strcmp(msg->topic, "quit")){ run = 0; return; } 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); } } 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); if(mosq == NULL){ return 1; } 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){ rc = mosquitto_loop(mosq, 300, 1); if(rc){ printf("%d:%s\n", rc, mosquitto_strerror(rc)); exit(1); } } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-b2c-qos1.c0000664000175000017500000000253314060132747020214 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return 1; } mosquitto-2.0.11/test/lib/c/03-publish-c2b-qos2-maximum-qos-0.c0000664000175000017500000000266514060132747022633 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/03-publish-qos0.c0000664000175000017500000000173414060132747017551 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/09-util-topic-tokenise.c0000664000175000017500000000650214060132747021137 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/Makefile0000664000175000017500000000331514060132747016274 0ustar rogerroger.PHONY: all clean reallyclean CFLAGS=-I../../../include -Werror LIBS=../../../lib/libmosquitto.so.1 SRC = \ 01-con-discon-success.c \ 01-keepalive-pingreq.c \ 01-no-clean-session.c \ 01-server-keepalive-pingreq.c \ 01-unpwd-set.c \ 01-will-set.c \ 01-will-unpwd-set.c \ 02-subscribe-qos0.c \ 02-subscribe-qos1-async1.c \ 02-subscribe-qos1-async2.c \ 02-subscribe-qos1.c \ 02-subscribe-qos2.c \ 02-unsubscribe-multiple-v5.c \ 02-unsubscribe-v5.c \ 02-unsubscribe.c \ 03-publish-b2c-qos1-unexpected-puback.c \ 03-publish-b2c-qos1.c \ 03-publish-b2c-qos2-len.c \ 03-publish-b2c-qos2-unexpected-pubrel.c \ 03-publish-b2c-qos2-unexpected-pubcomp.c \ 03-publish-b2c-qos2.c \ 03-publish-c2b-qos1-disconnect.c \ 03-publish-c2b-qos1-len.c \ 03-publish-c2b-qos1-receive-maximum.c \ 03-publish-c2b-qos2-disconnect.c \ 03-publish-c2b-qos2-len.c \ 03-publish-c2b-qos2-maximum-qos-0.c \ 03-publish-c2b-qos2-maximum-qos-1.c \ 03-publish-c2b-qos2-pubrec-error.c \ 03-publish-c2b-qos2-receive-maximum-1.c \ 03-publish-c2b-qos2-receive-maximum-2.c \ 03-publish-c2b-qos2.c \ 03-publish-qos0-no-payload.c \ 03-publish-qos0.c \ 03-request-response-1.c \ 03-request-response-2.c \ 03-request-response-correlation-1.c \ 04-retain-qos0.c \ 08-ssl-bad-cacert.c \ 08-ssl-connect-cert-auth-enc.c \ 08-ssl-connect-cert-auth.c \ 08-ssl-connect-no-auth.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-2.0.11/test/lib/c/11-prop-send-payload-format.c0000664000175000017500000000241114060132747022037 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); mosquitto_property_free_all(&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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/02-subscribe-qos2.c0000664000175000017500000000177314060132747020070 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/c/08-ssl-connect-cert-auth-enc.c0000664000175000017500000000221414060132747022107 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); if(mosq == NULL){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/02-subscribe-qos0.py0000775000175000017500000000370114060132747020046 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, subscribe_packet, suback_packet, "subscribe") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/01-no-clean-session.py0000775000175000017500000000223114060132747020356 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) mosq_test.expect_packet(conn, "connect", connect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-c2b-qos2-timeout.py0000775000175000017500000000574714060132747021702 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish", publish_packet) # Delay for > 3 seconds (message retry time) mosq_test.expect_packet(conn, "dup publish", publish_dup_packet) conn.send(pubrec_packet) mosq_test.expect_packet(conn, "pubrel", pubrel_packet) mosq_test.expect_packet(conn, "dup pubrel", pubrel_packet) conn.send(pubcomp_packet) mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/01-will-unpwd-set.py0000775000175000017500000000266214060132747020104 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) mosq_test.expect_packet(conn, "connect", connect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-c2b-qos2-receive-maximum-1.py0000775000175000017500000000725714060132747023445 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, property_helper=False) 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, publish_1_packet, pubrec_1_packet, "publish 1") mosq_test.do_receive_send(conn, pubrel_1_packet, pubcomp_1_packet, "pubrel 1") mosq_test.do_receive_send(conn, publish_2_packet, pubrec_2_packet, "publish 2") mosq_test.do_receive_send(conn, pubrel_2_packet, pubcomp_2_packet, "pubrel 2") mosq_test.do_receive_send(conn, publish_3_packet, pubrec_3_packet, "publish 3") mosq_test.do_receive_send(conn, pubrel_3_packet, pubcomp_3_packet, "pubrel 3") mosq_test.do_receive_send(conn, publish_4_packet, pubrec_4_packet, "publish 4") mosq_test.do_receive_send(conn, pubrel_4_packet, pubcomp_4_packet, "pubrel 4") mosq_test.do_receive_send(conn, publish_5_packet, pubrec_5_packet, "publish 5") mosq_test.do_receive_send(conn, pubrel_5_packet, pubcomp_5_packet, "pubrel 5") rc = 0 conn.close() except mosq_test.TestError: pass 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-2.0.11/test/lib/11-prop-oversize-packet.py0000775000175000017500000000342714060132747021303 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish", publish_packet) mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-c2b-qos1-receive-maximum.py0000775000175000017500000000600714060132747023276 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, property_helper=False) 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish 1", publish_1_packet) mosq_test.expect_packet(conn, "publish 2", publish_2_packet) mosq_test.expect_packet(conn, "publish 3", publish_3_packet) conn.send(puback_1_packet) conn.send(puback_2_packet) mosq_test.expect_packet(conn, "publish 4", publish_4_packet) mosq_test.expect_packet(conn, "publish 5", publish_5_packet) conn.send(puback_3_packet) 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() except mosq_test.TestError: pass 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-2.0.11/test/lib/01-unpwd-set.py0000775000175000017500000000231414060132747017131 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) mosq_test.expect_packet(conn, "connect", connect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/02-unsubscribe-multiple-v5.py0000775000175000017500000000340314060132747021711 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, subscribe_packet, suback_packet, "subscribe") mosq_test.do_receive_send(conn, unsubscribe_packet, unsuback_packet, "unsubscribe") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-b2c-qos2-unexpected-pubcomp.py0000775000175000017500000000267314060132747024016 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 5 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 pubcomp_packet = mosq_test.gen_pubcomp(mid) pingreq_packet = mosq_test.gen_pingreq() 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(pubcomp_packet) if mosq_test.expect_packet(conn, "pingreq", pingreq_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 rc != 0 or client.returncode != 0: exit(1) exit(rc) mosquitto-2.0.11/test/lib/03-publish-qos0.py0000775000175000017500000000354014060132747017535 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish", publish_packet) mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-2.0.11/test/lib/02-unsubscribe.py0000775000175000017500000000257514060132747017541 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, unsubscribe_packet, unsuback_packet, "unsubscribe") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/11-prop-recv-qos1.py0000775000175000017500000000340114060132747020000 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") conn.send(publish_packet) mosq_test.expect_packet(conn, "puback", puback_packet) mosq_test.expect_packet(conn, "ok", ok_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-2.0.11/test/lib/mosq_test_helper.py0000664000175000017500000000064414060132747020343 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-2.0.11/test/lib/test.py0000775000175000017500000001230614060132747015746 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-qos1-unexpected-puback.py', 'c/03-publish-b2c-qos1-unexpected-puback.test']), (1, ['./03-publish-b2c-qos2-len.py', 'c/03-publish-b2c-qos2-len.test']), (1, ['./03-publish-b2c-qos2-unexpected-pubrel.py', 'c/03-publish-b2c-qos2-unexpected-pubrel.test']), (1, ['./03-publish-b2c-qos2-unexpected-pubcomp.py', 'c/03-publish-b2c-qos2-unexpected-pubcomp.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-2.0.11/test/lib/03-publish-c2b-qos1-disconnect.py0000775000175000017500000000350314060132747022330 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) mosq_test.expect_packet(conn, "connect", connect_packet) conn.send(connack_packet) mosq_test.expect_packet(conn, "publish", publish_packet) # Disconnect client. It should reconnect. conn.close() (conn, address) = sock.accept() conn.settimeout(15) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, publish_packet_dup, puback_packet, "retried publish") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/cpp/0000775000175000017500000000000014060132747015172 5ustar rogerrogermosquitto-2.0.11/test/lib/cpp/03-publish-b2c-qos2.cpp0000664000175000017500000000262514060132747021117 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(); } delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/02-unsubscribe.cpp0000664000175000017500000000155014060132747020442 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(); } delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/08-ssl-bad-cacert.cpp0000664000175000017500000000105514060132747020710 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; } delete mosq; mosqpp::lib_cleanup(); return rc; } mosquitto-2.0.11/test/lib/cpp/08-ssl-fake-cacert.cpp0000664000175000017500000000151114060132747021065 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(); delete mosq; mosqpp::lib_cleanup(); if(rc == MOSQ_ERR_ERRNO && errno == EPROTO){ return 0; }else{ return 1; } } mosquitto-2.0.11/test/lib/cpp/03-publish-qos0-no-payload.cpp0000664000175000017500000000161614060132747022511 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/03-publish-c2b-qos1-disconnect.cpp0000664000175000017500000000212414060132747023237 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/09-util-topic-tokenise.cpp0000664000175000017500000000642514060132747022043 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/08-ssl-connect-cert-auth-enc.cpp0000664000175000017500000000226314060132747023013 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/02-subscribe-qos2.cpp0000664000175000017500000000167614060132747020772 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/03-publish-c2b-qos2.cpp0000664000175000017500000000165114060132747021115 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(); } delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/01-will-set.cpp0000664000175000017500000000133014060132747017651 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/03-publish-b2c-qos1.cpp0000664000175000017500000000260114060132747021110 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return 1; } mosquitto-2.0.11/test/lib/cpp/01-con-discon-success.cpp0000664000175000017500000000146314060132747021622 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(); } delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/08-ssl-connect-no-auth.cpp0000664000175000017500000000157214060132747021731 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/03-publish-c2b-qos2-disconnect.cpp0000664000175000017500000000212414060132747023240 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/01-will-unpwd-set.cpp0000664000175000017500000000130214060132747021003 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/01-keepalive-pingreq.cpp0000664000175000017500000000121214060132747021520 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/03-publish-qos0.cpp0000664000175000017500000000162514060132747020450 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/02-subscribe-qos0.cpp0000664000175000017500000000167514060132747020767 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/04-retain-qos0.cpp0000664000175000017500000000140114060132747020255 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/01-no-clean-session.cpp0000664000175000017500000000117114060132747021271 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/02-subscribe-qos1.cpp0000664000175000017500000000166014060132747020762 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(); } delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/01-unpwd-set.cpp0000664000175000017500000000114214060132747020040 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(); } delete mosq; delete mosq; mosqpp::lib_cleanup(); return run; } mosquitto-2.0.11/test/lib/cpp/Makefile0000664000175000017500000000572014060132747016636 0ustar rogerroger.PHONY: all test 01 02 03 04 08 09 clean reallyclean CFLAGS=-I../../../include -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-2.0.11/test/lib/03-publish-c2b-qos2-pubrec-error.py0000775000175000017500000000451114060132747022607 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, property_helper=False) 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, publish_1_packet, pubrec_1_packet, "publish 1") mosq_test.do_receive_send(conn, publish_2_packet, pubrec_2_packet, "publish 2") mosq_test.do_receive_send(conn, pubrel_2_packet, pubcomp_2_packet, "pubrel 2") rc = 0 conn.close() except mosq_test.TestError: pass 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-2.0.11/test/lib/11-prop-recv-qos2.py0000775000175000017500000000367214060132747020013 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_send_receive(conn, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(conn, pubrel_packet, pubcomp_packet, "pubcomp") mosq_test.expect_packet(conn, "ok", ok_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-b2c-qos1.py0000775000175000017500000000400414060132747020176 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_send_receive(conn, publish_packet, puback_packet, "puback") rc = 0 conn.close() except mosq_test.TestError: pass 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-2.0.11/test/lib/03-publish-c2b-qos2-maximum-qos-0.py0000775000175000017500000000334614060132747022617 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish 1", publish_1_packet) mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass 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-2.0.11/test/lib/11-prop-send-payload-format.py0000775000175000017500000000375314060132747022040 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish", publish_packet) mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() if rc: (stdo, stde) = client.communicate() print(stde) sock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-b2c-qos1-unexpected-puback.py0000775000175000017500000000267014060132747023612 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_lib_port() rc = 1 keepalive = 5 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 = 13423 puback_packet = mosq_test.gen_puback(mid) pingreq_packet = mosq_test.gen_pingreq() 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(puback_packet) if mosq_test.expect_packet(conn, "pingreq", pingreq_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 rc != 0 or client.returncode != 0: exit(1) exit(rc) mosquitto-2.0.11/test/lib/08-ssl-fake-cacert.py0000775000175000017500000000231114060132747020153 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 except mosq_test.TestError: 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-2.0.11/test/lib/03-publish-b2c-qos2-len.py0000775000175000017500000000502114060132747020753 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) 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") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass 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-2.0.11/test/lib/03-publish-c2b-qos2-disconnect.py0000775000175000017500000000441214060132747022331 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish", publish_packet) # Disconnect client. It should reconnect. conn.close() (conn, address) = sock.accept() conn.settimeout(15) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, publish_dup_packet, pubrec_packet, "retried publish") 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. mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, pubrel_packet, pubcomp_packet, "retried pubrel") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/03-publish-c2b-qos2-maximum-qos-1.py0000775000175000017500000000375214060132747022621 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, publish_1_packet, puback_1_packet, "publish 1") mosq_test.expect_packet(conn, "publish 2", publish_2_packet) mosq_test.expect_packet(conn, "disconnect", disconnect_packet) rc = 0 conn.close() except mosq_test.TestError: pass 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-2.0.11/test/lib/Makefile0000664000175000017500000000665014060132747016057 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-qos1-unexpected-puback.py $@/03-publish-b2c-qos1-unexpected-puback.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-b2c-qos2-unexpected-pubrel.py $@/03-publish-b2c-qos2-unexpected-pubrel.test ./03-publish-b2c-qos2-unexpected-pubcomp.py $@/03-publish-b2c-qos2-unexpected-pubcomp.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-2.0.11/test/lib/04-retain-qos0.py0000775000175000017500000000237214060132747017354 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish", publish_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/lib/01-will-set.py0000775000175000017500000000254214060132747016746 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) mosq_test.expect_packet(conn, "connect", connect_packet) rc = 0 conn.close() except mosq_test.TestError: pass finally: client.terminate() client.wait() sock.close() exit(rc) mosquitto-2.0.11/test/client/0000775000175000017500000000000014060132747015120 5ustar rogerrogermosquitto-2.0.11/test/client/test.sh0000775000175000017500000000307214060132747016440 0ustar rogerroger#!/bin/bash # Very basic client testing. set -e export BASE_PATH=../../ export LD_LIBRARY_PATH=${BASE_PATH}/lib export PORT=1888 export SUB_TIMEOUT=1 # Start broker ../../src/mosquitto -p ${PORT} 2>/dev/null & export MOSQ_PID=$! sleep 0.5 # Kill broker on exit trap "kill $MOSQ_PID" EXIT # Simple subscribe test - single message from $SYS ${BASE_PATH}/client/mosquitto_sub -p ${PORT} -W ${SUB_TIMEOUT} -C 1 -t '$SYS/broker/uptime' >/dev/null echo "Simple subscribe ok" # Simple publish/subscribe test - single message from mosquitto_pub ${BASE_PATH}/client/mosquitto_sub -p ${PORT} -W ${SUB_TIMEOUT} -C 1 -t 'single/test' >/dev/null & export SUB_PID=$! ${BASE_PATH}/client/mosquitto_pub -p ${PORT} -t 'single/test' -m 'single-test' kill ${SUB_PID} 2>/dev/null || true echo "Simple publish/subscribe ok" # Publish a file and subscribe, do we get at least that many lines? export TEST_LINES=$(wc -l test.sh | cut -d' ' -f1) ${BASE_PATH}/client/mosquitto_sub -p ${PORT} -W ${SUB_TIMEOUT} -C ${TEST_LINES} -t 'file-publish' >/dev/null & export SUB_PID=$! ${BASE_PATH}/client/mosquitto_pub -p ${PORT} -t 'file-publish' -f ./test.sh kill ${SUB_PID} 2>/dev/null || true echo "File publish ok" # Publish a file from stdin and subscribe, do we get at least that many lines? export TEST_LINES=$(wc -l test.sh | cut -d' ' -f1) ${BASE_PATH}/client/mosquitto_sub -p ${PORT} -W ${SUB_TIMEOUT} -C ${TEST_LINES} -t 'file-publish' >/dev/null & export SUB_PID=$! ${BASE_PATH}/client/mosquitto_pub -p ${PORT} -t 'file-publish' -l < ./test.sh kill ${SUB_PID} 2>/dev/null || true echo "stdin publish ok" mosquitto-2.0.11/test/client/Makefile0000664000175000017500000000013714060132747016561 0ustar rogerroger.PHONY: all check test ptest clean all : check : test ptest : test test : ./test.sh clean: mosquitto-2.0.11/test/ssl/0000775000175000017500000000000014060132747014443 5ustar rogerrogermosquitto-2.0.11/test/ssl/test-signing-ca.key0000664000175000017500000000321314060132747020150 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-2.0.11/test/ssl/server.key0000664000175000017500000000321714060132747016466 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-2.0.11/test/ssl/test-root-ca.key0000664000175000017500000000321714060132747017501 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-2.0.11/test/ssl/client-revoked.key0000664000175000017500000000321314060132747020067 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-2.0.11/test/ssl/test-signing-ca.crt0000664000175000017500000001044414060132747020154 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-2.0.11/test/ssl/gen.sh0000775000175000017500000001113114060132747015550 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-2.0.11/test/ssl/test-alt-ca.key0000664000175000017500000000321314060132747017272 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-2.0.11/test/ssl/client-encrypted.crt0000664000175000017500000001072314060132747020431 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-2.0.11/test/ssl/server.crt0000664000175000017500000001066314060132747016471 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-2.0.11/test/ssl/test-root-ca.crt0000664000175000017500000000252314060132747017500 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-2.0.11/test/ssl/server-expired.crt0000664000175000017500000001070714060132747020126 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-2.0.11/test/ssl/client-expired.crt0000664000175000017500000001071514060132747020075 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-2.0.11/test/ssl/signingCA/0000775000175000017500000000000014060132747016305 5ustar rogerrogermosquitto-2.0.11/test/ssl/signingCA/serial0000664000175000017500000000000314060132747017500 0ustar rogerroger07 mosquitto-2.0.11/test/ssl/signingCA/index.txt.attr0000664000175000017500000000002514060132747021123 0ustar rogerrogerunique_subject = yes mosquitto-2.0.11/test/ssl/signingCA/crlnumber0000664000175000017500000000000314060132747020212 0ustar rogerroger03 mosquitto-2.0.11/test/ssl/test-bad-root-ca.crt0000664000175000017500000000253714060132747020231 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-2.0.11/test/ssl/test-alt-ca.crt0000664000175000017500000001050014060132747017267 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-2.0.11/test/ssl/test-bad-root-ca.key0000664000175000017500000000321714060132747020225 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-2.0.11/test/ssl/client.crt0000664000175000017500000001067114060132747016440 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-2.0.11/test/ssl/client-encrypted.key0000664000175000017500000000332714060132747020433 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-2.0.11/test/ssl/test-fake-root-ca.key0000664000175000017500000000321314060132747020401 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-2.0.11/test/ssl/client.key0000664000175000017500000000321714060132747016436 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-2.0.11/test/ssl/openssl.cnf0000664000175000017500000002707014060132747016624 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-2.0.11/test/ssl/server-expired.key0000664000175000017500000000321314060132747020120 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-2.0.11/test/ssl/readme.txt0000664000175000017500000000015414060132747016441 0ustar rogerrogerThis directory contains certificates and keys required for SSL testing. The CA key has password "password". mosquitto-2.0.11/test/ssl/test-fake-root-ca.crt0000664000175000017500000000252314060132747020404 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-2.0.11/test/ssl/rootCA/0000775000175000017500000000000014060132747015632 5ustar rogerrogermosquitto-2.0.11/test/ssl/rootCA/serial0000664000175000017500000000000314060132747017025 0ustar rogerroger03 mosquitto-2.0.11/test/ssl/rootCA/index.txt.attr0000664000175000017500000000002514060132747020450 0ustar rogerrogerunique_subject = yes mosquitto-2.0.11/test/ssl/rootCA/crlnumber0000664000175000017500000000000314060132747017537 0ustar rogerroger01 mosquitto-2.0.11/test/ssl/crl-empty.pem0000664000175000017500000000122614060132747017063 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-2.0.11/test/ssl/crl.pem0000664000175000017500000000126214060132747015727 0ustar rogerroger-----BEGIN X509 CRL----- MIIB1jCBvwIBATANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjETMBEGA1UE CAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3QxEDAOBgNV BAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EXDTIwMDIyNTE0NTQxOVoY DzIxMDIwNDE2MTQ1NDE5WjAUMBICAQUXDTIwMDIyNTE0NTQxOVqgDjAMMAoGA1Ud FAQDAgECMA0GCSqGSIb3DQEBCwUAA4IBAQCMM5PyBAY5BuNVk0k2Bqn5FvlIrSnS LMZaoUVG/OtgjMD6g47dSXVHgIXmuFu3Bp44mRM85ZVd1URjmjR4ZwfVfcprkqo7 L655K+nyPUoq5IZh7y4MKVYwbEfetu0HjWuOqFI9T7zalOF9MfeoOx6u93CTgUvy 1s5EVnG0d0qon3CEHTJwpzYQDgXVesUX0ZqNwvKnMGQhB8YQ/NOX807xQR5Ckl7s 6CYkAySe84lMascnwe1nFp3nGIxbOTxXqohWkvscM6933+veisgh6F4p63oF4rKs Xr93Bf9FsvwfitI/PfMWkKzFEEaZTjAM26ioLgBBcBxxIJleLysyudd2 -----END X509 CRL----- mosquitto-2.0.11/test/ssl/client-revoked.crt0000664000175000017500000001071514060132747020074 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-2.0.11/test/ssl/all-ca.crt0000664000175000017500000001316714060132747016316 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-2.0.11/test/ssl/client-expired.key0000664000175000017500000000321314060132747020070 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-2.0.11/test/broker/0000775000175000017500000000000014060132747015126 5ustar rogerrogermosquitto-2.0.11/test/broker/12-prop-subpub-content-type.py0000775000175000017500000000102614060132747022627 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-2.0.11/test/broker/12-prop-maximum-packet-size-broker.py0000775000175000017500000000256714060132747024067 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("allow_anonymous true\n") 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() os.remove(conf_file) (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/08-tls-psk-pub.py0000775000175000017500000000366014060132747020116 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() mosq_test.expect_packet(sock, "publish", publish_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/04-retain-qos1-qos0.py0000775000175000017500000000363014060132747020751 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 * def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("retain-qos1-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 6 publish_packet = mosq_test.gen_publish("retain/qos1/test", qos=1, mid=mid, payload="retained message", retain=True, proto_ver=proto_ver) if proto_ver == 5: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) else: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) mid = 18 subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos1/test", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) publish0_packet = mosq_test.gen_publish("retain/qos1/test", qos=0, payload="retained message", retain=True, 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, publish_packet, puback_packet, "puback") mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.expect_packet(sock, "publish0", publish0_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subpub-qos1-bad-pubrec.py0000775000175000017500000000471014060132747022107 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 * def helper(port, proto_ver): connect_packet = mosq_test.gen_connect("helper", keepalive=60, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish1s_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=proto_ver) puback1s_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, publish1s_packet, puback1s_packet, "puback 1s") sock.close() def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos1-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid = 1 publish1r_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=proto_ver) pubrec1r_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) 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(port, proto_ver) 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/09-acl-change.py0000775000175000017500000001032614060132747017715 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("allow_anonymous true\n") 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 sock.send(publish3s_packet) mosq_test.receive_unordered(sock, puback3s_packet, publish3r_packet, "puback3/publish3r") # 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 except mosq_test.TestError: pass 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-2.0.11/test/broker/03-publish-qos1-queued-bytes.py0000775000175000017500000001232014060132747022662 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 except mosq_test.TestError: pass 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-2.0.11/test/broker/02-subpub-qos1.py0000775000175000017500000000321714060132747020106 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 do_test(proto_ver): rc = 1 mid = 530 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos1-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid = 300 publish_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) mid = 1 publish_packet2 = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="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(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.receive_unordered(sock, puback_packet, publish_packet2, "puback/publish2") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/09-plugin-auth-unpwd-success.py0000775000175000017500000000244314060132747022772 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, plugin_ver): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v%d.so\n" % (plugin_ver)) f.write("allow_anonymous false\n") def do_test(plugin_ver): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, plugin_ver) 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) mosquitto-2.0.11/test/broker/12-prop-response-topic.py0000775000175000017500000000433514060132747021660 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) 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) mosq_test.expect_packet(sock2, "publish2", publish_packet1) rc = 0 sock1.close() sock2.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/09-plugin-auth-defer-unpwd-fail.py0000775000175000017500000000241414060132747023316 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, plugin_ver): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v%d.so\n" % (plugin_ver)) f.write("allow_anonymous false\n") def do_test(plugin_ver): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, plugin_ver) 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) mosquitto-2.0.11/test/broker/09-plugin-auth-defer-unpwd-success.py0000775000175000017500000000260014060132747024050 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, plugin_ver): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v%d.so\n" % (plugin_ver)) f.write("auth_plugin c/auth_plugin_v2.so\n") f.write("allow_anonymous false\n") def do_test(plugin_ver): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, plugin_ver) 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) mosquitto-2.0.11/test/broker/03-publish-c2b-qos2-len.py0000775000175000017500000000373514060132747021503 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): 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) 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") mosq_test.do_ping(sock) rc = 0 sock.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/01-connect-uname-password-denied.py0000775000175000017500000000300614060132747023542 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") def do_test(proto_ver): 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", proto_ver=proto_ver) if proto_ver == 5: connack_packet = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=proto_ver, properties=None) else: connack_packet = mosq_test.gen_connack(rc=5, proto_ver=proto_ver) 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 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-unsubscribe-invalid-no-topic.py0000775000175000017500000000272714060132747023430 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) def do_test(proto_ver): rc = 1 mid = 3 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-invalid-no-topic-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) 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) if proto_ver == 4: mosq_test.do_send_receive(sock, unsubscribe_packet, b"", "disconnect") else: disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_MALFORMED_PACKET) mosq_test.do_send_receive(sock, unsubscribe_packet, disconnect_packet, "disconnect") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-unsubscribe-qos1.py0000775000175000017500000000250414060132747021130 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 * def do_test(proto_ver): rc = 1 mid = 79 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-qos1-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "qos1/test", proto_ver=proto_ver) if proto_ver == 5: unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=proto_ver, reason_code=17) else: unsuback_packet = mosq_test.gen_unsuback(mid, 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, unsubscribe_packet, unsuback_packet, "unsuback") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subpub-qos0-topic-alias-unknown.py0000775000175000017500000000227614060132747024011 0ustar rogerroger#!/usr/bin/env python3 # Test whether "topic alias" works to the broker # MQTT v5 from mosq_test_helper import * def do_test(): 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=mqtt5_rc.MQTT_RC_PROTOCOL_ERROR, 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) mosq_test.expect_packet(sock, "disconnect", disconnect_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() exit(0) mosquitto-2.0.11/test/broker/04-retain-qos0-clear.py0000775000175000017500000000500714060132747021154 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 * def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("retain-clear-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("retain/clear/test", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) retain_clear_packet = mosq_test.gen_publish("retain/clear/test", qos=0, payload=None, retain=True, proto_ver=proto_ver) mid_sub = 592 subscribe_packet = mosq_test.gen_subscribe(mid_sub, "retain/clear/test", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid_sub, 0, proto_ver=proto_ver) mid_unsub = 593 unsubscribe_packet = mosq_test.gen_unsubscribe(mid_unsub, "retain/clear/test", proto_ver=proto_ver) unsuback_packet = mosq_test.gen_unsuback(mid_unsub, 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, 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") 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/08-ssl-connect-no-auth.py0000775000175000017500000000306714060132747021537 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("allow_anonymous true\n") f.write("\n") f.write("listener %d\n" % (port1)) f.write("allow_anonymous true\n") 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/02-subpub-qos0-subscription-id.py0000775000175000017500000001154114060132747023220 0ustar rogerroger#!/usr/bin/env python3 # Does setting and updating subscription identifiers work as expected? # MQTT v5 from mosq_test_helper import * def do_test(proto_ver): 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/03-publish-qos2-max-inflight.py0000775000175000017500000000377314060132747022652 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("allow_anonymous true\n") f.write("max_inflight_messages 1\n") def do_test(proto_ver): 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, proto_ver=proto_ver) properties = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS_MAXIMUM, 10) \ + mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 1) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver, properties=properties, property_helper=False) mid = 312 publish_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message", proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/09-plugin-auth-v2-unpwd-fail.py0000775000175000017500000000214614060132747022562 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/02-subpub-qos0-retain-as-publish.py0000775000175000017500000000417014060132747023431 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 * def do_test(): 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() exit(0) mosquitto-2.0.11/test/broker/07-will-delay-session-expiry.py0000775000175000017500000000357014060132747022776 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) mosq_test.expect_packet(sock1, "publish", publish_packet) rc = 0 sock1.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/14-dynsec-client-invalid.py0000775000175000017500000005671314060132747022126 0ustar rogerroger#!/usr/bin/env python3 # Check invalid inputs for client commands from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response, msg=""): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(expected_response) print(response) if msg != "": print(msg) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) # ========================================================================== # Create client # ========================================================================== # No username create_client1_command = { 'commands': [{'command': 'createClient' }] } create_client1_response = {'responses': [{'command': 'createClient', 'error': 'Invalid/missing username'}]} # Username not a string create_client2_command = { 'commands': [{'command': 'createClient', 'username': 5 }] } create_client2_response = {'responses': [{'command': 'createClient', 'error': 'Invalid/missing username'}]} # Username not UTF-8 create_client3_command = { 'commands': [{'command': 'createClient', 'username': '￿LO' }] } create_client3_response = {'responses': [{'command': 'createClient', 'error': 'Username not valid UTF-8'}]} # Password not a string create_client4_command = { 'commands': [{'command': 'createClient', 'username': 'user', 'password':5 }] } create_client4_response = {'responses': [{'command': 'createClient', 'error': 'Invalid/missing password'}]} # Client id not a string create_client5_command = { 'commands': [{'command': 'createClient', 'username': 'user', 'password':'5', 'clientid':5}] } create_client5_response = {'responses': [{'command': 'createClient', 'error': 'Invalid/missing client id'}]} # Client id not UTF-8 create_client6_command = { 'commands': [{'command': 'createClient', 'username': 'user', 'clientid':'￿LO' }] } create_client6_response = {'responses': [{'command': 'createClient', 'error': 'Client ID not valid UTF-8'}]} # Text name not a string create_client7_command = { 'commands': [{'command': 'createClient', 'username': 'user', 'password':'5', 'textname':5}] } create_client7_response = {'responses': [{'command': 'createClient', 'error': 'Invalid/missing textname'}]} # Text description not a string create_client8_command = { 'commands': [{'command': 'createClient', 'username': 'user', 'password':'5', 'textdescription':5}] } create_client8_response = {'responses': [{'command': 'createClient', 'error': 'Invalid/missing textdescription'}]} # Client already exists create_client9_command = { 'commands': [{'command': 'createClient', 'username': 'admin', 'password':'5'}]} create_client9_response = {'responses': [{'command': 'createClient', 'error': 'Client already exists'}]} # Roles not an array create_client10_command = { 'commands': [{'command': 'createClient', 'username': 'user', 'password':'5', 'roles':'bad'}] } create_client10_response = {'responses': [{'command': 'createClient', 'error': "'roles' not an array or missing/invalid rolename"}]} # Role not found create_client11_command = { 'commands': [{'command': 'createClient', 'username': 'user', 'password':'5', 'roles':[{'rolename':'notfound'}]}] } create_client11_response = {'responses': [{'command': 'createClient', 'error': 'Role not found'}]} # Group not found create_client12_command = { 'commands': [{'command': 'createClient', 'username': 'user', 'password':'5', 'groups':[{'groupname':'notfound'}]}] } create_client12_response = {'responses': [{'command': 'createClient', 'error': 'Group not found'}]} # ========================================================================== # Delete client # ========================================================================== # No username delete_client1_command = { 'commands': [{'command': 'deleteClient'}]} delete_client1_response = {'responses': [{'command': 'deleteClient', 'error': 'Invalid/missing username'}]} # Username not a string delete_client2_command = { 'commands': [{'command': 'deleteClient', 'username':5}]} delete_client2_response = {'responses': [{'command': 'deleteClient', 'error': 'Invalid/missing username'}]} # Username not UTF-8 delete_client3_command = { 'commands': [{'command': 'deleteClient', 'username': '￿LO' }] } delete_client3_response = {'responses': [{'command': 'deleteClient', 'error': 'Username not valid UTF-8'}]} # Client not found delete_client4_command = { 'commands': [{'command': 'deleteClient', 'username':'notfound'}]} delete_client4_response = {'responses': [{'command': 'deleteClient', 'error': 'Client not found'}]} # ========================================================================== # Disable client # ========================================================================== # No username disable_client1_command = { 'commands': [{'command': 'disableClient'}]} disable_client1_response = {'responses': [{'command': 'disableClient', 'error': 'Invalid/missing username'}]} # Username not a string disable_client2_command = { 'commands': [{'command': 'disableClient', 'username':5}]} disable_client2_response = {'responses': [{'command': 'disableClient', 'error': 'Invalid/missing username'}]} # Username not UTF-8 disable_client3_command = { 'commands': [{'command': 'disableClient', 'username': '￿LO' }] } disable_client3_response = {'responses': [{'command': 'disableClient', 'error': 'Username not valid UTF-8'}]} # Client not found disable_client4_command = { 'commands': [{'command': 'disableClient', 'username':'notfound'}]} disable_client4_response = {'responses': [{'command': 'disableClient', 'error': 'Client not found'}]} # ========================================================================== # Enable client # ========================================================================== # No username enable_client1_command = { 'commands': [{'command': 'enableClient'}]} enable_client1_response = {'responses': [{'command': 'enableClient', 'error': 'Invalid/missing username'}]} # Username not a string enable_client2_command = { 'commands': [{'command': 'enableClient', 'username':5}]} enable_client2_response = {'responses': [{'command': 'enableClient', 'error': 'Invalid/missing username'}]} # Username not UTF-8 enable_client3_command = { 'commands': [{'command': 'enableClient', 'username': '￿LO' }] } enable_client3_response = {'responses': [{'command': 'enableClient', 'error': 'Username not valid UTF-8'}]} # Client not found enable_client4_command = { 'commands': [{'command': 'enableClient', 'username':'notfound'}]} enable_client4_response = {'responses': [{'command': 'enableClient', 'error': 'Client not found'}]} # ========================================================================== # Set client id # ========================================================================== # No username set_client_id1_command = { 'commands': [{'command': 'setClientId'}]} set_client_id1_response = {'responses': [{'command': 'setClientId', 'error': 'Invalid/missing username'}]} # Username not a string set_client_id2_command = { 'commands': [{'command': 'setClientId', 'username':5}]} set_client_id2_response = {'responses': [{'command': 'setClientId', 'error': 'Invalid/missing username'}]} # Username not UTF-8 set_client_id3_command = { 'commands': [{'command': 'setClientId', 'username': '￿LO' }] } set_client_id3_response = {'responses': [{'command': 'setClientId', 'error': 'Username not valid UTF-8'}]} # No client id set_client_id4_command = { 'commands': [{'command': 'setClientId', 'username':'user'}]} set_client_id4_response = {'responses': [{'command': 'setClientId', 'error': 'Client not found'}]} # Client id not a string set_client_id5_command = { 'commands': [{'command': 'setClientId', 'username':'user', 'clientid':5}]} set_client_id5_response = {'responses': [{'command': 'setClientId', 'error': 'Invalid/missing client ID'}]} # Client id not UTF-8 set_client_id6_command = { 'commands': [{'command': 'setClientId', 'username':'user', 'clientid': '￿LO' }] } set_client_id6_response = {'responses': [{'command': 'setClientId', 'error': 'Client ID not valid UTF-8'}]} # Client not found set_client_id7_command = { 'commands': [{'command': 'setClientId', 'username':'notfound', 'clientid':'newid'}]} set_client_id7_response = {'responses': [{'command': 'setClientId', 'error': 'Client not found'}]} # ========================================================================== # Set password # ========================================================================== # No username set_password1_command = { 'commands': [{'command': 'setClientPassword'}]} set_password1_response = {'responses': [{'command': 'setClientPassword', 'error': 'Invalid/missing username'}]} # Username not a string set_password2_command = { 'commands': [{'command': 'setClientPassword', 'username':5}]} set_password2_response = {'responses': [{'command': 'setClientPassword', 'error': 'Invalid/missing username'}]} # Username not UTF-8 set_password3_command = { 'commands': [{'command': 'setClientPassword', 'username':'￿LO' }] } set_password3_response = {'responses': [{'command': 'setClientPassword', 'error': 'Username not valid UTF-8'}]} # No password set_password4_command = { 'commands': [{'command': 'setClientPassword', 'username':'user'}]} set_password4_response = {'responses': [{'command': 'setClientPassword', 'error': 'Invalid/missing password'}]} # password not a string set_password5_command = { 'commands': [{'command': 'setClientPassword', 'username':'user', 'password':5}]} set_password5_response = {'responses': [{'command': 'setClientPassword', 'error': 'Invalid/missing password'}]} # password is empty set_password6_command = { 'commands': [{'command': 'setClientPassword', 'username':'user', 'password':''}]} set_password6_response = {'responses': [{'command': 'setClientPassword', 'error': 'Empty password is not allowed'}]} # Client not found set_password7_command = { 'commands': [{'command': 'setClientPassword', 'username':'notfound', 'password':'newpw'}]} set_password7_response = {'responses': [{'command': 'setClientPassword', 'error': 'Client not found'}]} # ========================================================================== # Get client # ========================================================================== # No username get_client1_command = { 'commands': [{'command': 'getClient'}]} get_client1_response = {'responses': [{'command': 'getClient', 'error': 'Invalid/missing username'}]} # Username not a string get_client2_command = { 'commands': [{'command': 'getClient', 'username':5}]} get_client2_response = {'responses': [{'command': 'getClient', 'error': 'Invalid/missing username'}]} # Username not UTF-8 get_client3_command = { 'commands': [{'command': 'getClient', 'username':'￿LO' }] } get_client3_response = {'responses': [{'command': 'getClient', 'error': 'Username not valid UTF-8'}]} # Client not found get_client4_command = { 'commands': [{'command': 'getClient', 'username':'notfound'}]} get_client4_response = {'responses': [{'command': 'getClient', 'error': 'Client not found'}]} # ========================================================================== # Add role # ========================================================================== # No username add_role1_command = { 'commands': [{'command': 'addClientRole'}]} add_role1_response = {'responses': [{'command': 'addClientRole', 'error': 'Invalid/missing username'}]} # Username not a string add_role2_command = { 'commands': [{'command': 'addClientRole', 'username':5}]} add_role2_response = {'responses': [{'command': 'addClientRole', 'error': 'Invalid/missing username'}]} # Username not UTF-8 add_role3_command = { 'commands': [{'command': 'addClientRole', 'username':'￿LO' }] } add_role3_response = {'responses': [{'command': 'addClientRole', 'error': 'Username not valid UTF-8'}]} # No rolename add_role4_command = { 'commands': [{'command': 'addClientRole', 'username':'user'}]} add_role4_response = {'responses': [{'command': 'addClientRole', 'error': 'Invalid/missing rolename'}]} # rolename not a string add_role5_command = { 'commands': [{'command': 'addClientRole', 'username':'user', 'rolename':5}]} add_role5_response = {'responses': [{'command': 'addClientRole', 'error': 'Invalid/missing rolename'}]} # rolename not UTF-8 add_role6_command = { 'commands': [{'command': 'addClientRole', 'username':'user', 'rolename':'￿LO' }] } add_role6_response = {'responses': [{'command': 'addClientRole', 'error': 'Role name not valid UTF-8'}]} # Client not found add_role7_command = { 'commands': [{'command': 'addClientRole', 'username':'notfound', 'rolename':'notfound'}]} add_role7_response = {'responses': [{'command': 'addClientRole', 'error': 'Client not found'}]} # Role not found add_role8_command = { 'commands': [{'command': 'addClientRole', 'username':'admin', 'rolename':'notfound'}]} add_role8_response = {'responses': [{'command': 'addClientRole', 'error': 'Role not found'}]} # ========================================================================== # Remove role # ========================================================================== # No username remove_role1_command = { 'commands': [{'command': 'removeClientRole'}]} remove_role1_response = {'responses': [{'command': 'removeClientRole', 'error': 'Invalid/missing username'}]} # Username not a string remove_role2_command = { 'commands': [{'command': 'removeClientRole', 'username':5}]} remove_role2_response = {'responses': [{'command': 'removeClientRole', 'error': 'Invalid/missing username'}]} # Username not UTF-8 remove_role3_command = { 'commands': [{'command': 'removeClientRole', 'username':'￿LO' }] } remove_role3_response = {'responses': [{'command': 'removeClientRole', 'error': 'Username not valid UTF-8'}]} # No rolename remove_role4_command = { 'commands': [{'command': 'removeClientRole', 'username':'user'}]} remove_role4_response = {'responses': [{'command': 'removeClientRole', 'error': 'Invalid/missing rolename'}]} # rolename not a string remove_role5_command = { 'commands': [{'command': 'removeClientRole', 'username':'user', 'rolename':5}]} remove_role5_response = {'responses': [{'command': 'removeClientRole', 'error': 'Invalid/missing rolename'}]} # rolename not UTF-8 remove_role6_command = { 'commands': [{'command': 'removeClientRole', 'username':'user', 'rolename':'￿LO' }] } remove_role6_response = {'responses': [{'command': 'removeClientRole', 'error': 'Role name not valid UTF-8'}]} # Client not found remove_role7_command = { 'commands': [{'command': 'removeClientRole', 'username':'notfound', 'rolename':'notfound'}]} remove_role7_response = {'responses': [{'command': 'removeClientRole', 'error': 'Client not found'}]} # Role not found remove_role8_command = { 'commands': [{'command': 'removeClientRole', 'username':'admin', 'rolename':'notfound'}]} remove_role8_response = {'responses': [{'command': 'removeClientRole', 'error': 'Role not found'}]} # ========================================================================== # Modify client # ========================================================================== # Create a client to modify modify_client0_command = { 'commands': [{'command': 'createClient', 'username':'user'}]} modify_client0_response = {'responses': [{'command': 'createClient'}]} # No username modify_client1_command = { 'commands': [{'command': 'modifyClient'}]} modify_client1_response = {'responses': [{'command': 'modifyClient', 'error': 'Invalid/missing username'}]} # Username not a string modify_client2_command = { 'commands': [{'command': 'modifyClient', 'username':5}]} modify_client2_response = {'responses': [{'command': 'modifyClient', 'error': 'Invalid/missing username'}]} # Username not UTF-8 modify_client3_command = { 'commands': [{'command': 'modifyClient', 'username':'￿LO' }] } modify_client3_response = {'responses': [{'command': 'modifyClient', 'error': 'Username not valid UTF-8'}]} # roles not a list modify_client4_command = { 'commands': [{'command': 'modifyClient', 'username':'user', 'password':'test', 'roles':'string'}]} modify_client4_response = {'responses': [{'command': 'modifyClient', 'error': "'roles' not an array or missing/invalid rolename"}]} # No rolename modify_client5_command = { 'commands': [{'command': 'modifyClient', 'username':'user', 'roles':[{'rolename':5}]}]} modify_client5_response = {'responses': [{'command': 'modifyClient', 'error': "'roles' not an array or missing/invalid rolename"}]} # rolename not UTF-8 #modify_client6_command = { 'commands': [{'command': 'modifyClient', 'username':'user', 'rolename':'￿LO' }] } #modify_client6_response = {'responses': [{'command': 'modifyClient', 'error': 'Username not valid UTF-8'}]} # Client not found modify_client7_command = { 'commands': [{'command': 'modifyClient', 'username':'notfound', 'rolename':'notfound'}]} modify_client7_response = {'responses': [{'command': 'modifyClient', 'error': 'Client not found'}]} # Role not found modify_client8_command = { 'commands': [{'command': 'modifyClient', 'username':'user', 'roles':[{'rolename':'notfound'}]}]} modify_client8_response = {'responses': [{'command': 'modifyClient', 'error': 'Role not found'}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") command_check(sock, create_client1_command, create_client1_response, "1") command_check(sock, create_client2_command, create_client2_response, "2") command_check(sock, create_client3_command, create_client3_response, "3") command_check(sock, create_client4_command, create_client4_response, "4") command_check(sock, create_client5_command, create_client5_response, "5") command_check(sock, create_client6_command, create_client6_response, "6") command_check(sock, create_client7_command, create_client7_response, "7") command_check(sock, create_client8_command, create_client8_response, "8") command_check(sock, create_client9_command, create_client9_response, "9") command_check(sock, create_client10_command, create_client10_response, "10") command_check(sock, create_client11_command, create_client11_response, "11") command_check(sock, create_client12_command, create_client12_response, "12") command_check(sock, delete_client1_command, delete_client1_response, "1") command_check(sock, delete_client2_command, delete_client2_response, "2") #command_check(sock, delete_client3_command, delete_client3_response, "3") command_check(sock, delete_client4_command, delete_client4_response, "4") command_check(sock, disable_client1_command, disable_client1_response, "1") command_check(sock, disable_client2_command, disable_client2_response, "2") command_check(sock, disable_client3_command, disable_client3_response, "3") command_check(sock, disable_client4_command, disable_client4_response, "4") command_check(sock, enable_client1_command, enable_client1_response, "1") command_check(sock, enable_client2_command, enable_client2_response, "2") command_check(sock, enable_client3_command, enable_client3_response, "3") command_check(sock, enable_client4_command, enable_client4_response, "4") command_check(sock, set_client_id1_command, set_client_id1_response, "1") command_check(sock, set_client_id2_command, set_client_id2_response, "2") command_check(sock, set_client_id3_command, set_client_id3_response, "3") command_check(sock, set_client_id4_command, set_client_id4_response, "4") command_check(sock, set_client_id5_command, set_client_id5_response, "5") command_check(sock, set_client_id6_command, set_client_id6_response, "6") command_check(sock, set_client_id7_command, set_client_id7_response, "7") command_check(sock, set_password1_command, set_password1_response, "1") command_check(sock, set_password2_command, set_password2_response, "2") command_check(sock, set_password3_command, set_password3_response, "3") command_check(sock, set_password4_command, set_password4_response, "4") command_check(sock, set_password5_command, set_password5_response, "5") command_check(sock, set_password6_command, set_password6_response, "6") command_check(sock, set_password7_command, set_password7_response, "7") command_check(sock, get_client1_command, get_client1_response, "1") command_check(sock, get_client2_command, get_client2_response, "2") command_check(sock, get_client3_command, get_client3_response, "3") command_check(sock, get_client4_command, get_client4_response, "4") command_check(sock, add_role1_command, add_role1_response, "1") command_check(sock, add_role2_command, add_role2_response, "2") command_check(sock, add_role3_command, add_role3_response, "3") command_check(sock, add_role4_command, add_role4_response, "4") command_check(sock, add_role5_command, add_role5_response, "5") command_check(sock, add_role6_command, add_role6_response, "6") command_check(sock, add_role7_command, add_role7_response, "7") command_check(sock, add_role8_command, add_role8_response, "8") command_check(sock, remove_role1_command, remove_role1_response, "1") command_check(sock, remove_role2_command, remove_role2_response, "2") command_check(sock, remove_role3_command, remove_role3_response, "3") command_check(sock, remove_role4_command, remove_role4_response, "4") command_check(sock, remove_role5_command, remove_role5_response, "5") command_check(sock, remove_role6_command, remove_role6_response, "6") command_check(sock, remove_role7_command, remove_role7_response, "7") command_check(sock, remove_role8_command, remove_role8_response, "8") command_check(sock, modify_client0_command, modify_client0_response, "1") command_check(sock, modify_client1_command, modify_client1_response, "1") command_check(sock, modify_client2_command, modify_client2_response, "2") command_check(sock, modify_client3_command, modify_client3_response, "3") command_check(sock, modify_client4_command, modify_client4_response, "4") command_check(sock, modify_client5_command, modify_client5_response, "5") #command_check(sock, modify_client6_command, modify_client6_response, "6") command_check(sock, modify_client7_command, modify_client7_response, "7") command_check(sock, modify_client8_command, modify_client8_response, "8") rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/02-subpub-qos0-queued-bytes.py0000775000175000017500000000412614060132747022517 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("max_inflight_messages 20\n") f.write("max_inflight_bytes 1000000\n") f.write("max_queued_messages 20\n") f.write("max_queued_bytes 1000000\n") def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos0-bytes", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connect_packet_helper = mosq_test.gen_connect("qos0-bytes-helper", keepalive=keepalive, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos0/queued/bytes", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) publish_packet0 = mosq_test.gen_publish("subpub/qos0/queued/bytes", qos=0, payload="message", proto_ver=proto_ver) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, 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, timeout=4, port=port, connack_error="connack 1") mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") helper = mosq_test.do_client_connect(connect_packet_helper, connack_packet, timeout=4, port=port, connack_error="connack helper") helper.send(publish_packet0) mosq_test.expect_packet(sock, "publish0", publish_packet0) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/14-dynsec-modify-role.py0000775000175000017500000001210014060132747021430 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(expected_response) print(response) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) create_role_command = { "commands": [{ "command": "createRole", "rolename": "role_one", "textname": "Name", "textdescription": "Description", "acls":[ { "acltype": "publishClientSend", "allow": True, "topic": "topic/#", "priority": 8 }, { "acltype": "publishClientSend", "allow": True, "topic": "topic/2/#", "priority": 9 } ], "correlationData": "2" }] } create_role_response = {'responses': [{'command': 'createRole', 'correlationData': '2'}]} modify_role_command = { "commands": [{ "command": "modifyRole", "rolename": "role_one", "textname": "Modified name", "textdescription": "Modified description", "acls":[ { "acltype": "publishClientReceive", "allow": True, "topic": "topic/#", "priority": 2 }, { "acltype": "publishClientReceive", "allow": True, "topic": "topic/2/#", "priority": 1 } ], "correlationData": "3" }] } modify_role_response = {'responses': [{'command': 'modifyRole', 'correlationData': '3'}]} get_role_command1 = { "commands": [{"command": "getRole", "rolename": "role_one"}]} get_role_response1 = {'responses':[{'command': 'getRole', 'data': {'role': {'rolename': 'role_one', 'textname': 'Name', 'textdescription': 'Description', 'acls': [ { "acltype": "publishClientSend", "topic": "topic/2/#", "allow": True, "priority": 9 }, { "acltype": "publishClientSend", "topic": "topic/#", "allow": True, "priority": 8 } ]}}}]} get_role_command2 = { "commands": [{ "command": "getRole", "rolename": "role_one"}]} get_role_response2 = {'responses':[{'command': 'getRole', 'data': {'role': {'rolename': 'role_one', 'textname': 'Modified name', 'textdescription': 'Modified description', 'acls': [ { "acltype": "publishClientReceive", "topic": "topic/#", "allow": True, "priority": 2 }, { "acltype": "publishClientReceive", "topic": "topic/2/#", "allow": True, "priority": 1 } ]}}}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Add role command_check(sock, create_role_command, create_role_response) # Get role command_check(sock, get_role_command1, get_role_response1) # Modify role command_check(sock, modify_role_command, modify_role_response) # Get role command_check(sock, get_role_command2, get_role_response2) # Kill broker and restart, checking whether our changes were saved. 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, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Get role command_check(sock, get_role_command2, get_role_response2) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/02-subpub-qos2-pubrec-error.py0000775000175000017500000000621214060132747022512 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBREC with reason code >= 0x80 is handled correctly from mosq_test_helper import * def helper(port): connect_packet = mosq_test.gen_connect("test-helper", keepalive=60) 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) 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") sock.close() def do_test(): 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") helper(port) # Should have now received a publish command mosq_test.expect_packet(sock, "publish 1", publish_1_packet) sock.send(pubrec_1_packet) 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test() exit(0) mosquitto-2.0.11/test/broker/08-ssl-connect-identity.py0000775000175000017500000000327314060132747022014 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/02-subpub-qos1-nolocal.py0000775000175000017500000000412414060132747021531 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 * def do_test(): 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") sock.send(publish2_packet) mosq_test.receive_unordered(sock, puback2_packet, publish3_packet, "puback2/publish3") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() exit(0) mosquitto-2.0.11/test/broker/01-connect-uname-password-denied-no-will.py0000775000175000017500000000520114060132747025120 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') def do_test(proto_ver): 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", proto_ver=proto_ver) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, topic="will/test", qos=0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) connect2_packet = mosq_test.gen_connect("connect-uname-pwd-test", keepalive=keepalive, username="user", password="password9", proto_ver=proto_ver) if proto_ver == 5: connack2_packet = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=proto_ver, properties=None) else: connack2_packet = mosq_test.gen_connack(rc=5, proto_ver=proto_ver) 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 except mosq_test.TestError: pass finally: os.remove(conf_file) os.remove(pw_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/07-will-delay-reconnect.py0000775000175000017500000000440414060132747021752 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() mosquitto-2.0.11/test/broker/dynamic-security-init.json0000664000175000017500000000233514060132747022256 0ustar rogerroger{ "clients": [{ "username": "admin", "textName": "Dynsec admin user", "password": "Rko31yHY12ryMoyZTBNIUsCPb5SDa4WmUP3Xe2+V6P+QOSW3Gj6IDmpl6zQsAjutb476zEYdBeTw9tU7WZ1new==", "salt": "Ezuo4G1TqYtTQDL/", "iterations": 101, "roles": [{ "rolename": "admin" }] }], "roles": [{ "rolename": "admin", "acls": [{ "acltype": "publishClientSend", "topic": "$CONTROL/dynamic-security/#", "allow": true }, { "acltype": "publishClientReceive", "topic": "$CONTROL/dynamic-security/#", "allow": true }, { "acltype": "subscribePattern", "topic": "$CONTROL/dynamic-security/#", "allow": true }, { "acltype": "publishClientReceive", "topic": "$SYS/#", "allow": true }, { "acltype": "subscribePattern", "topic": "$SYS/#", "allow": true }, { "acltype": "publishClientReceive", "topic": "#", "allow": true }, { "acltype": "subscribePattern", "topic": "#", "allow": true }, { "acltype": "unsubscribePattern", "topic": "#", "allow": true }] }], "defaultACLAccess": { "publishClientSend": false, "publishClientReceive": true, "subscribe": false, "unsubscribe": true } }mosquitto-2.0.11/test/broker/02-subpub-qos2-1322.py0000775000175000017500000001440214060132747020472 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 * def do_test(proto_ver): rc = 1 keepalive = 60 pub_connect_packet = mosq_test.gen_connect("pub", keepalive=keepalive, clean_session=False, proto_ver=proto_ver, session_expiry=60) pub_connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) pub_connack2_packet = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) sub1_connect_packet = mosq_test.gen_connect("sub1", keepalive=keepalive, proto_ver=proto_ver) sub1_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) sub2_connect_packet = mosq_test.gen_connect("sub2", keepalive=keepalive, proto_ver=proto_ver) sub2_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid, "topic1", 0, proto_ver=proto_ver) suback1_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) mid = 1 subscribe2_packet = mosq_test.gen_subscribe(mid, "topic2", 0, proto_ver=proto_ver) suback2_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) # All publishes have the same mid mid = 1 pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) publish1s_packet = mosq_test.gen_publish("topic1", qos=2, mid=mid, payload="message1", proto_ver=proto_ver) publish2s_packet = mosq_test.gen_publish("topic2", qos=2, mid=mid, payload="message2", proto_ver=proto_ver) publish3s_packet = mosq_test.gen_publish("topic1", qos=2, mid=mid, payload="message3", proto_ver=proto_ver) publish4s_packet = mosq_test.gen_publish("topic1", qos=2, mid=mid, payload="message4", proto_ver=proto_ver) publish5s_packet = mosq_test.gen_publish("topic1", qos=2, mid=mid, payload="message5", proto_ver=proto_ver) publish1r_packet = mosq_test.gen_publish("topic1", qos=0, payload="message1", proto_ver=proto_ver) publish2r_packet = mosq_test.gen_publish("topic2", qos=0, payload="message2", proto_ver=proto_ver) publish3r_packet = mosq_test.gen_publish("topic1", qos=0, payload="message3", proto_ver=proto_ver) publish4r_packet = mosq_test.gen_publish("topic1", qos=0, payload="message4", proto_ver=proto_ver) publish5r_packet = mosq_test.gen_publish("topic1", qos=0, payload="message5", proto_ver=proto_ver) 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() 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() 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") 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") mosq_test.expect_packet(sub1, "publish5", publish5r_packet) rc = 0 sub2.close() sub1.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/06-bridge-fail-persist-resend-qos2.py0000775000175000017500000000714714060132747023733 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, protocol_version): 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") f.write("bridge_protocol_version %s\n" % (protocol_version)) def do_test(proto_ver): if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, bridge_protocol) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("bridge-u-test", keepalive=keepalive, proto_ver=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 180 mid_unknown = 2000 publish_packet = mosq_test.gen_publish("bridge/unknown/qos2", qos=1, payload="bridge-message", mid=mid, proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) pubrec_packet_unknown1 = mosq_test.gen_pubrec(mid_unknown+1, proto_ver=proto_ver) pubrel_packet_unknown1 = mosq_test.gen_pubrel(mid_unknown+1, proto_ver=proto_ver) pubrel_packet_unknown2 = mosq_test.gen_pubrel(mid_unknown+2, proto_ver=proto_ver) pubcomp_packet_unknown2 = mosq_test.gen_pubcomp(mid_unknown+2, proto_ver=proto_ver) pubcomp_packet_unknown3 = mosq_test.gen_pubcomp(mid_unknown+3, proto_ver=proto_ver) unsubscribe_packet = mosq_test.gen_unsubscribe(1, "bridge/#", proto_ver=proto_ver) unsuback_packet = mosq_test.gen_unsuback(1, proto_ver=proto_ver) 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) mosq_test.expect_packet(conn, "connect", connect_packet) conn.send(connack_packet) mosq_test.expect_packet(conn, "unsubscribe", unsubscribe_packet) conn.send(unsuback_packet) # Send the unexpected pubrec packet conn.send(pubrec_packet_unknown1) mosq_test.expect_packet(conn, "pubrel", pubrel_packet_unknown1) conn.send(pubrel_packet_unknown2) 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) mosq_test.expect_packet(conn, "puback", puback_packet) rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() sock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subpub-qos2-bad-pubcomp.py0000775000175000017500000000525514060132747022302 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 * def helper(port, proto_ver): connect_packet = mosq_test.gen_connect("helper", keepalive=60, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish1s_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message", proto_ver=proto_ver) pubrec1s_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel1s_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp1s_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, publish1s_packet, pubrec1s_packet, "pubrec 1s") mosq_test.do_send_receive(sock, pubrel1s_packet, pubcomp1s_packet, "pubcomp 1s") sock.close() def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos2-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos2", 2, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 1 publish1r_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message", proto_ver=proto_ver) pubcomp1r_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) 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(port, proto_ver) 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/01-connect-duplicate.py0000775000175000017500000000202514060132747021321 0ustar rogerroger#!/usr/bin/env python3 # Test whether a duplicate CONNECT is rejected. from mosq_test_helper import * def do_test(proto_ver): rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=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) sock.settimeout(3) sock.send(connect_packet) data = sock.recv(1) if len(data) == 0: rc = 0 except socket.error: rc = 0 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/08-ssl-connect-cert-auth-revoked.py0000775000175000017500000000344114060132747023511 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("allow_anonymous true\n") f.write("listener %d\n" % (port1)) f.write("allow_anonymous true\n") 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) except mosq_test.TestError: pass 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-2.0.11/test/broker/01-connect-uname-no-password-denied.pwfile0000664000175000017500000000016214060132747025007 0ustar rogerrogeruser:$6$Ut1cUS9PG8+gC3vn$tOjCfSJJDe1Alu9HktxxyyzwN4+6mAMSWGRAF9gmMN8pzcGTPVEYYMAZpCEp96Oz2ZRRz5YKM6lPMf1tUbb6zA== mosquitto-2.0.11/test/broker/10-listener-mount-point.py0000775000175000017500000000447414060132747022046 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("allow_anonymous true\n") f.write("\n") f.write("listener %d\n" % (port2)) f.write("allow_anonymous true\n") f.write("mount_point mount/\n") f.write("\n") f.write("log_type debug\n") def helper(port, proto_ver): connect_packet = mosq_test.gen_connect("test-helper", keepalive=60, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("test", qos=0, payload="mount point", proto_ver=proto_ver) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port, connack_error="helper connack") sock.send(publish_packet) sock.close() def do_test(proto_ver): (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, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("mount/test", qos=0, payload="mount point", proto_ver=proto_ver) 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") helper(port2, proto_ver) # Should have now received a publish command mosq_test.expect_packet(sock, "publish", publish_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/09-extended-auth-unsupported.py0000775000175000017500000000166014060132747023061 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/11-persistent-subscription-v5.py0000775000175000017500000000455414060132747023204 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("allow_anonymous true\n") 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, proto_ver=5, session_expiry=60 ) 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) sock.send(publish_packet) mosq_test.receive_unordered(sock, puback_packet, publish_packet2, "puback/publish2") rc = 0 sock.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/02-subpub-qos2-receive-maximum-helper.py0000775000175000017500000000425414060132747024461 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 * def do_test(proto_ver): if proto_ver == 4: exit(0) 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() except mosq_test.TestError: pass finally: if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=5) exit(rc) mosquitto-2.0.11/test/broker/12-prop-assigned-client-identifier.py0000775000175000017500000000314214060132747024072 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/07-will-invalid-utf8.py0000775000175000017500000000204014060132747021202 0ustar rogerroger#!/usr/bin/env python3 # Test whether a will topic with invalid UTF-8 fails from mosq_test_helper import * def do_test(proto_ver): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("will-invalid-utf8", keepalive=keepalive, will_topic="invalid/utf8", proto_ver=proto_ver) 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subpub-qos2-bad-puback-1.py0000775000175000017500000000525114060132747022234 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 * def helper(port, proto_ver): connect_packet = mosq_test.gen_connect("helper", keepalive=60, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish1s_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message", proto_ver=proto_ver) pubrec1s_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel1s_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp1s_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, publish1s_packet, pubrec1s_packet, "pubrec 1s") mosq_test.do_send_receive(sock, pubrel1s_packet, pubcomp1s_packet, "pubcomp 1s") sock.close() def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos2-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos2", 2, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 1 publish1r_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message", proto_ver=proto_ver) puback1r_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) 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(port, proto_ver) 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/03-pattern-matching.py0000775000175000017500000000600014060132747021164 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * def helper(port, pub_topic): connect_packet = mosq_test.gen_connect("test-helper", keepalive=60) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish(pub_topic, 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) sock.close() 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") helper(port, pub_topic) 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") mosq_test.expect_packet(sock, "publish retained", publish_retained_packet) rc = 0 sock.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/02-subpub-qos0.py0000775000175000017500000000260714060132747020107 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 do_test(proto_ver): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos0-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos0", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("subpub/qos0", qos=0, payload="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(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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subpub-qos2.py0000775000175000017500000000434714060132747020114 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 do_test(proto_ver): rc = 1 mid = 530 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos2-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos2", 2, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 301 publish_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message", proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) mid = 1 publish_packet2 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message", proto_ver=proto_ver) pubrec_packet2 = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel_packet2 = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp_packet2 = mosq_test.gen_pubcomp(mid, 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, 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") sock.send(pubrel_packet) mosq_test.receive_unordered(sock, pubcomp_packet, publish_packet2, "pubcomp/publish2") 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/14-dynsec-disable-client.py0000775000175000017500000001070114060132747022066 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(expected_response) print(response) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) add_client_command = { "commands": [{ "command": "createClient", "username": "user_one", "password": "password", "clientid": "cid", "textname": "Name", "textdescription": "Description", "rolename": "", "correlationData": "2" }] } add_client_response = {'responses': [{'command': 'createClient', 'correlationData': '2'}]} add_client_repeat_response = {'responses':[{"command":"createClient","error":"Client already exists", "correlationData":"2"}]} get_client_command = { "commands": [{ "command": "getClient", "username": "user_one"}]} get_client_response1 = {'responses':[{'command': 'getClient', 'data': {'client': {'username': 'user_one', 'clientid': 'cid', 'textname': 'Name', 'textdescription': 'Description', 'groups': [], 'roles': []}}}]} get_client_response2 = {'responses':[{'command': 'getClient', 'data': {'client': {'username': 'user_one', 'clientid': 'cid', 'textname': 'Name', 'textdescription': 'Description', 'disabled':True, 'groups': [], 'roles': []}}}]} disable_client_command = { "commands": [{ "command": "disableClient", "username": "user_one"}]} disable_client_response = {'responses':[{'command': 'disableClient'}]} enable_client_command = { "commands": [{ "command": "enableClient", "username": "user_one"}]} enable_client_response = {'responses':[{'command': 'enableClient'}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) client_connect_packet = mosq_test.gen_connect("cid", keepalive=keepalive, username="user_one", password="password") client_connack_packet1 = mosq_test.gen_connack(rc=5) client_connack_packet2 = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Add client command_check(sock, add_client_command, add_client_response) # Get client command_check(sock, get_client_command, get_client_response1) # Disable client command_check(sock, disable_client_command, disable_client_response) # Get client - should be disabled command_check(sock, get_client_command, get_client_response2) # Try to log in - should fail client_sock = mosq_test.do_client_connect(client_connect_packet, client_connack_packet1, timeout=5, port=port) # Enable client command_check(sock, enable_client_command, enable_client_response) # Get client - should be enabled command_check(sock, get_client_command, get_client_response1) # Try to log in - should succeed client_sock = mosq_test.do_client_connect(client_connect_packet, client_connack_packet2, timeout=5, port=port) client_sock.close() rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/09-plugin-auth-context-params.py0000775000175000017500000000270714060132747023137 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/08-ssl-hup-disconnect.py0000775000175000017500000000470514060132747021460 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/14-dynsec-anon-group.py0000775000175000017500000001315114060132747021276 0ustar rogerroger#!/usr/bin/env python3 # Test the anonymous group support by adding a group, setting the anon group, adding a role to the group and checking a subscription. from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(expected_response) print(response) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) get_anon_group_none_command = { "commands": [{ "command": "getAnonymousGroup", "correlationData": "2" }] } get_anon_group_none_response = {'responses': [{'command': 'getAnonymousGroup', 'data': {'group': {'groupname': ''}}, 'correlationData': '2'}]} create_group_set_anon_command = { "commands": [ { "command": "createGroup", "groupname": "anon-clients", "correlationData": "3" }, { "command": "setAnonymousGroup", "groupname": "anon-clients", "correlationData": "4" } ] } create_group_set_anon_response = {'responses': [ {'command': 'createGroup', 'correlationData': '3'}, {'command': 'setAnonymousGroup', 'correlationData': '4'}, ]} get_anon_group_command = { "commands": [{ "command": "getAnonymousGroup", "correlationData": "3" }] } get_anon_group_response = {'responses': [{'command': 'getAnonymousGroup', 'data': {'group': {'groupname': 'anon-clients'}}, 'correlationData': '3'}]} create_role_apply_command = { "commands": [ { "command": "createRole", "rolename": "anon", "correlationData": "4" }, { "command": "addRoleACL", "rolename": "anon", "acltype": "subscribeLiteral", "topic": "anon/topic", "allow": True, "correlationData": "5" }, { "command": "addGroupRole", "groupname": "anon-clients", "rolename": "anon", "correlationData": "6"} ] } create_role_apply_response = {'responses': [ {'command': 'createRole', 'correlationData': '4'}, {'command': 'addRoleACL', 'correlationData': '5'}, {'command': 'addGroupRole', 'correlationData': '6'} ]} rc = 1 keepalive = 10 # Admin connect_packet_admin = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet_admin = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet_admin = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet_admin = mosq_test.gen_suback(mid, 1) # Client connect_packet = mosq_test.gen_connect("cid", 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, "anon/topic", qos=1, proto_ver=5) suback_packet_fail = mosq_test.gen_suback(mid, mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5) suback_packet_success = mosq_test.gen_suback(mid, 1, proto_ver=5) disconnect_packet_kick = mosq_test.gen_disconnect(reason_code=mqtt5_rc.MQTT_RC_ADMINISTRATIVE_ACTION, proto_ver=5) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet_admin, connack_packet_admin, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet_admin, suback_packet_admin, "suback admin") # Add client command_check(sock, get_anon_group_none_command, get_anon_group_none_response) # Client is anon, there is no anon group, so subscribe should fail csock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) mosq_test.do_send_receive(csock, subscribe_packet, suback_packet_fail, "suback 1") # Add group, and set to anon command_check(sock, create_group_set_anon_command, create_group_set_anon_response) command_check(sock, get_anon_group_command, get_anon_group_response) # Anon group is changed, so we are kicked mosq_test.expect_packet(csock, "disconnect 1", disconnect_packet_kick) csock.close() # Reconnect, subscribe should still fail csock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) mosq_test.do_send_receive(csock, subscribe_packet, suback_packet_fail, "suback 2") # Add role with subscribe ACL, and apply to anon group command_check(sock, create_role_apply_command, create_role_apply_response) # Anon group is changed, so we are kicked mosq_test.expect_packet(csock, "disconnect 2", disconnect_packet_kick) csock.close() # Reconnect, subscribe should now succeed csock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) mosq_test.do_send_receive(csock, subscribe_packet, suback_packet_success, "suback 3") rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/09-extended-auth-single.py0000775000175000017500000000705714060132747021760 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 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/02-subhier-crash.py0000775000175000017500000000270514060132747020465 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/02-unsubscribe-qos0.py0000775000175000017500000000256514060132747021136 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 * def do_test(proto_ver): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-qos0-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "qos0/test", proto_ver=proto_ver) if proto_ver == 5: unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=proto_ver, reason_code=17) else: unsuback_packet = mosq_test.gen_unsuback(mid, 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, unsubscribe_packet, unsuback_packet, "unsuback") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/07-will-delay-recover.py0000775000175000017500000000435514060132747021444 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/09-extended-auth-change-username.py0000775000175000017500000000646314060132747023541 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("allow_anonymous true\n") 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") sock.send(publish2s_packet) mosq_test.receive_unordered(sock, puback2s_packet, publish2r_packet, "puback2/publish2") mosq_test.do_ping(sock) rc = 0 sock.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/12-prop-server-keepalive.py0000775000175000017500000000231214060132747022150 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("allow_anonymous true\n") 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 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/14-dynsec-acl.py0000775000175000017500000003614014060132747017753 0ustar rogerroger#!/usr/bin/env python3 # Test ACL for allow/deny. This does not consider ACL priority and the ACLs do not overlap. from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous false\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(expected_response) print(response) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) add_client_command_with_id = { "commands": [{ "command": "createClient", "username": "user_one", "password": "password", "clientid": "cid", "correlationData": "2" }] } add_client_response_with_id = {'responses': [{'command': 'createClient', 'correlationData': '2'}]} add_client_group_role_command = {"commands":[ { "command": "createGroup", "groupname": "mygroup" }, { "command": "createRole", "rolename": "myrole" }, { "command": "addGroupRole", "groupname": "mygroup", "rolename": "myrole" }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "subscribeLiteral", "topic": "simple/topic", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "subscribePattern", "topic": "single-wildcard/+/topic", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "subscribePattern", "topic": "multilevel-wildcard/#", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "unsubscribeLiteral", "topic": "simple/topic", "allow": False }, { "command": "addGroupClient", "groupname": "mygroup", "username": "user_one" } ]} add_client_group_role_response = {'responses': [ {'command': 'createGroup'}, {'command': 'createRole'}, {'command': 'addGroupRole'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addGroupClient'} ]} add_publish_acl_command = {"commands":[ { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientSend", "topic": "simple/topic", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientSend", "topic": "single-wildcard/deny/deny", "priority":10, "allow": False }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientSend", "topic": "single-wildcard/+/+", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientSend", "topic": "multilevel-wildcard/topic/#", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientReceive", "topic": "single-wildcard/bob/bob", "allow": False }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientReceive", "topic": "multilevel-wildcard/topic/topic/denied", "allow": False }, ]} add_publish_acl_response = {'responses': [ {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'} ]} delete_role_command = {"commands":[ { "command": "deleteRole", "rolename": "myrole"} ]} delete_role_response = {'responses': [{'command': 'deleteRole'}]} rc = 1 keepalive = 10 connect_packet_admin = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet_admin = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet_admin = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet_admin = mosq_test.gen_suback(mid, 1) # Success connect_packet_with_id1 = mosq_test.gen_connect("cid", keepalive=keepalive, username="user_one", password="password", proto_ver=5) connack_packet_with_id1 = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 4 subscribe_simple_packet = mosq_test.gen_subscribe(mid, "simple/topic", 0, proto_ver=5) suback_simple_packet_success = mosq_test.gen_suback(mid, 0, proto_ver=5) suback_simple_packet_fail = mosq_test.gen_suback(mid, mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5) mid = 5 subscribe_single_packet = mosq_test.gen_subscribe(mid, "single-wildcard/bob/topic", 0, proto_ver=5) suback_single_packet_success = mosq_test.gen_suback(mid, 0, proto_ver=5) suback_single_packet_fail = mosq_test.gen_suback(mid, mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5) mid = 6 subscribe_multi_packet = mosq_test.gen_subscribe(mid, "multilevel-wildcard/topic/topic/#", 0, proto_ver=5) suback_multi_packet_success = mosq_test.gen_suback(mid, 0, proto_ver=5) suback_multi_packet_fail = mosq_test.gen_suback(mid, mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5) mid = 7 publish_simple_packet = mosq_test.gen_publish(mid=mid, topic="simple/topic", qos=1, payload="message", proto_ver=5) puback_simple_packet_success = mosq_test.gen_puback(mid, proto_ver=5) puback_simple_packet_fail = mosq_test.gen_puback(mid, reason_code=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5) publish_simple_packet_r = mosq_test.gen_publish(topic="simple/topic", qos=0, payload="message", proto_ver=5) # This message is in single-wildcard/+/+ so could be allowed, but the single-wildcard/deny/deny with higher priority should override mid = 9 publish_single_packet_denied = mosq_test.gen_publish(mid=mid, topic="single-wildcard/deny/deny", qos=1, payload="message", proto_ver=5) puback_single_packet_denied_fail = mosq_test.gen_puback(mid, reason_code=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5) mid = 8 publish_single_packet = mosq_test.gen_publish(mid=mid, topic="single-wildcard/bob/topic", qos=1, payload="message", proto_ver=5) puback_single_packet_success = mosq_test.gen_puback(mid, proto_ver=5) puback_single_packet_fail = mosq_test.gen_puback(mid, reason_code=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5) publish_single_packet_r = mosq_test.gen_publish(topic="single-wildcard/bob/topic", qos=0, payload="message", proto_ver=5) mid = 9 publish_multi_packet = mosq_test.gen_publish(mid=mid, topic="multilevel-wildcard/topic/topic/allowed", qos=1, payload="message", proto_ver=5) puback_multi_packet_success = mosq_test.gen_puback(mid, proto_ver=5) puback_multi_packet_fail = mosq_test.gen_puback(mid, reason_code=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5) mid = 10 publish_multi_denied_packet = mosq_test.gen_publish(mid=mid, topic="multilevel-wildcard/topic/topic/denied", qos=1, payload="message", proto_ver=5) puback_multi_denied_packet = mosq_test.gen_puback(mid, proto_ver=5) publish_multi_packet_r = mosq_test.gen_publish(topic="multilevel-wildcard/topic/topic/allowed", qos=0, payload="message", proto_ver=5) mid = 11 unsubscribe_simple_packet = mosq_test.gen_unsubscribe(mid, "simple/topic", proto_ver=5) unsuback_simple_packet_fail = mosq_test.gen_unsuback(mid, mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5) mid = 12 unsubscribe_single_packet = mosq_test.gen_unsubscribe(mid, "single-wildcard/bob/topic", proto_ver=5) unsuback_single_packet_success = mosq_test.gen_unsuback(mid, 0, proto_ver=5) mid = 13 unsubscribe_multi_packet = mosq_test.gen_unsubscribe(mid, "multilevel-wildcard/topic/topic/#", proto_ver=5) unsuback_multi_packet_success = mosq_test.gen_unsuback(mid, 0, proto_ver=5) disconnect_kick_packet = mosq_test.gen_disconnect(reason_code=mqtt5_rc.MQTT_RC_ADMINISTRATIVE_ACTION, proto_ver=5) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet_admin, connack_packet_admin, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet_admin, suback_packet_admin, "suback") # Add client command_check(sock, add_client_command_with_id, add_client_response_with_id) # Client with username, password, and client id csock = mosq_test.do_client_connect(connect_packet_with_id1, connack_packet_with_id1, timeout=5, port=port, connack_error="connack 1") # Subscribe to "simple/topic" - not allowed mosq_test.do_send_receive(csock, subscribe_simple_packet, suback_simple_packet_fail, "suback simple 1") # Subscribe to "single-wildcard/bob/topic" - not allowed mosq_test.do_send_receive(csock, subscribe_single_packet, suback_single_packet_fail, "suback single 1") # Subscribe to "multilevel-wildcard/topic/topic/topic" - not allowed mosq_test.do_send_receive(csock, subscribe_multi_packet, suback_multi_packet_fail, "suback multi 1") # Publish to "simple/topic" - not allowed mosq_test.do_send_receive(csock, publish_simple_packet, puback_simple_packet_fail, "puback simple 1") # Publish to "single-wildcard/bob/topic" - not allowed mosq_test.do_send_receive(csock, publish_single_packet, puback_single_packet_fail, "puback single 1") # Publish to "multilevel-wildcard/topic/topic/topic" - not allowed mosq_test.do_send_receive(csock, publish_multi_packet, puback_multi_packet_fail, "puback multi 1") # Create a group, add a role to the group, add the client to the group # Add some subscribe/unsubscribe ACLs - this will kick the client command_check(sock, add_client_group_role_command, add_client_group_role_response) mosq_test.expect_packet(csock, "disconnect kick 1", disconnect_kick_packet) csock.close() # Reconnect csock = mosq_test.do_client_connect(connect_packet_with_id1, connack_packet_with_id1, timeout=5, port=port, connack_error="connack 2") # Subscribe to "simple/topic" - this is now allowed mosq_test.do_send_receive(csock, subscribe_simple_packet, suback_simple_packet_success, "suback simple 2") # Subscribe to "single-wildcard/bob/topic" - this is now allowed mosq_test.do_send_receive(csock, subscribe_single_packet, suback_single_packet_success, "suback single 2") # Subscribe to "multilevel-wildcard/topic/topic/topic" - this is now allowed mosq_test.do_send_receive(csock, subscribe_multi_packet, suback_multi_packet_success, "suback multi 2") # Publish to "simple/topic" - not allowed mosq_test.do_send_receive(csock, publish_simple_packet, puback_simple_packet_fail, "puback 2") # Publish to "single-wildcard/bob/topic" - not allowed mosq_test.do_send_receive(csock, publish_single_packet, puback_single_packet_fail, "puback single 2") # Publish to "multilevel-wildcard/topic/topic/topic" - not allowed mosq_test.do_send_receive(csock, publish_multi_packet, puback_multi_packet_fail, "puback multi 2") # Add some publish ACLs - this will kick the client command_check(sock, add_publish_acl_command, add_publish_acl_response) mosq_test.expect_packet(csock, "disconnect kick 2", disconnect_kick_packet) csock.close() # Reconnect csock = mosq_test.do_client_connect(connect_packet_with_id1, connack_packet_with_id1, timeout=5, port=port, connack_error="connack 3") # Subscribe to "simple/topic" - this is now allowed mosq_test.do_send_receive(csock, subscribe_simple_packet, suback_simple_packet_success, "suback simple 3") # Subscribe to "single-wildcard/bob/topic" - this is now allowed mosq_test.do_send_receive(csock, subscribe_single_packet, suback_single_packet_success, "suback single 3") # Subscribe to "multilevel-wildcard/topic/topic/allowed" - this is now allowed mosq_test.do_send_receive(csock, subscribe_multi_packet, suback_multi_packet_success, "suback multi 3") # Publish to "simple/topic" - this is now allowed csock.send(publish_simple_packet) mosq_test.receive_unordered(csock, publish_simple_packet_r, puback_simple_packet_success, "puback simple 3 / publish r") # Publish to "single-wildcard/bob/topic" - this is now allowed csock.send(publish_single_packet) mosq_test.receive_unordered(csock, publish_single_packet_r, puback_single_packet_success, "puback single 3 / publish r") # Publish to "single-wildcard/deny/deny" - this is stillnot allowed mosq_test.do_send_receive(csock, publish_single_packet_denied, puback_single_packet_denied_fail, "puback single denied 1") # Publish to "multilevel-wildcard/topic/topic/allowed" - this is now allowed csock.send(publish_multi_packet) mosq_test.receive_unordered(csock, publish_multi_packet_r, puback_multi_packet_success, "puback multi 3 / publish r") # Publish to "multilevel-wildcard/topic/topic/denied" - receiving is denied by publishClientReceive mosq_test.do_send_receive(csock, publish_multi_denied_packet, puback_multi_denied_packet, "puback multi denied") mosq_test.do_ping(csock) # Simple unsubscribe should be denied mosq_test.do_send_receive(csock, unsubscribe_simple_packet, unsuback_simple_packet_fail, "unsuback simple 1") # Single unsubscribe should be allowed mosq_test.do_send_receive(csock, unsubscribe_single_packet, unsuback_single_packet_success, "unsuback single 1") # Multi unsubscribe should be allowed mosq_test.do_send_receive(csock, unsubscribe_multi_packet, unsuback_multi_packet_success, "unsuback multi 1") # Delete the role, client should be kicked command_check(sock, delete_role_command, delete_role_response) mosq_test.expect_packet(csock, "disconnect kick 3", disconnect_kick_packet) csock.close() # Reconnect - these should all be denied again. csock = mosq_test.do_client_connect(connect_packet_with_id1, connack_packet_with_id1, timeout=5, port=port, connack_error="connack 4") # Subscribe to "simple/topic" - not allowed mosq_test.do_send_receive(csock, subscribe_simple_packet, suback_simple_packet_fail, "suback simple 4") # Subscribe to "single-wildcard/bob/topic" - not allowed mosq_test.do_send_receive(csock, subscribe_single_packet, suback_single_packet_fail, "suback single 4") # Subscribe to "multilevel-wildcard/topic/topic/topic" - not allowed mosq_test.do_send_receive(csock, subscribe_multi_packet, suback_multi_packet_fail, "suback multi 4") # Publish to "simple/topic" - not allowed mosq_test.do_send_receive(csock, publish_simple_packet, puback_simple_packet_fail, "puback simple 4") # Publish to "single-wildcard/bob/topic" - not allowed mosq_test.do_send_receive(csock, publish_single_packet, puback_single_packet_fail, "puback single 4") # Publish to "multilevel-wildcard/topic/topic/topic" - not allowed mosq_test.do_send_receive(csock, publish_multi_packet, puback_multi_packet_fail, "puback multi 4") csock.close() rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) publishClientSend publishClientReceive subscribeLiteral subscribePattern mosquitto-2.0.11/test/broker/09-plugin-auth-acl-pub.py0000775000175000017500000000452614060132747021516 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, plugin_ver): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v%d.so\n" % (plugin_ver)) f.write("allow_anonymous false\n") def do_test(plugin_ver): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, plugin_ver) 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) mosquitto-2.0.11/test/broker/14-dynsec-default-access.py0000775000175000017500000001670014060132747022077 0ustar rogerroger#!/usr/bin/env python3 # This tests the default ACL type access behaviour for when no ACL matches. from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous false\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print("Expected: %s" % (expected_response)) print("Received: %s" % (response)) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) add_client_command = { "commands": [{ "command": "createClient", "username": "user_one", "password": "password", "clientid": "cid", "correlationData": "2" }] } add_client_response = {'responses': [{'command': 'createClient', 'correlationData': '2'}]} get_access_command = { "commands": [{"command": "getDefaultACLAccess", "correlationData": "3" }]} get_access_response = {'responses': [ { "command": "getDefaultACLAccess", 'data': {'acls': [ {'acltype': 'publishClientSend', 'allow': False}, {'acltype': 'publishClientReceive', 'allow': True}, {'acltype': 'subscribe', 'allow': False}, {'acltype': 'unsubscribe', 'allow': True} ]}, "correlationData": "3" }] } allow_subscribe_command = { "commands": [ { "command": "setDefaultACLAccess", "acls":[ { "acltype": "subscribe", "allow": True } ], "correlationData": "4" } ] } allow_subscribe_response = {'responses': [{'command': 'setDefaultACLAccess', 'correlationData': '4'}]} allow_publish_send_command = { "commands": [ { "command": "setDefaultACLAccess", "acls":[ { "acltype": "publishClientSend", "allow": True } ], "correlationData": "5" } ] } allow_publish_send_response = {'responses': [{'command': 'setDefaultACLAccess', 'correlationData': '5'}]} allow_publish_recv_command = { "commands": [ { "command": "setDefaultACLAccess", "acls":[ { "acltype": "publishClientReceive", "allow": False } ], "correlationData": "6" } ] } allow_publish_recv_response = {'responses': [{'command': 'setDefaultACLAccess', 'correlationData': '6'}]} allow_unsubscribe_command = { "commands": [ { "command": "setDefaultACLAccess", "acls":[ { "acltype": "unsubscribe", "allow": False } ], "correlationData": "7" } ] } allow_unsubscribe_response = {'responses': [{'command': 'setDefaultACLAccess', 'correlationData': '7'}]} rc = 1 keepalive = 10 connect_packet_admin = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet_admin = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet_admin = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet_admin = mosq_test.gen_suback(mid, 1) connect_packet = mosq_test.gen_connect("cid", keepalive=keepalive, username="user_one", password="password", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 3 subscribe_packet = mosq_test.gen_subscribe(mid, "topic", 0, proto_ver=5) suback_packet_fail = mosq_test.gen_suback(mid, mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5) suback_packet_success = mosq_test.gen_suback(mid, 0, proto_ver=5) mid = 4 unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "topic", proto_ver=5) unsuback_packet_fail = mosq_test.gen_unsuback(mid, mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5) unsuback_packet_success = mosq_test.gen_unsuback(mid, proto_ver=5) mid = 5 publish_packet = mosq_test.gen_publish(topic="topic", mid=mid, qos=1, payload="message", proto_ver=5) puback_packet_fail = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED) puback_packet_success = mosq_test.gen_puback(mid, proto_ver=5) publish_packet_recv = mosq_test.gen_publish(topic="topic", qos=0, payload="message", proto_ver=5) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sock = mosq_test.do_client_connect(connect_packet_admin, connack_packet_admin, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet_admin, suback_packet_admin, "admin suback") # Add client command_check(sock, add_client_command, add_client_response) command_check(sock, get_access_command, get_access_response) csock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Subscribe should fail because default access is deny mosq_test.do_send_receive(csock, subscribe_packet, suback_packet_fail, "suback fail") # Set default subscribe access to allow command_check(sock, allow_subscribe_command, allow_subscribe_response) # Subscribe should succeed because default access is now allowed mosq_test.do_send_receive(csock, subscribe_packet, suback_packet_success, "suback success") # Publish should fail because publishClientSend default is denied mosq_test.do_send_receive(csock, publish_packet, puback_packet_fail, "puback fail") # Set default publish send access to allow command_check(sock, allow_publish_send_command, allow_publish_send_response) # Publish should now succeed because publishClientSend default is allow # We also receive the message because publishClientReceive default is allow. csock.send(publish_packet) mosq_test.receive_unordered(csock, puback_packet_success, publish_packet_recv, "puback success / publish recv") # Set default publish receive access to deny command_check(sock, allow_publish_recv_command, allow_publish_recv_response) # Publish should succeed because publishClientSend default is allow # We should *not* receive the publish because it has been disabled. mosq_test.do_send_receive(csock, publish_packet, puback_packet_success, "puback success") mosq_test.do_ping(csock) # Unsubscribe should succeed because default access is allowed mosq_test.do_send_receive(csock, unsubscribe_packet, unsuback_packet_success, "unsuback success") # Set default unsubscribe access to allow command_check(sock, allow_unsubscribe_command, allow_unsubscribe_response) # Subscribe should succeed because default access is allowed mosq_test.do_send_receive(csock, subscribe_packet, suback_packet_success, "suback success 2") # Unsubscribe should fail because default access is no longer allowed mosq_test.do_send_receive(csock, unsubscribe_packet, unsuback_packet_fail, "unsuback fail") csock.close() rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/08-ssl-connect-cert-auth-expired.py0000775000175000017500000000335714060132747023520 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) except mosq_test.TestError: pass 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-2.0.11/test/broker/09-plugin-auth-acl-sub-denied.py0000775000175000017500000000306214060132747022741 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/12-prop-maximum-packet-size-publish.py0000775000175000017500000000270414060132747024242 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/02-subpub-qos0-long-topic.py0000775000175000017500000000316214060132747022155 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() except mosq_test.TestError: pass 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/"*201+"d", False) # Exceeds 200 max hierarchy limit, longer overall string than 200 exit(0) mosquitto-2.0.11/test/broker/14-dynsec-group-invalid.py0000775000175000017500000005404514060132747022000 0ustar rogerroger#!/usr/bin/env python3 # Check invalid inputs for group commands from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response, msg=""): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(expected_response) print(response) if msg != "": print(msg) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) # Create client for modifying create_client0_command = { 'commands': [{'command': 'createClient', 'username':'validclient' }] } create_client0_response = {'responses': [{'command': 'createClient'}]} # Create group for modifying create_group0_command = { 'commands': [{'command': 'createGroup', 'groupname':'validgroup' }] } create_group0_response = {'responses': [{'command': 'createGroup'}]} # Create role for modifying create_role0_command = { 'commands': [{'command': 'createRole', 'rolename':'validrole' }] } create_role0_response = {'responses': [{'command': 'createRole'}]} # ========================================================================== # Create group # ========================================================================== # No groupname create_group1_command = { 'commands': [{'command': 'createGroup' }] } create_group1_response = {'responses': [{'command': 'createGroup', 'error': 'Invalid/missing groupname'}]} # Groupname not a string create_group2_command = { 'commands': [{'command': 'createGroup', 'groupname':5 }] } create_group2_response = {'responses': [{'command': 'createGroup', 'error': 'Invalid/missing groupname'}]} # Groupname not UTF-8 create_group3_command = { 'commands': [{'command': 'createGroup', 'groupname': '￿LO' }] } create_group3_response = {'responses': [{'command': 'createGroup', 'error': 'Group name not valid UTF-8'}]} # textname not a string create_group4_command = { 'commands': [{'command': 'createGroup', 'groupname':'g', 'textname':5 }] } create_group4_response = {'responses': [{'command': 'createGroup', 'error': 'Invalid/missing textname'}]} # textdescription not a string create_group5_command = { 'commands': [{'command': 'createGroup', 'groupname':'g', 'textdescription':5 }] } create_group5_response = {'responses': [{'command': 'createGroup', 'error': 'Invalid/missing textdescription'}]} # Group already exists create_group6_command = { 'commands': [{'command': 'createGroup', 'groupname': 'validgroup'}]} create_group6_response = {'responses': [{'command': 'createGroup', 'error': 'Group already exists'}]} # Role not found create_group7_command = { 'commands': [{'command': 'createGroup', 'groupname': 'group', 'roles':[{'rolename':'notfound'}]}] } create_group7_response = {'responses': [{'command': 'createGroup', 'error': 'Role not found'}]} # ========================================================================== # Delete group # ========================================================================== # No groupname delete_group1_command = { 'commands': [{'command': 'deleteGroup' }] } delete_group1_response = {'responses': [{'command': 'deleteGroup', 'error': 'Invalid/missing groupname'}]} # Groupname not a string delete_group2_command = { 'commands': [{'command': 'deleteGroup', 'groupname':5 }] } delete_group2_response = {'responses': [{'command': 'deleteGroup', 'error': 'Invalid/missing groupname'}]} # Groupname not UTF-8 delete_group3_command = { 'commands': [{'command': 'deleteGroup', 'groupname': '￿LO' }] } delete_group3_response = {'responses': [{'command': 'deleteGroup', 'error': 'Group name not valid UTF-8'}]} # Group not found delete_group4_command = { 'commands': [{'command': 'deleteGroup', 'groupname': 'group'}]} delete_group4_response = {'responses': [{'command': 'deleteGroup', 'error': 'Group not found'}]} # ========================================================================== # Add role # ========================================================================== # No groupname add_role1_command = { 'commands': [{'command': 'addGroupRole' }] } add_role1_response = {'responses': [{'command': 'addGroupRole', 'error': 'Invalid/missing groupname'}]} # Groupname not a string add_role2_command = { 'commands': [{'command': 'addGroupRole', 'groupname':5 }] } add_role2_response = {'responses': [{'command': 'addGroupRole', 'error': 'Invalid/missing groupname'}]} # Groupname not UTF-8 add_role3_command = { 'commands': [{'command': 'addGroupRole', 'groupname': '￿LO' }] } add_role3_response = {'responses': [{'command': 'addGroupRole', 'error': 'Group name not valid UTF-8'}]} # No rolename add_role4_command = { 'commands': [{'command': 'addGroupRole', 'groupname':'g' }] } add_role4_response = {'responses': [{'command': 'addGroupRole', 'error': 'Invalid/missing rolename'}]} # Rolename not a string add_role5_command = { 'commands': [{'command': 'addGroupRole', 'groupname':'g', 'rolename':5 }] } add_role5_response = {'responses': [{'command': 'addGroupRole', 'error': 'Invalid/missing rolename'}]} # Rolename not UTF-8 add_role6_command = { 'commands': [{'command': 'addGroupRole', 'groupname':'g', 'rolename':'￿LO' }] } add_role6_response = {'responses': [{'command': 'addGroupRole', 'error': 'Role name not valid UTF-8'}]} # Group not found add_role7_command = { 'commands': [{'command': 'addGroupRole', 'groupname':'notfound', 'rolename':'notfound' }] } add_role7_response = {'responses': [{'command': 'addGroupRole', 'error': 'Group not found'}]} # Role not found add_role8_command = { 'commands': [{'command': 'addGroupRole', 'groupname':'validgroup', 'rolename':'notfound' }] } add_role8_response = {'responses': [{'command': 'addGroupRole', 'error': 'Role not found'}]} # ========================================================================== # Remove role # ========================================================================== # No groupname remove_role1_command = { 'commands': [{'command': 'removeGroupRole' }] } remove_role1_response = {'responses': [{'command': 'removeGroupRole', 'error': 'Invalid/missing groupname'}]} # Groupname not a string remove_role2_command = { 'commands': [{'command': 'removeGroupRole', 'groupname':5 }] } remove_role2_response = {'responses': [{'command': 'removeGroupRole', 'error': 'Invalid/missing groupname'}]} # Groupname not UTF-8 remove_role3_command = { 'commands': [{'command': 'removeGroupRole', 'groupname': '￿LO' }] } remove_role3_response = {'responses': [{'command': 'removeGroupRole', 'error': 'Group name not valid UTF-8'}]} # No rolename remove_role4_command = { 'commands': [{'command': 'removeGroupRole', 'groupname':'g' }] } remove_role4_response = {'responses': [{'command': 'removeGroupRole', 'error': 'Invalid/missing rolename'}]} # Rolename not a string remove_role5_command = { 'commands': [{'command': 'removeGroupRole', 'groupname':'g', 'rolename':5 }] } remove_role5_response = {'responses': [{'command': 'removeGroupRole', 'error': 'Invalid/missing rolename'}]} # Rolename not UTF-8 remove_role6_command = { 'commands': [{'command': 'removeGroupRole', 'groupname': 'g', 'rolename':'￿LO' }] } remove_role6_response = {'responses': [{'command': 'removeGroupRole', 'error': 'Role name not valid UTF-8'}]} # Group not found remove_role7_command = { 'commands': [{'command': 'removeGroupRole', 'groupname':'notfound', 'rolename':'notfound' }] } remove_role7_response = {'responses': [{'command': 'removeGroupRole', 'error': 'Group not found'}]} # Role not found remove_role8_command = { 'commands': [{'command': 'removeGroupRole', 'groupname':'validgroup', 'rolename':'notfound' }] } remove_role8_response = {'responses': [{'command': 'removeGroupRole', 'error': 'Role not found'}]} # ========================================================================== # Add client # ========================================================================== # No groupname add_client1_command = { 'commands': [{'command': 'addGroupClient', 'username':'g' }] } add_client1_response = {'responses': [{'command': 'addGroupClient', 'error': 'Invalid/missing groupname'}]} # Groupname not a string add_client2_command = { 'commands': [{'command': 'addGroupClient', 'groupname':5, 'username':'g' }] } add_client2_response = {'responses': [{'command': 'addGroupClient', 'error': 'Invalid/missing groupname'}]} # Groupname not UTF-8 add_client3_command = { 'commands': [{'command': 'addGroupClient', 'groupname': '￿LO', 'username':'g' }] } add_client3_response = {'responses': [{'command': 'addGroupClient', 'error': 'Group name not valid UTF-8'}]} # No username add_client4_command = { 'commands': [{'command': 'addGroupClient', 'groupname':'g' }] } add_client4_response = {'responses': [{'command': 'addGroupClient', 'error': 'Invalid/missing username'}]} # Username not a string add_client5_command = { 'commands': [{'command': 'addGroupClient', 'groupname':'g', 'username':5 }] } add_client5_response = {'responses': [{'command': 'addGroupClient', 'error': 'Invalid/missing username'}]} # Username not UTF-8 add_client6_command = { 'commands': [{'command': 'addGroupClient', 'groupname':'g', 'username': '￿LO' }] } add_client6_response = {'responses': [{'command': 'addGroupClient', 'error': 'Username not valid UTF-8'}]} # Group not found add_client7_command = { 'commands': [{'command': 'addGroupClient', 'groupname':'notfound', 'username':'validclient' }] } add_client7_response = {'responses': [{'command': 'addGroupClient', 'error': 'Group not found'}]} # Client not found add_client8_command = { 'commands': [{'command': 'addGroupClient', 'groupname':'validgroup', 'username':'notfound' }] } add_client8_response = {'responses': [{'command': 'addGroupClient', 'error': 'Client not found'}]} # ========================================================================== # Remove client # ========================================================================== # No groupname remove_client1_command = { 'commands': [{'command': 'removeGroupClient', 'username':'g' }] } remove_client1_response = {'responses': [{'command': 'removeGroupClient', 'error': 'Invalid/missing groupname'}]} # Groupname not a string remove_client2_command = { 'commands': [{'command': 'removeGroupClient', 'groupname':5, 'username':'g' }] } remove_client2_response = {'responses': [{'command': 'removeGroupClient', 'error': 'Invalid/missing groupname'}]} # Groupname not UTF-8 remove_client3_command = { 'commands': [{'command': 'removeGroupClient', 'groupname':'￿LO', 'username':'g' }] } remove_client3_response = {'responses': [{'command': 'removeGroupClient', 'error': 'Group name not valid UTF-8'}]} # No username remove_client4_command = { 'commands': [{'command': 'removeGroupClient', 'groupname':'g' }] } remove_client4_response = {'responses': [{'command': 'removeGroupClient', 'error': 'Invalid/missing username'}]} # Username not a string remove_client5_command = { 'commands': [{'command': 'removeGroupClient', 'groupname':'g', 'username':5 }] } remove_client5_response = {'responses': [{'command': 'removeGroupClient', 'error': 'Invalid/missing username'}]} # Username not UTF-8 remove_client6_command = { 'commands': [{'command': 'removeGroupClient', 'groupname':'g', 'username': '￿LO' }] } remove_client6_response = {'responses': [{'command': 'removeGroupClient', 'error': 'Username not valid UTF-8'}]} # Group not found remove_client7_command = { 'commands': [{'command': 'removeGroupClient', 'groupname':'notfound', 'username':'validclient' }] } remove_client7_response = {'responses': [{'command': 'removeGroupClient', 'error': 'Group not found'}]} # Client not found remove_client8_command = { 'commands': [{'command': 'removeGroupClient', 'groupname':'validgroup', 'username':'notfound' }] } remove_client8_response = {'responses': [{'command': 'removeGroupClient', 'error': 'Client not found'}]} # ========================================================================== # Get group # ========================================================================== # No groupname get_group1_command = { 'commands': [{'command': 'getGroup'}] } get_group1_response = {'responses': [{'command': 'getGroup', 'error': 'Invalid/missing groupname'}]} # Groupname not a string get_group2_command = { 'commands': [{'command': 'getGroup', 'groupname':5}] } get_group2_response = {'responses': [{'command': 'getGroup', 'error': 'Invalid/missing groupname'}]} # Groupname not UTF-8 get_group3_command = { 'commands': [{'command': 'getGroup', 'groupname':'￿LO' }] } get_group3_response = {'responses': [{'command': 'getGroup', 'error': 'Group name not valid UTF-8'}]} # Group not found get_group4_command = { 'commands': [{'command': 'getGroup', 'groupname':"missing"}] } get_group4_response = {'responses': [{'command': 'getGroup', 'error': 'Group not found'}]} # ========================================================================== # Set anon group # ========================================================================== # No groupname set_anon_group1_command = { 'commands': [{'command': 'setAnonymousGroup'}] } set_anon_group1_response = {'responses': [{'command': 'setAnonymousGroup', 'error': 'Invalid/missing groupname'}]} # Groupname not a string set_anon_group2_command = { 'commands': [{'command': 'setAnonymousGroup', 'groupname':5}] } set_anon_group2_response = {'responses': [{'command': 'setAnonymousGroup', 'error': 'Invalid/missing groupname'}]} # Groupname not UTF-8 set_anon_group3_command = { 'commands': [{'command': 'setAnonymousGroup', 'groupname':'￿LO' }] } set_anon_group3_response = {'responses': [{'command': 'setAnonymousGroup', 'error': 'Group name not valid UTF-8'}]} # Group not found set_anon_group4_command = { 'commands': [{'command': 'setAnonymousGroup', 'groupname':'notfound' }] } set_anon_group4_response = {'responses': [{'command': 'setAnonymousGroup', 'error': 'Group not found'}]} # ========================================================================== # Modify group # ========================================================================== # No groupname modify_group1_command = { 'commands': [{'command': 'modifyGroup'}]} modify_group1_response = {'responses': [{'command': 'modifyGroup', 'error': 'Invalid/missing groupname'}]} # Group name not a string modify_group2_command = { 'commands': [{'command': 'modifyGroup', 'groupname':5}]} modify_group2_response = {'responses': [{'command': 'modifyGroup', 'error': 'Invalid/missing groupname'}]} # Group name not UTF-8 modify_group3_command = { 'commands': [{'command': 'modifyGroup', 'groupname':'￿LO' }] } modify_group3_response = {'responses': [{'command': 'modifyGroup', 'error': 'Group name not valid UTF-8'}]} # roles not a list modify_group4_command = { 'commands': [{'command': 'modifyGroup', 'groupname':'validgroup', 'password':'test', 'roles':'string'}]} modify_group4_response = {'responses': [{'command': 'modifyGroup', 'error': "'roles' not an array or missing/invalid rolename"}]} # No rolename modify_group5_command = { 'commands': [{'command': 'modifyGroup', 'groupname':'validgroup', 'roles':[{}]}]} modify_group5_response = {'responses': [{'command': 'modifyGroup', 'error': "'roles' not an array or missing/invalid rolename"}]} # rolename not a string modify_group6_command = { 'commands': [{'command': 'modifyGroup', 'groupname':'validgroup', 'roles':[{'rolename':5}]}]} modify_group6_response = {'responses': [{'command': 'modifyGroup', 'error': "'roles' not an array or missing/invalid rolename"}]} # rolename not UTF-8 #modify_group7_command = { 'commands': [{'command': 'modifyGroup', 'groupname':'validgroup','roles':[{'rolename':'￿LO'}] }] } #modify_group7_response = {'responses': [{'command': 'modifyGroup', 'error': 'Role name not valid UTF-8'}]} # Group not found modify_group8_command = { 'commands': [{'command': 'modifyGroup', 'groupname':'notfound', 'rolename':'notfound'}]} modify_group8_response = {'responses': [{'command': 'modifyGroup', 'error': 'Group not found'}]} # Role not found modify_group9_command = { 'commands': [{'command': 'modifyGroup', 'groupname':'validgroup', 'roles':[{'rolename':'notfound'}]}]} modify_group9_response = {'responses': [{'command': 'modifyGroup', 'error': 'Role not found'}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") command_check(sock, create_client0_command, create_client0_response, "0") command_check(sock, create_group0_command, create_group0_response, "0") command_check(sock, create_role0_command, create_role0_response, "0") command_check(sock, create_group1_command, create_group1_response, "1") command_check(sock, create_group2_command, create_group2_response, "2") command_check(sock, create_group3_command, create_group3_response, "3") command_check(sock, create_group4_command, create_group4_response, "4") command_check(sock, create_group5_command, create_group5_response, "5") command_check(sock, create_group6_command, create_group6_response, "6") command_check(sock, create_group7_command, create_group7_response, "7") command_check(sock, delete_group1_command, delete_group1_response, "1") command_check(sock, delete_group2_command, delete_group2_response, "2") command_check(sock, delete_group3_command, delete_group3_response, "3") command_check(sock, delete_group4_command, delete_group4_response, "4") command_check(sock, add_role1_command, add_role1_response, "1") command_check(sock, add_role2_command, add_role2_response, "2") command_check(sock, add_role3_command, add_role3_response, "3") command_check(sock, add_role4_command, add_role4_response, "4") command_check(sock, add_role5_command, add_role5_response, "5") command_check(sock, add_role6_command, add_role6_response, "6") command_check(sock, add_role7_command, add_role7_response, "7") command_check(sock, add_role8_command, add_role8_response, "8") command_check(sock, remove_role1_command, remove_role1_response, "1") command_check(sock, remove_role2_command, remove_role2_response, "2") command_check(sock, remove_role3_command, remove_role3_response, "3") command_check(sock, remove_role4_command, remove_role4_response, "4") command_check(sock, remove_role5_command, remove_role5_response, "5") command_check(sock, remove_role6_command, remove_role6_response, "6") command_check(sock, remove_role7_command, remove_role7_response, "7") command_check(sock, remove_role8_command, remove_role8_response, "8") command_check(sock, add_client1_command, add_client1_response, "1") command_check(sock, add_client2_command, add_client2_response, "2") command_check(sock, add_client3_command, add_client3_response, "3") command_check(sock, add_client4_command, add_client4_response, "4") command_check(sock, add_client5_command, add_client5_response, "5") command_check(sock, add_client6_command, add_client6_response, "6") command_check(sock, add_client7_command, add_client7_response, "7") command_check(sock, add_client8_command, add_client8_response, "8") command_check(sock, remove_client1_command, remove_client1_response, "1") command_check(sock, remove_client2_command, remove_client2_response, "2") command_check(sock, remove_client3_command, remove_client3_response, "3") command_check(sock, remove_client4_command, remove_client4_response, "4") command_check(sock, remove_client5_command, remove_client5_response, "5") command_check(sock, remove_client6_command, remove_client6_response, "6") command_check(sock, remove_client7_command, remove_client7_response, "7") command_check(sock, remove_client8_command, remove_client8_response, "8") command_check(sock, get_group1_command, get_group1_response, "1") command_check(sock, get_group2_command, get_group2_response, "2") command_check(sock, get_group3_command, get_group3_response, "3") command_check(sock, get_group4_command, get_group4_response, "4") command_check(sock, set_anon_group1_command, set_anon_group1_response, "1") command_check(sock, set_anon_group2_command, set_anon_group2_response, "2") command_check(sock, set_anon_group3_command, set_anon_group3_response, "3") command_check(sock, set_anon_group4_command, set_anon_group4_response, "4") command_check(sock, modify_group1_command, modify_group1_response, "1") command_check(sock, modify_group2_command, modify_group2_response, "2") command_check(sock, modify_group3_command, modify_group3_response, "3") command_check(sock, modify_group4_command, modify_group4_response, "4") command_check(sock, modify_group5_command, modify_group5_response, "5") command_check(sock, modify_group6_command, modify_group6_response, "6") #command_check(sock, modify_group7_command, modify_group7_response, "7") command_check(sock, modify_group8_command, modify_group8_response, "8") command_check(sock, modify_group9_command, modify_group9_response, "9") rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/02-subscribe-dollar-v5.py0000775000175000017500000000254614060132747021515 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/02-subscribe-qos1.py0000775000175000017500000000227214060132747020567 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 * def do_test(proto_ver): rc = 1 mid = 79 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-qos1-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "qos1/test", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, 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, subscribe_packet, suback_packet, "suback") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/01-connect-zero-length-id.py0000775000175000017500000002105114060132747022177 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("listener %d\n" % (port2)) f.write("allow_anonymous true\n") if allow_zero != "": f.write("allow_zero_length_clientid %s\n" % (allow_zero)) f.write("listener %d\n" % (port1)) f.write("allow_anonymous true\n") 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[:-39] 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 except mosq_test.TestError: pass 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-2.0.11/test/broker/02-subscribe-qos2.py0000775000175000017500000000227114060132747020567 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 * def do_test(proto_ver): rc = 1 mid = 3 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-qos2-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/test", 2, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, 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, subscribe_packet, suback_packet, "suback") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/03-publish-qos1-retain-disabled.py0000775000175000017500000000333214060132747023300 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("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("retain_available false\n") def do_test(proto_ver): 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/06-bridge-br2b-disconnect-qos1.py0000775000175000017500000001043114060132747023016 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, protocol_version): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("allow_anonymous true\n") 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") f.write("bridge_protocol_version %s\n" % (protocol_version)) def do_test(proto_ver): if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, bridge_protocol) 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=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) if proto_ver == 5: opts = mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL | mqtt5_opts.MQTT_SUB_OPT_RETAIN_AS_PUBLISHED else: opts = 0 mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 1 | opts, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid = 3 subscribe2_packet = mosq_test.gen_subscribe(mid, "bridge/#", 1 | opts, proto_ver=proto_ver) suback2_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid = 2 publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message", proto_ver=proto_ver) publish_dup_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message", dup=True, proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) 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) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) mosq_test.expect_packet(bridge, "subscribe", subscribe_packet) bridge.send(suback_packet) # Helper helper_connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive, proto_ver=proto_ver) helper_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 128 helper_publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message", proto_ver=proto_ver) helper_puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) helper_sock = mosq_test.do_client_connect(helper_connect_packet, helper_connack_packet, port=port2, connack_error="helper connack") mosq_test.do_send_receive(helper_sock, publish_packet, puback_packet, "helper puback") helper_sock.close() # End helper mosq_test.expect_packet(bridge, "publish", publish_packet) bridge.close() (bridge, address) = ssock.accept() bridge.settimeout(20) mosq_test.expect_packet(bridge, "2nd connect", connect_packet) bridge.send(connack_packet) mosq_test.expect_packet(bridge, "2nd subscribe", subscribe2_packet) bridge.send(suback2_packet) mosq_test.expect_packet(bridge, "2nd publish", publish_dup_packet) rc = 0 bridge.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() ssock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subscribe-persistence-flipflop.py0000775000175000017500000000622014060132747024036 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 * def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet_sub_persistent = mosq_test.gen_connect("flipflop-test", keepalive=keepalive, clean_session=False, proto_ver=proto_ver) connect_packet_sub_clean = mosq_test.gen_connect("flipflop-test", keepalive=keepalive, clean_session=True, proto_ver=proto_ver) connack_packet_sub = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connect_packet_pub = mosq_test.gen_connect("flipflop-test-pub", keepalive=keepalive, proto_ver=proto_ver) connack_packet_pub = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid=1 subscribe_packet = mosq_test.gen_subscribe(mid, "flipflop/test", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid=1 publish_packet = mosq_test.gen_publish("flipflop/test", qos=1, mid=mid, payload="message", proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) 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") mosq_test.expect_packet(sub_sock, "publish receive", publish_packet) rc = 0 sub_sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/06-bridge-no-local.py0000775000175000017500000000276614060132747020677 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 * 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/06-bridge-outgoing-retain.py0000775000175000017500000000762514060132747022305 0ustar rogerroger#!/usr/bin/env python3 # Does a bridge with bridge_outgoing_retain set to false not set the retain bit # on outgoing messages? from mosq_test_helper import * def write_config(filename, port1, port2, protocol_version, outgoing_retain): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("allow_anonymous true\n") 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") f.write("bridge_protocol_version %s\n" %(protocol_version)) f.write("bridge_outgoing_retain %s\n" %(outgoing_retain)) def do_test(proto_ver, outgoing_retain): if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, bridge_protocol, outgoing_retain) 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=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 if proto_ver == 5: opts = mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL | mqtt5_opts.MQTT_SUB_OPT_RETAIN_AS_PUBLISHED else: opts = 0 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 1 | opts, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) if outgoing_retain == "true": publish_packet = mosq_test.gen_publish("bridge/retain/test", qos=0, retain=True, payload="message", proto_ver=proto_ver) else: publish_packet = mosq_test.gen_publish("bridge/retain/test", qos=0, retain=False, payload="message", proto_ver=proto_ver) helper_connect_packet = mosq_test.gen_connect("helper", keepalive=keepalive, clean_session=True, proto_ver=proto_ver) helper_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) helper_publish_packet = mosq_test.gen_publish("bridge/retain/test", qos=0, retain=True, payload="message", proto_ver=proto_ver) 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) try: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) (bridge, address) = ssock.accept() bridge.settimeout(20) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) mosq_test.expect_packet(bridge, "subscribe", subscribe_packet) bridge.send(suback_packet) # Broker is now connected to us on port1. # Connect our client to the broker on port2 and send a publish # message, which we will then receive by way of the bridge helper = mosq_test.do_client_connect(helper_connect_packet, helper_connack_packet, port=port2) helper.send(helper_publish_packet) helper.close() mosq_test.expect_packet(bridge, "publish", publish_packet) rc = 0 bridge.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() ssock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4, outgoing_retain="true") do_test(proto_ver=4, outgoing_retain="false") do_test(proto_ver=5, outgoing_retain="true") do_test(proto_ver=5, outgoing_retain="false") exit(0) mosquitto-2.0.11/test/broker/08-ssl-connect-no-identity.py0000775000175000017500000000313014060132747022416 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/04-retain-check-source-persist.py0000775000175000017500000000735114060132747023254 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("allow_anonymous true\n") 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(proto_ver, 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, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish_packet = mosq_test.gen_publish("test/topic", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "test/topic", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) 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") 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() except mosq_test.TestError: pass 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(proto_ver=4, per_listener="true", username=None) do_test(proto_ver=4, per_listener="true", username="test") do_test(proto_ver=4, per_listener="false", username=None) do_test(proto_ver=4, per_listener="false", username="test") do_test(proto_ver=5, per_listener="true", username=None) do_test(proto_ver=5, per_listener="true", username="test") do_test(proto_ver=5, per_listener="false", username=None) do_test(proto_ver=5, per_listener="false", username="test") mosquitto-2.0.11/test/broker/02-subpub-qos1-message-expiry-will.py0000775000175000017500000000556414060132747024022 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 * def do_test(): 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test() exit(0) mosquitto-2.0.11/test/broker/03-publish-qos1-max-inflight.py0000775000175000017500000000352614060132747022645 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("allow_anonymous true\n") f.write("max_inflight_messages 1\n") def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos1-test", keepalive=keepalive, proto_ver=proto_ver) properties = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS_MAXIMUM, 10) \ + mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 1) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver, properties=properties, property_helper=False) mid = 311 publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS, proto_ver=proto_ver) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/11-pub-props.py0000775000175000017500000000557414060132747017664 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("allow_anonymous true\n") 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") 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") mosq_test.expect_packet(sock, "publish2", publish2_packet) rc = 0 sock.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/14-dynsec-plugin-invalid.py0000775000175000017500000001242414060132747022135 0ustar rogerroger#!/usr/bin/env python3 # Check invalid inputs for plugin commands from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response, msg=""): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(expected_response) print(response) if msg != "": print(msg) raise ValueError(response) def command_check_text(sock, command_payload, expected_response, msg=""): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=command_payload) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(expected_response) print(response) if msg != "": print(msg) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) # ========================================================================== # Bad commands # ========================================================================== # Invalid JSON bad1_command = 'not json' bad1_response = {'responses': [{'command': 'Unknown command', 'error': 'Invalid/missing commands'}]} # No commands bad2_command = {} bad2_response = {'responses': [{'command': 'Unknown command', 'error': 'Invalid/missing commands'}]} # Commands not an array bad3_command = {'commands': 'test'} bad3_response = {'responses': [{'command': 'Unknown command', 'error': 'Invalid/missing commands'}]} # Empty commands array bad4_command = {'commands': []} bad4_response = {'responses': []} # Empty command bad5_command = {'commands': ['bad']} bad5_response = {'responses': [{'command': 'Unknown command', 'error': 'Command not an object'}]} # Bad array type bad6_command = {'commands': [{}]} bad6_response = {'responses': [{'command': 'Unknown command', 'error': 'Missing command'}]} # Bad command type bad7_command = {'commands': [{'command':6}]} bad7_response = {'responses': [{'command': 'Unknown command', 'error': 'Missing command'}]} # Bad correlationData type bad8_command = {'commands': [{'command':'command', 'correlationData':6}]} bad8_response = {'responses': [{'command': 'command', 'error': 'Invalid correlationData data type.'}]} # Unknown command bad9_command = {'commands': [{'command':'command'}]} bad9_response = {'responses': [{'command': 'command', 'error': 'Unknown command'}]} # ========================================================================== # setDefaultACLAccess # ========================================================================== # Missing actions array set_default1_command = {'commands': [{'command':'setDefaultACLAccess'}]} set_default1_response = {'responses': [{'command': 'setDefaultACLAccess', 'error': 'Missing/invalid actions array'}]} # Actions array not an array set_default2_command = {'commands': [{'command':'setDefaultACLAccess', 'actions':'bad'}]} set_default2_response = {'responses': [{'command': 'setDefaultACLAccess', 'error': 'Missing/invalid actions array'}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") command_check(sock, bad1_command, bad1_response, "1") command_check(sock, bad2_command, bad2_response, "2") command_check(sock, bad3_command, bad3_response, "3") command_check(sock, bad4_command, bad4_response, "4") command_check(sock, bad5_command, bad5_response, "5") command_check(sock, bad6_command, bad6_response, "6") command_check(sock, bad7_command, bad7_response, "7") command_check(sock, bad8_command, bad8_response, "8") command_check(sock, bad9_command, bad9_response, "9") command_check(sock, set_default1_command, set_default1_response, "1") command_check(sock, set_default2_command, set_default2_response, "2") rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/01-connect-invalid-id-0.py0000775000175000017500000000214414060132747021526 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 * def do_test(proto_ver): rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("", keepalive=keepalive, proto_ver=proto_ver) if proto_ver == 3: connack_packet = mosq_test.gen_connack(rc=2, proto_ver=proto_ver) elif proto_ver == 4: connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver, 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=3) do_test(proto_ver=4) exit(0) mosquitto-2.0.11/test/broker/08-ssl-connect-cert-auth.py0000775000175000017500000000321214060132747022050 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("allow_anonymous true\n") f.write("listener %d\n" % (port1)) f.write("allow_anonymous true\n") 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/07-will-delay-session-expiry2.py0000775000175000017500000000357114060132747023061 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) mosq_test.expect_packet(sock1, "publish", publish_packet) rc = 0 sock1.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/01-connect-uname-or-anon.py0000775000175000017500000000603514060132747022030 0ustar rogerroger#!/usr/bin/env python3 # Test whether an anonymous connection is correctly denied. from mosq_test_helper import * def write_config(filename, port, allow_anonymous, password_file): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) if allow_anonymous: f.write("allow_anonymous true\n") else: f.write("allow_anonymous false\n") if password_file: f.write("password_file %s\n" % (filename.replace('.conf', '.pwfile'))) def do_test(allow_anonymous, password_file, username, expect_success): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, allow_anonymous, password_file) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: for proto_ver in [4, 5]: rc = 1 keepalive = 10 if username: connect_packet = mosq_test.gen_connect("connect-test-%d" % (proto_ver), keepalive=keepalive, proto_ver=proto_ver, username="user", password="password") else: connect_packet = mosq_test.gen_connect("connect-test-%d" % (proto_ver), keepalive=keepalive, proto_ver=proto_ver) if proto_ver == 5: if expect_success == True: connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) else: connack_packet = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=proto_ver, properties=None) else: if expect_success == True: connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) else: connack_packet = mosq_test.gen_connack(rc=5, proto_ver=proto_ver) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d, allow_anonymous=%d, password_file=%d, username=%d" % (proto_ver, allow_anonymous, password_file, username)) exit(rc) do_test(allow_anonymous=True, password_file=True, username=True, expect_success=True) do_test(allow_anonymous=True, password_file=True, username=False, expect_success=True) do_test(allow_anonymous=True, password_file=False, username=True, expect_success=True) do_test(allow_anonymous=True, password_file=False, username=False, expect_success=True) do_test(allow_anonymous=False, password_file=True, username=True, expect_success=True) do_test(allow_anonymous=False, password_file=True, username=False, expect_success=False) do_test(allow_anonymous=False, password_file=False, username=True, expect_success=False) do_test(allow_anonymous=False, password_file=False, username=False, expect_success=False) exit(0) mosquitto-2.0.11/test/broker/c/0000775000175000017500000000000014060132747015350 5ustar rogerrogermosquitto-2.0.11/test/broker/c/auth_plugin_acl_sub_denied.c0000664000175000017500000000241314060132747023033 0ustar rogerroger#include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 4; } 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-2.0.11/test/broker/c/auth_plugin_msg_params.c0000664000175000017500000000335314060132747022250 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 4; } 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-2.0.11/test/broker/c/auth_plugin_v5_handle_message.c0000664000175000017500000000204614060132747023466 0ustar rogerroger#include #include #include #include #include #include static int handle_publish(int event, void *event_data, void *user_data); static mosquitto_plugin_id_t *plg_id; int mosquitto_plugin_version(int supported_version_count, const int *supported_versions) { return 5; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_MESSAGE, handle_publish, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { mosquitto_callback_unregister(plg_id, MOSQ_EVT_MESSAGE, handle_publish, NULL); return MOSQ_ERR_SUCCESS; } int handle_publish(int event, void *event_data, void *user_data) { struct mosquitto_evt_message *ed = event_data; mosquitto_free(ed->topic); ed->topic = mosquitto_strdup("fixed-topic"); return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/test/broker/c/auth_plugin_v2.c0000664000175000017500000000333614060132747020447 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 2; } 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-2.0.11/test/broker/c/mosquitto_plugin_v2.h0000664000175000017500000001764114060132747021563 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ 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-2.0.11/test/broker/c/auth_plugin_extended_single2.c0000664000175000017500000000411714060132747023341 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 4; } 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 4; } 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-2.0.11/test/broker/c/plugin_control.c0000664000175000017500000000243514060132747020556 0ustar rogerroger#include #include #include #include #include #include static mosquitto_plugin_id_t *plg_id = NULL; int control_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_control *ed = event_data; mosquitto_broker_publish_copy(NULL, ed->topic, ed->payloadlen, ed->payload, 0, 0, NULL); return 0; } int mosquitto_plugin_version(int supported_version_count, const int *supported_versions) { return MOSQ_PLUGIN_VERSION; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { int i; char buf[100]; plg_id = identifier; for(i=0; i<100; i++){ snprintf(buf, sizeof(buf), "$CONTROL/user-management/v%d", i); mosquitto_callback_register(plg_id, MOSQ_EVT_CONTROL, control_callback, "$CONTROL/user-management/v1", NULL); } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { int i; char buf[100]; for(i=0; i<100; i++){ snprintf(buf, sizeof(buf), "$CONTROL/user-management/v%d", i); mosquitto_callback_unregister(plg_id, MOSQ_EVT_CONTROL, control_callback, "$CONTROL/user-management/v1"); } return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/test/broker/c/auth_plugin_v5.c0000664000175000017500000000453014060132747020447 0ustar rogerroger#include #include #include #include #include int mosquitto_auth_acl_check_v5(int event, void *event_data, void *user_data); int mosquitto_auth_unpwd_check_v5(int event, void *event_data, void *user_data); static mosquitto_plugin_id_t *plg_id; int mosquitto_plugin_version(int supported_version_count, const int *supported_versions) { return 5; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_ACL_CHECK, mosquitto_auth_acl_check_v5, NULL, NULL); mosquitto_callback_register(plg_id, MOSQ_EVT_BASIC_AUTH, mosquitto_auth_unpwd_check_v5, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { mosquitto_callback_unregister(plg_id, MOSQ_EVT_ACL_CHECK, mosquitto_auth_acl_check_v5, NULL); mosquitto_callback_unregister(plg_id, MOSQ_EVT_BASIC_AUTH, mosquitto_auth_unpwd_check_v5, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check_v5(int event, void *event_data, void *user_data) { struct mosquitto_evt_acl_check *ed = event_data; const char *username = mosquitto_client_username(ed->client); if(username && !strcmp(username, "readonly") && ed->access == MOSQ_ACL_READ){ return MOSQ_ERR_SUCCESS; }else if(username && !strcmp(username, "readonly") && ed->access == MOSQ_ACL_SUBSCRIBE &&!strchr(ed->topic, '#') && !strchr(ed->topic, '+')) { return MOSQ_ERR_SUCCESS; }else if(username && !strcmp(username, "readwrite")){ if((!strcmp(ed->topic, "readonly") && ed->access == MOSQ_ACL_READ) || !strcmp(ed->topic, "writeable")){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } }else{ return MOSQ_ERR_ACL_DENIED; } } int mosquitto_auth_unpwd_check_v5(int event, void *event_data, void *user_data) { struct mosquitto_evt_basic_auth *ed = event_data; if(!strcmp(ed->username, "test-username") && ed->password && !strcmp(ed->password, "cnwTICONIURW")){ return MOSQ_ERR_SUCCESS; }else if(!strcmp(ed->username, "readonly") || !strcmp(ed->username, "readwrite")){ return MOSQ_ERR_SUCCESS; }else if(!strcmp(ed->username, "test-username@v2")){ return MOSQ_ERR_PLUGIN_DEFER; }else{ return MOSQ_ERR_AUTH; } } mosquitto-2.0.11/test/broker/c/auth_plugin_publish.c0000664000175000017500000000540114060132747021561 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 4; } 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) { static int count = 0; mosquitto_property *props = NULL; if(access == MOSQ_ACL_WRITE){ if(count == 0){ /* "missing-client" isn't connected, so we can check memory usage properly. */ mosquitto_broker_publish_copy("missing-client", "topic/2", strlen("test-message-2"), "test-message-2", 2, true, NULL); mosquitto_broker_publish_copy("test-client", "topic/0", strlen("test-message-0"), "test-message-0", 0, true, NULL); mosquitto_broker_publish_copy("missing-client", "topic/2", strlen("test-message-2"), "test-message-2", 2, true, NULL); mosquitto_broker_publish_copy("test-client", "topic/1", strlen("test-message-1"), "test-message-1", 1, true, NULL); mosquitto_broker_publish_copy("missing-client", "topic/2", strlen("test-message-2"), "test-message-2", 2, true, NULL); mosquitto_broker_publish_copy("test-client", "topic/2", strlen("test-message-2"), "test-message-2", 2, true, NULL); count = 1; }else{ mosquitto_property_add_byte(&props, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); mosquitto_broker_publish_copy("test-client", "topic/0", strlen("test-message-0"), "test-message-0", 0, true, props); props = NULL; mosquitto_property_add_byte(&props, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); mosquitto_broker_publish_copy("test-client", "topic/1", strlen("test-message-1"), "test-message-1", 1, true, props); props = NULL; mosquitto_property_add_byte(&props, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); mosquitto_broker_publish_copy("test-client", "topic/2", strlen("test-message-2"), "test-message-2", 2, true, props); } } 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-2.0.11/test/broker/c/08-tls-psk-bridge.c0000664000175000017500000000240714060132747020573 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-2.0.11/test/broker/c/auth_plugin_v4.c0000664000175000017500000000407514060132747020452 0ustar rogerroger#include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 4; } 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-2.0.11/test/broker/c/auth_plugin_extended_single.c0000664000175000017500000000411214060132747023252 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 4; } 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-2.0.11/test/broker/c/auth_plugin_pwd.c0000664000175000017500000000273114060132747020710 0ustar rogerroger#include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 4; } 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-2.0.11/test/broker/c/auth_plugin_context_params.c0000664000175000017500000000500114060132747023136 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 4; } 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-2.0.11/test/broker/c/auth_plugin_extended_multiple.c0000664000175000017500000000401114060132747023622 0ustar rogerroger#include #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 4; } 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-2.0.11/test/broker/c/Makefile0000664000175000017500000000145414060132747017014 0ustar rogerroger.PHONY: all test clean reallyclean CFLAGS=-I../../../include -Wall -Werror PLUGIN_SRC = \ auth_plugin_v4.c \ auth_plugin_v5.c \ auth_plugin_v5_handle_message.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 \ auth_plugin_publish.c \ plugin_control.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-2.0.11/test/broker/04-retain-check-source.py0000775000175000017500000000540014060132747021556 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("allow_anonymous true\n") 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(proto_ver, 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, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish_packet = mosq_test.gen_publish("test/topic", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "test/topic", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) 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") 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() except mosq_test.TestError: pass 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(proto_ver=4, per_listener="true") do_test(proto_ver=4, per_listener="false") do_test(proto_ver=5, per_listener="true") do_test(proto_ver=5, per_listener="false") mosquitto-2.0.11/test/broker/07-will-oversize-payload.py0000775000175000017500000000526514060132747022201 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client will that is too large is handled from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("message_size_limit 1\n") def do_test(proto_ver, clean_session): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("will-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connect_packet_ok = mosq_test.gen_connect("test-helper", keepalive=keepalive, will_topic="will/qos0/test", will_payload=b"A", clean_session=clean_session, proto_ver=proto_ver, session_expiry=60) connack_packet_ok = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connect_packet_bad = mosq_test.gen_connect("test-helper", keepalive=keepalive, will_topic="will/qos0/test", will_payload=b"AB", clean_session=clean_session, proto_ver=proto_ver, session_expiry=60) if proto_ver == 5: connack_packet_bad = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_PACKET_TOO_LARGE, proto_ver=proto_ver, property_helper=False) else: connack_packet_bad = mosq_test.gen_connack(rc=5, 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="A", proto_ver=proto_ver) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, 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, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock2 = mosq_test.do_client_connect(connect_packet_bad, connack_packet_bad, port=port, timeout=5) sock2.close() sock2 = mosq_test.do_client_connect(connect_packet_ok, connack_packet_ok, port=port, timeout=5) sock2.close() mosq_test.expect_packet(sock, "publish", publish_packet) # Check there are no more messages mosq_test.do_ping(sock) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) 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-2.0.11/test/broker/04-retain-upgrade-outgoing-qos.py0000775000175000017500000000365414060132747023274 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("allow_anonymous true\n") f.write("upgrade_outgoing_qos true\n") def do_test(proto_ver): 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, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos0/test", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) publish_packet2 = mosq_test.gen_publish("retain/qos0/test", mid=1, qos=1, payload="retained message", retain=True, proto_ver=proto_ver) 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") mosq_test.expect_packet(sock, "publish", publish_packet2) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subscribe-qos0.py0000775000175000017500000000232314060132747020563 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 * def do_test(proto_ver): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-qos0-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "qos0/test", 0, proto_ver=proto_ver) suback_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: 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/03-publish-dollar-v5.py0000775000175000017500000000275614060132747021206 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/02-subpub-qos0-oversize-payload.py0000775000175000017500000000472214060132747023402 0ustar rogerroger#!/usr/bin/env python3 # Test whether message size limits apply. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("message_size_limit 1\n") def do_test(proto_ver): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos0-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos0", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) connect2_packet = mosq_test.gen_connect("subpub-qos0-helper", keepalive=keepalive, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet_ok = mosq_test.gen_publish("subpub/qos0", qos=0, payload="A", proto_ver=proto_ver) publish_packet_bad = mosq_test.gen_publish("subpub/qos0", qos=0, payload="AB", proto_ver=proto_ver) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, 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, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=20, port=port) sock2.send(publish_packet_ok) mosq_test.expect_packet(sock, "publish 1", publish_packet_ok) # Check all is still well on the publishing client mosq_test.do_ping(sock2) sock2.send(publish_packet_bad) # Check all is still well on the publishing client mosq_test.do_ping(sock2) # The subscribing client shouldn't have received a PUBLISH mosq_test.do_ping(sock) rc = 0 sock.close() except SyntaxError: raise except TypeError: raise except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/08-ssl-connect-cert-auth-crl.py0000775000175000017500000000312714060132747022633 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("allow_anonymous true\n") f.write("listener %d\n" % (port1)) f.write("allow_anonymous true\n") 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/09-plugin-auth-v2-unpwd-success.py0000775000175000017500000000215514060132747023317 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/03-publish-c2b-disconnect-qos2.py0000775000175000017500000000630614060132747023053 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * def do_test(proto_ver): rc = 1 mid = 3265 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos2-disco-test", keepalive=keepalive, clean_session=False, proto_ver=proto_ver, session_expiry=60) connack1_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=proto_ver) if proto_ver == 3: connack2_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=proto_ver) else: connack2_packet = mosq_test.gen_connack(flags=1, rc=0, proto_ver=proto_ver) helper_connect_packet = mosq_test.gen_connect("pub-qos2-disco-helper", keepalive=keepalive, clean_session=True, proto_ver=proto_ver) helper_connack_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/disconnect/test", 2, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 1 publish_packet = mosq_test.gen_publish("qos2/disconnect/test", qos=2, mid=mid, payload="disconnect-message", proto_ver=proto_ver) publish_dup_packet = mosq_test.gen_publish("qos2/disconnect/test", qos=2, mid=mid, payload="disconnect-message", dup=True, proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) if proto_ver == 3: pubrel_dup_packet = mosq_test.gen_pubrel(mid, dup=True, proto_ver=proto_ver) else: pubrel_dup_packet = mosq_test.gen_pubrel(mid, dup=False, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: # Add a subscriber, so we ensure that the QoS 2 flow must be completed helper = mosq_test.do_client_connect(helper_connect_packet, helper_connack_packet, port=port) mosq_test.do_send_receive(helper, subscribe_packet, suback_packet) sock = mosq_test.do_client_connect(connect_packet, connack1_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, connack2_packet, port=port, connack_error="connack 2") sock.send(publish_dup_packet) 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, connack2_packet, port=port) mosq_test.do_send_receive(sock, pubrel_dup_packet, pubcomp_packet, "pubcomp") rc = 0 sock.close() helper.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=3) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/06-bridge-fail-persist-resend-qos1.py0000775000175000017500000000601714060132747023725 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, protocol_version): 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") f.write("bridge_protocol_version %s\n" % (protocol_version)) def do_test(proto_ver): if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, bridge_protocol) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("bridge-u-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 180 mid_unknown = 2000 publish_packet = mosq_test.gen_publish("bridge/unknown/qos1", qos=1, payload="bridge-message", mid=mid, proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) puback_packet_unknown = mosq_test.gen_puback(mid_unknown, proto_ver=proto_ver) unsubscribe_packet = mosq_test.gen_unsubscribe(1, "bridge/#", proto_ver=proto_ver) unsuback_packet = mosq_test.gen_unsuback(1, proto_ver=proto_ver) 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) mosq_test.expect_packet(conn, "connect", connect_packet) conn.send(connack_packet) 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) mosq_test.expect_packet(conn, "puback", puback_packet) rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() sock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-unsubscribe-qos2.py0000775000175000017500000000250314060132747021130 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 * def do_test(proto_ver): rc = 1 mid = 3 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-qos2-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "qos2/test", proto_ver=proto_ver) if proto_ver == 5: unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=proto_ver, reason_code=17) else: unsuback_packet = mosq_test.gen_unsuback(mid, 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, unsubscribe_packet, unsuback_packet, "unsuback") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/12-prop-maximum-packet-size-publish-qos1.py0000775000175000017500000000320614060132747025121 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) sock.send(publish2_packet) mosq_test.receive_unordered(sock, puback2_packet, publish2_packet, "puback 2/publish2") rc = 0 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/13-malformed-subscribe-v5.py0000775000175000017500000001074214060132747022205 0ustar rogerroger#!/usr/bin/env python3 # Test whether the broker handles malformed packets correctly - SUBSCRIBE # MQTTv5 from mosq_test_helper import * rc = 1 def do_test(subscribe_packet, reason_code, error_string): global rc 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) mid = 0 disconnect_packet = mosq_test.gen_disconnect(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, subscribe_packet, disconnect_packet, error_string=error_string) rc = 0 port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: # mid == 0 subscribe_packet = mosq_test.gen_subscribe(topic="test/topic", qos=1, mid=0, proto_ver=5) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "mid == 0") # qos > 2 subscribe_packet = mosq_test.gen_subscribe(topic="test/topic", qos=3, mid=1, proto_ver=5) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "qos > 2") # retain handling = 0x30 subscribe_packet = mosq_test.gen_subscribe(topic="test/topic", qos=0x30, mid=1, proto_ver=5) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "retain handling = 0x30") # subscription options = 0xC0 subscribe_packet = mosq_test.gen_subscribe(topic="test/topic", qos=0xC0, mid=1, proto_ver=5) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "subscription options = 0xC0") # command flags != 0x02 subscribe_packet = mosq_test.gen_subscribe(topic="test/topic", qos=1, mid=1, proto_ver=5, cmd=128) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "command flags != 0x02") # Incorrect property props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 0) subscribe_packet = mosq_test.gen_subscribe(topic="test/topic", qos=1, mid=1, proto_ver=5, properties=props) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Incorrect property") # Truncated packet, no mid subscribe_packet = struct.pack("!BB", 130, 0) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, no mid") # Truncated packet, no properties subscribe_packet = struct.pack("!BBH", 130, 2, 1) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, no properties") # Truncated packet, with properties field subscribe_packet = struct.pack("!BBHB", 130, 3, 1, 0) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, with properties field") # Truncated packet, with properties field, empty topic subscribe_packet = struct.pack("!BBHBH", 130, 5, 1, 0, 0) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, with properties field, empty topic") # Truncated packet, with properties field, empty topic, with qos subscribe_packet = struct.pack("!BBHBHB", 130, 6, 1, 0, 0, 1) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, with properties field, empty topic, with qos") # Truncated packet, with properties field, with topic, no qos subscribe_packet = struct.pack("!BBHBH1s", 130, 6, 1, 0, 1, b"a") do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, with properties field, with topic, no qos") # Truncated packet, with properties field, with 1st topic and qos ok, second topic ok, no second qos subscribe_packet = struct.pack("!BBHHH1sBH1s", 130, 10, 1, 0, 1, b"a", 0, 1, b"b") do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, with properties field, with 1st topic and qos ok, second topic ok, no second qos") # Bad topic subscribe_packet = mosq_test.gen_subscribe(topic="#/test/topic", qos=1, mid=1, proto_ver=5) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Bad topic") # Subscription ID set to 0 props = mqtt5_props.gen_varint_prop(mqtt5_props.PROP_SUBSCRIPTION_IDENTIFIER, 0) subscribe_packet = mosq_test.gen_subscribe(topic="test/topic", qos=1, mid=1, proto_ver=5, properties=props) do_test(subscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Subscription ID set to 0") except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/06-bridge-br2b-disconnect-qos2.py0000775000175000017500000001260414060132747023023 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, protocol_version): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("allow_anonymous true\n") 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") f.write("bridge_protocol_version %s\n" % (protocol_version)) def do_test(proto_ver): if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, bridge_protocol) 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=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) if proto_ver == 5: opts = mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL | mqtt5_opts.MQTT_SUB_OPT_RETAIN_AS_PUBLISHED else: opts = 0 mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2 | opts, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 3 subscribe2_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2 | opts, proto_ver=proto_ver) suback2_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 4 subscribe3_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2 | opts, proto_ver=proto_ver) suback3_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 2 publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=2, mid=mid, payload="disconnect-message", proto_ver=proto_ver) publish_dup_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=2, mid=mid, payload="disconnect-message", dup=True, proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) 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) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) mosq_test.expect_packet(bridge, "subscribe", subscribe_packet) bridge.send(suback_packet) # Helper helper_connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive, proto_ver=proto_ver) helper_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 312 helper_publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=2, mid=mid, payload="disconnect-message", proto_ver=proto_ver) helper_pubrec_packet = mosq_test.gen_pubrec(mid=mid, proto_ver=proto_ver) helper_pubrel_packet = mosq_test.gen_pubrel(mid=mid, proto_ver=proto_ver) helper_pubcomp_packet = mosq_test.gen_pubcomp(mid=mid, proto_ver=proto_ver) helper_sock = mosq_test.do_client_connect(helper_connect_packet, helper_connack_packet, port=port2, connack_error="helper connack") mosq_test.do_send_receive(helper_sock, helper_publish_packet, helper_pubrec_packet, "helper pubrec") mosq_test.do_send_receive(helper_sock, helper_pubrel_packet, helper_pubcomp_packet, "helper pubcomp") helper_sock.close() # End helper mosq_test.expect_packet(bridge, "publish", publish_packet) bridge.close() (bridge, address) = ssock.accept() bridge.settimeout(20) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) mosq_test.expect_packet(bridge, "2nd subscribe", subscribe2_packet) bridge.send(suback2_packet) mosq_test.expect_packet(bridge, "2nd publish", publish_dup_packet) bridge.send(pubrec_packet) mosq_test.expect_packet(bridge, "pubrel", pubrel_packet) bridge.close() (bridge, address) = ssock.accept() bridge.settimeout(20) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) mosq_test.expect_packet(bridge, "3rd subscribe", subscribe3_packet) bridge.send(suback3_packet) mosq_test.expect_packet(bridge, "2nd pubrel", pubrel_packet) bridge.send(pubcomp_packet) rc = 0 bridge.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() ssock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subpub-qos2-bad-puback-2.py0000775000175000017500000000555114060132747022240 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 * def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos2-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos2", 2, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) helper_connect = mosq_test.gen_connect("helper", keepalive=keepalive, proto_ver=proto_ver) helper_connack = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish1s_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message", proto_ver=proto_ver) pubrec1s_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel1s_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp1s_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) mid = 1 publish1r_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="message", proto_ver=proto_ver) pubrec1r_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel1r_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) puback1r_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) 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() 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/06-bridge-b2br-late-connection.py0000775000175000017500000000562614060132747023100 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, protocol_version): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("allow_anonymous true\n") 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("bridge_protocol_version %s\n" % (protocol_version)) def do_test(proto_ver): if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, bridge_protocol) 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=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) c_connect_packet = mosq_test.gen_connect("client", keepalive=keepalive, proto_ver=proto_ver) c_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish_packet = mosq_test.gen_publish("bridge/test", qos=1, mid=mid, payload="message", proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) 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 mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) mosq_test.expect_packet(bridge, "publish", publish_packet) rc = 0 bridge.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() ssock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/12-prop-maximum-packet-size-publish-qos2.py0000775000175000017500000000401614060132747025122 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") sock.send(pubrel2_packet) mosq_test.receive_unordered(sock, pubcomp2_packet, publish2_packet, "pubcomp 2/publish2") rc = 0 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/13-malformed-publish-v5.py0000775000175000017500000000776314060132747021703 0ustar rogerroger#!/usr/bin/env python3 # Test whether the broker handles malformed packets correctly - PUBLISH # MQTTv5 from mosq_test_helper import * rc = 1 def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("maximum_qos 1\n") f.write("retain_available false\n") def do_test(publish_packet, reason_code, error_string): global rc rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("test", proto_ver=5, keepalive=keepalive) connack_props = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS_MAXIMUM, 10) connack_props += mqtt5_props.gen_byte_prop(mqtt5_props.PROP_RETAIN_AVAILABLE, 0) connack_props += mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 20) connack_props += mqtt5_props.gen_byte_prop(mqtt5_props.PROP_MAXIMUM_QOS, 1) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=connack_props, property_helper=False) mid = 0 disconnect_packet = mosq_test.gen_disconnect(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, disconnect_packet, error_string=error_string) rc = 0 port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: # mid == 0 publish_packet = mosq_test.gen_publish(topic="test/topic", qos=1, mid=0, proto_ver=5) do_test(publish_packet, mqtt5_rc.MQTT_RC_PROTOCOL_ERROR, "mid == 0") # qos > 2 publish_packet = mosq_test.gen_publish(topic="test/topic", qos=3, mid=1, proto_ver=5) do_test(publish_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "qos > 2") # qos > maximum qos publish_packet = mosq_test.gen_publish(topic="test/topic", qos=2, mid=1, proto_ver=5) do_test(publish_packet, mqtt5_rc.MQTT_RC_QOS_NOT_SUPPORTED, "qos > maximum qos") # retain not supported publish_packet = mosq_test.gen_publish(topic="test/topic", qos=0, retain=True, proto_ver=5, payload="a") do_test(publish_packet, mqtt5_rc.MQTT_RC_RETAIN_NOT_SUPPORTED, "retain not supported") # Incorrect property props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 0) publish_packet = mosq_test.gen_publish(topic="test/topic", qos=1, mid=1, proto_ver=5, properties=props) do_test(publish_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Incorrect property") # Truncated packet, remaining length only publish_packet = struct.pack("!BB", 48, 0) do_test(publish_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, remaining length only") # Truncated packet, empty topic publish_packet = struct.pack("!BBH", 48, 2, 0) do_test(publish_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, empty topic") # Truncated packet, with topic, no properties publish_packet = struct.pack("!BBH1s", 48, 3, 1, b"a") do_test(publish_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, with topic, no properties") # Truncated packet, with topic, no mid publish_packet = struct.pack("!BBH1s", 48+2, 3, 1, b"a") do_test(publish_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, with topic, no mid") # Truncated packet, with topic, with mid, no properties publish_packet = struct.pack("!BBH1sH", 48+2, 5, 1, b"a", 1) do_test(publish_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, with topic, with mid, no properties") # Bad topic publish_packet = mosq_test.gen_publish(topic="#/test/topic", qos=1, mid=1, proto_ver=5) do_test(publish_packet, mqtt5_rc.MQTT_RC_PROTOCOL_ERROR, "Bad topic") except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() os.remove(conf_file) if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/01-connect-uname-password-success-no-tls.py0000775000175000017500000000254614060132747025204 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") def do_test(proto_ver): 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", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) 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 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/06-bridge-clean-session.py0000775000175000017500000002610214060132747021724 0ustar rogerroger#!/usr/bin/env python3 # Test whether a broker handles cleansession and local_cleansession correctly on bridges # # Test cases (with settings for broker A (edge). The settings on broker B (core) # are irrelevant, though you'll need persistence enabled to test, unless you # can simulate network interruptions. # Similarly, you'll need persistence on A, _purely_ to simplify the testing with a client # t# | LCS | CS | queued from (expected) # | A->B | B->A # 1 | -(t| t | no | no # 2 | -(f| f | yes | yes # 3 | t | t | no | no (as per #1) # 4 | t | f | no | yes # 5 | f | t | yes | no # 6 | f | f | yes | yes (as per #2) # # Test setup is two (real) brokers, so that messages can be published and subscribed in both # directions, with two test clients, one at each end. # Disable on Travis for now, too unreliable import os if os.environ.get('TRAVIS') is not None: exit(0) from mosq_test_helper import * from collections import namedtuple # Normally we don't want tests to spew debug, but if you're working on a test, it's useful VERBOSE_TEST=False def tprint(*args, **kwargs): if VERBOSE_TEST: print(" ".join(map(str,args)), **kwargs) # this is our "A" broker def write_config_edge(filename, persistence_file, remote_port, listen_port, protocol_version, cs=False, lcs=None): with open(filename, 'w') as f: f.write("port %d\n" % (listen_port)) f.write("allow_anonymous true\n") f.write("\n") f.write("persistence true\n") f.write("persistence_file %s\n" % (persistence_file)) f.write("\n") f.write("connection bridge_sample\n") f.write("address 127.0.0.1:%d\n" % (remote_port)) f.write("topic br_out/# out 1\n") f.write("topic br_in/# in 1\n") f.write("notifications false\n") # We need to ensure connections break fast enough to keep test times sane f.write("keepalive_interval 5\n") f.write("restart_timeout 5\n") f.write("cleansession %s\n" % ("true" if cs else "false")) # Ensure defaults are tested if lcs is not None: f.write("local_cleansession %s\n" % ("true" if lcs else "false")) f.write("bridge_protocol_version %s\n" % (protocol_version)) # this is our "B" broker def write_config_core(filename, listen_port, persistence_file): with open(filename, 'w') as f: f.write("port %d\n" % (listen_port)) f.write("allow_anonymous true\n") f.write("\n") f.write("persistence true\n") f.write("persistence_file %s\n" % (persistence_file)) def do_test(proto_ver, cs, lcs=None): tprint("Running test with cs:%s, lcs: %s and proto: %d" % (cs, lcs, proto_ver)) if proto_ver == 4: bridge_protocol = "mqttv311" else: bridge_protocol = "mqttv50" # Match default behaviour of broker expect_queued_ab = True expect_queued_ba = True if lcs is None: lcs = cs if lcs: expect_queued_ab = False if cs: expect_queued_ba = False (port_a_listen, port_b_listen) = mosq_test.get_port(2) conf_file_a = os.path.basename(__file__).replace('.py', '_a_edge.conf') persistence_file_a = os.path.basename(__file__).replace('.py', '_a_edge.db') write_config_edge(conf_file_a, persistence_file_a, port_b_listen, port_a_listen, bridge_protocol, cs=cs, lcs=lcs) conf_file_b = os.path.basename(__file__).replace('.py', '_b_core.conf') persistence_file_b = os.path.basename(__file__).replace('.py', '_b_core.db') write_config_core(conf_file_b, port_b_listen, persistence_file_b) AckedPair = namedtuple("AckedPair", "p ack") def make_conn(client_tag, proto, cs, session_present=False): client_id = socket.gethostname() + "." + client_tag keepalive = 60 conn = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=cs, proto_ver=proto, session_expiry=0 if cs else 5000) connack = mosq_test.gen_connack(rc=0, proto_ver=proto_ver, flags=1 if session_present else 0) return AckedPair(conn, connack) def make_sub(topic, mid, qos, proto): if proto_ver == 5: opts = mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL | mqtt5_opts.MQTT_SUB_OPT_RETAIN_AS_PUBLISHED else: opts = 0 sub = mosq_test.gen_subscribe(mid, topic, qos | opts, proto_ver=proto) suback = mosq_test.gen_suback(mid, qos, proto_ver=proto) return AckedPair(sub, suback) def make_pub(topic, mid, proto, qos=1, payload_tag="message", rc=-1): # Using the mid automatically makes it hard to verify messages that might have been retransmitted. # encourage users to put sequence numbers in topics instead.... pub = mosq_test.gen_publish(topic, mid=mid, qos=qos, retain=False, payload=payload_tag + "-from-" + topic, proto_ver=proto) puback = mosq_test.gen_puback(mid, proto_ver=proto, reason_code=rc) return AckedPair(pub, puback) # Clients are testing messages in both directions, they need to be durable conn_a = make_conn("client_a_edge", proto_ver, False) conn_b = make_conn("client_b_core", proto_ver, False) # We expect session present when we reconnect reconn_a = make_conn("client_a_edge", proto_ver, False, session_present=True) reconn_b = make_conn("client_b_core", proto_ver, False, session_present=True) # remember, mids are from each broker's point of view, not the "world" sub_a = make_sub("br_in/#", qos=1, mid=1, proto=proto_ver) sub_b = make_sub("br_out/#", qos=1, mid=1, proto=proto_ver) pub_a1 = make_pub("br_out/test-queued1", mid=1, proto=proto_ver) pub_a2 = make_pub("br_out/test-queued2", mid=2, proto=proto_ver) pub_a3 = make_pub("br_out/test-queued3", mid=3, proto=proto_ver) pub_a3r = make_pub("br_out/test-queued3", mid=2, proto=proto_ver) # without queueing, there is no a2 pub_b1 = make_pub("br_in/test-queued1", mid=1, proto=proto_ver) pub_b2 = make_pub("br_in/test-queued2", mid=2, proto=proto_ver) pub_b3 = make_pub("br_in/test-queued3", mid=3, proto=proto_ver) pub_b3r = make_pub("br_in/test-queued3", mid=2, proto=proto_ver) # without queueing, there is no b2 success = False stde_a1 = stde_b1 = None try: # b must start first, as it's the destination of a broker_b = mosq_test.start_broker(filename=conf_file_b, port=port_b_listen, use_conf=True) broker_a = mosq_test.start_broker(filename=conf_file_a, port=port_a_listen, use_conf=True) client_a = mosq_test.do_client_connect(conn_a.p, conn_a.ack, port=port_a_listen) mosq_test.do_send_receive(client_a, sub_a.p, sub_a.ack, "suback_a") client_b = mosq_test.do_client_connect(conn_b.p, conn_b.ack, port=port_b_listen) mosq_test.do_send_receive(client_b, sub_b.p, sub_b.ack, "suback_b") mosq_test.do_send_receive(client_a, pub_a1.p, pub_a1.ack, "puback_a1") mosq_test.do_receive_send(client_b, pub_a1.p, pub_a1.ack, "a->b1 (b-side)") mosq_test.do_send_receive(client_b, pub_b1.p, pub_b1.ack, "puback_b1") mosq_test.do_receive_send(client_a, pub_b1.p, pub_b1.ack, "b->a1 (a-side)") tprint("Normal bi-dir bridging works. continuing") broker_b.terminate() broker_b.wait() (stdo_b1, stde_b1) = broker_b.communicate() # as we're _terminating_ the connections should close ~straight away tprint("terminated B", time.time()) time.sleep(0.5) # should be queued (or not) mosq_test.do_send_receive(client_a, pub_a2.p, pub_a2.ack, "puback_a2") broker_b = mosq_test.start_broker(filename=conf_file_b, port=port_b_listen, use_conf=True) # client b needs to reconnect now! client_b = mosq_test.do_client_connect(reconn_b.p, reconn_b.ack, port=port_b_listen) tprint("client b reconnected after restarting broker b at ", time.time()) # Need to sleep long enough to be sure of a re-connection... time.sleep(10) # yuck, this makes the test run for ages! # should go through tprint("(B should be alive again now!) sending (after reconn!) a3 at ", time.time()) mosq_test.do_send_receive(client_a, pub_a3.p, pub_a3.ack, "puback_a3") if expect_queued_ab: tprint("1.expecting a->b queueing") mosq_test.do_receive_send(client_b, pub_a2.p, pub_a2.ack, "a->b_2") mosq_test.do_receive_send(client_b, pub_a3.p, pub_a3.ack, "a->b_3") else: tprint("not expecting a->b queueing") mosq_test.do_receive_send(client_b, pub_a3r.p, pub_a3r.ack, "a->b_3(r)") tprint("Stage 1 complete, repeating in other direction") # ok, now repeat in the other direction... broker_a.terminate() broker_a.wait() (stdo_a1, stde_a1) = broker_a.communicate() time.sleep(0.5) mosq_test.do_send_receive(client_b, pub_b2.p, pub_b2.ack, "puback_b2") broker_a = mosq_test.start_broker(filename=conf_file_a, port=port_a_listen, use_conf=True) # client a needs to reconnect now! client_a = mosq_test.do_client_connect(reconn_a.p, reconn_a.ack, port=port_a_listen) tprint("client A reconnected after restarting broker A at ", time.time()) # Need to sleep long enough to be sure of a re-connection... time.sleep(10) # yuck, this makes the test run for ages! # should go through mosq_test.do_send_receive(client_b, pub_b3.p, pub_b3.ack, "puback_b3") if expect_queued_ba: tprint("2.expecting b->a queueueing") mosq_test.do_receive_send(client_a, pub_b2.p, pub_b2.ack, "b->a_2") mosq_test.do_receive_send(client_a, pub_b3.p, pub_b3.ack, "b->a_3") else: tprint("not expecting message b->a_2") mosq_test.do_receive_send(client_a, pub_b3r.p, pub_b3r.ack, "b->a_3(r)") success = True except mosq_test.TestError: pass finally: os.remove(conf_file_a) os.remove(conf_file_b) broker_a.terminate() broker_b.terminate() broker_a.wait() broker_b.wait() (stdo_a, stde_a) = broker_a.communicate() (stdo_b, stde_b) = broker_b.communicate() # Must be after terminating! try: os.remove(persistence_file_a) except FileNotFoundError: print("persistence file a didn't exist, skipping remove") try: os.remove(persistence_file_b) except FileNotFoundError: print("persistence file b didn't exist, skipping remove") if not success: print("Test failed, dumping broker A logs: ") if stde_a1: print(stde_a1.decode('utf-8')) print(stde_a.decode('utf-8')) print("Test failed, dumping broker B logs: ") if stde_b1: print(stde_b1.decode('utf-8')) print(stde_b.decode('utf-8')) exit(1) for cs in [True, False]: for lcs in [None, True, False]: do_test(proto_ver=4, cs=cs, lcs=lcs) # FIXME - v5 clean session bridging doesn't work: see # https://github.com/eclipse/mosquitto/issues/1632 #do_test(proto_ver=5, cs=cs, lcs=lcs) exit(0) mosquitto-2.0.11/test/broker/02-subpub-qos2-receive-maximum-1.py0000775000175000017500000000541714060132747023344 0ustar rogerroger#!/usr/bin/env python3 # Does the broker respect receive maximum==1? # MQTT v5 from mosq_test_helper import * def do_test(): 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() mosq_test.expect_packet(sock, "publish1", publish_packet1) mosq_test.do_send_receive(sock, pubrec_packet1, pubrel_packet1, "pubrel1") sock.send(pubcomp_packet1) mosq_test.expect_packet(sock, "publish2", publish_packet2) mosq_test.do_send_receive(sock, pubrec_packet2, pubrel_packet2, "pubrel2") sock.send(pubcomp_packet2) 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() exit(0) mosquitto-2.0.11/test/broker/01-connect-invalid-id-utf8.py0000775000175000017500000000210014060132747022245 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client id with invalid UTF-8 fails. from mosq_test_helper import * def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("connect-invalid-utf8", keepalive=keepalive, proto_ver=proto_ver) 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/09-acl-empty-file.py0000775000175000017500000000357114060132747020547 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("allow_anonymous true\n") 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/12-prop-response-topic-correlation-data.py0000775000175000017500000000454014060132747025104 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) 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) mosq_test.expect_packet(sock2, "publish2", publish_packet1) rc = 0 sock1.close() sock2.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/12-prop-topic-alias-invalid.py0000775000175000017500000000233114060132747022531 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) mosq_test.expect_packet(sock, "disconnect", disconnect_packet) rc = 0 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(11) mosquitto-2.0.11/test/broker/09-acl-access-variants.py0000775000175000017500000001070414060132747021556 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("allow_anonymous true\n") 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') f.write('topic deny topic/global/except\n') if user_en: f.write('user username\n') f.write('topic readwrite topic/username/#\n') f.write('topic deny topic/username/except\n') if pattern_en: f.write('pattern readwrite pattern/%u/#\n') f.write('pattern deny pattern/%u/except\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") sock.send(publish1s_packet) if expect_deny: mosq_test.expect_packet(sock, "puback", puback1s_packet) mosq_test.do_ping(sock) else: mosq_test.receive_unordered(sock, puback1s_packet, publish1r_packet, "puback / publish1r") sock.close() rc = 0 except mosq_test.TestError: pass 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) single_test(port, per_listener, username=None, topic="topic/global/except", 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) single_test(port, per_listener, username="username", topic="topic/username/except", expect_deny=True) 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) single_test(port, per_listener, username="username", topic="pattern/username/except", expect_deny=True) 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-2.0.11/test/broker/12-prop-subpub-payload-format.py0000775000175000017500000000106214060132747023115 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-2.0.11/test/broker/09-auth-bad-method.py0000775000175000017500000000161714060132747020701 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/14-dynsec-client.py0000775000175000017500000001233514060132747020472 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(expected_response) print(response) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) add_client_command = { "commands": [{ "command": "createClient", "username": "user_one", "password": "password", "clientid": "cid", "textname": "Name", "textdescription": "Description", "rolename": "", "correlationData": "2" }] } add_client_response = {'responses': [{'command': 'createClient', 'correlationData': '2'}]} add_client_repeat_response = {'responses':[{"command":"createClient","error":"Client already exists", "correlationData":"2"}]} list_clients_command = { "commands": [{ "command": "listClients", "verbose": False, "correlationData": "10"}] } list_clients_response = {'responses': [{"command": "listClients", "data":{"totalCount":2, "clients":["admin", "user_one"]},"correlationData":"10"}]} list_clients_verbose_command = { "commands": [{ "command": "listClients", "verbose": True, "correlationData": "20"}] } list_clients_verbose_response = {'responses':[{"command": "listClients", "data":{"totalCount":2, "clients":[ {'username': 'admin', 'textname': 'Dynsec admin user', 'roles': [{'rolename': 'admin'}], 'groups': []}, {"username":"user_one", "clientid":"cid", "textname":"Name", "textdescription":"Description", "roles":[], "groups":[]}]}, "correlationData":"20"}]} get_client_command = { "commands": [{ "command": "getClient", "username": "user_one", "correlationData": "42"}]} get_client_response = {'responses':[{'command': 'getClient', 'data': {'client': {'username': 'user_one', 'clientid': 'cid', 'textname': 'Name', 'textdescription': 'Description', 'groups': [], 'roles': []}}, "correlationData":"42"}]} set_client_password_command = {"commands": [{ "command": "setClientPassword", "username": "user_one", "password": "password"}]} set_client_password_response = {"responses": [{"command":"setClientPassword"}]} delete_client_command = { "commands": [{ "command": "deleteClient", "username": "user_one"}]} delete_client_response = {'responses':[{'command': 'deleteClient'}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Add client command_check(sock, add_client_command, add_client_response) # List clients non-verbose command_check(sock, list_clients_command, list_clients_response) # List clients verbose command_check(sock, list_clients_verbose_command, list_clients_verbose_response) # Kill broker and restart, checking whether our changes were saved. 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, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Get client command_check(sock, get_client_command, get_client_response) # List clients non-verbose command_check(sock, list_clients_command, list_clients_response) # List clients verbose command_check(sock, list_clients_verbose_command, list_clients_verbose_response) # Add duplicate client command_check(sock, add_client_command, add_client_repeat_response) # Set client password command_check(sock, set_client_password_command, set_client_password_response) # Delete client command_check(sock, delete_client_command, delete_client_response) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/08-tls-psk-bridge.py0000775000175000017500000000552714060132747020570 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("allow_anonymous true\n") 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() mosq_test.expect_packet(sock, "publish", publish_packet) rc = 0 sock.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/01-connect-invalid-reserved.py0000775000175000017500000000150614060132747022615 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/08-tls-psk-bridge.psk0000664000175000017500000000002214060132747020713 0ustar rogerrogerpsk-test:deadbeef mosquitto-2.0.11/test/broker/02-subpub-qos0-send-retain.py0000775000175000017500000000705614060132747022321 0ustar rogerroger#!/usr/bin/env python3 # Test whether "send retain" subscribe options work # MQTT v5 from mosq_test_helper import * def do_test(): 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") 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") 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") mosq_test.expect_packet(sock, "publish1r1", publish1r2_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() exit(0) mosquitto-2.0.11/test/broker/02-subscribe-invalid-utf8.py0000775000175000017500000000315514060132747022217 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 * def do_test(proto_ver): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-invalid-utf8", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "invalid/utf8", 0, proto_ver=proto_ver) 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, proto_ver=proto_ver) 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) if proto_ver == 4: mosq_test.do_send_receive(sock, subscribe_packet, b"", "suback") else: disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code = mqtt5_rc.MQTT_RC_MALFORMED_PACKET) mosq_test.do_send_receive(sock, subscribe_packet, disconnect_packet, "suback") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/09-plugin-publish.py0000775000175000017500000000646214060132747020703 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_publish.so\n") f.write("allow_anonymous true\n") proto_ver = 5 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("test-client", keepalive=keepalive, username="readwrite", clean_session=False, proto_ver=proto_ver) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("init", qos=0, proto_ver=proto_ver) publish0_packet = mosq_test.gen_publish("topic/0", qos=0, payload="test-message-0", proto_ver=proto_ver) mid = 1 publish1_packet = mosq_test.gen_publish("topic/1", qos=1, mid=mid, payload="test-message-1", proto_ver=proto_ver) puback1_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) mid = 2 publish2_packet = mosq_test.gen_publish("topic/2", qos=2, mid=mid, payload="test-message-2", proto_ver=proto_ver) pubrec2_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel2_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp2_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) props = mqtt5_props.gen_byte_prop(mqtt5_props.PROP_PAYLOAD_FORMAT_INDICATOR, 1) publish0p_packet = mosq_test.gen_publish("topic/0", qos=0, payload="test-message-0", proto_ver=proto_ver, properties=props) mid = 3 publish1p_packet = mosq_test.gen_publish("topic/1", qos=1, mid=mid, payload="test-message-1", proto_ver=proto_ver, properties=props) puback1p_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) mid = 4 publish2p_packet = mosq_test.gen_publish("topic/2", qos=2, mid=mid, payload="test-message-2", proto_ver=proto_ver, properties=props) pubrec2p_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel2p_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp2p_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) 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) # Trigger the plugin to send us some messages sock.send(publish_packet) mosq_test.expect_packet(sock, "publish0", publish0_packet) mosq_test.expect_packet(sock, "publish1", publish1_packet) sock.send(puback1_packet) mosq_test.expect_packet(sock, "publish2", publish2_packet) mosq_test.do_send_receive(sock, pubrec2_packet, pubrel2_packet, "pubrel1") sock.send(pubcomp2_packet) # And trigger the second set of messages, with properties sock.send(publish_packet) mosq_test.expect_packet(sock, "publish0p", publish0p_packet) mosq_test.expect_packet(sock, "publish1p", publish1p_packet) sock.send(puback1_packet) mosq_test.expect_packet(sock, "publish2p", publish2p_packet) mosq_test.do_send_receive(sock, pubrec2p_packet, pubrel2p_packet, "pubrel1p") sock.send(pubcomp2p_packet) mosq_test.do_ping(sock) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/01-connect-uname-password-success-no-tls.pwfile0000664000175000017500000000001614060132747026025 0ustar rogerrogeruser:password mosquitto-2.0.11/test/broker/05-session-expiry-v5.py0000775000175000017500000001001114060132747021247 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/07-will-null-topic.py0000775000175000017500000000214114060132747020760 0ustar rogerroger#!/usr/bin/env python3 import struct from mosq_test_helper import * def do_test(proto_ver): 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"), proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=2, 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, 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/14-dynsec-modify-client.py0000775000175000017500000001614714060132747021764 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response, msg=""): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(msg) print(expected_response) print(response) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) create_client_command = { "commands": [{ "command": "createClient", "username": "user_one", "password": "password", "clientid": "cid", "textname": "Name", "textdescription": "Description", "correlationData": "2" }] } create_client_response = {'responses': [{'command': 'createClient', 'correlationData': '2'}]} create_groups_command = { "commands": [ { "command": "createGroup", "groupname": "group_one", "textname": "Name", "textdescription": "Description", "correlationData": "12" }, { "command": "createGroup", "groupname": "group_two", "textname": "Name", "textdescription": "Description", "correlationData": "13" } ] } create_groups_response = {'responses': [ {'command': 'createGroup', 'correlationData': '12'}, {'command': 'createGroup', 'correlationData': '13'} ]} create_roles_command = { "commands": [ { "command": "createRole", "rolename": "role_one", "textname": "Name", "textdescription": "Description", "acls":[], "correlationData": "21" }, { "command": "createRole", "rolename": "role_two", "textname": "Name", "textdescription": "Description", "acls":[], "correlationData": "22" }, { "command": "createRole", "rolename": "role_three", "textname": "Name", "textdescription": "Description", "acls":[], "correlationData": "23" } ] } create_roles_response = {'responses': [ {'command': 'createRole', 'correlationData': '21'}, {'command': 'createRole', 'correlationData': '22'}, {'command': 'createRole', 'correlationData': '23'} ]} modify_client_command1 = { "commands": [{ "command": "modifyClient", "username": "user_one", "textname": "Modified name", "textdescription": "Modified description", "clientid": "", "roles":[ {'rolename':'role_one', 'priority':2}, {'rolename':'role_two'}, {'rolename':'role_three', 'priority':10} ], "groups":[ {'groupname':'group_one', 'priority':3}, {'groupname':'group_two', 'priority':8} ], "correlationData": "3" }] } modify_client_response1 = {'responses': [{'command': 'modifyClient', 'correlationData': '3'}]} modify_client_command2 = { "commands": [{ "command": "modifyClient", "username": "user_one", "textname": "Modified name", "textdescription": "Modified description", "groups":[], "correlationData": "4" }] } modify_client_response2 = {'responses': [{'command': 'modifyClient', 'correlationData': '4'}]} get_client_command1 = { "commands": [{ "command": "getClient", "username": "user_one"}]} get_client_response1 = {'responses':[{'command': 'getClient', 'data': {'client': {'username': 'user_one', 'clientid': 'cid', 'textname': 'Name', 'textdescription': 'Description', 'roles': [], 'groups': [], }}}]} get_client_command2 = { "commands": [{ "command": "getClient", "username": "user_one"}]} get_client_response2 = {'responses':[{'command': 'getClient', 'data': {'client': {'username': 'user_one', 'textname': 'Modified name', 'textdescription': 'Modified description', 'roles': [ {'rolename':'role_three', 'priority':10}, {'rolename':'role_one', 'priority':2}, {'rolename':'role_two'} ], 'groups': [ {'groupname':'group_two', 'priority':8}, {'groupname':'group_one', 'priority':3} ]}}}]} get_client_command3 = { "commands": [{ "command": "getClient", "username": "user_one"}]} get_client_response3 = {'responses':[{'command': 'getClient', 'data': {'client': {'username': 'user_one', 'textname': 'Modified name', 'textdescription': 'Modified description', 'groups': [], 'roles': [ {'rolename':'role_three', 'priority':10}, {'rolename':'role_one', 'priority':2}, {'rolename':'role_two'} ]}}}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Create client command_check(sock, create_client_command, create_client_response) # Create groups command_check(sock, create_groups_command, create_groups_response) # Create role command_check(sock, create_roles_command, create_roles_response) # Get client command_check(sock, get_client_command1, get_client_response1, "get client 1") # Modify client - with groups command_check(sock, modify_client_command1, modify_client_response1) # Get client command_check(sock, get_client_command2, get_client_response2, "get client 2a") # Kill broker and restart, checking whether our changes were saved. 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, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Get client command_check(sock, get_client_command2, get_client_response2, "get client 2b") # Modify client - without groups command_check(sock, modify_client_command2, modify_client_response2) # Get client command_check(sock, get_client_command3, get_client_response3, "get client 3") rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") pass except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/09-extended-auth-single2.py0000775000175000017500000000775514060132747022047 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 except mosq_test.TestError: pass 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-2.0.11/test/broker/09-pwfile-parse-invalid.py0000775000175000017500000001520614060132747021757 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/03-publish-b2c-disconnect-qos1.py0000775000175000017500000000614414060132747023052 0ustar rogerroger#!/usr/bin/env python3 # Does an interrupted QoS 1 flow from broker to client get handled correctly? from mosq_test_helper import * def helper(port): connect_packet = mosq_test.gen_connect("test-helper", keepalive=60) 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") sock.close() def do_test(proto_ver): 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, proto_ver=proto_ver, session_expiry=60) connack1_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(flags=1, rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "qos1/disconnect/test", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid = 1 publish_packet = mosq_test.gen_publish("qos1/disconnect/test", qos=1, mid=mid, payload="disconnect-message", proto_ver=proto_ver) publish_dup_packet = mosq_test.gen_publish("qos1/disconnect/test", qos=1, mid=mid, payload="disconnect-message", dup=True, proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) mid = 3266 publish2_packet = mosq_test.gen_publish("qos1/outgoing", qos=1, mid=mid, payload="outgoing-message", proto_ver=proto_ver) puback2_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) 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") helper(port) # Should have now received a publish command 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") mosq_test.expect_packet(sock, "dup publish", publish_dup_packet) sock.send(puback_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/03-publish-b2c-disconnect-qos2.py0000775000175000017500000000673314060132747023057 0ustar rogerroger#!/usr/bin/env python3 # Does an interrupted QoS 1 flow from broker to client get handled correctly? from mosq_test_helper import * def helper(port): connect_packet = mosq_test.gen_connect("test-helper", keepalive=60) 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") sock.close() def do_test(proto_ver): rc = 1 mid = 3265 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos2-disco-test", keepalive=keepalive, clean_session=False, proto_ver=proto_ver, session_expiry=60) connack1_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(flags=1, rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/disconnect/test", 2, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 1 publish_packet = mosq_test.gen_publish("qos2/disconnect/test", qos=2, mid=mid, payload="disconnect-message", proto_ver=proto_ver) publish_dup_packet = mosq_test.gen_publish("qos2/disconnect/test", qos=2, mid=mid, payload="disconnect-message", dup=True, proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) mid = 3266 publish2_packet = mosq_test.gen_publish("qos1/outgoing", qos=1, mid=mid, payload="outgoing-message", proto_ver=proto_ver) puback2_packet = mosq_test.gen_puback(mid, 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, connack1_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") helper(port) # Should have now received a publish command 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) 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) mosq_test.expect_packet(sock, "dup pubrel", pubrel_packet) sock.send(pubcomp_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/04-retain-qos0-repeated.py0000775000175000017500000000364614060132747021666 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 * def do_test(proto_ver): rc = 1 keepalive = 60 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-rep-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos0/test", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) unsub_mid = 13 unsubscribe_packet = mosq_test.gen_unsubscribe(unsub_mid, "retain/qos0/test", proto_ver=proto_ver) unsuback_packet = mosq_test.gen_unsuback(unsub_mid, 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, timeout=20, port=port) sock.send(publish_packet) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") 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") mosq_test.expect_packet(sock, "publish", publish_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-shared-qos0-v5.py0000775000175000017500000001400114060132747020374 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) mosq_test.expect_packet(sock1, "publish1 1", publish1_packet) mosq_test.expect_packet(sock2, "publish1 2", publish1_packet) mosq_test.expect_packet(sock3, "publish1 3", publish1_packet) sock1.send(publish2_packet) mosq_test.expect_packet(sock1, "publish2 1", publish2_packet) mosq_test.expect_packet(sock3, "publish2 3", publish2_packet) mosq_test.expect_packet(sock4, "publish2 4", publish2_packet) sock1.send(publish3_packet) mosq_test.expect_packet(sock1, "publish3 1", publish3_packet) mosq_test.expect_packet(sock3, "publish3 3", publish3_packet) 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/01-connect-invalid-id-missing.py0000775000175000017500000000130114060132747023032 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/06-bridge-per-listener-settings.py0000775000175000017500000001241014060132747023425 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, protocol_version): 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") f.write("bridge_protocol_version %s\n" % (protocol_version)) def inner_test(bridge, sock, proto_ver): global connect_packet, connack_packet if not mosq_test.expect_packet(bridge, "connect", connect_packet): return 1 bridge.send(connack_packet) if proto_ver == 5: opts = mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL | mqtt5_opts.MQTT_SUB_OPT_RETAIN_AS_PUBLISHED else: opts = 0 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 | opts, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) 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 | opts, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) 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='', proto_ver=proto_ver) local_publish_packet = mosq_test.gen_publish( local_topic, qos=0, mid=mid, payload='', proto_ver=proto_ver) 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 def do_test(proto_ver): global connect_packet, connack_packet if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2, port3) = mosq_test.get_port(3) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, port3, bridge_protocol) 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=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) client_connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive, proto_ver=proto_ver) client_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) 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) try: (bridge, address) = ssock.accept() bridge.settimeout(2) sock = mosq_test.do_client_connect( client_connect_packet, client_connack_packet, port=port2, ) rc = inner_test(bridge, sock, proto_ver) sock.close() bridge.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() ssock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/14-dynsec-group.py0000775000175000017500000002116414060132747020350 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response, msg=""): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(msg) print(expected_response) print(response) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) create_client_command = { "commands": [{ "command": "createClient", "username": "user_one", "password": "password", "clientid": "cid", "textname": "Name", "textdescription": "description", "rolename": "", "correlationData": "2" }]} create_client_response = {'responses':[{"command":"createClient","correlationData":"2"}]} create_client2_command = { "commands": [{ "command": "createClient", "username": "user_two", "password": "password", "textname": "Name", "textdescription": "description", "rolename": "", "correlationData": "1" }]} create_client2_response = {'responses':[{"command":"createClient","correlationData":"1"}]} create_group_command = { "commands": [{ "command": "createGroup", "groupname": "group_one", "textname": "Name", "textdescription": "description", "correlationData":"3"}]} create_group_response = {'responses':[{"command":"createGroup","correlationData":"3"}]} create_group_repeat_response = {'responses':[{"command":"createGroup","error":"Group already exists","correlationData":"3"}]} create_group2_command = { "commands": [{ "command": "createGroup", "groupname": "group_two", "textname": "Name", "textdescription": "description", "correlationData":"30"}]} create_group2_response = {'responses':[{"command":"createGroup","correlationData":"30"}]} list_groups_command = { "commands": [{ "command": "listGroups", "verbose": False, "correlationData": "10"}]} list_groups_response = {'responses':[{"command": "listGroups", "data":{"totalCount":2, "groups":["group_one","group_two"]},"correlationData":"10"}]} list_groups_verbose_command = { "commands": [{ "command": "listGroups", "verbose": True, "correlationData": "15"}]} list_groups_verbose_response = {'responses':[{'command': 'listGroups', 'data': {"totalCount":2, 'groups':[ {'groupname': 'group_one', 'textname': 'Name', 'textdescription': 'description', 'clients': [ {"username":"user_one"}, {"username":"user_two"}], "roles":[]}, {'groupname': 'group_two', 'textname': 'Name', 'textdescription': 'description', 'clients': [ {"username":"user_one"}], "roles":[]} ]}, 'correlationData': '15'}]} list_clients_verbose_command = { "commands": [{ "command": "listClients", "verbose": True, "correlationData": "20"}]} list_clients_verbose_response = {'responses':[{"command": "listClients", "data":{"totalCount":3, "clients":[ {'username': 'admin', 'textname': 'Dynsec admin user', 'roles': [{'rolename': 'admin'}], 'groups': []}, {"username":"user_one", "clientid":"cid", "textname":"Name", "textdescription":"description", "groups":[{"groupname":"group_one"}, {"groupname":"group_two"}], "roles":[]}, {"username":"user_two", "textname":"Name", "textdescription":"description", "groups":[{"groupname":"group_one"}], "roles":[]}, ]}, "correlationData":"20"}]} get_group_command = { "commands": [{"command": "getGroup", "groupname":"group_one"}]} get_group_response = {'responses':[{'command': 'getGroup', 'data': {'group': {'groupname': 'group_one', 'textname':'Name', 'textdescription':'description', 'clients': [{"username":"user_one"}, {"username":"user_two"}], 'roles': []}}}]} add_client_to_group_command = {"commands": [{"command":"addGroupClient", "username":"user_one", "groupname": "group_one", "correlationData":"1234"}]} add_client_to_group_response = {'responses':[{'command': 'addGroupClient', 'correlationData': '1234'}]} add_duplicate_client_to_group_response = {'responses':[{'command': 'addGroupClient', 'error':'Client is already in this group', 'correlationData': '1234'}]} add_client_to_group2_command = {"commands": [{"command":"addGroupClient", "username":"user_one", "groupname": "group_two", "correlationData":"1234"}]} add_client_to_group2_response = {'responses':[{'command': 'addGroupClient', 'correlationData': '1234'}]} add_client2_to_group_command = {"commands": [{"command":"addGroupClient", "username":"user_two", "groupname": "group_one", "correlationData":"1235"}]} add_client2_to_group_response = {'responses':[{'command': 'addGroupClient', 'correlationData': '1235'}]} remove_client_from_group_command = {"commands": [{"command":"removeGroupClient", "username":"user_one", "groupname": "group_one", "correlationData":"4321"}]} remove_client_from_group_response = {'responses':[{'command': 'removeGroupClient', 'correlationData': '4321'}]} delete_group_command = {"commands": [{"command":"deleteGroup", "groupname":"group_one", "correlationData":"5678"}]} delete_group_response = {'responses':[{"command":"deleteGroup", "correlationData":"5678"}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Add client command_check(sock, create_client_command, create_client_response) command_check(sock, create_client2_command, create_client2_response) # Add group command_check(sock, create_group2_command, create_group2_response) command_check(sock, create_group_command, create_group_response) # Add client to group command_check(sock, add_client_to_group_command, add_client_to_group_response) command_check(sock, add_client_to_group2_command, add_client_to_group2_response) command_check(sock, add_client2_to_group_command, add_client2_to_group_response) command_check(sock, add_client_to_group_command, add_duplicate_client_to_group_response) # Get group command_check(sock, get_group_command, get_group_response) # List groups non-verbose command_check(sock, list_groups_command, list_groups_response) # List groups verbose command_check(sock, list_groups_verbose_command, list_groups_verbose_response, "list groups") # List clients verbose command_check(sock, list_clients_verbose_command, list_clients_verbose_response) # Kill broker and restart, checking whether our changes were saved. 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, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Add duplicate group command_check(sock, create_group_command, create_group_repeat_response) # Remove client from group command_check(sock, remove_client_from_group_command, remove_client_from_group_response) # Add client back to group command_check(sock, add_client_to_group_command, add_client_to_group_response) # Delete group entirely command_check(sock, delete_group_command, delete_group_response) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/01-connect-uname-invalid-utf8.py0000775000175000017500000000212714060132747022767 0ustar rogerroger#!/usr/bin/env python3 # Test whether a username with invalid UTF-8 fails. from mosq_test_helper import * def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("connect-invalid-utf8", keepalive=keepalive, username="invalid/utf8", proto_ver=proto_ver) 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/mosq_test_helper.py0000664000175000017500000000072314060132747021057 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-2.0.11/test/broker/01-connect-uname-password-denied.pwfile0000664000175000017500000000016214060132747024375 0ustar rogerrogeruser:$6$vZY4TS+/HBxHw38S$vvjVFECzb8dyuu/mruD2QKTfdFn0WmKxbc+1TsdB0L8EdHk3v9JRmfjHd56+VaTnUcSZOZ/hzkdvWCtxlX7AUQ== mosquitto-2.0.11/test/broker/11-persistent-subscription-no-local.py0000775000175000017500000000655014060132747024354 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("allow_anonymous true\n") 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-subscription-test", keepalive=keepalive, clean_session=False, proto_ver=5, session_expiry=60 ) 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") sock.send(publish2s_packet) mosq_test.receive_unordered(sock, puback2s_packet, publish2a_packet, "puback2a/publish2a") 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") sock.send(publish2s_packet) mosq_test.receive_unordered(sock, puback2s_packet, publish2b_packet, "puback2b/publish2b") rc = 0 sock.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/03-publish-b2c-qos1-len.py0000775000175000017500000000516714060132747021503 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 helper(port): connect_packet = mosq_test.gen_connect("test-helper", keepalive=60) 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") sock.close() def len_test(test, puback_packet): 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) 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") helper(port) # Should have now received a publish command mosq_test.expect_packet(sock, "publish", publish_packet) sock.send(puback_packet) mosq_test.do_ping(sock) rc = 0 sock.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/14-dynsec-auth.py0000775000175000017500000002070714060132747020157 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous false\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(expected_response) print(response) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) add_client_command_with_id = { "commands": [{ "command": "createClient", "username": "user_one", "password": "password", "clientid": "cid", "correlationData": "2" }] } add_client_response_with_id = {'responses': [{'command': 'createClient', 'correlationData': '2'}]} add_client_command_without_id = { "commands": [{ "command": "createClient", "username": "user_two", "password": "asdfgh", "correlationData": "3" }] } add_client_response_without_id = {'responses': [{'command': 'createClient', 'correlationData': '3'}]} set_client_id_command = { "commands": [{ "command": "setClientId", "username": "user_two", "clientid": "new-cid", "correlationData": "5" }] } set_client_id_response = {'responses': [{'command': 'setClientId', 'correlationData': '5'}]} # No password defined, this client should never be able to connect. add_client_command_without_pw = { "commands": [{ "command": "createClient", "username": "user_three", "correlationData": "4" }] } add_client_response_without_pw = {'responses': [{'command': 'createClient', 'correlationData': '4'}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) # Success connect_packet_with_id1 = mosq_test.gen_connect("cid", keepalive=keepalive, username="user_one", password="password", proto_ver=5) connack_packet_with_id1 = mosq_test.gen_connack(rc=0, proto_ver=5) # Fail - bad client id connect_packet_with_id2 = mosq_test.gen_connect("bad-cid", keepalive=keepalive, username="user_one", password="password", proto_ver=5) connack_packet_with_id2 = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - bad password connect_packet_with_id3 = mosq_test.gen_connect("cid", keepalive=keepalive, username="user_one", password="ttt", proto_ver=5) connack_packet_with_id3 = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - no password connect_packet_with_id4 = mosq_test.gen_connect("cid", keepalive=keepalive, username="user_one", proto_ver=5) connack_packet_with_id4 = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Success connect_packet_without_id1 = mosq_test.gen_connect("no-cid", keepalive=keepalive, username="user_two", password="asdfgh", proto_ver=5) connack_packet_without_id1 = mosq_test.gen_connack(rc=0, proto_ver=5) # Fail - bad password connect_packet_without_id2 = mosq_test.gen_connect("no-cid", keepalive=keepalive, username="user_two", password="pass", proto_ver=5) connack_packet_without_id2 = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - no password connect_packet_without_id3 = mosq_test.gen_connect("no-cid", keepalive=keepalive, username="user_two", proto_ver=5) connack_packet_without_id3 = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Success connect_packet_set_id1 = mosq_test.gen_connect("new-cid", keepalive=keepalive, username="user_two", password="asdfgh", proto_ver=5) connack_packet_set_id1 = mosq_test.gen_connack(rc=0, proto_ver=5) # Fail - bad client id connect_packet_set_id2 = mosq_test.gen_connect("bad-cid", keepalive=keepalive, username="user_two", password="asdfgh", proto_ver=5) connack_packet_set_id2 = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - bad password connect_packet_without_pw1 = mosq_test.gen_connect("cid2", keepalive=keepalive, username="user_three", password="pass", proto_ver=5) connack_packet_without_pw1 = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - no password connect_packet_without_pw2 = mosq_test.gen_connect("cid2", keepalive=keepalive, username="user_three", proto_ver=5) connack_packet_without_pw2 = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - no username connect_packet_without_un = mosq_test.gen_connect("cid3", keepalive=keepalive, proto_ver=5) connack_packet_without_un = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=5, property_helper=False) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Add client command_check(sock, add_client_command_with_id, add_client_response_with_id) command_check(sock, add_client_command_without_id, add_client_response_without_id) command_check(sock, add_client_command_without_pw, add_client_response_without_pw) # Client with username, password, and client id csock = mosq_test.do_client_connect(connect_packet_with_id1, connack_packet_with_id1, timeout=5, port=port, connack_error="with id 1") csock.close() csock = mosq_test.do_client_connect(connect_packet_with_id2, connack_packet_with_id2, timeout=5, port=port, connack_error="with id 2") csock.close() csock = mosq_test.do_client_connect(connect_packet_with_id3, connack_packet_with_id3, timeout=5, port=port, connack_error="with id 3") csock.close() csock = mosq_test.do_client_connect(connect_packet_with_id4, connack_packet_with_id4, timeout=5, port=port, connack_error="with id 4") csock.close() # Client with just username and password csock = mosq_test.do_client_connect(connect_packet_without_id1, connack_packet_without_id1, timeout=5, port=port, connack_error="without id 1") csock.close() csock = mosq_test.do_client_connect(connect_packet_without_id2, connack_packet_without_id2, timeout=5, port=port, connack_error="without id 2") csock.close() csock = mosq_test.do_client_connect(connect_packet_without_id3, connack_packet_without_id3, timeout=5, port=port, connack_error="without id 3") csock.close() # Client with no password set csock = mosq_test.do_client_connect(connect_packet_without_pw1, connack_packet_without_pw1, timeout=5, port=port, connack_error="without pw 1") csock.close() csock = mosq_test.do_client_connect(connect_packet_without_pw2, connack_packet_without_pw2, timeout=5, port=port, connack_error="without pw 2") csock.close() # Add client id to "user_two" command_check(sock, set_client_id_command, set_client_id_response) csock = mosq_test.do_client_connect(connect_packet_set_id1, connack_packet_set_id1, timeout=5, port=port, connack_error="set id 1") csock.close() csock = mosq_test.do_client_connect(connect_packet_set_id2, connack_packet_set_id2, timeout=5, port=port, connack_error="set id 2") csock.close() # No username, anon disabled csock = mosq_test.do_client_connect(connect_packet_without_un, connack_packet_without_un, timeout=5, port=port, connack_error="without username") csock.close() rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/03-publish-qos1-queued-bytes.conf0000664000175000017500000000010414060132747023151 0ustar rogerrogersys_interval 1 max_queued_messages 0 max_queued_bytes 400 port 1888 mosquitto-2.0.11/test/broker/test.py0000775000175000017500000002027514060132747016470 0ustar rogerroger#!/usr/bin/env python3 import mosq_test_helper import ptest tests = [ #(ports required, 'path'), (1, './01-connect-allow-anonymous.py'), (1, './01-connect-bad-packet.py'), (1, './01-connect-connack-2163.py'), (1, './01-connect-disconnect-v5.py'), (1, './01-connect-duplicate.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.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-or-anon.py'), (1, './01-connect-uname-password-denied-no-will.py'), (1, './01-connect-uname-password-denied.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-oversize-payload.py'), (1, './02-subpub-qos0-queued-bytes.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.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-oversize-payload.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.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.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-max-inflight-expire.py'), (1, './03-publish-qos1-max-inflight.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-clean-session.py'), (2, './06-bridge-fail-persist-resend-qos1.py'), (2, './06-bridge-fail-persist-resend-qos2.py'), (1, './06-bridge-no-local.py'), (2, './06-bridge-outgoing-retain.py'), (3, './06-bridge-per-listener-settings.py'), (2, './06-bridge-reconnect-local-out.py'), (1, './07-will-delay-invalid-573191.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-oversize-payload.py'), (1, './07-will-properties.py'), (1, './07-will-qos0.py'), (1, './07-will-reconnect-1273.py'), (1, './07-will-takeover.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-plugin-publish.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'), (1, './13-malformed-publish-v5.py'), (1, './13-malformed-subscribe-v5.py'), (1, './13-malformed-unsubscribe-v5.py'), (1, './14-dynsec-acl.py'), (1, './14-dynsec-anon-group.py'), (1, './14-dynsec-auth.py'), (1, './14-dynsec-client.py'), (1, './14-dynsec-client-invalid.py'), (1, './14-dynsec-default-access.py'), (1, './14-dynsec-disable-client.py'), (1, './14-dynsec-group.py'), (1, './14-dynsec-group-invalid.py'), (1, './14-dynsec-modify-client.py'), (1, './14-dynsec-modify-group.py'), (1, './14-dynsec-modify-role.py'), (1, './14-dynsec-plugin-invalid.py'), (1, './14-dynsec-role.py'), (1, './14-dynsec-role-invalid.py'), ] ptest.run_tests(tests) mosquitto-2.0.11/test/broker/02-unsubscribe-qos2-multiple.py0000775000175000017500000000323714060132747022766 0ustar rogerroger#!/usr/bin/env python3 # Test whether a 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 * def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("unsubscribe-qos2-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "qos2/two", 2, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 3 unsubscribe_packet = mosq_test.gen_unsubscribe_multiple(mid, ["qos2/one", "qos2/two"], proto_ver=proto_ver) if proto_ver == 5: unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=proto_ver, reason_code=[17, 0]) else: unsuback_packet = mosq_test.gen_unsuback(mid, 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, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/09-plugin-auth-unpwd-fail.py0000775000175000017500000000243514060132747022236 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, plugin_ver): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v%d.so\n" % (plugin_ver)) f.write("allow_anonymous false\n") def do_test(plugin_ver): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, plugin_ver) 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) mosquitto-2.0.11/test/broker/01-connect-uname-pwd-no-flag.py0000775000175000017500000000214114060132747022564 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 * def do_test(proto_ver): rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-test", keepalive=keepalive, username="user", password="pw", proto_ver=proto_ver) 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/01-connect-success.py0000775000175000017500000000167514060132747021031 0ustar rogerroger#!/usr/bin/env python3 # Test whether a valid CONNECT results in the correct CONNACK packet. from mosq_test_helper import * def do_test(proto_ver): rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-success-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=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) sock.close() rc = 0 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=3) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/06-bridge-br2b-remapping.py0000775000175000017500000001074014060132747021771 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, protocol_version): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("allow_anonymous true\n") 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("notifications false\n") f.write("restart_timeout 5\n") f.write("bridge_protocol_version %s\n" % (protocol_version)) def inner_test(bridge, sock, proto_ver): global connect_packet, connack_packet 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='', proto_ver=proto_ver ) sock.send(local_publish_packet) if remote_topic: remote_publish_packet = mosq_test.gen_publish( remote_topic, qos=0, mid=mid, payload='', proto_ver=proto_ver ) 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 def do_test(proto_ver): global connect_packet, connack_packet if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, bridge_protocol) 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=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) client_connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive, proto_ver=proto_ver) client_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) 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) try: (bridge, address) = ssock.accept() bridge.settimeout(2) sock = mosq_test.do_client_connect( client_connect_packet, client_connack_packet, port=port2, ) rc = inner_test(bridge, sock, proto_ver) sock.close() bridge.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() ssock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subpub-qos0-topic-alias.py0000775000175000017500000000365314060132747022314 0ustar rogerroger#!/usr/bin/env python3 # Test whether "topic alias" works to the broker # MQTT v5 from mosq_test_helper import * def do_test(): 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) mosq_test.expect_packet(sock2, "publish2r", publish2r_packet) rc = 0 sock1.close() sock2.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() exit() mosquitto-2.0.11/test/broker/readme.txt0000664000175000017500000000063014060132747017123 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-2.0.11/test/broker/04-retain-check-source-persist-diff-port.py0000775000175000017500000001071514060132747025142 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("allow_anonymous true\n") 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)) f.write("allow_anonymous true\n") 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(proto_ver, 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, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) 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, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish_packet = mosq_test.gen_publish("test/topic", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "test/topic", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) 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") 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() except mosq_test.TestError: pass 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(proto_ver=4, per_listener="true", username=None) do_test(proto_ver=4, per_listener="true", username="test") do_test(proto_ver=4, per_listener="false", username=None) do_test(proto_ver=4, per_listener="false", username="test") do_test(proto_ver=5, per_listener="true", username=None) do_test(proto_ver=5, per_listener="true", username="test") do_test(proto_ver=5, per_listener="false", username=None) do_test(proto_ver=5, per_listener="false", username="test") mosquitto-2.0.11/test/broker/07-will-properties.py0000775000175000017500000001113414060132747021070 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() mosq_test.expect_packet(sock1, "publish", publish_packet) rc = 0 sock1.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/01-connect-uname-no-flag.py0000775000175000017500000000212014060132747021771 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 * def do_test(proto_ver): rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-uname-test", keepalive=keepalive, username="user", proto_ver=proto_ver) 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/08-tls-psk-pub.psk0000664000175000017500000000002014060132747020243 0ustar rogerrogerpsk-id:deadbeef mosquitto-2.0.11/test/broker/07-will-no-flag.py0000775000175000017500000000225414060132747020222 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 * def do_test(proto_ver): 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, proto_ver=proto_ver) 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/04-retain-qos0-fresh.py0000775000175000017500000000307514060132747021200 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 * def do_test(proto_ver): rc = 1 keepalive = 60 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-fresh-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) publish_fresh_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message", proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos0/test", 0, proto_ver=proto_ver) suback_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, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, publish_fresh_packet, "publish") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/01-connect-allow-anonymous.py0000775000175000017500000000635114060132747022521 0ustar rogerroger#!/usr/bin/env python3 # Test whether an anonymous connection is correctly denied. from mosq_test_helper import * def write_config1(filename, port): with open(filename, 'w') as f: f.write("max_connections 10\n") # So the file isn't completely empty def write_config2(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) def write_config3(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) def write_config4(filename, port): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("allow_anonymous true\n") def write_config5(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") def do_test(use_conf, write_config, expect_success): port = mosq_test.get_port() if write_config is not None: conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=use_conf, port=port) try: for proto_ver in [4, 5]: rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-anon-test-%d" % (proto_ver), keepalive=keepalive, proto_ver=proto_ver) if proto_ver == 5: if expect_success == True: connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) else: connack_packet = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=proto_ver, properties=None) else: if expect_success == True: connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) else: connack_packet = mosq_test.gen_connack(rc=5, proto_ver=proto_ver) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 except mosq_test.TestError: pass finally: if write_config is not None: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) # No config file - allow_anonymous should be true do_test(use_conf=False, write_config=None, expect_success=True) # Config file but no listener - allow_anonymous should be true # Not possible right now because the test doesn't allow us to use a config file and -p at the same time. #do_test(use_conf=True, write_config=write_config1, expect_success=True) # Config file with "port" - allow_anonymous should be false do_test(use_conf=True, write_config=write_config2, expect_success=False) # Config file with "listener" - allow_anonymous should be false do_test(use_conf=True, write_config=write_config3, expect_success=False) # Config file with "port" - allow_anonymous explicitly true do_test(use_conf=True, write_config=write_config4, expect_success=True) # Config file with "listener" - allow_anonymous explicitly true do_test(use_conf=True, write_config=write_config5, expect_success=True) exit(0) mosquitto-2.0.11/test/broker/03-publish-qos2.py0000775000175000017500000000264214060132747020257 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 * def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos2-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 312 publish_packet = mosq_test.gen_publish("pub/qos2/test", qos=2, mid=mid, payload="message", proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid, 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, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/prop_subpub_helper.py0000775000175000017500000000274514060132747021412 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/02-subpub-qos1-message-expiry.py0000775000175000017500000000616514060132747023053 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 * def do_test(): 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test() exit(0) mosquitto-2.0.11/test/broker/05-clean-session-qos1.py0000775000175000017500000000463514060132747021361 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 * def helper(port): connect_packet = mosq_test.gen_connect("test-helper", keepalive=60) 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) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") sock.close() def do_test(proto_ver): rc = 1 mid = 109 keepalive = 60 connect_packet = mosq_test.gen_connect("clean-qos2-test", keepalive=keepalive, clean_session=False, proto_ver=proto_ver, session_expiry=60) connack1_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(flags=1, rc=0, proto_ver=proto_ver) disconnect_packet = mosq_test.gen_disconnect(proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "qos1/clean_session/test", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid = 1 publish_packet = mosq_test.gen_publish("qos1/clean_session/test", qos=1, mid=mid, payload="clean-session-message", proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, 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, connack1_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock.send(disconnect_packet) sock.close() helper(port) # Now reconnect and expect a publish message. sock = mosq_test.do_client_connect(connect_packet, connack2_packet, timeout=30, port=port) mosq_test.expect_packet(sock, "publish", publish_packet) sock.send(puback_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/11-subscription-id.py0000775000175000017500000000564514060132747021052 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("allow_anonymous true\n") 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-subscription-test", keepalive=keepalive, clean_session=False, proto_ver=5, session_expiry=60 ) 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) mosq_test.expect_packet(sock, "publish2", publish_packet2) rc = 0 sock.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/09-extended-auth-multistep.py0000775000175000017500000000363314060132747022521 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/03-publish-qos1-no-subscribers-v5.py0000775000175000017500000000574614060132747023554 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/09-extended-auth-multistep-reauth.py0000775000175000017500000000753314060132747024012 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("allow_anonymous true\n") 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/09-plugin-auth-msg-params.py0000775000175000017500000000321214060132747022231 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") sock.send(publish_packet) mosq_test.receive_unordered(sock, puback_packet, publish_packet_recv, "puback/publish_receive") rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/01-connect-disconnect-v5.py0000775000175000017500000000425314060132747022035 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) except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) if rc != 0: print(test) exit(rc) mosquitto-2.0.11/test/broker/07-will-takeover.py0000775000175000017500000001047014060132747020516 0ustar rogerroger#!/usr/bin/env python3 # Test whether a will is published when a client takes over an existing session that has a will set. # from mosq_test_helper import * def do_test(proto_ver, clean_session1, clean_session2): rc = 1 keepalive = 60 mid = 1 connect1_packet = mosq_test.gen_connect("will-helper", keepalive=keepalive, proto_ver=proto_ver) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) if proto_ver == 5: if clean_session1 == False: connect_props1 = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 60) else: connect_props1 = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 0) if clean_session2 == False: connect_props2 = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 60) else: connect_props2 = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 0) else: connect_props1 = b"" connect_props2 = b"" connect2_packet = mosq_test.gen_connect("will-test", keepalive=keepalive, proto_ver=proto_ver, will_topic="will/test", will_payload=b"LWT", clean_session=clean_session1, properties=connect_props1) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connect3_packet = mosq_test.gen_connect("will-test", keepalive=keepalive, proto_ver=proto_ver, clean_session=clean_session2, properties=connect_props2) if clean_session1 == False and clean_session2 == False: connack3_packet = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) else: connack3_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "will/test", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish(topic="will/test", qos=0, payload="Client ready", proto_ver=proto_ver) publish_lwt_packet = mosq_test.gen_publish(topic="will/test", qos=0, payload="LWT", proto_ver=proto_ver) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: # Connect helper to look for will being published sock1 = mosq_test.do_client_connect(connect1_packet, connack1_packet, timeout=5, port=port) mosq_test.do_send_receive(sock1, subscribe_packet, suback_packet, "suback") # Connect client with will sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=5, port=port) # Send a "ready" message sock2.send(publish_packet) mosq_test.expect_packet(sock1, "publish 1", publish_packet) # Connect client with will again as a separate connection, this should # take over from the previous one but only trigger a Will if we are taking # over a clean session/session-expiry-interval==0 client sock3 = mosq_test.do_client_connect(connect3_packet, connack3_packet, timeout=5, port=port) sock2.close() if clean_session1 == True or clean_session2 == True: mosq_test.expect_packet(sock1, "publish LWT", publish_lwt_packet) # Send the "ready" message again sock3.send(publish_packet) mosq_test.expect_packet(sock1, "publish 2", publish_packet) # If the helper has received a will message, then the ping test will fail mosq_test.do_ping(sock1) rc = 0 sock1.close() sock2.close() sock3.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d clean_session1=%d clean_session2=%d" % (proto_ver, clean_session1, clean_session2)) exit(rc) do_test(proto_ver=4, clean_session1=True, clean_session2=True) do_test(proto_ver=4, clean_session1=False, clean_session2=True) do_test(proto_ver=4, clean_session1=True, clean_session2=False) do_test(proto_ver=4, clean_session1=False, clean_session2=False) do_test(proto_ver=5, clean_session1=True, clean_session2=True) do_test(proto_ver=5, clean_session1=False, clean_session2=True) do_test(proto_ver=5, clean_session1=True, clean_session2=False) do_test(proto_ver=5, clean_session1=False, clean_session2=False) mosquitto-2.0.11/test/broker/12-prop-session-expiry-invalid.py0000775000175000017500000000232314060132747023326 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/01-connect-invalid-protonum.py0000775000175000017500000000133014060132747022654 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/02-subpub-qos2-receive-maximum-2.py0000775000175000017500000000557314060132747023350 0ustar rogerroger#!/usr/bin/env python3 # Does the broker respect receive maximum==2? # MQTT v5 from mosq_test_helper import * def do_test(proto_ver): if proto_ver == 4: exit(0) 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() mosq_test.expect_packet(sock, "publish1", publish_packet1) mosq_test.expect_packet(sock, "publish2", publish_packet2) mosq_test.do_send_receive(sock, pubrec_packet1, pubrel_packet1, "pubrel1") sock.send(pubcomp_packet1) 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/01-connect-uname-or-anon.pwfile0000664000175000017500000000016214060132747022656 0ustar rogerrogeruser:$6$Ut1cUS9PG8+gC3vn$tOjCfSJJDe1Alu9HktxxyyzwN4+6mAMSWGRAF9gmMN8pzcGTPVEYYMAZpCEp96Oz2ZRRz5YKM6lPMf1tUbb6zA== mosquitto-2.0.11/test/broker/02-subpub-qos1-oversize-payload.py0000775000175000017500000000554514060132747023407 0ustar rogerroger#!/usr/bin/env python3 # Test whether message size limits apply. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("message_size_limit 1\n") def do_test(proto_ver): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos1-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) connect2_packet = mosq_test.gen_connect("subpub-qos1-helper", keepalive=keepalive, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish_packet_ok = mosq_test.gen_publish("subpub/qos1", mid=mid, qos=1, payload="A", proto_ver=proto_ver) puback_packet_ok = mosq_test.gen_puback(mid=mid, proto_ver=proto_ver) mid = 2 publish_packet_bad = mosq_test.gen_publish("subpub/qos1", mid=mid, qos=1, payload="AB", proto_ver=proto_ver) if proto_ver == 5: puback_packet_bad = mosq_test.gen_puback(reason_code=mqtt5_rc.MQTT_RC_PACKET_TOO_LARGE, mid=mid, proto_ver=proto_ver) else: puback_packet_bad = mosq_test.gen_puback(mid=mid, proto_ver=proto_ver) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, 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, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=20, port=port) mosq_test.do_send_receive(sock2, publish_packet_ok, puback_packet_ok, "puback 1") mosq_test.expect_packet(sock, "publish 1", publish_packet_ok) sock.send(puback_packet_ok) # Check all is still well on the publishing client mosq_test.do_ping(sock2) mosq_test.do_send_receive(sock2, publish_packet_bad, puback_packet_bad, "puback 2") # The subscribing client shouldn't have received a PUBLISH mosq_test.do_ping(sock) rc = 0 sock.close() except SyntaxError: raise except TypeError: raise except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/07-will-delay.py0000775000175000017500000000357214060132747020001 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() 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/07-will-reconnect-1273.py0000775000175000017500000000520114060132747021244 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) 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, session_expiry=60) 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/08-ssl-bridge-helper.py0000775000175000017500000000104414060132747021237 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-2.0.11/test/broker/03-publish-long-topic.py0000775000175000017500000000304414060132747021443 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 * def do_test(proto_ver): rc = 1 mid = 19 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos1-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("/"*65535, qos=1, mid=mid, payload="message", proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, 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) if proto_ver == 4: mosq_test.do_send_receive(sock, publish_packet, b"", "puback") else: disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_PROTOCOL_ERROR) mosq_test.do_send_receive(sock, publish_packet, disconnect_packet, "puback") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subpub-qos1-message-expiry-retain.py0000775000175000017500000000732414060132747024331 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 * def do_test(): 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") 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") 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") mosq_test.expect_packet(sock, "publish 2", publish2r_packet) sock.send(puback2r_packet) sock.close() rc = 0 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test() exit(0) mosquitto-2.0.11/test/broker/07-will-null.py0000775000175000017500000000327014060132747017650 0ustar rogerroger#!/usr/bin/env python3 # Test whether a client will is transmitted correctly with a null payload. from mosq_test_helper import * def helper(port, proto_ver): connect_packet = mosq_test.gen_connect("test-helper", keepalive=60, will_topic="will/null/test", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() def do_test(proto_ver): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("will-qos0-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "will/null/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/null/test", qos=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, timeout=30, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") helper(port, proto_ver) mosq_test.expect_packet(sock, "publish", publish_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/14-dynsec-role.py0000775000175000017500000003107514060132747020157 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response, msg=""): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(msg) print(expected_response) print(response) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) create_client_command = { "commands": [{ "command": "createClient", "username": "user_one", "password": "password", "clientid": "cid", "textname": "Name", "textdescription": "Description", "rolename": "", "correlationData": "2" }] } create_client_response = {'responses': [{'command': 'createClient', 'correlationData': '2'}]} create_client2_command = { "commands": [{ "command": "createClient", "username": "user_two", "password": "password", "textname": "Name", "textdescription": "Description", "rolename": "", "correlationData": "3" }] } create_client2_response = {'responses': [{'command': 'createClient', 'correlationData': '3'}]} create_group_command = { "commands": [{ "command": "createGroup", "groupname": "group_one", "textname": "Name", "textdescription": "Description", "correlationData":"3"}]} create_group_response = {'responses':[{"command":"createGroup","correlationData":"3"}]} create_role_command = { "commands": [{'command': 'createRole', 'correlationData': '3', "rolename": "basic", "acls":[ {"acltype":"publishClientSend", "topic": "out/#", "priority":3, "allow": True}], "textname":"name", "textdescription":"desc" }]} create_role_response = {'responses': [{'command': 'createRole', 'correlationData': '3'}]} create_role2_command = { "commands": [{'command': 'createRole', 'correlationData': '3', "rolename": "basic2", "acls":[ {"acltype":"publishClientSend", "topic": "out/#", "priority":3, "allow": True}], "textname":"name", "textdescription":"desc" }]} create_role2_response = {'responses': [{'command': 'createRole', 'correlationData': '3'}]} add_role_to_client_command = {"commands": [{'command': 'addClientRole', "username": "user_one", "rolename": "basic"}]} add_role_to_client_response = {'responses': [{'command': 'addClientRole'}]} add_role_to_client2_command = {"commands": [{'command': 'addClientRole', "username": "user_one", "rolename": "basic2"}]} add_role_to_client2_response = {'responses': [{'command': 'addClientRole'}]} add_role_to_group_command = {"commands": [{'command': 'addGroupRole', "groupname": "group_one", "rolename": "basic"}]} add_role_to_group_response = {'responses': [{'command': 'addGroupRole'}]} list_roles_verbose_command1 = { "commands": [{ "command": "listRoles", "verbose": True, "correlationData": "21"}] } list_roles_verbose_response1 = {'responses': [{'command': 'listRoles', 'data': {'totalCount':3, 'roles': [ {"rolename":"admin","acls":[ {"acltype": "publishClientSend", "topic": "$CONTROL/dynamic-security/#", "priority":0, "allow": True }, {"acltype": "publishClientReceive", "topic": "$CONTROL/dynamic-security/#", "priority":0, "allow": True }, {"acltype": "publishClientReceive", "topic": "$SYS/#", "priority":0, "allow": True }, {"acltype": "publishClientReceive", "topic": "#", "priority":0, "allow": True }, {"acltype": "subscribePattern", "topic": "$CONTROL/dynamic-security/#", "priority":0, "allow": True }, {"acltype": "subscribePattern", "topic": "$SYS/#", "priority":0, "allow": True }, {"acltype": "subscribePattern", "topic": "#", "priority":0, "allow": True}, {"acltype": "unsubscribePattern", "topic": "#", "priority":0, "allow": True}]}, {'rolename': 'basic', "textname": "name", "textdescription": "desc", 'acls': [{'acltype':'publishClientSend', 'topic': 'out/#', 'priority': 3, 'allow': True}]}, {'rolename': 'basic2', "textname": "name", "textdescription": "desc", 'acls': [{'acltype':'publishClientSend', 'topic': 'out/#', 'priority': 3, 'allow': True}] }]}, 'correlationData': '21'}]} add_acl_command = {"commands": [{'command': "addRoleACL", "rolename":"basic", "acltype":"subscribeLiteral", "topic":"basic/out", "priority":1, "allow":True}]} add_acl_response = {'responses': [{'command': 'addRoleACL'}]} add_acl2_command = {"commands": [{'command': "addRoleACL", "rolename":"basic", "acltype":"subscribeLiteral", "topic":"basic/out", "priority":1, "allow":True}]} add_acl2_response = {'responses': [{'command': 'addRoleACL', 'error':'ACL with this topic already exists'}]} list_roles_verbose_command2 = { "commands": [{ "command": "listRoles", "verbose": True, "correlationData": "22"}] } list_roles_verbose_response2 = {'responses': [{'command': 'listRoles', 'data': {'totalCount':3, 'roles': [{"rolename":"admin","acls":[ {"acltype": "publishClientSend", "topic": "$CONTROL/dynamic-security/#", "priority":0, "allow": True }, {"acltype": "publishClientReceive", "topic": "$CONTROL/dynamic-security/#", "priority":0, "allow": True }, {"acltype": "publishClientReceive", "topic": "$SYS/#", "priority":0, "allow": True }, {"acltype": "publishClientReceive", "topic": "#", "priority":0, "allow": True }, {"acltype": "subscribePattern", "topic": "$CONTROL/dynamic-security/#", "priority":0, "allow": True }, {"acltype": "subscribePattern", "topic": "$SYS/#", "priority":0, "allow": True }, {"acltype": "subscribePattern", "topic": "#", "priority":0, "allow": True}, {"acltype": "unsubscribePattern", "topic": "#", "priority":0, "allow": True}]}, {'rolename': 'basic', 'textname': 'name', 'textdescription': 'desc', 'acls': [{'acltype':'publishClientSend', 'topic': 'out/#', 'priority': 3, 'allow': True}, {'acltype':'subscribeLiteral', 'topic': 'basic/out', 'priority': 1, 'allow': True}]}, {'rolename': 'basic2', "textname": "name", "textdescription": "desc", 'acls': [{'acltype':'publishClientSend', 'topic': 'out/#', 'priority': 3, 'allow': True}] }]}, 'correlationData': '22'}]} get_role_command = {"commands": [{'command': "getRole", "rolename":"basic"}]} get_role_response = {'responses': [{'command': 'getRole', 'data': {'role': {'rolename': 'basic', 'textname': 'name', 'textdescription': 'desc', 'acls': [{'acltype':'publishClientSend', 'topic': 'out/#', 'priority': 3, 'allow': True}, {'acltype':'subscribeLiteral', 'topic': 'basic/out', 'priority': 1, 'allow': True}], }}}]} remove_acl_command = {"commands": [{'command': "removeRoleACL", "rolename":"basic", "acltype":"subscribeLiteral", "topic":"basic/out"}]} remove_acl_response = {'responses': [{'command': 'removeRoleACL'}]} remove_acl2_command = {"commands": [{'command': "removeRoleACL", "rolename":"basic", "acltype":"subscribeLiteral", "topic":"basic/out"}]} remove_acl2_response = {'responses': [{'command': 'removeRoleACL', 'error':'ACL not found'}]} delete_role_command = {"commands": [{'command': "deleteRole", "rolename":"basic"}]} delete_role_response = {"responses": [{"command": "deleteRole"}]} delete_role2_command = {"commands": [{'command': "deleteRole", "rolename":"basic"}]} delete_role2_response = {"responses": [{"command": "deleteRole"}]} list_clients_verbose_command = { "commands": [{ "command": "listClients", "verbose": True, "correlationData": "20"}] } list_clients_verbose_response = {'responses':[{"command": "listClients", "data":{'totalCount':3, "clients":[ {'username': 'admin', 'textname': 'Dynsec admin user', 'roles': [{'rolename': 'admin'}], 'groups': []}, {"username":"user_one", "clientid":"cid", "textname":"Name", "textdescription":"Description", "groups":[], "roles":[{'rolename':'basic'}, {'rolename':'basic2'}]}, {"username":"user_two", "textname":"Name", "textdescription":"Description", "groups":[], "roles":[]}]}, "correlationData":"20"}]} list_groups_verbose_command = { "commands": [{ "command": "listGroups", "verbose": True, "correlationData": "20"}] } list_groups_verbose_response = {'responses':[{"command": "listGroups", "data":{'totalCount':1, "groups":[ {"groupname":"group_one", "textname":"Name", "textdescription":"Description", "clients":[], "roles":[{'rolename':'basic'}]}]}, "correlationData":"20"}]} remove_role_from_client_command = {"commands": [{'command': 'removeClientRole', "username": "user_one", "rolename": "basic"}]} remove_role_from_client_response = {'responses': [{'command': 'removeClientRole'}]} remove_role_from_group_command = {"commands": [{'command': 'removeGroupRole', "groupname": "group_one", "rolename": "basic"}]} remove_role_from_group_response = {'responses': [{'command': 'removeGroupRole'}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Create client command_check(sock, create_client2_command, create_client2_response) command_check(sock, create_client_command, create_client_response) # Create group command_check(sock, create_group_command, create_group_response) # Create role command_check(sock, create_role_command, create_role_response) command_check(sock, create_role2_command, create_role2_response) # Add role to client command_check(sock, add_role_to_client2_command, add_role_to_client2_response) command_check(sock, add_role_to_client_command, add_role_to_client_response) # Add role to group command_check(sock, add_role_to_group_command, add_role_to_group_response) # List clients verbose command_check(sock, list_clients_verbose_command, list_clients_verbose_response) # List groups verbose command_check(sock, list_groups_verbose_command, list_groups_verbose_response) # List roles verbose 1 command_check(sock, list_roles_verbose_command1, list_roles_verbose_response1, "list roles verbose 1a") # Add ACL command_check(sock, add_acl_command, add_acl_response) command_check(sock, add_acl2_command, add_acl2_response) # List roles verbose 2 command_check(sock, list_roles_verbose_command2, list_roles_verbose_response2, "list roles verbose 2a") # Kill broker and restart, checking whether our changes were saved. 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, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # List roles verbose 2 command_check(sock, list_roles_verbose_command2, list_roles_verbose_response2, "list roles verbose 2b") # Get role command_check(sock, get_role_command, get_role_response) # Remove ACL command_check(sock, remove_acl_command, remove_acl_response) command_check(sock, remove_acl2_command, remove_acl2_response) # List roles verbose 1 command_check(sock, list_roles_verbose_command1, list_roles_verbose_response1, "list roles verbose 1b") # Remove role from client command_check(sock, remove_role_from_client_command, remove_role_from_client_response) # Remove role from group command_check(sock, remove_role_from_group_command, remove_role_from_group_response) # Delete role command_check(sock, delete_role_command, delete_role_response) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/13-malformed-unsubscribe-v5.py0000775000175000017500000000532314060132747022547 0ustar rogerroger#!/usr/bin/env python3 # Test whether the broker handles malformed packets correctly - UNSUBSCRIBE # MQTTv5 from mosq_test_helper import * rc = 1 def do_test(unsubscribe_packet, reason_code, error_string): global rc 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) mid = 0 disconnect_packet = mosq_test.gen_disconnect(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, unsubscribe_packet, disconnect_packet, error_string=error_string) rc = 0 port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: # mid == 0 unsubscribe_packet = mosq_test.gen_unsubscribe(topic="test/topic", mid=0, proto_ver=5) do_test(unsubscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "mid == 0") # command flags != 0x02 unsubscribe_packet = mosq_test.gen_unsubscribe(topic="test/topic", mid=1, proto_ver=5, cmd=160) do_test(unsubscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "command flags != 0x02") # Incorrect property props = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 0) unsubscribe_packet = mosq_test.gen_unsubscribe(topic="test/topic", mid=1, proto_ver=5, properties=props) do_test(unsubscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Incorrect property") # Truncated packet, no mid unsubscribe_packet = struct.pack("!BB", 162, 0) do_test(unsubscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, no mid") # Truncated packet, no properties unsubscribe_packet = struct.pack("!BBH", 162, 2, 1) do_test(unsubscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, no properties") # Truncated packet, with properties field, no topic unsubscribe_packet = struct.pack("!BBHH", 162, 4, 1, 0) do_test(unsubscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, with properties field, no topic") # Truncated packet, with properties field, empty topic unsubscribe_packet = struct.pack("!BBHHH", 162, 5, 1, 0, 0) do_test(unsubscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Truncated packet, with properties field, empty topic") # Bad topic unsubscribe_packet = mosq_test.gen_unsubscribe(topic="#/test/topic", mid=1, proto_ver=5) do_test(unsubscribe_packet, mqtt5_rc.MQTT_RC_MALFORMED_PACKET, "Bad topic") except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/14-dynsec-role-invalid.py0000775000175000017500000004112014060132747021573 0ustar rogerroger#!/usr/bin/env python3 # Check invalid inputs for role commands from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response, msg=""): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(expected_response) print(response) if msg != "": print(msg) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) # Create client for modifying create_client0_command = { 'commands': [{'command': 'createClient', 'username':'validclient' }] } create_client0_response = {'responses': [{'command': 'createClient'}]} # Create group for modifying create_group0_command = { 'commands': [{'command': 'createGroup', 'groupname':'validgroup' }] } create_group0_response = {'responses': [{'command': 'createGroup'}]} # Create role for modifying create_role0_command = { 'commands': [{'command': 'createRole', 'rolename':'validrole' }] } create_role0_response = {'responses': [{'command': 'createRole'}]} # Add ACL for modifying add_role_acl0_command = { 'commands': [{'command': 'addRoleACL', 'rolename':'validrole', 'acltype':'unsubscribePattern', 'topic':'validtopic', 'allow':True }] } add_role_acl0_response = {'responses': [{'command': 'addRoleACL'}]} # ========================================================================== # Create role # ========================================================================== # No rolename create_role1_command = { 'commands': [{'command': 'createRole' }] } create_role1_response = {'responses': [{'command': 'createRole', 'error': 'Invalid/missing rolename'}]} # Rolename not a string create_role2_command = { 'commands': [{'command': 'createRole', 'rolename':5 }] } create_role2_response = {'responses': [{'command': 'createRole', 'error': 'Invalid/missing rolename'}]} # Rolename not UTF-8 create_role3_command = { 'commands': [{'command': 'createRole', 'rolename': '￿LO' }] } create_role3_response = {'responses': [{'command': 'createRole', 'error': 'Role name not valid UTF-8'}]} # textname not a string create_role4_command = { 'commands': [{'command': 'createRole', 'rolename':'g', 'textname':5 }] } create_role4_response = {'responses': [{'command': 'createRole', 'error': 'Invalid/missing textname'}]} # textdescription not a string create_role5_command = { 'commands': [{'command': 'createRole', 'rolename':'g', 'textdescription':5 }] } create_role5_response = {'responses': [{'command': 'createRole', 'error': 'Invalid/missing textdescription'}]} # Role already exists create_role6_command = { 'commands': [{'command': 'createRole', 'rolename': 'validrole'}]} create_role6_response = {'responses': [{'command': 'createRole', 'error': 'Role already exists'}]} # Bad ACLs #create_role7_command = { 'commands': [{'command': 'createRole', 'rolename': 'role', 'roles':[{'rolename':'notfound'}]}] } #create_role7_response = {'responses': [{'command': 'createRole', 'error': 'Role not found'}]} # ========================================================================== # Delete role # ========================================================================== # No rolename delete_role1_command = { 'commands': [{'command': 'deleteRole' }] } delete_role1_response = {'responses': [{'command': 'deleteRole', 'error': 'Invalid/missing rolename'}]} # Rolename not a string delete_role2_command = { 'commands': [{'command': 'deleteRole', 'rolename':5 }] } delete_role2_response = {'responses': [{'command': 'deleteRole', 'error': 'Invalid/missing rolename'}]} # Rolename not UTF-8 delete_role3_command = { 'commands': [{'command': 'deleteRole', 'rolename': '￿LO' }] } delete_role3_response = {'responses': [{'command': 'deleteRole', 'error': 'Role name not valid UTF-8'}]} # Role not found delete_role4_command = { 'commands': [{'command': 'deleteRole', 'rolename': 'role'}]} delete_role4_response = {'responses': [{'command': 'deleteRole', 'error': 'Role not found'}]} # ========================================================================== # Get role # ========================================================================== # No rolename get_role1_command = { 'commands': [{'command': 'getRole'}] } get_role1_response = {'responses': [{'command': 'getRole', 'error': 'Invalid/missing rolename'}]} # rolename not a string get_role2_command = { 'commands': [{'command': 'getRole', 'rolename':5}] } get_role2_response = {'responses': [{'command': 'getRole', 'error': 'Invalid/missing rolename'}]} # rolename not UTF-8 get_role3_command = { 'commands': [{'command': 'getRole', 'rolename': '￿LO' }] } get_role3_response = {'responses': [{'command': 'getRole', 'error': 'Role name not valid UTF-8'}]} # role not found get_role4_command = { 'commands': [{'command': 'getRole', 'rolename':"notfound"}] } get_role4_response = {'responses': [{'command': 'getRole', 'error': 'Role not found'}]} # ========================================================================== # Add role ACL # ========================================================================== add_role_acl1_command = { 'commands': [{'command': 'addRoleACL'}]} add_role_acl1_response = {'responses': [{'command': 'addRoleACL', 'error': 'Invalid/missing rolename'}]} add_role_acl2_command = { 'commands': [{'command': 'addRoleACL', 'rolename':5}]} add_role_acl2_response = {'responses': [{'command': 'addRoleACL', 'error': 'Invalid/missing rolename'}]} add_role_acl3_command = { 'commands': [{'command': 'addRoleACL', 'rolename': '￿LO' }] } add_role_acl3_response = {'responses': [{'command': 'addRoleACL', 'error': 'Role name not valid UTF-8'}]} add_role_acl4_command = { 'commands': [{'command': 'addRoleACL', 'rolename': 'notvalid' }] } add_role_acl4_response = {'responses': [{'command': 'addRoleACL', 'error': 'Role not found'}]} add_role_acl5_command = { 'commands': [{'command': 'addRoleACL', 'rolename': 'validrole' }] } add_role_acl5_response = {'responses': [{'command': 'addRoleACL', 'error': 'Invalid/missing acltype'}]} add_role_acl6_command = { 'commands': [{'command': 'addRoleACL', 'rolename': 'validrole', 'acltype':'notvalid' }] } add_role_acl6_response = {'responses': [{'command': 'addRoleACL', 'error': 'Unknown acltype'}]} add_role_acl7_command = { 'commands': [{'command': 'addRoleACL', 'rolename': 'validrole', 'acltype':'unsubscribePattern' }] } add_role_acl7_response = {'responses': [{'command': 'addRoleACL', 'error': 'Invalid/missing topic'}]} add_role_acl8_command = { 'commands': [{'command': 'addRoleACL', 'rolename': 'validrole', 'acltype':'subscribePattern', 'topic':5 }] } add_role_acl8_response = {'responses': [{'command': 'addRoleACL', 'error': 'Invalid/missing topic'}]} add_role_acl9_command = { 'commands': [{'command': 'addRoleACL', 'rolename': 'validrole', 'acltype':'unsubscribeLiteral', 'topic':'￿LO' }] } add_role_acl9_response = {'responses': [{'command': 'addRoleACL', 'error': 'Topic not valid UTF-8'}]} add_role_acl10_command = { 'commands': [{'command': 'addRoleACL', 'rolename': 'validrole', 'acltype':'unsubscribeLiteral', 'topic':'not/#/valid' }] } add_role_acl10_response = {'responses': [{'command': 'addRoleACL', 'error': 'Invalid ACL topic'}]} # ========================================================================== # Remove role ACL # ========================================================================== remove_role_acl1_command = { 'commands': [{'command': 'removeRoleACL'}]} remove_role_acl1_response = {'responses': [{'command': 'removeRoleACL', 'error': 'Invalid/missing rolename'}]} remove_role_acl2_command = { 'commands': [{'command': 'removeRoleACL', 'rolename':5}]} remove_role_acl2_response = {'responses': [{'command': 'removeRoleACL', 'error': 'Invalid/missing rolename'}]} remove_role_acl3_command = { 'commands': [{'command': 'removeRoleACL', 'rolename': '￿LO' }] } remove_role_acl3_response = {'responses': [{'command': 'removeRoleACL', 'error': 'Role name not valid UTF-8'}]} remove_role_acl4_command = { 'commands': [{'command': 'removeRoleACL', 'rolename': 'notvalid' }] } remove_role_acl4_response = {'responses': [{'command': 'removeRoleACL', 'error': 'Role not found'}]} remove_role_acl5_command = { 'commands': [{'command': 'removeRoleACL', 'rolename': 'validrole' }] } remove_role_acl5_response = {'responses': [{'command': 'removeRoleACL', 'error': 'Invalid/missing acltype'}]} remove_role_acl6_command = { 'commands': [{'command': 'removeRoleACL', 'rolename': 'validrole', 'acltype':'notvalid' }] } remove_role_acl6_response = {'responses': [{'command': 'removeRoleACL', 'error': 'Unknown acltype'}]} remove_role_acl7_command = { 'commands': [{'command': 'removeRoleACL', 'rolename': 'validrole', 'acltype':'unsubscribePattern' }] } remove_role_acl7_response = {'responses': [{'command': 'removeRoleACL', 'error': 'Invalid/missing topic'}]} remove_role_acl8_command = { 'commands': [{'command': 'removeRoleACL', 'rolename': 'validrole', 'acltype':'unsubscribePattern', 'topic':5 }] } remove_role_acl8_response = {'responses': [{'command': 'removeRoleACL', 'error': 'Invalid/missing topic'}]} remove_role_acl9_command = { 'commands': [{'command': 'removeRoleACL', 'rolename': 'validrole', 'acltype':'unsubscribePattern', 'topic':'￿LO' }] } remove_role_acl9_response = {'responses': [{'command': 'removeRoleACL', 'error': 'Topic not valid UTF-8'}]} # ========================================================================== # Modify role # ========================================================================== # No groupname modify_group1_command = { 'commands': [{'command': 'modifyRole'}]} modify_group1_response = {'responses': [{'command': 'modifyRole', 'error': 'Invalid/missing groupname'}]} # Username not a string modify_group2_command = { 'commands': [{'command': 'modifyRole', 'groupname':5}]} modify_group2_response = {'responses': [{'command': 'modifyRole', 'error': 'Invalid/missing groupname'}]} # Username not UTF-8 modify_group3_command = { 'commands': [{'command': 'modifyRole', 'rolename': '￿LO' }] } modify_group3_response = {'responses': [{'command': 'modifyRole', 'error': 'Role name not valid UTF-8'}]} # roles not a list modify_group4_command = { 'commands': [{'command': 'modifyRole', 'groupname':'validgroup', 'password':'test', 'roles':'string'}]} modify_group4_response = {'responses': [{'command': 'modifyRole', 'error': "'roles' not an array or missing/invalid rolename"}]} # No rolename modify_group5_command = { 'commands': [{'command': 'modifyRole', 'groupname':'validgroup', 'roles':[{}]}]} modify_group5_response = {'responses': [{'command': 'modifyRole', 'error': "'roles' not an array or missing/invalid rolename"}]} # rolename not a string modify_group6_command = { 'commands': [{'command': 'modifyRole', 'groupname':'validgroup', 'roles':[{'rolename':5}]}]} modify_group6_response = {'responses': [{'command': 'modifyRole', 'error': "'roles' not an array or missing/invalid rolename"}]} # rolename not UTF-8 modify_group3_command = { 'commands': [{'command': 'modifyRole', 'rolename': '￿LO' }] } #modify_group7_command = { 'commands': [{'command': 'modifyRole', 'groupname':'validgroup'}]} #modify_group7_response = {'responses': [{'command': 'modifyRole', 'error': 'Invalid/missing rolename'}]} # Role not found modify_group8_command = { 'commands': [{'command': 'modifyRole', 'groupname':'notfound', 'rolename':'notfound'}]} modify_group8_response = {'responses': [{'command': 'modifyRole', 'error': 'Role not found'}]} # Role not found modify_group9_command = { 'commands': [{'command': 'modifyRole', 'groupname':'validgroup', 'roles':[{'rolename':'notfound'}]}]} modify_group9_response = {'responses': [{'command': 'modifyRole', 'error': 'Role not found'}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") command_check(sock, create_client0_command, create_client0_response, "0") command_check(sock, create_group0_command, create_group0_response, "0") command_check(sock, create_role0_command, create_role0_response, "0") command_check(sock, add_role_acl0_command, add_role_acl0_response, "0") command_check(sock, create_role1_command, create_role1_response, "1") command_check(sock, create_role2_command, create_role2_response, "2") command_check(sock, create_role3_command, create_role3_response, "3") command_check(sock, create_role4_command, create_role4_response, "4") command_check(sock, create_role5_command, create_role5_response, "5") command_check(sock, create_role6_command, create_role6_response, "6") #command_check(sock, create_role7_command, create_role7_response, "7") command_check(sock, delete_role1_command, delete_role1_response, "1") command_check(sock, delete_role2_command, delete_role2_response, "2") command_check(sock, delete_role3_command, delete_role3_response, "3") command_check(sock, delete_role4_command, delete_role4_response, "4") command_check(sock, get_role1_command, get_role1_response, "1") command_check(sock, get_role2_command, get_role2_response, "2") command_check(sock, get_role3_command, get_role3_response, "3") command_check(sock, get_role4_command, get_role4_response, "4") command_check(sock, add_role_acl1_command, add_role_acl1_response, "1") command_check(sock, add_role_acl2_command, add_role_acl2_response, "2") command_check(sock, add_role_acl3_command, add_role_acl3_response, "3") command_check(sock, add_role_acl4_command, add_role_acl4_response, "4") command_check(sock, add_role_acl5_command, add_role_acl5_response, "5") command_check(sock, add_role_acl6_command, add_role_acl6_response, "6") command_check(sock, add_role_acl7_command, add_role_acl7_response, "7") command_check(sock, add_role_acl8_command, add_role_acl8_response, "8") command_check(sock, add_role_acl9_command, add_role_acl9_response, "9") command_check(sock, add_role_acl10_command, add_role_acl10_response, "10") command_check(sock, remove_role_acl1_command, remove_role_acl1_response, "1") command_check(sock, remove_role_acl2_command, remove_role_acl2_response, "2") command_check(sock, remove_role_acl3_command, remove_role_acl3_response, "3") command_check(sock, remove_role_acl4_command, remove_role_acl4_response, "4") command_check(sock, remove_role_acl5_command, remove_role_acl5_response, "5") command_check(sock, remove_role_acl6_command, remove_role_acl6_response, "6") command_check(sock, remove_role_acl7_command, remove_role_acl7_response, "7") command_check(sock, remove_role_acl8_command, remove_role_acl8_response, "8") command_check(sock, remove_role_acl9_command, remove_role_acl9_response, "9") #command_check(sock, modify_role1_command, modify_role1_response, "1") #command_check(sock, modify_role2_command, modify_role2_response, "2") ##command_check(sock, modify_role3_command, modify_role3_response, "3") #command_check(sock, modify_role4_command, modify_role4_response, "4") #command_check(sock, modify_role5_command, modify_role5_response, "5") #command_check(sock, modify_role6_command, modify_role6_response, "6") ##command_check(sock, modify_role7_command, modify_role7_response, "7") #command_check(sock, modify_role8_command, modify_role8_response, "8") #command_check(sock, modify_role9_command, modify_role9_response, "9") rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/14-dynsec-modify-group.py0000775000175000017500000001604514060132747021637 0ustar rogerroger#!/usr/bin/env python3 from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("plugin ../../plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) def command_check(sock, command_payload, expected_response, msg=""): command_packet = mosq_test.gen_publish(topic="$CONTROL/dynamic-security/v1", qos=0, payload=json.dumps(command_payload)) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) if response != expected_response: print(msg) print(expected_response) print(response) raise ValueError(response) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) create_client_command = { "commands": [{ "command": "createClient", "username": "user_one", "password": "password", "clientid": "cid", "textname": "Name", "textdescription": "Description", "correlationData": "2" }] } create_client_response = {'responses': [{'command': 'createClient', 'correlationData': '2'}]} create_group_command = { "commands": [{ "command": "createGroup", "groupname": "group_one", "textname": "Name", "textdescription": "Description", "rolename": "", "correlationData": "2" }] } create_group_response = {'responses': [{'command': 'createGroup', 'correlationData': '2'}]} create_role_command = { "commands": [ { "command": "createRole", "rolename": "role_one", "textname": "Name", "textdescription": "Description", "acls":[], "correlationData": "2" }, { "command": "createRole", "rolename": "role_two", "textname": "Name", "textdescription": "Description", "acls":[], "correlationData": "3" } ] } create_role_response = {'responses': [ {'command': 'createRole', 'correlationData': '2'}, {'command': 'createRole', 'correlationData': '3'} ]} modify_group_command1 = { "commands": [{ "command": "modifyGroup", "groupname": "group_one", "textname": "Modified name", "textdescription": "Modified description", "roles":[{'rolename':'role_one'}], "clients":[{'username':'user_one'}], "correlationData": "3" }] } modify_group_response1 = {'responses': [{'command': 'modifyGroup', 'correlationData': '3'}]} modify_group_command2 = { "commands": [{ "command": "modifyGroup", "groupname": "group_one", "textname": "Modified name", "textdescription": "Modified description", "roles":[ {'rolename':'role_one', 'priority':99}, {'rolename':'role_two', 'priority':87} ], "clients":[], "correlationData": "3" }] } modify_group_response2 = {'responses': [{'command': 'modifyGroup', 'correlationData': '3'}]} modify_group_command3 = { "commands": [{ "command": "modifyGroup", "groupname": "group_one", "textname": "Modified name", "textdescription": "Modified description", "roles":[], "clients":[], "correlationData": "3" }] } modify_group_response3 = {'responses': [{'command': 'modifyGroup', 'correlationData': '3'}]} get_group_command1 = { "commands": [{ "command": "getGroup", "groupname": "group_one"}]} get_group_response1 = {'responses':[{'command': 'getGroup', 'data': {'group': {'groupname': 'group_one', 'textname': 'Name', 'textdescription': 'Description', 'clients':[], 'roles': []}}}]} get_group_command2 = { "commands": [{ "command": "getGroup", "groupname": "group_one"}]} get_group_response2 = {'responses':[{'command': 'getGroup', 'data': {'group': {'groupname': 'group_one', 'textname': 'Modified name', 'textdescription': 'Modified description', 'clients':[{'username':'user_one'}], 'roles': [{'rolename':'role_one'}]}}}]} get_group_command3 = { "commands": [{ "command": "getGroup", "groupname": "group_one"}]} get_group_response3 = {'responses':[{'command': 'getGroup', 'data': {'group': {'groupname': 'group_one', 'textname': 'Modified name', 'textdescription': 'Modified description', 'clients':[], 'roles': [ {'rolename':'role_one', 'priority':99}, {'rolename':'role_two', 'priority':87} ]}}}]} get_group_command4 = { "commands": [{ "command": "getGroup", "groupname": "group_one"}]} get_group_response4 = {'responses':[{'command': 'getGroup', 'data': {'group': {'groupname': 'group_one', 'textname': 'Modified name', 'textdescription': 'Modified description', 'clients':[], 'roles': []}}}]} rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("ctrl-test", keepalive=keepalive, username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) try: os.mkdir(str(port)) shutil.copyfile("dynamic-security-init.json", "%d/dynamic-security.json" % (port)) except FileExistsError: pass 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=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Create client command_check(sock, create_client_command, create_client_response) # Create group command_check(sock, create_group_command, create_group_response) # Create role command_check(sock, create_role_command, create_role_response) # Get group command_check(sock, get_group_command1, get_group_response1, "get group 1") # Modify group command_check(sock, modify_group_command1, modify_group_response1) # Get group command_check(sock, get_group_command2, get_group_response2, "get group 2a") # Kill broker and restart, checking whether our changes were saved. 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, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Get group command_check(sock, get_group_command2, get_group_response2, "get group 2b") # Modify group command_check(sock, modify_group_command2, modify_group_response2) # Get group command_check(sock, get_group_command3, get_group_response3, "get group 3") # Modify group command_check(sock, modify_group_command3, modify_group_response3) # Get group command_check(sock, get_group_command4, get_group_response4, "get group 4") rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") pass except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/01-connect-bad-packet.py0000775000175000017500000000232014060132747021340 0ustar rogerroger#!/usr/bin/env python3 # Test whether a first packet of non-CONNECT is rejected. from mosq_test_helper import * def do_test(proto_ver): rc = 1 mid = 2 publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/11-persistent-subscription.py0000775000175000017500000000535114060132747022650 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("allow_anonymous true\n") f.write("persistence true\n") f.write("persistence_file mosquitto-%d.db\n" % (port)) def do_test(proto_ver): 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, proto_ver=proto_ver, session_expiry=60 ) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) # session present subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid = 300 publish_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) mid = 1 publish_packet2 = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=proto_ver) 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) sock.send(publish_packet) mosq_test.receive_unordered(sock, puback_packet, publish_packet2, "puback/publish2") rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if os.path.exists('mosquitto-%d.db' % (port)): os.unlink('mosquitto-%d.db' % (port)) if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/08-ssl-bridge.py0000775000175000017500000000451414060132747017767 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("allow_anonymous true\n") 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) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) 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() mosq_test.expect_packet(bridge, "publish", publish_packet) rc = 0 bridge.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/06-bridge-b2br-remapping.py0000775000175000017500000001234614060132747021775 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, protocol_version): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("allow_anonymous true\n") 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") f.write("bridge_protocol_version %s\n" % (protocol_version)) connect_packet = None connack_packet = None def inner_test(bridge, sock, proto_ver): global connect_packet, connack_packet if not mosq_test.expect_packet(bridge, "connect", connect_packet): return 1 bridge.send(connack_packet) if proto_ver == 5: opts = mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL | mqtt5_opts.MQTT_SUB_OPT_RETAIN_AS_PUBLISHED else: opts = 0 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 | opts, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) 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 | opts, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) 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='', proto_ver=proto_ver) local_publish_packet = mosq_test.gen_publish( local_topic, qos=0, mid=mid, payload='', proto_ver=proto_ver) 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 def do_test(proto_ver): global connect_packet, connack_packet if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, bridge_protocol) 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=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) client_connect_packet = mosq_test.gen_connect("pub-test", keepalive=keepalive, proto_ver=proto_ver) client_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) 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) try: (bridge, address) = ssock.accept() bridge.settimeout(2) sock = mosq_test.do_client_connect( client_connect_packet, client_connack_packet, port=port2, ) rc = inner_test(bridge, sock, proto_ver) sock.close() bridge.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() ssock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/06-bridge-reconnect-local-out.py0000775000175000017500000001063214060132747023037 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, protocol_version): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("allow_anonymous true\n") 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") f.write("bridge_protocol_version %s\n" % (protocol_version)) def do_test(proto_ver): if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2) = mosq_test.get_port(2) conf_file = '06-bridge-reconnect-local-out.conf' write_config(conf_file, port1, port2, bridge_protocol) rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("bridge-reconnect-test", keepalive=keepalive, proto_ver=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 180 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("bridge/reconnect", qos=0, payload="bridge-reconnect-message", proto_ver=proto_ver) 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") # Helper helper_connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive, proto_ver=proto_ver) helper_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) helper_publish_packet = mosq_test.gen_publish("bridge/reconnect", qos=1, mid=1, payload="bridge-reconnect-message", proto_ver=proto_ver) helper_puback_packet = mosq_test.gen_puback(mid=1, proto_ver=proto_ver) helper_disconnect_packet = mosq_test.gen_disconnect(proto_ver=proto_ver) helper_sock = mosq_test.do_client_connect(helper_connect_packet, helper_connack_packet, port=port2, connack_error="helper connack") mosq_test.do_send_receive(helper_sock, helper_publish_packet, helper_puback_packet, "puback") helper_sock.send(helper_disconnect_packet) helper_sock.close() # End of helper # Should have now received a publish command mosq_test.expect_packet(sock, "publish", publish_packet) rc = 0 sock.close() except mosq_test.TestError: pass 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() try: os.remove('mosquitto-%d.db' % (port1)) except OSError: pass if rc: (stdo, stde) = local_broker.communicate() print(stde.decode('utf-8')) if pub: (stdo, stde) = pub.communicate() print(stdo.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subpub-qos1-bad-pubcomp.py0000775000175000017500000000511414060132747022273 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 * def helper(port, proto_ver): connect_packet = mosq_test.gen_connect("helper", keepalive=60, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish1s_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=proto_ver) puback1s_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, publish1s_packet, puback1s_packet, "puback 1s") sock.close() def do_test(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub-qos1-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subpub/qos1", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid = 1 publish_packet2 = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=proto_ver) mid = 1 publish1r_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=mid, payload="message", proto_ver=proto_ver) pubcomp1r_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) 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(port, proto_ver) 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/03-publish-b2c-qos2-len.py0000775000175000017500000000657714060132747021512 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 helper(port): connect_packet = mosq_test.gen_connect("test-helper", keepalive=60) 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") sock.close() def len_test(test, pubrec_packet, pubcomp_packet): 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) 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") helper(port) # Should have now received a publish command 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/09-plugin-auth-acl-sub.py0000775000175000017500000000327014060132747021514 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, plugin_ver): with open(filename, 'w') as f: f.write("port %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v%d.so\n" % (plugin_ver)) f.write("allow_anonymous false\n") def do_test(plugin_ver): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, plugin_ver) 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() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) mosquitto-2.0.11/test/broker/06-bridge-b2br-disconnect-qos1.py0000775000175000017500000000765414060132747023033 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, protocol_version): 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") f.write("bridge_protocol_version %s\n" % (protocol_version)) def do_test(proto_ver): if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, bridge_protocol) 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=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) if proto_ver == 5: opts = mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL | mqtt5_opts.MQTT_SUB_OPT_RETAIN_AS_PUBLISHED else: opts = 0 mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 1 | opts, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid = 2 subscribe2_packet = mosq_test.gen_subscribe(mid, "bridge/#", 1 | opts, proto_ver=proto_ver) suback2_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid = 3 publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message", proto_ver=proto_ver) publish_dup_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message", dup=True, proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) mid = 20 publish2_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=1, mid=mid, payload="disconnect-message", proto_ver=proto_ver) puback2_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) 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) try: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) (bridge, address) = ssock.accept() bridge.settimeout(20) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) 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) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) 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) mosq_test.expect_packet(bridge, "puback", puback2_packet) rc = 0 bridge.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() ssock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/08-ssl-connect-cert-auth-without.py0000775000175000017500000000303314060132747023552 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 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/03-publish-dollar.py0000775000175000017500000000157514060132747020654 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() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/07-will-disconnect-with-will.py0000775000175000017500000000331214060132747022742 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) mosq_test.expect_packet(sock1, "publish", publish_packet) rc = 0 sock2.close() sock1.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() mosquitto-2.0.11/test/broker/01-connect-uname-no-password-denied.py0000775000175000017500000000276614060132747024170 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") def do_test(proto_ver): 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", proto_ver=proto_ver) if proto_ver == 5: connack_packet = mosq_test.gen_connack(rc=mqtt5_rc.MQTT_RC_NOT_AUTHORIZED, proto_ver=proto_ver, properties=None) else: connack_packet = mosq_test.gen_connack(rc=5, proto_ver=proto_ver) 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 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/01-connect-connack-2163.py0000775000175000017500000000304514060132747021357 0ustar rogerroger#!/usr/bin/env python3 # Test https://github.com/eclipse/mosquitto/issues/2163 # Does the broker cope with a malformed CONNACK sent to it after a valid CONNECT? from mosq_test_helper import * def do_test(proto_ver): rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("connect-connack-2163", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_malformed = struct.pack("BBBBB", 0x02, 0x00, 0x01, 0xE0, 0x00) connack_malformed = struct.pack("BBBB", 0x29, 0x02, 0x00, 0x01) pingreq_packet = mosq_test.gen_pingreq() 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(connack_malformed) try: mosq_test.do_send_receive(sock, pingreq_packet, b"", "pingreq") except ConnectionResetError: pass sock.close() # Does the broker still exist? sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_ping(sock) sock.close() rc = 0 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=3) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/02-subscribe-long-topic.py0000775000175000017500000000303514060132747021755 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 * def do_test(proto_ver): rc = 1 mid = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subscribe-long-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "/"*65535, 0, proto_ver=proto_ver) suback_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) if proto_ver == 4: mosq_test.do_send_receive(sock, subscribe_packet, b"", "suback") else: disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code = mqtt5_rc.MQTT_RC_MALFORMED_PACKET) mosq_test.do_send_receive(sock, subscribe_packet, disconnect_packet, "suback") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/11-message-expiry.py0000775000175000017500000000761714060132747020677 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("allow_anonymous true\n") 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("subpub-qos0-test", keepalive=keepalive, proto_ver=5, clean_session=False, session_expiry=60) 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() except mosq_test.TestError: pass 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-2.0.11/test/broker/Makefile0000664000175000017500000001464614060132747016601 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 13 14 01 : ./01-connect-allow-anonymous.py ./01-connect-bad-packet.py ./01-connect-connack-2163.py ./01-connect-disconnect-v5.py ./01-connect-duplicate.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.py ./01-connect-uname-invalid-utf8.py ./01-connect-uname-no-flag.py ./01-connect-uname-no-password-denied.py ./01-connect-uname-or-anon.py ./01-connect-uname-password-denied-no-will.py ./01-connect-uname-password-denied.py ./01-connect-uname-pwd-no-flag.py ./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-oversize-payload.py ./02-subpub-qos0-queued-bytes.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.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-oversize-payload.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.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.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-max-inflight-expire.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-clean-session.py ./06-bridge-fail-persist-resend-qos1.py ./06-bridge-fail-persist-resend-qos2.py ./06-bridge-no-local.py ./06-bridge-outgoing-retain.py ./06-bridge-per-listener-settings.py ./06-bridge-reconnect-local-out.py 07 : ./07-will-delay-invalid-573191.py ./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-oversize-payload.py ./07-will-properties.py ./07-will-qos0.py ./07-will-reconnect-1273.py ./07-will-takeover.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-plugin-publish.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 13 : ./13-malformed-publish-v5.py ./13-malformed-subscribe-v5.py ./13-malformed-unsubscribe-v5.py 14 : ifeq ($(WITH_TLS),yes) ifeq ($(WITH_CJSON),yes) ./14-dynsec-acl.py ./14-dynsec-anon-group.py ./14-dynsec-auth.py ./14-dynsec-client.py ./14-dynsec-client-invalid.py ./14-dynsec-default-access.py ./14-dynsec-disable-client.py ./14-dynsec-group.py ./14-dynsec-group-invalid.py ./14-dynsec-modify-client.py ./14-dynsec-modify-group.py ./14-dynsec-modify-role.py ./14-dynsec-plugin-invalid.py ./14-dynsec-role.py ./14-dynsec-role-invalid.py endif endif mosquitto-2.0.11/test/broker/08-ssl-connect-no-auth-wrong-ca.py0000775000175000017500000000266614060132747023256 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 except mosq_test.TestError: pass 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-2.0.11/test/broker/04-retain-qos0.py0000775000175000017500000000263514060132747020074 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 * def do_test(proto_ver): rc = 1 keepalive = 60 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos0/test", 0, proto_ver=proto_ver) suback_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) sock.send(publish_packet) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.expect_packet(sock, "publish", publish_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/07-will-qos0.py0000775000175000017500000000335314060132747017562 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) 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, session_expiry=60) 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() mosq_test.expect_packet(sock, "publish", publish_packet) rc = 0 sock.close() except mosq_test.TestError: pass 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-2.0.11/test/broker/03-publish-invalid-utf8.py0000775000175000017500000000313314060132747021701 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 * def do_test(proto_ver): rc = 1 mid = 53 keepalive = 60 connect_packet = mosq_test.gen_connect("publish-invalid-utf8", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("invalid/utf8", 1, mid=mid, proto_ver=proto_ver) 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, proto_ver=proto_ver) 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) if proto_ver == 4: mosq_test.do_send_receive(sock, publish_packet, b"", "puback") else: disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=mqtt5_rc.MQTT_RC_MALFORMED_PACKET) mosq_test.do_send_receive(sock, publish_packet, disconnect_packet, "puback") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/12-prop-maximum-packet-size-connect.py0000775000175000017500000000145514060132747024227 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 = 5 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 except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) mosquitto-2.0.11/test/broker/03-publish-qos1-max-inflight-expire.py0000775000175000017500000001003614060132747024131 0ustar rogerroger#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with QoS 1 results in the correct packet flow for a subscriber. # 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("allow_anonymous true\n") f.write("max_inflight_messages 1\n") def do_test(proto_ver): rc = 1 keepalive = 60 properties = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_SESSION_EXPIRY_INTERVAL, 1000) sub_connect_packet = mosq_test.gen_connect("sub", keepalive=keepalive, properties=properties, proto_ver=proto_ver, clean_session=False) properties = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS_MAXIMUM, 10) \ + mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 1) sub_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver, properties=properties, property_helper=False) sub_connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver, properties=properties, property_helper=False) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "pub/qos1/test", 1, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) connect_packet = mosq_test.gen_connect("pub-qos1-test", keepalive=keepalive, proto_ver=proto_ver) properties = mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_TOPIC_ALIAS_MAXIMUM, 10) \ + mqtt5_props.gen_uint16_prop(mqtt5_props.PROP_RECEIVE_MAXIMUM, 1) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver, properties=properties, property_helper=False) mid = 311 properties = mqtt5_props.gen_uint32_prop(mqtt5_props.PROP_MESSAGE_EXPIRY_INTERVAL, 1) publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", proto_ver=proto_ver, properties=properties) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) mid = 1 r_publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", proto_ver=proto_ver) r_puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: sub_sock = mosq_test.do_client_connect(sub_connect_packet, sub_connack_packet, port=port, timeout=10) mosq_test.do_send_receive(sub_sock, subscribe_packet, suback_packet, "suback") sub_sock.close() 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") time.sleep(2) sub_sock = mosq_test.do_client_connect(sub_connect_packet, sub_connack_packet2, port=port, timeout=10) # This message has expired, so we don't expect it #mosq_test.expect_packet(sub_sock, "publish 2", r_publish_packet) #sub_sock.send(r_puback_packet) # mid = 1 s_publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message2", proto_ver=proto_ver) s_puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) mosq_test.do_send_receive(sock, s_publish_packet, s_puback_packet, "puback") mid = 2 r_publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message2", proto_ver=proto_ver) r_puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) mosq_test.expect_packet(sub_sock, "publish 3", r_publish_packet) sub_sock.send(r_puback_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/06-bridge-b2br-disconnect-qos2.py0000775000175000017500000001060314060132747023020 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, protocol_version): 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") f.write("bridge_protocol_version %s\n" % (protocol_version)) def do_test(proto_ver): if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2, bridge_protocol) 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=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) if proto_ver == 5: opts = mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL | mqtt5_opts.MQTT_SUB_OPT_RETAIN_AS_PUBLISHED else: opts = 0 mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2 | opts, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 2 subscribe2_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2 | opts, proto_ver=proto_ver) suback2_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 3 subscribe3_packet = mosq_test.gen_subscribe(mid, "bridge/#", 2 | opts, proto_ver=proto_ver) suback3_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 5 publish_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=2, mid=mid, payload="disconnect-message", proto_ver=proto_ver) publish_dup_packet = mosq_test.gen_publish("bridge/disconnect/test", qos=2, mid=mid, payload="disconnect-message", dup=True, proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid, proto_ver=proto_ver) 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) try: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) (bridge, address) = ssock.accept() bridge.settimeout(20) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) 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) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) mosq_test.expect_packet(bridge, "2nd subscribe", subscribe2_packet) bridge.send(suback2_packet) bridge.send(publish_dup_packet) mosq_test.expect_packet(bridge, "pubrec", pubrec_packet) bridge.send(pubrel_packet) bridge.close() (bridge, address) = ssock.accept() bridge.settimeout(20) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) mosq_test.expect_packet(bridge, "3rd subscribe", subscribe3_packet) bridge.send(suback3_packet) bridge.send(publish_dup_packet) mosq_test.expect_packet(bridge, "2nd pubrec", pubrec_packet) bridge.send(pubrel_packet) mosq_test.expect_packet(bridge, "pubcomp", pubcomp_packet) rc = 0 bridge.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() ssock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/03-publish-qos1.py0000775000175000017500000000255414060132747020260 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 * def do_test(proto_ver): rc = 1 mid = 19 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qos1-test", keepalive=keepalive, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("pub/qos1/test", qos=1, mid=mid, payload="message", proto_ver=proto_ver) if proto_ver == 5: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver, reason_code=mqtt5_rc.MQTT_RC_NO_MATCHING_SUBSCRIBERS) else: puback_packet = mosq_test.gen_puback(mid, 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, publish_packet, puback_packet, "puback") rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/broker/06-bridge-b2br-late-connection-retain.py0000775000175000017500000000776714060132747024370 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("allow_anonymous true\n") f.write("\n") f.write("persistence true\n") f.write("persistence_file %s\n" % (persistence_file)) def write_config2(filename, persistence_file, port1, port2, protocol_version): with open(filename, 'w') as f: f.write("port %d\n" % (port2)) f.write("allow_anonymous true\n") 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("bridge_protocol_version %s\n" % (protocol_version)) f.write("persistence true\n") f.write("persistence_file %s\n" % (persistence_file)) def do_test(proto_ver): if proto_ver == 4: bridge_protocol = "mqttv311" proto_ver_connect = 128+4 else: bridge_protocol = "mqttv50" proto_ver_connect = 5 (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=proto_ver_connect) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) c_connect_packet = mosq_test.gen_connect("client", keepalive=keepalive, proto_ver=proto_ver) c_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish_packet = mosq_test.gen_publish("bridge/test", qos=1, mid=mid, payload="message", retain=True, proto_ver=proto_ver) if proto_ver == 5: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver, reason_code=16) else: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) 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) try: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) 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, bridge_protocol) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) (bridge, address) = ssock.accept() bridge.settimeout(20) mosq_test.expect_packet(bridge, "connect", connect_packet) bridge.send(connack_packet) 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() except mosq_test.TestError: pass finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() broker.wait() (stdo, stde) = broker.communicate() os.remove(persistence_file) ssock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) mosquitto-2.0.11/test/mqtt5_props.py0000664000175000017500000000370414060132747016515 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-2.0.11/test/Makefile0000664000175000017500000000057214060132747015306 0ustar rogerrogerinclude ../config.mk .PHONY: all check test ptest clean all : check : test test : utest $(MAKE) -C broker test $(MAKE) -C lib test $(MAKE) -C client test ptest : utest $(MAKE) -C broker ptest $(MAKE) -C lib ptest $(MAKE) -C client test utest : $(MAKE) -C unit test reallyclean : clean clean : $(MAKE) -C lib clean $(MAKE) -C broker clean $(MAKE) -C unit clean mosquitto-2.0.11/test/unit/0000775000175000017500000000000014060132747014621 5ustar rogerrogermosquitto-2.0.11/test/unit/persist_write_stubs.c0000664000175000017500000000426414060132747021116 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(mosq_sock_t sock) { UNUSED(sock); return mosquitto__calloc(1, sizeof(struct mosquitto)); } int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { UNUSED(mosq); UNUSED(priority); UNUSED(fmt); return 0; } time_t mosquitto_time(void) { return 123; } int net__socket_close(struct mosquitto *mosq) { UNUSED(mosq); return MOSQ_ERR_SUCCESS; } int send__pingreq(struct mosquitto *mosq) { UNUSED(mosq); return MOSQ_ERR_SUCCESS; } int mosquitto_acl_check(struct mosquitto *context, const char *topic, uint32_t payloadlen, void* payload, uint8_t qos, bool retain, int access) { UNUSED(context); UNUSED(topic); UNUSED(payloadlen); UNUSED(payload); UNUSED(qos); UNUSED(retain); UNUSED(access); return MOSQ_ERR_SUCCESS; } int acl__find_acls(struct mosquitto *context) { UNUSED(context); return MOSQ_ERR_SUCCESS; } int send__publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, uint8_t qos, bool retain, bool dup, const mosquitto_property *cmsg_props, const mosquitto_property *store_props, uint32_t expiry_interval) { UNUSED(mosq); UNUSED(mid); UNUSED(topic); UNUSED(payloadlen); UNUSED(payload); UNUSED(qos); UNUSED(retain); UNUSED(dup); UNUSED(cmsg_props); UNUSED(store_props); UNUSED(expiry_interval); return MOSQ_ERR_SUCCESS; } int send__pubcomp(struct mosquitto *mosq, uint16_t mid, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(mid); UNUSED(properties); return MOSQ_ERR_SUCCESS; } int send__pubrec(struct mosquitto *mosq, uint16_t mid, uint8_t reason_code, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(mid); UNUSED(reason_code); UNUSED(properties); return MOSQ_ERR_SUCCESS; } int send__pubrel(struct mosquitto *mosq, uint16_t mid, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(mid); UNUSED(properties); return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/test/unit/utf8.c0000664000175000017500000004620014060132747015655 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, (int)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) { uint8_t buf[4]; /* As per boundary condition tests, but less one character */ buf[0] = 0xC2; buf[1] = 0; utf8_helper((char *)buf, MOSQ_ERR_MALFORMED_UTF8); buf[0] = 0xE0; buf[1] = 0xA0; buf[2] = 0; utf8_helper((char *)buf, MOSQ_ERR_MALFORMED_UTF8); buf[0] = 0xF0; buf[1] = 0x90; buf[2] = 0x80; buf[3] = 0; utf8_helper((char *)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) { uint8_t 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] = (uint8_t)i; } utf8_helper((char *)buf, MOSQ_ERR_MALFORMED_UTF8); memset(buf, 0, sizeof(buf)); for(i=0x90; i<0xa0; i++){ buf[i-0x90] = (uint8_t)i; } utf8_helper((char *)buf, MOSQ_ERR_MALFORMED_UTF8); for(i=0x80; i<0xA0; i++){ buf[0] = (uint8_t)i; buf[1] = 0; utf8_helper((char *)buf, MOSQ_ERR_MALFORMED_UTF8); } for(i=0xA0; i<0xC0; i++){ buf[0] = (uint8_t)i; buf[1] = 0; utf8_helper((char *)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] = (uint8_t)i; buf[1] = ' '; buf[2] = 0; utf8_helper((char *)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] = (uint8_t)i; buf[1] = ' '; buf[2] = 0; utf8_helper((char *)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] = (uint8_t)i; buf[1] = ' '; buf[2] = 0; utf8_helper((char *)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] = (uint8_t)i; buf[1] = ' '; buf[2] = 0; utf8_helper((char *)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] = (uint8_t)i; buf[1] = ' '; buf[2] = 0; utf8_helper((char *)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) { uint8_t buf[10]; int i; /* U+0001 to U+001F are single byte control characters */ for(i=0x01; i<0x20; i++){ buf[0] = (uint8_t)i; buf[1] = '\0'; utf8_helper((char *)buf, MOSQ_ERR_MALFORMED_UTF8); } /* U+007F is a single byte control character */ buf[0] = 0x7F; buf[1] = '\0'; utf8_helper((char *)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] = (uint8_t)(i-0x80); buf[2] = '\0'; utf8_helper((char *)buf, MOSQ_ERR_MALFORMED_UTF8); } } void TEST_utf8_mqtt_1_5_4_2(void) { uint8_t buf[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', '\0'}; utf8_helper_len((char *)buf, 9, MOSQ_ERR_SUCCESS); buf[3] = '\0'; utf8_helper_len((char *)buf, 9, MOSQ_ERR_MALFORMED_UTF8); } void TEST_utf8_mqtt_1_5_4_3(void) { uint8_t buf[10] = {'a', 'b', 0xEF, 0xBB, 0xBF, 'f', 'g', 'h', 'i', '\0'}; utf8_helper_len((char *)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-2.0.11/test/unit/property_add.c0000664000175000017500000005710214060132747017466 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); } static void TEST_check_length(void) { mosquitto_property *proplist = NULL; int rc; unsigned int len; int varbytes; int i; len = property__get_remaining_length(proplist); CU_ASSERT_EQUAL(len, 1); for(i=1; i<10000; i++){ 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); if(proplist){ len = property__get_remaining_length(proplist); if(i < 64){ varbytes = 1; }else if(i < 8192){ varbytes = 2; }else{ varbytes = 3; } CU_ASSERT_EQUAL(len, varbytes+2*i); }else{ break; } } 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 nothing, check length", TEST_check_length) || !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-2.0.11/test/unit/misc_trim_test.c0000664000175000017500000001012514060132747020011 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-2.0.11/test/unit/bridge_topic_test.c0000664000175000017500000000567314060132747020471 0ustar rogerroger#include "config.h" #include #include #include #define WITH_BRIDGE #define WITH_BROKER #include "mosquitto_broker_internal.h" #include "property_mosq.h" #include "packet_mosq.h" static void map_valid_helper(const char *topic, const char *local_prefix, const char *remote_prefix, const char *incoming, const char *expected) { struct mosquitto mosq; struct mosquitto__bridge bridge; char *map_topic; int rc; memset(&mosq, 0, sizeof(struct mosquitto)); memset(&bridge, 0, sizeof(struct mosquitto__bridge)); mosq.bridge = &bridge; rc = bridge__add_topic(&bridge, topic, bd_in, 0, local_prefix, remote_prefix); CU_ASSERT_EQUAL(rc, 0); map_topic = strdup(incoming); rc = bridge__remap_topic_in(&mosq, &map_topic); CU_ASSERT_EQUAL(rc, 0); CU_ASSERT_PTR_NOT_NULL(map_topic); if(topic){ CU_ASSERT_STRING_EQUAL(map_topic, expected); free(map_topic); } } static void map_invalid_helper(const char *topic, const char *local_prefix, const char *remote_prefix) { struct mosquitto mosq; struct mosquitto__bridge bridge; int rc; memset(&mosq, 0, sizeof(struct mosquitto)); memset(&bridge, 0, sizeof(struct mosquitto__bridge)); mosq.bridge = &bridge; rc = bridge__add_topic(&bridge, topic, bd_in, 0, local_prefix, remote_prefix); CU_ASSERT_NOT_EQUAL(rc, 0); } static void TEST_remap_valid(void) { /* Examples from man page */ map_valid_helper("pattern", "L/", "R/", "R/pattern", "L/pattern"); map_valid_helper("pattern", "L/", NULL, "pattern", "L/pattern"); map_valid_helper("pattern", NULL, "R/", "R/pattern", "pattern"); map_valid_helper("pattern", NULL, NULL, "pattern", "pattern"); map_valid_helper(NULL, "local", "remote", "local", "remote"); } static void TEST_remap_invalid(void) { /* Examples from man page */ map_invalid_helper(NULL, "L/", NULL); map_invalid_helper(NULL, NULL, "R/"); map_invalid_helper(NULL, NULL, NULL); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_bridge_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("Bridge remap", NULL, NULL); if(!test_suite){ printf("Error adding CUnit Bridge remap test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "Remap valid", TEST_remap_valid) || !CU_add_test(test_suite, "Remap invalid", TEST_remap_invalid) ){ printf("Error adding Bridge remap CUnit tests.\n"); return 1; } return 0; } int main(int argc, char *argv[]) { unsigned int fails; UNUSED(argc); UNUSED(argv); if(CU_initialize_registry() != CUE_SUCCESS){ printf("Error initializing CUnit registry.\n"); return 1; } if(0 || init_bridge_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-2.0.11/test/unit/stubs.c0000664000175000017500000000077414060132747016135 0ustar rogerroger#include "config.h" #include #include struct mosquitto_db{ }; int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { UNUSED(mosq); UNUSED(priority); UNUSED(fmt); return 0; } time_t mosquitto_time(void) { return 123; } int net__socket_close(struct mosquitto_db *db, struct mosquitto *mosq) { UNUSED(db); UNUSED(mosq); return MOSQ_ERR_SUCCESS; } int send__pingreq(struct mosquitto *mosq) { UNUSED(mosq); return MOSQ_ERR_SUCCESS; } mosquitto-2.0.11/test/unit/util_topic_test.c0000664000175000017500000002335614060132747020210 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-2.0.11/test/unit/files/0000775000175000017500000000000014060132747015723 5ustar rogerrogermosquitto-2.0.11/test/unit/files/persist_read/0000775000175000017500000000000014060132747020407 5ustar rogerrogermosquitto-2.0.11/test/unit/files/persist_read/v6-sub.test-db0000664000175000017500000000021014060132747023006 0ustar rogerrogermosquitto db4Vx(#R [client-idusrname!v#  client-idsubscriptionmosquitto-2.0.11/test/unit/files/persist_read/unsupported-version.test-db0000664000175000017500000000002714060132747025745 0ustar rogerrogermosquitto dbmosquitto-2.0.11/test/unit/files/persist_read/v3-client-message.test-db0000664000175000017500000000022314060132747025116 0ustar rogerrogermosquitto db 4VxT source_idtopicpayload client-idR# client-idTsmosquitto-2.0.11/test/unit/files/persist_read/v3-cfg.test-db0000664000175000017500000000004714060132747022761 0ustar rogerrogermosquitto db 4Vxmosquitto-2.0.11/test/unit/files/persist_read/v5-cfg-truncated.test-db0000664000175000017500000000005614060132747024752 0ustar rogerrogermosquitto db4Vxmosquitto-2.0.11/test/unit/files/persist_read/v4-cfg.test-db0000664000175000017500000000004714060132747022762 0ustar rogerrogermosquitto db 4Vxmosquitto-2.0.11/test/unit/files/persist_read/v3-cfg-truncated.test-db0000664000175000017500000000004614060132747024747 0ustar rogerrogermosquitto db mosquitto-2.0.11/test/unit/files/persist_read/v3-retain.test-db0000664000175000017500000000014614060132747023504 0ustar rogerrogermosquitto db 4VxT source_idtopicpayloadTmosquitto-2.0.11/test/unit/files/persist_read/v6-message-store.test-db0000664000175000017500000000016414060132747025003 0ustar rogerrogermosquitto db4Vx= [source_idusernametopicpayloadmosquitto-2.0.11/test/unit/files/persist_read/v6-retain.test-db0000664000175000017500000000020414060132747023502 0ustar rogerrogermosquitto db4Vx=T [source_idusernametopicpayloadTmosquitto-2.0.11/test/unit/files/persist_read/v3-message-store.test-db0000664000175000017500000000013014060132747024771 0ustar rogerrogermosquitto db 4Vx source_idtopicpayloadmosquitto-2.0.11/test/unit/files/persist_read/v3-bad-chunk.test-db0000664000175000017500000000006414060132747024055 0ustar rogerrogermosquitto dbnochunk mosquitto-2.0.11/test/unit/files/persist_read/v6-client-message-props.test-db0000664000175000017500000000031014060132747026257 0ustar rogerrogermosquitto db4Vx=T [source_idusernametopicpayload(#R [client-idusrnameTs client-idmosquitto-2.0.11/test/unit/files/persist_read/v4-message-store.test-db0000664000175000017500000000014414060132747024777 0ustar rogerrogermosquitto db 4Vx2Tv source_idusername[topicpayloadmosquitto-2.0.11/test/unit/files/persist_read/empty.test-db0000664000175000017500000000000014060132747023017 0ustar rogerrogermosquitto-2.0.11/test/unit/files/persist_read/corrupt-header-short.test-db0000664000175000017500000000001014060132747025743 0ustar rogerrogercorrupt mosquitto-2.0.11/test/unit/files/persist_read/v5-client.test-db0000664000175000017500000000012014060132747023472 0ustar rogerrogermosquitto db4Vx#R client-idmosquitto-2.0.11/test/unit/files/persist_read/v3-client.test-db0000664000175000017500000000010214060132747023470 0ustar rogerrogermosquitto db 4Vx client-idR#mosquitto-2.0.11/test/unit/files/persist_read/v6-client-message.test-db0000664000175000017500000000030514060132747025122 0ustar rogerrogermosquitto db4Vx=T [source_idusernametopicpayload(#R [client-idusrnameTs client-idmosquitto-2.0.11/test/unit/files/persist_read/v6-cfg.test-db0000664000175000017500000000005714060132747022765 0ustar rogerrogermosquitto db4Vxmosquitto-2.0.11/test/unit/files/persist_read/v5-bad-chunk.test-db0000664000175000017500000000010114060132747024047 0ustar rogerrogermosquitto db abcdefghijmosquitto-2.0.11/test/unit/files/persist_read/v3-sub.test-db0000664000175000017500000000014214060132747023007 0ustar rogerrogermosquitto db 5Vx client-idR# client-id subscriptionmosquitto-2.0.11/test/unit/files/persist_read/v6-message-store-props.test-db0000664000175000017500000000031014060132747026135 0ustar rogerrogermosquitto db4Vx@ [source_idusernametopicpayload(#R [client-idusrnames client-idmosquitto-2.0.11/test/unit/files/persist_read/v3-cfg-bad-dbid.test-db0000664000175000017500000000004714060132747024405 0ustar rogerrogermosquitto db  mosquitto-2.0.11/test/unit/files/persist_read/v6-client.test-db0000664000175000017500000000013714060132747023503 0ustar rogerrogermosquitto db4Vx(#R [client-idusrnamemosquitto-2.0.11/test/unit/files/persist_read/corrupt-header-long.test-db0000664000175000017500000000005314060132747025552 0ustar rogerrogercorruptcorruptcorruptcorruptcorruptcorrupt mosquitto-2.0.11/test/unit/files/persist_write/0000775000175000017500000000000014060132747020626 5ustar rogerrogermosquitto-2.0.11/test/unit/files/persist_write/v6-message-store-no-ref.test-db0000664000175000017500000000005714060132747026407 0ustar rogerrogermosquitto db4Vxmosquitto-2.0.11/test/unit/files/persist_write/v4-full.test-db0000664000175000017500000000071214060132747023403 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-2.0.11/test/unit/files/persist_write/empty.test-db0000664000175000017500000000005714060132747023252 0ustar rogerrogermosquitto dbmosquitto-2.0.11/test/unit/test.c0000664000175000017500000000216614060132747015751 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; UNUSED(argc); UNUSED(argv); 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-2.0.11/test/unit/persist_write_test.c0000664000175000017500000002375314060132747020741 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; struct mosquitto_db db; /* 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 = (size_t)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__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; config.persistence = true; rc = persist__backup(false); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); config.persistence_filepath = "disabled.db"; rc = persist__backup(false); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); } static void TEST_empty_file(void) { 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(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_v6_config_ok(void) { 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/v6-cfg.test-db"; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v6-cfg.db"; rc = persist__backup(true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v6-cfg.test-db", "v6-cfg.db")); unlink("v6-cfg.db"); } static void TEST_v6_message_store_no_ref(void) { 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/v6-message-store.test-db"; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v6-message-store-no-ref.db"; rc = persist__backup(true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_write/v6-message-store-no-ref.test-db", "v6-message-store-no-ref.db")); unlink("v6-message-store-no-ref.db"); } static void TEST_v6_message_store_props(void) { 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.per_listener_settings = true; config.listeners = &listener; config.listener_count = 1; config.persistence = true; config.persistence_filepath = "files/persist_read/v6-message-store-props.test-db"; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v6-message-store-props.db"; rc = persist__backup(true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v6-message-store-props.test-db", "v6-message-store-props.db")); unlink("v6-message-store-props.db"); } static void TEST_v6_client(void) { 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.per_listener_settings = true; config.listeners = &listener; config.listener_count = 1; config.persistence = true; config.persistence_filepath = "files/persist_read/v6-client.test-db"; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v6-client.db"; rc = persist__backup(true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v6-client.test-db", "v6-client.db")); unlink("v6-client.db"); } static void TEST_v6_client_message(void) { 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.per_listener_settings = true; config.listeners = &listener; config.listener_count = 1; config.persistence = true; config.persistence_filepath = "files/persist_read/v6-client-message.test-db"; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v6-client-message.db"; rc = persist__backup(true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v6-client-message.test-db", "v6-client-message.db")); unlink("v6-client-message.db"); } static void TEST_v6_client_message_props(void) { 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.per_listener_settings = true; config.listeners = &listener; config.listener_count = 1; config.persistence = true; config.persistence_filepath = "files/persist_read/v6-client-message-props.test-db"; rc = persist__restore(); 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 = "v6-client-message-props.db"; rc = persist__backup(true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v6-client-message-props.test-db", "v6-client-message-props.db")); unlink("v6-client-message-props.db"); } static void TEST_v6_sub(void) { 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.per_listener_settings = true; config.listeners = &listener; config.listener_count = 1; db__open(&config); config.persistence = true; config.persistence_filepath = "files/persist_read/v6-sub.test-db"; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v6-sub.db"; rc = persist__backup(true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(0, file_diff("files/persist_read/v6-sub.test-db", "v6-sub.db")); unlink("v6-sub.db"); } #if 0 NOT WORKING static void TEST_v5_full(void) { 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); config.persistence = true; config.persistence_filepath = "files/persist_write/v5-full.test-db"; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); config.persistence_filepath = "v5-full.db"; rc = persist__backup(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; UNUSED(argc); UNUSED(argv); 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, "v6 config ok", TEST_v6_config_ok) || !CU_add_test(test_suite, "v6 message store (message has no refs)", TEST_v6_message_store_no_ref) || !CU_add_test(test_suite, "v6 message store + props", TEST_v6_message_store_props) || !CU_add_test(test_suite, "v6 client", TEST_v6_client) || !CU_add_test(test_suite, "v6 client message", TEST_v6_client_message) || !CU_add_test(test_suite, "v6 client message+props", TEST_v6_client_message_props) || !CU_add_test(test_suite, "v6 sub", TEST_v6_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-2.0.11/test/unit/property_read.c0000664000175000017500000016377214060132747017664 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, uint32_t remaining_length, int rc_expected, uint8_t 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, uint8_t 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, uint8_t 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, uint32_t remaining_length, int rc_expected, uint8_t 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, uint8_t 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, uint32_t remaining_length, int rc_expected, uint8_t 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, uint8_t 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, uint32_t remaining_length, int rc_expected, uint8_t 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, uint8_t 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(uint8_t 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, uint32_t remaining_length, int rc_expected, uint8_t 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, (size_t)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, uint8_t 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, uint32_t remaining_length, int rc_expected, uint8_t 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, uint32_t remaining_length, int rc_expected, uint8_t 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-2.0.11/test/unit/persist_read_test.c0000664000175000017500000006351314060132747020520 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" char *last_sub = NULL; int last_qos; uint32_t last_identifier; struct mosquitto_db db; static void TEST_persistence_disabled(void) { 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(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); } static void TEST_empty_file(void) { 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(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); } static void TEST_corrupt_header(void) { 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(); CU_ASSERT_EQUAL(rc, 1); config.persistence_filepath = "files/persist_read/corrupt-header-long.test-db"; rc = persist__restore(); CU_ASSERT_EQUAL(rc, 1); } static void TEST_unsupported_version(void) { 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(); CU_ASSERT_EQUAL(rc, 1); } static void TEST_v3_config_ok(void) { 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(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.last_db_id, 0x7856341200000000); } static void TEST_v4_config_ok(void) { 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(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.last_db_id, 0x7856341200000000); } static void TEST_v3_config_truncated(void) { 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(); CU_ASSERT_EQUAL(rc, 1); CU_ASSERT_EQUAL(db.last_db_id, 0); } static void TEST_v3_config_bad_dbid(void) { 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(); CU_ASSERT_EQUAL(rc, 1); CU_ASSERT_EQUAL(db.last_db_id, 0); } static void TEST_v3_bad_chunk(void) { 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(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.last_db_id, 0x17); } static void TEST_v3_message_store(void) { 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(); 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(db.msg_store->payload, "payload", 7); } } } static void TEST_v3_client(void) { 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(); 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__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(); 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(context->msgs_out.inflight->store->payload, "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__config config; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); db.config = &config; retain__init(); config.persistence = true; config.persistence_filepath = "files/persist_read/v3-retain.test-db"; rc = persist__restore(); 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(db.msg_store->payload, "payload", 7); } } CU_ASSERT_PTR_NOT_NULL(db.retains); if(db.retains){ CU_ASSERT_STRING_EQUAL(db.retains->topic, ""); CU_ASSERT_PTR_NOT_NULL(db.retains->children); if(db.retains->children){ CU_ASSERT_STRING_EQUAL(db.retains->children->topic, ""); CU_ASSERT_PTR_NOT_NULL(db.retains->children->children); if(db.retains->children->children){ CU_ASSERT_STRING_EQUAL(db.retains->children->children->topic, "topic"); } } } } static void TEST_v3_sub(void) { 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(); 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__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(); 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(db.msg_store->payload, "payload", 7); } } } static void TEST_v6_config_ok(void) { 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/v6-cfg.test-db"; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.last_db_id, 0x7856341200000000); } static void TEST_v5_config_truncated(void) { 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(); CU_ASSERT_EQUAL(rc, 1); CU_ASSERT_EQUAL(db.last_db_id, 0); } static void TEST_v5_bad_chunk(void) { 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(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(db.last_db_id, 0x17); } static void TEST_v6_message_store(void) { 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/v6-message-store.test-db"; rc = persist__restore(); 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(db.msg_store->payload, "payload", 7); } CU_ASSERT_PTR_NULL(db.msg_store->properties); } } static void TEST_v6_message_store_props(void) { 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/v6-message-store-props.test-db"; rc = persist__restore(); 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(db.msg_store->payload, "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__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(); 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_v6_client(void) { struct mosquitto__config config; struct mosquitto *context; 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.per_listener_settings = true; config.listeners = &listener; config.listener_count = 1; config.persistence = true; config.persistence_filepath = "files/persist_read/v6-client.test-db"; rc = persist__restore(); 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); CU_ASSERT_EQUAL(context->listener, &listener); CU_ASSERT_PTR_NOT_NULL(context->username); if(context->username){ CU_ASSERT_STRING_EQUAL(context->username, "usrname"); } } } static void TEST_v6_client_message(void) { 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/v6-client-message.test-db"; rc = persist__restore(); 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(context->msgs_out.inflight->store->payload, "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_v6_client_message_props(void) { 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/v6-client-message-props.test-db"; rc = persist__restore(); 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(context->msgs_out.inflight->store->payload, "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_v6_retain(void) { 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/v6-retain.test-db"; retain__init(); rc = persist__restore(); 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(db.msg_store->payload, "payload", 7); } } CU_ASSERT_PTR_NOT_NULL(db.retains); if(db.retains){ CU_ASSERT_STRING_EQUAL(db.retains->topic, ""); CU_ASSERT_PTR_NOT_NULL(db.retains->children); if(db.retains->children){ CU_ASSERT_STRING_EQUAL(db.retains->children->topic, ""); CU_ASSERT_PTR_NOT_NULL(db.retains->children->children); if(db.retains->children->children){ CU_ASSERT_STRING_EQUAL(db.retains->children->children->topic, "topic"); } } } } static void TEST_v6_sub(void) { 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/v6-sub.test-db"; rc = persist__restore(); 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 client", TEST_v5_client) || !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, "v6 config ok", TEST_v6_config_ok) || !CU_add_test(test_suite, "v6 message store", TEST_v6_message_store) || !CU_add_test(test_suite, "v6 message store+props", TEST_v6_message_store_props) || !CU_add_test(test_suite, "v6 client", TEST_v6_client) || !CU_add_test(test_suite, "v6 client message", TEST_v6_client_message) || !CU_add_test(test_suite, "v6 client message+props", TEST_v6_client_message_props) || !CU_add_test(test_suite, "v6 retain", TEST_v6_retain) || !CU_add_test(test_suite, "v6 sub", TEST_v6_sub) ){ printf("Error adding persist CUnit tests.\n"); return 1; } return 0; } int main(int argc, char *argv[]) { unsigned int fails; UNUSED(argc); UNUSED(argv); 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-2.0.11/test/unit/publish_test.c0000664000175000017500000000167714060132747017505 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-2.0.11/test/unit/subs_stubs.c0000664000175000017500000001032614060132747017163 0ustar rogerroger#include #define WITH_BROKER #include #include #include #include #include #include #if 0 extern uint64_t last_retained; extern char *last_sub; extern int last_qos; struct mosquitto *context__init(mosq_sock_t sock) { return mosquitto__calloc(1, sizeof(struct mosquitto)); } int db__message_insert(struct mosquitto *context, uint16_t mid, enum mosquitto_msg_direction dir, uint8_t qos, bool retain, struct mosquitto_msg_store *stored, mosquitto_property *properties) { return MOSQ_ERR_SUCCESS; } void db__msg_store_ref_dec(struct mosquitto_msg_store **store) { } void db__msg_store_ref_inc(struct mosquitto_msg_store *store) { store->ref_count++; } #endif int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { UNUSED(mosq); UNUSED(priority); UNUSED(fmt); return 0; } time_t mosquitto_time(void) { return 123; } #if 0 int net__socket_close(struct mosquitto *mosq) { return MOSQ_ERR_SUCCESS; } int send__pingreq(struct mosquitto *mosq) { return MOSQ_ERR_SUCCESS; } int mosquitto_acl_check(struct mosquitto *context, const char *topic, uint32_tn payloadlen, void* payload, uint8_t qos, bool retain, int access) { return MOSQ_ERR_SUCCESS; } int acl__find_acls(struct mosquitto *context) { return MOSQ_ERR_SUCCESS; } #endif int send__publish(struct mosquitto *mosq, uint16_t mid, const char *topic, uint32_t payloadlen, const void *payload, uint8_t qos, bool retain, bool dup, const mosquitto_property *cmsg_props, const mosquitto_property *store_props, uint32_t expiry_interval) { UNUSED(mosq); UNUSED(mid); UNUSED(topic); UNUSED(payloadlen); UNUSED(payload); UNUSED(qos); UNUSED(retain); UNUSED(dup); UNUSED(cmsg_props); UNUSED(store_props); UNUSED(expiry_interval); return MOSQ_ERR_SUCCESS; } int send__pubcomp(struct mosquitto *mosq, uint16_t mid, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(mid); UNUSED(properties); return MOSQ_ERR_SUCCESS; } int send__pubrec(struct mosquitto *mosq, uint16_t mid, uint8_t reason_code, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(mid); UNUSED(reason_code); UNUSED(properties); return MOSQ_ERR_SUCCESS; } int send__pubrel(struct mosquitto *mosq, uint16_t mid, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(mid); UNUSED(properties); return MOSQ_ERR_SUCCESS; } int mosquitto_acl_check(struct mosquitto *context, const char *topic, uint32_t payloadlen, void* payload, uint8_t qos, bool retain, int access) { UNUSED(context); UNUSED(topic); UNUSED(payloadlen); UNUSED(payload); UNUSED(qos); UNUSED(retain); UNUSED(access); return MOSQ_ERR_SUCCESS; } uint16_t mosquitto__mid_generate(struct mosquitto *mosq) { static uint16_t mid = 1; UNUSED(mosq); return ++mid; } int mosquitto_property_add_varint(mosquitto_property **proplist, int identifier, uint32_t value) { UNUSED(proplist); UNUSED(identifier); UNUSED(value); return MOSQ_ERR_SUCCESS; } int persist__backup(bool shutdown) { UNUSED(shutdown); return MOSQ_ERR_SUCCESS; } int persist__restore(void) { return MOSQ_ERR_SUCCESS; } void mosquitto_property_free_all(mosquitto_property **properties) { UNUSED(properties); } int retain__init(void) { return MOSQ_ERR_SUCCESS; } void retain__clean(struct mosquitto__retainhier **retainhier) { UNUSED(retainhier); } int retain__queue(struct mosquitto *context, const char *sub, uint8_t sub_qos, uint32_t subscription_identifier) { UNUSED(context); UNUSED(sub); UNUSED(sub_qos); UNUSED(subscription_identifier); return MOSQ_ERR_SUCCESS; } int retain__store(const char *topic, struct mosquitto_msg_store *stored, char **split_topics) { UNUSED(topic); UNUSED(stored); UNUSED(split_topics); return MOSQ_ERR_SUCCESS; } 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--; } } void util__increment_receive_quota(struct mosquitto *mosq) { mosq->msgs_in.inflight_quota++; } void util__increment_send_quota(struct mosquitto *mosq) { mosq->msgs_out.inflight_quota++; } mosquitto-2.0.11/test/unit/property_write.c0000664000175000017500000004566114060132747020077 0ustar rogerroger#include #include #include "mqtt_protocol.h" #include "property_mosq.h" #include "packet_mosq.h" static void byte_prop_write_helper( int command, uint32_t 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, uint32_t 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, uint32_t 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, uint32_t 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 = (uint16_t)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, uint32_t remaining_length, int rc_expected, int identifier, const uint8_t *value_expected, uint16_t 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( uint32_t 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 = (uint16_t)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 = (uint16_t)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( uint32_t 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; CU_ASSERT_EQUAL(packet.remaining_length, remaining_length); 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-2.0.11/test/unit/datatype_write.c0000664000175000017500000000774314060132747020025 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, (uint8_t)(255-i)); } CU_ASSERT_EQUAL(packet.pos, 256); for(i=0; i<256; i++){ CU_ASSERT_EQUAL(payload[i], (uint8_t)(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, (uint16_t)(100*i)); } CU_ASSERT_EQUAL(packet.pos, 650); payload16 = (uint16_t *)payload; for(i=0; i<325; i++){ CU_ASSERT_EQUAL(payload16[i], htons((uint16_t)(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, (uint32_t)(1000*i)); } CU_ASSERT_EQUAL(packet.pos, 42000); payload32 = (uint32_t *)payload; for(i=0; i<10500; i++){ CU_ASSERT_EQUAL(payload32[i], htonl((uint32_t)(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-2.0.11/test/unit/persist_read_stubs.c0000664000175000017500000000760314060132747020677 0ustar rogerroger#include #define WITH_BROKER #include #include #include #include #include #include extern char *last_sub; extern int last_qos; extern uint32_t last_identifier; extern struct mosquitto_db db; struct mosquitto *context__init(mosq_sock_t sock) { struct mosquitto *m; UNUSED(sock); 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; } void db__msg_store_free(struct mosquitto_msg_store *store) { int i; 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); mosquitto__free(store->payload); mosquitto__free(store); } int db__message_store(const struct mosquitto *source, struct mosquitto_msg_store *stored, uint32_t message_expiry_interval, dbid_t store_id, enum mosquitto_msg_origin origin) { int rc = MOSQ_ERR_SUCCESS; UNUSED(origin); if(source && source->id){ stored->source_id = mosquitto__strdup(source->id); }else{ stored->source_id = mosquitto__strdup(""); } if(!stored->source_id){ rc = MOSQ_ERR_NOMEM; goto error; } if(source && source->username){ stored->source_username = mosquitto__strdup(source->username); if(!stored->source_username){ rc = MOSQ_ERR_NOMEM; goto error; } } if(source){ stored->source_listener = source->listener; } stored->mid = 0; if(message_expiry_interval > 0){ stored->message_expiry_time = time(NULL) + message_expiry_interval; }else{ stored->message_expiry_time = 0; } stored->dest_ids = NULL; stored->dest_id_count = 0; db.msg_store_count++; db.msg_store_bytes += stored->payloadlen; if(!store_id){ stored->db_id = ++db.last_db_id; }else{ stored->db_id = store_id; } db.msg_store = stored; return MOSQ_ERR_SUCCESS; error: db__msg_store_free(stored); return rc; } int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { UNUSED(mosq); UNUSED(priority); UNUSED(fmt); return 0; } time_t mosquitto_time(void) { return 123; } int net__socket_close(struct mosquitto *mosq) { UNUSED(mosq); return MOSQ_ERR_SUCCESS; } int send__pingreq(struct mosquitto *mosq) { UNUSED(mosq); return MOSQ_ERR_SUCCESS; } int mosquitto_acl_check(struct mosquitto *context, const char *topic, uint32_t payloadlen, void* payload, uint8_t qos, bool retain, int access) { UNUSED(context); UNUSED(topic); UNUSED(payloadlen); UNUSED(payload); UNUSED(qos); UNUSED(retain); UNUSED(access); return MOSQ_ERR_SUCCESS; } int acl__find_acls(struct mosquitto *context) { UNUSED(context); return MOSQ_ERR_SUCCESS; } int sub__add(struct mosquitto *context, const char *sub, uint8_t qos, uint32_t identifier, int options, struct mosquitto__subhier **root) { UNUSED(context); UNUSED(options); UNUSED(root); last_sub = strdup(sub); last_qos = qos; last_identifier = identifier; return MOSQ_ERR_SUCCESS; } int db__message_insert(struct mosquitto *context, uint16_t mid, enum mosquitto_msg_direction dir, uint8_t qos, bool retain, struct mosquitto_msg_store *stored, mosquitto_property *properties, bool update) { UNUSED(context); UNUSED(mid); UNUSED(dir); UNUSED(qos); UNUSED(retain); UNUSED(stored); UNUSED(properties); UNUSED(update); return MOSQ_ERR_SUCCESS; } void db__msg_store_ref_dec(struct mosquitto_msg_store **store) { UNUSED(store); } void db__msg_store_ref_inc(struct mosquitto_msg_store *store) { store->ref_count++; } mosquitto-2.0.11/test/unit/datatype_read.c0000664000175000017500000005315214060132747017601 0ustar rogerroger#include #include #include "packet_mosq.h" static void byte_read_helper( uint8_t *payload, uint32_t 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, uint32_t 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, uint32_t 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, uint32_t remaining_length, int rc_expected, uint32_t value_expected, uint8_t bytes_expected) { struct mosquitto__packet packet; uint32_t value = UINT32_MAX; uint8_t bytes = UINT8_MAX; 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, uint32_t remaining_length, int rc_expected, const uint8_t *value_expected, int length_expected) { struct mosquitto__packet packet; uint8_t *value = NULL; uint16_t length = UINT16_MAX; 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, uint32_t remaining_length, int rc_expected, const uint8_t *value_expected, uint16_t length_expected) { struct mosquitto__packet packet; uint8_t *value = NULL; uint16_t length = UINT16_MAX; 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, uint32_t 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, (uint32_t)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 #define WITH_BROKER #define WITH_PERSISTENCE #include "mosquitto_broker_internal.h" #include "memory_mosq.h" struct mosquitto_db db; static void hier_quick_check(struct mosquitto__subhier **sub, struct mosquitto *context, const char *topic) { if(sub != NULL){ CU_ASSERT_EQUAL((*sub)->topic_len, strlen(topic)); CU_ASSERT_PTR_NOT_NULL((*sub)->topic); if((*sub)->topic){ CU_ASSERT_STRING_EQUAL((*sub)->topic, topic); } if(context){ CU_ASSERT_PTR_NOT_NULL((*sub)->subs); if((*sub)->subs){ CU_ASSERT_PTR_EQUAL((*sub)->subs->context, context); CU_ASSERT_PTR_NULL((*sub)->subs->next); } }else{ CU_ASSERT_PTR_NULL((*sub)->subs); } (*sub) = (*sub)->children; } } static void TEST_sub_add_single(void) { struct mosquitto__config config; struct mosquitto__listener listener; struct mosquitto context; struct mosquitto__subhier *sub; int rc; memset(&db, 0, sizeof(struct mosquitto_db)); memset(&config, 0, sizeof(struct mosquitto__config)); memset(&listener, 0, sizeof(struct mosquitto__listener)); memset(&context, 0, sizeof(struct mosquitto)); context.id = "client"; db.config = &config; listener.port = 1883; config.listeners = &listener; config.listener_count = 1; db__open(&config); rc = sub__add(&context, "a/b/c/d/e", 0, 0, 0, &db.subs); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(db.subs); if(db.subs){ sub = db.subs; hier_quick_check(&sub, NULL, ""); hier_quick_check(&sub, NULL, ""); hier_quick_check(&sub, NULL, "a"); hier_quick_check(&sub, NULL, "b"); hier_quick_check(&sub, NULL, "c"); hier_quick_check(&sub, NULL, "d"); hier_quick_check(&sub, &context, "e"); CU_ASSERT_PTR_NULL(sub); } mosquitto__free(context.subs); db__close(); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int main(int argc, char *argv[]) { CU_pSuite test_suite = NULL; unsigned int fails; UNUSED(argc); UNUSED(argv); if(CU_initialize_registry() != CUE_SUCCESS){ printf("Error initializing CUnit registry.\n"); return 1; } test_suite = CU_add_suite("Subs", NULL, NULL); if(!test_suite){ printf("Error adding CUnit Subs test suite.\n"); CU_cleanup_registry(); return 1; } if(0 || !CU_add_test(test_suite, "Sub add single", TEST_sub_add_single) ){ printf("Error adding Subs 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-2.0.11/test/unit/property_user_read.c0000664000175000017500000006341514060132747020713 0ustar rogerroger#include #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, uint16_t 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-2.0.11/test/unit/Makefile0000664000175000017500000001145114060132747016263 0ustar rogerrogerinclude ../../config.mk .PHONY: all check test test-broker test-lib clean coverage CPPFLAGS:=$(CPPFLAGS) -I../.. -I../../include -I../../lib -I../../src ifeq ($(WITH_BUNDLED_DEPS),yes) CPPFLAGS:=$(CPPFLAGS) -I../../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 \ memory_public.o \ misc_mosq.o \ packet_datatypes.o \ property_mosq.o \ util_mosq.o \ util_topic.o \ utf8_mosq.o BRIDGE_TOPIC_TEST_OBJS = \ bridge_topic_test.o \ stubs.o \ BRIDGE_TOPIC_OBJS = \ bridge_topic.o \ memory_mosq.o \ memory_public.o \ util_topic.o \ PERSIST_READ_TEST_OBJS = \ persist_read_test.o \ persist_read_stubs.o PERSIST_READ_OBJS = \ memory_mosq.o \ memory_public.o \ misc_mosq.o \ packet_datatypes.o \ persist_read.o \ persist_read_v234.o \ persist_read_v5.o \ property_mosq.o \ retain.o \ topic_tok.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 \ memory_public.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 \ retain.o \ subs.o \ topic_tok.o \ utf8_mosq.o \ util_mosq.o SUBS_TEST_OBJS = \ subs_test.o \ subs_stubs.o SUBS_OBJS = \ database.o \ memory_mosq.o \ memory_public.o \ subs.o \ topic_tok.o all : test check : test mosq_test : ${TEST_OBJS} ${LIB_OBJS} $(CROSS_COMPILE)$(CC) $(LDFLAGS) -o $@ $^ $(LDADD) bridge_topic_test : ${BRIDGE_TOPIC_TEST_OBJS} ${BRIDGE_TOPIC_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) subs_test : ${SUBS_TEST_OBJS} ${SUBS_OBJS} $(CROSS_COMPILE)$(CC) $(LDFLAGS) -o $@ $^ $(LDADD) bridge_topic.o : ../../src/bridge_topic.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -DWITH_BROKER -DWITH_BRIDGE -c -o $@ $^ 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 $@ $^ memory_public.o : ../../src/memory_public.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 $@ $^ retain.o : ../../src/retain.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -DWITH_BROKER -DWITH_PERSISTENCE -c -o $@ $^ subs.o : ../../src/subs.c $(CROSS_COMPILE)$(CC) $(CPPFLAGS) $(CFLAGS) -DWITH_BROKER -DWITH_PERSISTENCE -c -o $@ $^ topic_tok.o : ../../src/topic_tok.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 $@ $^ build : mosq_test bridge_topic_test persist_read_test persist_write_test subs_test test-lib : build ./mosq_test test-broker : build ./bridge_topic_test ./persist_read_test ./persist_write_test ./subs_test test : test-broker test-lib clean : -rm -rf mosq_test bridge_topic_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-2.0.11/test/mqtt5_opts.py0000664000175000017500000000026614060132747016337 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-2.0.11/config.h0000664000175000017500000000414014060132747014300 0ustar rogerroger#ifndef CONFIG_H #define CONFIG_H /* ============================================================ * Platform options * ============================================================ */ #ifdef __APPLE__ # define __DARWIN_C_SOURCE #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__SYMBIAN32__) # define _XOPEN_SOURCE 700 # define __BSD_VISIBLE 1 # define HAVE_NETINET_IN_H #elif defined(__QNX__) # define _XOPEN_SOURCE 600 # 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 # ifndef ECONNABORTED # define ECONNABORTED WSAECONNABORTED # endif # ifndef ENOTCONN # define ENOTCONN WSAENOTCONN # endif # ifndef ECONNREFUSED # define ECONNREFUSED WSAECONNREFUSED # endif #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 #ifdef WITH_CJSON # include # define CJSON_VERSION_FULL (CJSON_VERSION_MAJOR*1000000+CJSON_VERSION_MINOR*1000+CJSON_VERSION_PATCH) #endif #endif mosquitto-2.0.11/misc/0000775000175000017500000000000014060132747013616 5ustar rogerrogermosquitto-2.0.11/misc/letsencrypt/0000775000175000017500000000000014060132747016172 5ustar rogerrogermosquitto-2.0.11/misc/letsencrypt/mosquitto-copy.sh0000775000175000017500000000217414060132747021551 0ustar rogerroger#!/bin/sh # This is an example deploy renewal hook for certbot that copies newly updated # certificates to the Mosquitto certificates directory and sets the ownership # and permissions so only the mosquitto user can access them, then signals # Mosquitto to reload certificates. # RENEWED_DOMAINS will match the domains being renewed for that certificate, so # may be just "example.com", or multiple domains "www.example.com example.com" # depending on your certificate. # Place this script in /etc/letsencrypt/renewal-hooks/deploy/ and make it # executable after editing it to your needs. if [ ${RENEWED_DOMAINS} = "my-mosquitto-domain" ]; then # Copy new certificate to Mosquitto directory cp ${RENEWED_LINEAGE}/fullchain.pem /etc/mosquitto/certs/server.pem cp ${RENEWED_LINEAGE}/privkey.pem /etc/mosquitto/certs/server.key # Set ownership to Mosquitto chown mosquitto: /etc/mosquitto/certs/server.pem /etc/mosquitto/certs/server.key # Ensure permissions are restrictive chmod 0600 /etc/mosquitto/certs/server.pem /etc/mosquitto/certs/server.key # Tell Mosquitto to reload certificates and configuration pkill -HUP -x mosquitto fi mosquitto-2.0.11/misc/currentcost/0000775000175000017500000000000014060132747016171 5ustar rogerrogermosquitto-2.0.11/misc/currentcost/cc128_read.pl0000775000175000017500000000071714060132747020351 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-2.0.11/misc/currentcost/gnome-panel/0000775000175000017500000000000014060132747020373 5ustar rogerrogermosquitto-2.0.11/misc/currentcost/gnome-panel/CurrentCostMQTT.server0000664000175000017500000000217614060132747024612 0ustar rogerroger mosquitto-2.0.11/misc/currentcost/gnome-panel/CurrentCostMQTT.py0000775000175000017500000000421114060132747023727 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-2.0.11/misc/currentcost/gnome-panel/currentcost.png0000664000175000017500000001230414060132747023454 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-2.0.11/misc/currentcost/cc128_log_mysql.pl0000775000175000017500000000266614060132747021451 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-2.0.11/misc/currentcost/cc128_parse.pl0000775000175000017500000000244714060132747020552 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-2.0.11/misc/currentcost/cc128_read.py0000775000175000017500000000060714060132747020364 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-2.0.11/apps/0000775000175000017500000000000014060132747013626 5ustar rogerrogermosquitto-2.0.11/apps/CMakeLists.txt0000664000175000017500000000010414060132747016361 0ustar rogerrogeradd_subdirectory(mosquitto_ctrl) add_subdirectory(mosquitto_passwd) mosquitto-2.0.11/apps/mosquitto_passwd/0000775000175000017500000000000014060132747017253 5ustar rogerrogermosquitto-2.0.11/apps/mosquitto_passwd/CMakeLists.txt0000664000175000017500000000115214060132747022012 0ustar rogerrogerinclude_directories(${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/include ${mosquitto_SOURCE_DIR}/lib ${mosquitto_SOURCE_DIR}/src ${OPENSSL_INCLUDE_DIR} ${STDBOOL_H_PATH} ${STDINT_H_PATH}) if (WITH_TLS) add_executable(mosquitto_passwd mosquitto_passwd.c get_password.c get_password.h ../../lib/memory_mosq.c ../../lib/memory_mosq.h ../../src/memory_public.c ../../lib/misc_mosq.c ../../src/password_mosq.c ../../src/password_mosq.h ) target_link_libraries(mosquitto_passwd ${OPENSSL_LIBRARIES}) install(TARGETS mosquitto_passwd RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") endif (WITH_TLS) mosquitto-2.0.11/apps/mosquitto_passwd/get_password.h0000664000175000017500000000144514060132747022131 0ustar rogerroger#ifndef GET_PASSWORD_H #define GET_PASSWORD_H /* 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include void get_password__reset_term(void); int get_password(const char *prompt, const char *verify_prompt, bool quiet, char *password, size_t len); #endif mosquitto-2.0.11/apps/mosquitto_passwd/get_password.c0000664000175000017500000000560614060132747022127 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #ifdef WIN32 # include # include # define snprintf sprintf_s # include # include #else # include # include # include #endif #include "get_password.h" #define MAX_BUFFER_LEN 65500 #define SALT_LEN 12 void get_password__reset_term(void) { #ifndef WIN32 struct termios ts; tcgetattr(0, &ts); ts.c_lflag |= ECHO | ICANON; tcsetattr(0, TCSANOW, &ts); #endif } static 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, (size_t)len); tcgetattr(0, &ts_orig); ts_quiet = ts_orig; ts_quiet.c_lflag &= (unsigned int)(~(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(const char *prompt, const char *verify_prompt, bool quiet, 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("%s", prompt); fflush(stdout); if(gets_quiet(pw1, (int)minLen)){ if(!quiet){ fprintf(stderr, "Error: Empty password.\n"); } return 1; } printf("\n"); if(verify_prompt){ printf("%s", verify_prompt); fflush(stdout); if(gets_quiet(pw2, (int)minLen)){ if(!quiet){ fprintf(stderr, "Error: Empty password.\n"); } return 1; } printf("\n"); if(strcmp(pw1, pw2)){ if(!quiet){ fprintf(stderr, "Error: Passwords do not match.\n"); } return 2; } } strncpy(password, pw1, minLen); return 0; } mosquitto-2.0.11/apps/mosquitto_passwd/mosquitto_passwd.c0000664000175000017500000004073214060132747023052 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include #include #include #include "get_password.h" #include "password_mosq.h" #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 65500 #define SALT_LEN 12 #include "misc_mosq.h" struct cb_helper { const char *line; const char *username; const char *password; int iterations; bool found; }; static enum mosquitto_pwhash_type hashtype = pw_sha512_pbkdf2; #ifdef WIN32 static FILE *mpw_tmpfile(void) { return tmpfile(); } #else static char unsigned 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); iusername)){ /* 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; } static 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) { UNUSED(fptr); UNUSED(line); if(helper){ return output_new_password(ftmp, username, password, helper->iterations); }else{ return output_new_password(ftmp, username, password, PW_DEFAULT_ITERATIONS); } } static 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; UNUSED(fptr); UNUSED(password); if(strcmp(username, helper->username)){ /* If this isn't the matching user, then writing out the exiting line */ fprintf(ftmp, "%s", line); }else{ /* Write out a new line for our matching username */ helper->found = true; rc = output_new_password(ftmp, username, helper->password, helper->iterations); } return rc; } static int update_pwuser(FILE *fptr, FILE *ftmp, const char *username, const char *password, int iterations) { struct cb_helper helper; int rc; memset(&helper, 0, sizeof(helper)); helper.username = username; helper.password = password; helper.iterations = iterations; rc = pwfile_iterate(fptr, ftmp, update_pwuser_cb, &helper); if(helper.found){ return rc; }else{ return output_new_password(ftmp, username, password, iterations); } } static 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; } static 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; } static void handle_sigint(int signal) { get_password__reset_term(); UNUSED(signal); exit(0); } static bool is_username_valid(const char *username) { size_t i; size_t slen; if(username){ slen = strlen(username); if(slen > 65535){ fprintf(stderr, "Error: Username must be less than 65536 characters long.\n"); return false; } for(i=0; i 0.\n"); return 1; } }else if(!strcmp(argv[idx], "-U")){ do_update_file = true; }else{ break; } } if(create_new && delete_user){ fprintf(stderr, "Error: -c and -D cannot be used together.\n"); return 1; } if(create_new && do_update_file){ fprintf(stderr, "Error: -c and -U cannot be used together.\n"); return 1; } if(delete_user && do_update_file){ fprintf(stderr, "Error: -D and -U cannot be used together.\n"); return 1; } if(delete_user && batch_mode){ fprintf(stderr, "Error: -b and -D cannot be used together.\n"); return 1; } if(create_new){ if(batch_mode){ if(idx+2 >= argc){ fprintf(stderr, "Error: -c argument given but password file, username, or password missing.\n"); return 1; }else{ password_file_tmp = argv[idx]; username = argv[idx+1]; password_cmd = argv[idx+2]; } }else{ if(idx+1 >= argc){ fprintf(stderr, "Error: -c argument given but password file or username missing.\n"); return 1; }else{ password_file_tmp = argv[idx]; username = argv[idx+1]; } } }else if(delete_user){ if(idx+1 >= argc){ fprintf(stderr, "Error: -D argument given but password file or username missing.\n"); return 1; }else{ password_file_tmp = argv[idx]; username = argv[idx+1]; } }else if(do_update_file){ if(idx+1 != argc){ fprintf(stderr, "Error: -U argument given but password file missing.\n"); return 1; }else{ password_file_tmp = argv[idx]; } }else if(batch_mode == true && idx+3 == argc){ password_file_tmp = argv[idx]; username = argv[idx+1]; password_cmd = argv[idx+2]; }else if(batch_mode == false && idx+2 == argc){ password_file_tmp = argv[idx]; username = argv[idx+1]; }else{ print_usage(); return 1; } if(!is_username_valid(username)){ 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){ if(batch_mode == false){ rc = get_password("Password: ", "Reenter password: ", false, password, MAX_BUFFER_LEN); if(rc){ free(password_file); return rc; } password_cmd = password; } 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_cmd, iterations); 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((size_t)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, iterations); }else{ rc = get_password("Password: ", "Reenter password: ", false, 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, iterations); } } 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-2.0.11/apps/mosquitto_passwd/Makefile0000664000175000017500000000245514060132747020721 0ustar rogerrogerinclude ../../config.mk .PHONY: all install uninstall clean reallyclean OBJS= mosquitto_passwd.o \ get_password.o \ memory_mosq.o \ memory_public.o \ misc_mosq.o \ password_mosq.o ifeq ($(WITH_TLS),yes) all: mosquitto_passwd else all: endif mosquitto_passwd : ${OBJS} ${CROSS_COMPILE}${CC} ${APP_LDFLAGS} $^ -o $@ $(PASSWD_LDADD) mosquitto_passwd.o : mosquitto_passwd.c ${CROSS_COMPILE}${CC} $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ get_password.o : get_password.c ${CROSS_COMPILE}${CC} $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ memory_mosq.o : ../../lib/memory_mosq.c ${CROSS_COMPILE}${CC} $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ memory_public.o : ../../src/memory_public.c ${CROSS_COMPILE}${CC} $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ misc_mosq.o : ../../lib/misc_mosq.c ../../lib/misc_mosq.h ${CROSS_COMPILE}${CC} $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ password_mosq.o : ../../src/password_mosq.c ../../src/password_mosq.h ${CROSS_COMPILE}${CC} $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ install : all $(INSTALL) -d "${DESTDIR}$(prefix)/bin" $(INSTALL) ${STRIP_OPTS} mosquitto_passwd "${DESTDIR}${prefix}/bin/mosquitto_passwd" uninstall : -rm -f "${DESTDIR}${prefix}/bin/mosquitto_passwd" clean : -rm -f *.o mosquitto_passwd *.gcda *.gcno reallyclean : clean -rm -rf *.orig *.db mosquitto-2.0.11/apps/db_dump/0000775000175000017500000000000014060132747015240 5ustar rogerrogermosquitto-2.0.11/apps/db_dump/stubs.c0000664000175000017500000000440314060132747016545 0ustar rogerroger#include #include #include "misc_mosq.h" #include "mosquitto_broker_internal.h" #include "mosquitto_internal.h" #include "util_mosq.h" #ifndef UNUSED # define UNUSED(A) (void)(A) #endif struct mosquitto *context__init(mosq_sock_t sock) { UNUSED(sock); return NULL; } int db__message_store(const struct mosquitto *source, struct mosquitto_msg_store *stored, uint32_t message_expiry_interval, dbid_t store_id, enum mosquitto_msg_origin origin) { UNUSED(source); UNUSED(stored); UNUSED(message_expiry_interval); UNUSED(store_id); UNUSED(origin); return 0; } void db__msg_store_ref_inc(struct mosquitto_msg_store *store) { UNUSED(store); } int handle__packet(struct mosquitto *context) { UNUSED(context); return 0; } int log__printf(struct mosquitto *mosq, unsigned int level, const char *fmt, ...) { UNUSED(mosq); UNUSED(level); UNUSED(fmt); return 0; } FILE *mosquitto__fopen(const char *path, const char *mode, bool restrict_read) { UNUSED(path); UNUSED(mode); UNUSED(restrict_read); return NULL; } enum mosquitto_client_state mosquitto__get_state(struct mosquitto *mosq) { UNUSED(mosq); return mosq_cs_new; } int mux__add_out(struct mosquitto *mosq) { UNUSED(mosq); return 0; } int mux__remove_out(struct mosquitto *mosq) { UNUSED(mosq); return 0; } ssize_t net__read(struct mosquitto *mosq, void *buf, size_t count) { UNUSED(mosq); UNUSED(buf); UNUSED(count); return 0; } ssize_t net__write(struct mosquitto *mosq, const void *buf, size_t count) { UNUSED(mosq); UNUSED(buf); UNUSED(count); return 0; } int retain__store(const char *topic, struct mosquitto_msg_store *stored, char **split_topics) { UNUSED(topic); UNUSED(stored); UNUSED(split_topics); return 0; } int sub__add(struct mosquitto *context, const char *sub, uint8_t qos, uint32_t identifier, int options, struct mosquitto__subhier **root) { UNUSED(context); UNUSED(sub); UNUSED(qos); UNUSED(identifier); UNUSED(options); UNUSED(root); return 0; } int sub__messages_queue(const char *source_id, const char *topic, uint8_t qos, int retain, struct mosquitto_msg_store **stored) { UNUSED(source_id); UNUSED(topic); UNUSED(qos); UNUSED(retain); UNUSED(stored); return 0; } int keepalive__update(struct mosquitto *context) { UNUSED(context); return 0; } mosquitto-2.0.11/apps/db_dump/db_dump.c0000664000175000017500000002701014060132747017016 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include #include #include #include #include #include #include #include #include #include #include "db_dump.h" #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; uint32_t subscriptions; uint32_t subscription_size; int messages; long message_size; }; struct msg_store_chunk { UT_hash_handle hh; dbid_t store_id; uint32_t length; }; struct mosquitto_db db; 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->topic); free(chunk->payload); mosquitto_property_free_all(&chunk->properties); } static int dump__cfg_chunk_process(FILE *db_fd, uint32_t length) { struct PF_cfg chunk; int rc; cfg_count++; memset(&chunk, 0, sizeof(struct PF_cfg)); if(db_version == 6 || db_version == 5){ rc = persist__chunk_cfg_read_v56(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(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 == 6 || db_version == 5){ rc = persist__chunk_client_read_v56(db_fd, &chunk, db_version); }else{ rc = persist__chunk_client_read_v234(db_fd, &chunk, db_version); } if(rc){ fprintf(stderr, "Error: Corrupt persistent database."); 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(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 == 6 || db_version == 5){ rc = persist__chunk_client_msg_read_v56(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(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 == 6 || db_version == 5){ rc = persist__chunk_msg_store_read_v56(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); mosquitto__free(chunk.payload); 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; } stored = mosquitto__calloc(1, sizeof(struct mosquitto_msg_store)); if(stored == NULL){ mosquitto__free(load); fclose(db_fptr); mosquitto__free(chunk.source.id); mosquitto__free(chunk.source.username); mosquitto__free(chunk.topic); mosquitto__free(chunk.payload); return MOSQ_ERR_NOMEM; } stored->source_mid = chunk.F.source_mid; stored->topic = chunk.topic; stored->qos = chunk.F.qos; stored->retain = chunk.F.retain; stored->payloadlen = chunk.F.payloadlen; stored->payload = chunk.payload; stored->properties = chunk.properties; rc = db__message_store(&chunk.source, stored, message_expiry_interval, 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); }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(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 == 6 || db_version == 5){ rc = persist__chunk_retain_read_v56(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(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 == 6 || db_version == 5){ rc = persist__chunk_sub_read_v56(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; uint32_t length; uint32_t chunk; 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){ fprintf(stderr, "Error: Unable to open %s\n", filename); 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(fd, length)) return 1; break; case DB_CHUNK_MSG_STORE: if(dump__msg_store_chunk_process(fd, length)) return 1; break; case DB_CHUNK_CLIENT_MSG: if(dump__client_msg_chunk_process(fd, length)) return 1; break; case DB_CHUNK_RETAIN: if(dump__retain_chunk_process(fd, length)) return 1; break; case DB_CHUNK_SUB: if(dump__sub_chunk_process(fd, length)) return 1; break; case DB_CHUNK_CLIENT: if(dump__client_chunk_process(fd, length)) return 1; break; default: fprintf(stderr, "Warning: Unsupported chunk \"%d\" in persistent database file. Ignoring.\n", chunk); if(fseek(fd, length, SEEK_CUR) < 0){ fprintf(stderr, "Error seeking in file.\n"); return 1; } 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) fclose(fd); return 1; } mosquitto-2.0.11/apps/db_dump/db_dump.h0000664000175000017500000000161114060132747017022 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include void print__client(struct P_client *chunk, uint32_t length); void print__client_msg(struct P_client_msg *chunk, uint32_t length); void print__msg_store(struct P_msg_store *chunk, uint32_t length); void print__sub(struct P_sub *chunk, uint32_t length); #endif mosquitto-2.0.11/apps/db_dump/Makefile0000664000175000017500000000500114060132747016674 0ustar rogerrogerinclude ../../config.mk CFLAGS_FINAL=${CFLAGS} -I../../include -I../../ -I../../lib -I../../src -I../../deps -DWITH_BROKER -DWITH_PERSISTENCE OBJS = \ db_dump.o \ print.o \ \ memory_mosq.o \ memory_public.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 \ topic_tok.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 ../../src/persist.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ print.o : print.c db_dump.h ../../src/persist.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ memory_mosq.o : ../../lib/memory_mosq.c ../../lib/memory_mosq.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ memory_public.o : ../../src/memory_public.c ${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 : ../../src/persist_read.c ../../src/persist.h ../../src/mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ persist_read_v234.o : ../../src/persist_read_v234.c ../../src/persist.h ../../src/mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(CFLAGS_FINAL) -c $< -o $@ persist_read_v5.o : ../../src/persist_read_v5.c ../../src/persist.h ../../src/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 $@ reallyclean: clean clean : -rm -f *.o mosquitto_db_dump install: uninstall: mosquitto-2.0.11/apps/db_dump/print.c0000664000175000017500000001553514060132747016551 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include #include #include "db_dump.h" #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, uint32_t length) { printf("DB_CHUNK_CLIENT:\n"); printf("\tLength: %d\n", length); printf("\tClient ID: %s\n", chunk->client_id); if(chunk->username){ printf("\tUsername: %s\n", chunk->username); } if(chunk->F.listener_port > 0){ printf("\tListener port: %u\n", chunk->F.listener_port); } 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, uint32_t 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, uint32_t length) { uint8_t *payload; 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); payload = chunk->payload; if(chunk->F.payloadlen < 256){ /* Print payloads with UTF-8 data below an arbitrary limit of 256 bytes */ if(mosquitto_validate_utf8((char *)payload, (uint16_t)chunk->F.payloadlen) == MOSQ_ERR_SUCCESS){ printf("\tPayload: %s\n", payload); } } print__properties(chunk->properties); } void print__sub(struct P_sub *chunk, uint32_t length) { printf("DB_CHUNK_SUB:\n"); printf("\tLength: %u\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-2.0.11/apps/mosquitto_ctrl/0000775000175000017500000000000014060132747016716 5ustar rogerrogermosquitto-2.0.11/apps/mosquitto_ctrl/dynsec_client.c0000664000175000017500000001451414060132747021712 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include #include #include #include #include "mosquitto.h" #include "mosquitto_ctrl.h" #include "get_password.h" #include "password_mosq.h" int dynsec_client__create(int argc, char *argv[], cJSON *j_command) { char *username = NULL, *password = NULL, *clientid = NULL; char prompt[200], verify_prompt[200]; char password_buf[200]; int rc; int i; bool request_password = true; if(argc == 0){ return MOSQ_ERR_INVAL; } username = argv[0]; for(i=1; i 0 && cJSON_AddIntToObject(j_command, "count", count) == NULL) || (offset > 0 && cJSON_AddIntToObject(j_command, "offset", offset) == NULL) ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } mosquitto-2.0.11/apps/mosquitto_ctrl/CMakeLists.txt0000664000175000017500000000252414060132747021461 0ustar rogerrogerif (WITH_TLS AND CJSON_FOUND) add_definitions("-DWITH_CJSON") include_directories(${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/include ${mosquitto_SOURCE_DIR}/lib ${mosquitto_SOURCE_DIR}/src ${OPENSSL_INCLUDE_DIR} ${STDBOOL_H_PATH} ${STDINT_H_PATH} ${CJSON_INCLUDE_DIRS} ${mosquitto_SOURCE_DIR}/apps/mosquitto_passwd) link_directories(${CJSON_DIR}) add_executable(mosquitto_ctrl mosquitto_ctrl.c mosquitto_ctrl.h client.c dynsec.c dynsec_client.c dynsec_group.c dynsec_role.c ../mosquitto_passwd/get_password.c ../mosquitto_passwd/get_password.h ../../lib/memory_mosq.c ../../lib/memory_mosq.h ../../src/memory_public.c options.c ../../src/password_mosq.c ../../src/password_mosq.h ) if (WITH_STATIC_LIBRARIES) target_link_libraries(mosquitto_ctrl libmosquitto_static) else() target_link_libraries(mosquitto_ctrl libmosquitto) endif() if (UNIX) if (APPLE) target_link_libraries(mosquitto_ctrl dl) elseif (${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD") # elseif (${CMAKE_SYSTEM_NAME} MATCHES "NetBSD") # elseif(QNX) # else(APPLE) target_link_libraries(mosquitto_ctrl dl) endif (APPLE) endif (UNIX) target_link_libraries(mosquitto_ctrl ${OPENSSL_LIBRARIES} ${CJSON_LIBRARIES}) install(TARGETS mosquitto_ctrl RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") endif (WITH_TLS AND CJSON_FOUND) mosquitto-2.0.11/apps/mosquitto_ctrl/mosquitto_ctrl.h0000664000175000017500000000776214060132747022173 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef MOSQUITTO_CTRL_H #define MOSQUITTO_CTRL_H #include #include #include "mosquitto.h" #define PORT_UNDEFINED -1 #define PORT_UNIX 0 struct mosq_config { char *id; int protocol_version; int keepalive; char *host; int port; int qos; char *bind_address; bool debug; bool quiet; char *username; char *password; char *options_file; #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 verbose; /* sub */ unsigned int timeout; /* sub */ #ifdef WITH_SOCKS char *socks5_host; int socks5_port; char *socks5_username; char *socks5_password; #endif }; struct mosq_ctrl { struct mosq_config cfg; char *request_topic; char *response_topic; char *payload; void (*payload_callback)(struct mosq_ctrl *, long , const void *); void *userdata; }; typedef int (*FUNC_ctrl_main)(int argc, char *argv[], struct mosq_ctrl *ctrl); void init_config(struct mosq_config *cfg); int ctrl_config_parse(struct mosq_config *cfg, int *argc, char **argv[]); int client_config_load(struct mosq_config *cfg); void client_config_cleanup(struct mosq_config *cfg); int client_request_response(struct mosq_ctrl *ctrl); int client_opts_set(struct mosquitto *mosq, struct mosq_config *cfg); int client_connect(struct mosquitto *mosq, struct mosq_config *cfg); cJSON *cJSON_AddIntToObject(cJSON * const object, const char * const name, int number); void dynsec__print_usage(void); int dynsec__main(int argc, char *argv[], struct mosq_ctrl *ctrl); int dynsec_client__add_remove_role(int argc, char *argv[], cJSON *j_command, const char *command); int dynsec_client__create(int argc, char *argv[], cJSON *j_command); int dynsec_client__delete(int argc, char *argv[], cJSON *j_command); int dynsec_client__enable_disable(int argc, char *argv[], cJSON *j_command, const char *command); int dynsec_client__get(int argc, char *argv[], cJSON *j_command); int dynsec_client__list_all(int argc, char *argv[], cJSON *j_command); int dynsec_client__set_id(int argc, char *argv[], cJSON *j_command); int dynsec_client__set_password(int argc, char *argv[], cJSON *j_command); int dynsec_group__add_remove_client(int argc, char *argv[], cJSON *j_command, const char *command); int dynsec_group__add_remove_role(int argc, char *argv[], cJSON *j_command, const char *command); int dynsec_group__create(int argc, char *argv[], cJSON *j_command); int dynsec_group__delete(int argc, char *argv[], cJSON *j_command); int dynsec_group__get(int argc, char *argv[], cJSON *j_command); int dynsec_group__list_all(int argc, char *argv[], cJSON *j_command); int dynsec_group__set_anonymous(int argc, char *argv[], cJSON *j_command); int dynsec_group__get_anonymous(int argc, char *argv[], cJSON *j_command); int dynsec_role__create(int argc, char *argv[], cJSON *j_command); int dynsec_role__delete(int argc, char *argv[], cJSON *j_command); int dynsec_role__get(int argc, char *argv[], cJSON *j_command); int dynsec_role__list_all(int argc, char *argv[], cJSON *j_command); int dynsec_role__add_acl(int argc, char *argv[], cJSON *j_command); int dynsec_role__remove_acl(int argc, char *argv[], cJSON *j_command); /* Functions to implement as an external module: */ void ctrl_help(void); int ctrl_main(int argc, char *argv[], struct mosq_ctrl *ctrl); #endif mosquitto-2.0.11/apps/mosquitto_ctrl/dynsec.c0000664000175000017500000006626114060132747020362 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include "mosquitto_ctrl.h" #include "mosquitto.h" #include "password_mosq.h" #include "get_password.h" void dynsec__print_usage(void) { printf("\nDynamic Security module\n"); printf("=======================\n"); printf("\nInitialisation\n--------------\n"); printf("Create a new configuration file with an admin user:\n"); printf(" mosquitto_ctrl dynsec init [admin-password]\n"); printf("\nGeneral\n-------\n"); printf("Get ACL default access: getDefaultACLAccess\n"); printf("Set ACL default access: setDefaultACLAccess allow|deny\n"); printf("Get group for anonymous clients: getAnonymousGroup\n"); printf("Set group for anonymous clients: setAnonymousGroup \n"); printf("\nClients\n-------\n"); printf("Create a new client: createClient [-c clientid] [-p password]\n"); printf("Delete a client: deleteClient \n"); printf("Set a client password: setClientPassword [password]\n"); printf("Set a client id: setClientId [clientid]\n"); printf("Add a role to a client: addClientRole [priority]\n"); printf(" Higher priority (larger numerical value) roles are evaluated first.\n"); printf("Remove role from a client: removeClientRole \n"); printf("Get client information: getClient \n"); printf("List all clients: listClients [count [offset]]\n"); printf("Enable client: enableClient \n"); printf("Disable client: disableClient \n"); printf("\nGroups\n------\n"); printf("Create a new group: createGroup \n"); printf("Delete a group: deleteGroup \n"); printf("Add a role to a group: addGroupRole [priority]\n"); printf(" Higher priority (larger numerical value) roles are evaluated first.\n"); printf("Remove role from a group: removeGroupRole \n"); printf("Add client to a group: addGroupClient [priority]\n"); printf(" Priority sets the group priority for the given client only.\n"); printf(" Higher priority (larger numerical value) groups are evaluated first.\n"); printf("Remove client from a group: removeGroupClient \n"); printf("Get group information: getGroup \n"); printf("List all groups: listGroups [count [offset]]\n"); printf("\nRoles\n------\n"); printf("Create a new role: createRole \n"); printf("Delete a role: deleteRole \n"); printf("Add an ACL to a role: addRoleACL [priority]\n"); printf(" Higher priority (larger numerical value) ACLs are evaluated first.\n"); printf("Remove ACL from a role: removeRoleACL \n"); printf("Get role information: getRole \n"); printf("List all roles: listRoles [count [offset]]\n"); printf("\naclspec: allow|deny\n"); printf("acltype: publishClientSend|publishClientReceive\n"); printf(" |subscribeLiteral|subscribePattern\n"); printf(" |unsubscribeLiteral|unsubscribePattern\n"); printf("\nFor more information see:\n"); printf(" https://mosquitto.org/documentation/dynamic-security/\n\n"); } cJSON *cJSON_AddIntToObject(cJSON * const object, const char * const name, int number) { char buf[30]; snprintf(buf, sizeof(buf), "%d", number); return cJSON_AddRawToObject(object, name, buf); } /* ################################################################ * # * # Payload callback * # * ################################################################ */ static void print_list(cJSON *j_response, const char *arrayname, const char *keyname) { cJSON *j_data, *j_array, *j_elem, *j_name; j_data = cJSON_GetObjectItem(j_response, "data"); if(j_data == NULL){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } j_array = cJSON_GetObjectItem(j_data, arrayname); if(j_array == NULL || !cJSON_IsArray(j_array)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } cJSON_ArrayForEach(j_elem, j_array){ if(cJSON_IsObject(j_elem)){ j_name = cJSON_GetObjectItem(j_elem, keyname); if(j_name && cJSON_IsString(j_name)){ printf("%s\n", j_name->valuestring); } }else if(cJSON_IsString(j_elem)){ printf("%s\n", j_elem->valuestring); } } } static void print_roles(cJSON *j_roles, size_t slen) { bool first; cJSON *j_elem, *jtmp; if(j_roles && cJSON_IsArray(j_roles)){ first = true; cJSON_ArrayForEach(j_elem, j_roles){ jtmp = cJSON_GetObjectItem(j_elem, "rolename"); if(jtmp && cJSON_IsString(jtmp)){ if(first){ first = false; printf("%-*s %s", (int)slen, "Roles:", jtmp->valuestring); }else{ printf("%-*s %s", (int)slen, "", jtmp->valuestring); } jtmp = cJSON_GetObjectItem(j_elem, "priority"); if(jtmp && cJSON_IsNumber(jtmp)){ printf(" (priority: %d)", (int)jtmp->valuedouble); }else{ printf(" (priority: -1)"); } printf("\n"); } } }else{ printf("Roles:\n"); } } static void print_client(cJSON *j_response) { cJSON *j_data, *j_client, *j_array, *j_elem, *jtmp; bool first; j_data = cJSON_GetObjectItem(j_response, "data"); if(j_data == NULL || !cJSON_IsObject(j_data)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } j_client = cJSON_GetObjectItem(j_data, "client"); if(j_client == NULL || !cJSON_IsObject(j_client)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } jtmp = cJSON_GetObjectItem(j_client, "username"); if(jtmp == NULL || !cJSON_IsString(jtmp)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } printf("Username: %s\n", jtmp->valuestring); jtmp = cJSON_GetObjectItem(j_client, "clientid"); if(jtmp && cJSON_IsString(jtmp)){ printf("Clientid: %s\n", jtmp->valuestring); }else{ printf("Clientid:\n"); } jtmp = cJSON_GetObjectItem(j_client, "disabled"); if(jtmp && cJSON_IsBool(jtmp)){ printf("Disabled: %s\n", cJSON_IsTrue(jtmp)?"true":"false"); } j_array = cJSON_GetObjectItem(j_client, "roles"); print_roles(j_array, strlen("Username:")); j_array = cJSON_GetObjectItem(j_client, "groups"); if(j_array && cJSON_IsArray(j_array)){ first = true; cJSON_ArrayForEach(j_elem, j_array){ jtmp = cJSON_GetObjectItem(j_elem, "groupname"); if(jtmp && cJSON_IsString(jtmp)){ if(first){ printf("Groups: %s", jtmp->valuestring); first = false; }else{ printf(" %s", jtmp->valuestring); } jtmp = cJSON_GetObjectItem(j_elem, "priority"); if(jtmp && cJSON_IsNumber(jtmp)){ printf(" (priority: %d)", (int)jtmp->valuedouble); }else{ printf(" (priority: -1)"); } printf("\n"); } } }else{ printf("Groups:\n"); } } static void print_group(cJSON *j_response) { cJSON *j_data, *j_group, *j_array, *j_elem, *jtmp; bool first; j_data = cJSON_GetObjectItem(j_response, "data"); if(j_data == NULL || !cJSON_IsObject(j_data)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } j_group = cJSON_GetObjectItem(j_data, "group"); if(j_group == NULL || !cJSON_IsObject(j_group)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } jtmp = cJSON_GetObjectItem(j_group, "groupname"); if(jtmp == NULL || !cJSON_IsString(jtmp)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } printf("Groupname: %s\n", jtmp->valuestring); j_array = cJSON_GetObjectItem(j_group, "roles"); print_roles(j_array, strlen("Groupname:")); j_array = cJSON_GetObjectItem(j_group, "clients"); if(j_array && cJSON_IsArray(j_array)){ first = true; cJSON_ArrayForEach(j_elem, j_array){ jtmp = cJSON_GetObjectItem(j_elem, "username"); if(jtmp && cJSON_IsString(jtmp)){ if(first){ first = false; printf("Clients: %s\n", jtmp->valuestring); }else{ printf(" %s\n", jtmp->valuestring); } } } } } static void print_role(cJSON *j_response) { cJSON *j_data, *j_role, *j_array, *j_elem, *jtmp; bool first; j_data = cJSON_GetObjectItem(j_response, "data"); if(j_data == NULL || !cJSON_IsObject(j_data)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } j_role = cJSON_GetObjectItem(j_data, "role"); if(j_role == NULL || !cJSON_IsObject(j_role)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } jtmp = cJSON_GetObjectItem(j_role, "rolename"); if(jtmp == NULL || !cJSON_IsString(jtmp)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } printf("Rolename: %s\n", jtmp->valuestring); j_array = cJSON_GetObjectItem(j_role, "acls"); if(j_array && cJSON_IsArray(j_array)){ first = true; cJSON_ArrayForEach(j_elem, j_array){ jtmp = cJSON_GetObjectItem(j_elem, "acltype"); if(jtmp && cJSON_IsString(jtmp)){ if(first){ first = false; printf("ACLs: %-20s", jtmp->valuestring); }else{ printf(" %-20s", jtmp->valuestring); } jtmp = cJSON_GetObjectItem(j_elem, "allow"); if(jtmp && cJSON_IsBool(jtmp)){ printf(" : %s", cJSON_IsTrue(jtmp)?"allow":"deny "); } jtmp = cJSON_GetObjectItem(j_elem, "topic"); if(jtmp && cJSON_IsString(jtmp)){ printf(" : %s", jtmp->valuestring); } jtmp = cJSON_GetObjectItem(j_elem, "priority"); if(jtmp && cJSON_IsNumber(jtmp)){ printf(" (priority: %d)", (int)jtmp->valuedouble); }else{ printf(" (priority: -1)"); } printf("\n"); } } } } static void print_anonymous_group(cJSON *j_response) { cJSON *j_data, *j_group, *j_groupname; j_data = cJSON_GetObjectItem(j_response, "data"); if(j_data == NULL || !cJSON_IsObject(j_data)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } j_group = cJSON_GetObjectItem(j_data, "group"); if(j_group == NULL || !cJSON_IsObject(j_group)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } j_groupname = cJSON_GetObjectItem(j_group, "groupname"); if(j_groupname == NULL || !cJSON_IsString(j_groupname)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } printf("%s\n", j_groupname->valuestring); } static void print_default_acl_access(cJSON *j_response) { cJSON *j_data, *j_acls, *j_acl, *j_acltype, *j_allow; j_data = cJSON_GetObjectItem(j_response, "data"); if(j_data == NULL || !cJSON_IsObject(j_data)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } j_acls = cJSON_GetObjectItem(j_data, "acls"); if(j_acls == NULL || !cJSON_IsArray(j_acls)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } cJSON_ArrayForEach(j_acl, j_acls){ j_acltype = cJSON_GetObjectItem(j_acl, "acltype"); j_allow = cJSON_GetObjectItem(j_acl, "allow"); if(j_acltype == NULL || !cJSON_IsString(j_acltype) || j_allow == NULL || !cJSON_IsBool(j_allow) ){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } printf("%-20s : %s\n", j_acltype->valuestring, cJSON_IsTrue(j_allow)?"allow":"deny"); } } static void dynsec__payload_callback(struct mosq_ctrl *ctrl, long payloadlen, const void *payload) { cJSON *tree, *j_responses, *j_response, *j_command, *j_error; UNUSED(ctrl); #if CJSON_VERSION_FULL < 1007013 UNUSED(payloadlen); tree = cJSON_Parse(payload); #else tree = cJSON_ParseWithLength(payload, (size_t)payloadlen); #endif if(tree == NULL){ fprintf(stderr, "Error: Payload not JSON.\n"); return; } j_responses = cJSON_GetObjectItem(tree, "responses"); if(j_responses == NULL || !cJSON_IsArray(j_responses)){ fprintf(stderr, "Error: Payload missing data.\n"); cJSON_Delete(tree); return; } j_response = cJSON_GetArrayItem(j_responses, 0); if(j_response == NULL){ fprintf(stderr, "Error: Payload missing data.\n"); cJSON_Delete(tree); return; } j_command = cJSON_GetObjectItem(j_response, "command"); if(j_command == NULL){ fprintf(stderr, "Error: Payload missing data.\n"); cJSON_Delete(tree); return; } j_error = cJSON_GetObjectItem(j_response, "error"); if(j_error){ fprintf(stderr, "%s: Error: %s\n", j_command->valuestring, j_error->valuestring); }else{ if(!strcasecmp(j_command->valuestring, "listClients")){ print_list(j_response, "clients", "username"); }else if(!strcasecmp(j_command->valuestring, "listGroups")){ print_list(j_response, "groups", "groupname"); }else if(!strcasecmp(j_command->valuestring, "listRoles")){ print_list(j_response, "roles", "rolename"); }else if(!strcasecmp(j_command->valuestring, "getClient")){ print_client(j_response); }else if(!strcasecmp(j_command->valuestring, "getGroup")){ print_group(j_response); }else if(!strcasecmp(j_command->valuestring, "getRole")){ print_role(j_response); }else if(!strcasecmp(j_command->valuestring, "getDefaultACLAccess")){ print_default_acl_access(j_response); }else if(!strcasecmp(j_command->valuestring, "getAnonymousGroup")){ print_anonymous_group(j_response); }else{ /* fprintf(stderr, "%s: Success\n", j_command->valuestring); */ } } cJSON_Delete(tree); } /* ################################################################ * # * # Default ACL access * # * ################################################################ */ static int dynsec__set_default_acl_access(int argc, char *argv[], cJSON *j_command) { char *acltype, *access; cJSON *j_acls, *j_acl; if(argc == 2){ acltype = argv[0]; access = argv[1]; }else{ return MOSQ_ERR_INVAL; } if(strcasecmp(acltype, "publishClientSend") && strcasecmp(acltype, "publishClientReceive") && strcasecmp(acltype, "subscribe") && strcasecmp(acltype, "unsubscribe")){ return MOSQ_ERR_INVAL; } if(strcasecmp(access, "allow") && strcasecmp(access, "deny")){ fprintf(stderr, "Error: access must be \"allow\" or \"deny\".\n"); return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "setDefaultACLAccess") == NULL || (j_acls = cJSON_AddArrayToObject(j_command, "acls")) == NULL ){ return MOSQ_ERR_NOMEM; } j_acl = cJSON_CreateObject(); if(j_acl == NULL){ return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_acls, j_acl); if(cJSON_AddStringToObject(j_acl, "acltype", acltype) == NULL || cJSON_AddStringToObject(j_acl, "access", access) == NULL ){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } static int dynsec__get_default_acl_access(int argc, char *argv[], cJSON *j_command) { UNUSED(argc); UNUSED(argv); if(cJSON_AddStringToObject(j_command, "command", "getDefaultACLAccess") == NULL ){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } /* ################################################################ * # * # Init * # * ################################################################ */ static cJSON *init_add_acl_to_role(cJSON *j_acls, const char *type, const char *topic) { cJSON *j_acl; j_acl = cJSON_CreateObject(); if(j_acl == NULL) return NULL; if(cJSON_AddStringToObject(j_acl, "acltype", type) == NULL || cJSON_AddStringToObject(j_acl, "topic", topic) == NULL || cJSON_AddBoolToObject(j_acl, "allow", true) == NULL ){ cJSON_Delete(j_acl); return NULL; } cJSON_AddItemToArray(j_acls, j_acl); return j_acl; } static cJSON *init_add_role(const char *rolename) { cJSON *j_role, *j_acls; j_role = cJSON_CreateObject(); if(j_role == NULL){ return NULL; } if(cJSON_AddStringToObject(j_role, "rolename", rolename) == NULL){ cJSON_Delete(j_role); return NULL; } j_acls = cJSON_CreateArray(); if(j_acls == NULL){ cJSON_Delete(j_role); return NULL; } cJSON_AddItemToObject(j_role, "acls", j_acls); if(init_add_acl_to_role(j_acls, "publishClientSend", "$CONTROL/dynamic-security/#") == NULL || init_add_acl_to_role(j_acls, "publishClientReceive", "$CONTROL/dynamic-security/#") == NULL || init_add_acl_to_role(j_acls, "subscribePattern", "$CONTROL/dynamic-security/#") == NULL || init_add_acl_to_role(j_acls, "publishClientReceive", "$SYS/#") == NULL || init_add_acl_to_role(j_acls, "subscribePattern", "$SYS/#") == NULL || init_add_acl_to_role(j_acls, "publishClientReceive", "#") == NULL || init_add_acl_to_role(j_acls, "subscribePattern", "#") == NULL || init_add_acl_to_role(j_acls, "unsubscribePattern", "#") == NULL ){ cJSON_Delete(j_role); return NULL; } return j_role; } static cJSON *init_add_client(const char *username, const char *password, const char *rolename) { cJSON *j_client, *j_roles, *j_role; struct mosquitto_pw pw; char *salt64 = NULL, *hash64 = NULL; char buf[10]; memset(&pw, 0, sizeof(pw)); pw.hashtype = pw_sha512_pbkdf2; if(pw__hash(password, &pw, true, PW_DEFAULT_ITERATIONS) != 0){ return NULL; } if(base64__encode(pw.salt, sizeof(pw.salt), &salt64) || base64__encode(pw.password_hash, sizeof(pw.password_hash), &hash64) ){ fprintf(stderr, "dynsec init: Internal error while encoding password.\n"); free(salt64); free(hash64); return NULL; } j_client = cJSON_CreateObject(); if(j_client == NULL){ free(salt64); free(hash64); return NULL; } snprintf(buf, sizeof(buf), "%d", PW_DEFAULT_ITERATIONS); if(cJSON_AddStringToObject(j_client, "username", username) == NULL || cJSON_AddStringToObject(j_client, "textName", "Dynsec admin user") == NULL || cJSON_AddStringToObject(j_client, "password", hash64) == NULL || cJSON_AddStringToObject(j_client, "salt", salt64) == NULL || cJSON_AddRawToObject(j_client, "iterations", buf) == NULL ){ free(salt64); free(hash64); cJSON_Delete(j_client); return NULL; } free(salt64); free(hash64); j_roles = cJSON_CreateArray(); if(j_roles == NULL){ cJSON_Delete(j_client); return NULL; } cJSON_AddItemToObject(j_client, "roles", j_roles); j_role = cJSON_CreateObject(); if(j_role == NULL){ cJSON_Delete(j_client); return NULL; } cJSON_AddItemToArray(j_roles, j_role); if(cJSON_AddStringToObject(j_role, "rolename", rolename) == NULL){ cJSON_Delete(j_client); return NULL; } return j_client; } static cJSON *init_create(const char *username, const char *password, const char *rolename) { cJSON *tree, *j_clients, *j_client, *j_roles, *j_role; cJSON *j_default_access; tree = cJSON_CreateObject(); if(tree == NULL) return NULL; if((j_clients = cJSON_AddArrayToObject(tree, "clients")) == NULL || (j_roles = cJSON_AddArrayToObject(tree, "roles")) == NULL || (j_default_access = cJSON_AddObjectToObject(tree, "defaultACLAccess")) == NULL ){ cJSON_Delete(tree); return NULL; } /* Set default behaviour: * * Client can not publish to the broker by default. * * Broker *CAN* publish to the client by default. * * Client con not subscribe to topics by default. * * Client *CAN* unsubscribe from topics by default. */ if(cJSON_AddBoolToObject(j_default_access, "publishClientSend", false) == NULL || cJSON_AddBoolToObject(j_default_access, "publishClientReceive", true) == NULL || cJSON_AddBoolToObject(j_default_access, "subscribe", false) == NULL || cJSON_AddBoolToObject(j_default_access, "unsubscribe", true) == NULL ){ cJSON_Delete(tree); return NULL; } j_client = init_add_client(username, password, rolename); if(j_client == NULL){ cJSON_Delete(tree); return NULL; } cJSON_AddItemToArray(j_clients, j_client); j_role = init_add_role(rolename); if(j_role == NULL){ cJSON_Delete(tree); return NULL; } cJSON_AddItemToArray(j_roles, j_role); return tree; } /* mosquitto_ctrl dynsec init [role-name] */ static int dynsec_init(int argc, char *argv[]) { char *filename; char *admin_user; char *admin_password; char *json_str; cJSON *tree; FILE *fptr; char prompt[200], verify_prompt[200]; char password[200]; int rc; if(argc < 2){ fprintf(stderr, "dynsec init: Not enough arguments - filename, or admin-user missing.\n"); return MOSQ_ERR_INVAL; } if(argc > 3){ fprintf(stderr, "dynsec init: Too many arguments.\n"); return MOSQ_ERR_INVAL; } filename = argv[0]; admin_user = argv[1]; if(argc == 3){ admin_password = argv[2]; }else{ snprintf(prompt, sizeof(prompt), "New password for %s: ", admin_user); snprintf(verify_prompt, sizeof(verify_prompt), "Reenter password for %s: ", admin_user); rc = get_password(prompt, verify_prompt, false, password, sizeof(password)); if(rc){ mosquitto_lib_cleanup(); return -1; } admin_password = password; } fptr = fopen(filename, "rb"); if(fptr){ fclose(fptr); fprintf(stderr, "dynsec init: '%s' already exists. Remove the file or use a different location..\n", filename); return -1; } tree = init_create(admin_user, admin_password, "admin"); if(tree == NULL){ fprintf(stderr, "dynsec init: Out of memory.\n"); return MOSQ_ERR_NOMEM; } json_str = cJSON_Print(tree); cJSON_Delete(tree); fptr = fopen(filename, "wb"); if(fptr){ fprintf(fptr, "%s", json_str); free(json_str); fclose(fptr); }else{ free(json_str); fprintf(stderr, "dynsec init: Unable to open '%s' for writing.\n", filename); return -1; } printf("The client '%s' has been created in the file '%s'.\n", admin_user, filename); printf("This client is configured to allow you to administer the dynamic security plugin only.\n"); printf("It does not have access to publish messages to normal topics.\n"); printf("You should create your application clients to do that, for example:\n"); printf(" mosquitto_ctrl dynsec createClient \n"); printf(" mosquitto_ctrl dynsec createRole \n"); printf(" mosquitto_ctrl dynsec addRoleACL publishClientSend my/topic [priority]\n"); printf(" mosquitto_ctrl dynsec addClientRole [priority]\n"); printf("See https://mosquitto.org/documentation/dynamic-security/ for details of all commands.\n"); return -1; /* Suppress client connection */ } /* ################################################################ * # * # Main * # * ################################################################ */ int dynsec__main(int argc, char *argv[], struct mosq_ctrl *ctrl) { int rc = -1; cJSON *j_tree; cJSON *j_commands, *j_command; if(!strcasecmp(argv[0], "help")){ dynsec__print_usage(); return -1; }else if(!strcasecmp(argv[0], "init")){ return dynsec_init(argc-1, &argv[1]); } /* The remaining commands need a network connection and JSON command. */ ctrl->payload_callback = dynsec__payload_callback; ctrl->request_topic = strdup("$CONTROL/dynamic-security/v1"); ctrl->response_topic = strdup("$CONTROL/dynamic-security/v1/response"); if(ctrl->request_topic == NULL || ctrl->response_topic == NULL){ return MOSQ_ERR_NOMEM; } j_tree = cJSON_CreateObject(); if(j_tree == NULL) return MOSQ_ERR_NOMEM; j_commands = cJSON_AddArrayToObject(j_tree, "commands"); if(j_commands == NULL){ cJSON_Delete(j_tree); j_tree = NULL; return MOSQ_ERR_NOMEM; } j_command = cJSON_CreateObject(); if(j_command == NULL){ cJSON_Delete(j_tree); j_tree = NULL; return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_commands, j_command); if(!strcasecmp(argv[0], "setDefaultACLAccess")){ rc = dynsec__set_default_acl_access(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "getDefaultACLAccess")){ rc = dynsec__get_default_acl_access(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "createClient")){ rc = dynsec_client__create(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "deleteClient")){ rc = dynsec_client__delete(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "getClient")){ rc = dynsec_client__get(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "listClients")){ rc = dynsec_client__list_all(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "setClientId")){ rc = dynsec_client__set_id(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "setClientPassword")){ rc = dynsec_client__set_password(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "addClientRole")){ rc = dynsec_client__add_remove_role(argc-1, &argv[1], j_command, argv[0]); }else if(!strcasecmp(argv[0], "removeClientRole")){ rc = dynsec_client__add_remove_role(argc-1, &argv[1], j_command, argv[0]); }else if(!strcasecmp(argv[0], "enableClient")){ rc = dynsec_client__enable_disable(argc-1, &argv[1], j_command, argv[0]); }else if(!strcasecmp(argv[0], "disableClient")){ rc = dynsec_client__enable_disable(argc-1, &argv[1], j_command, argv[0]); }else if(!strcasecmp(argv[0], "createGroup")){ rc = dynsec_group__create(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "deleteGroup")){ rc = dynsec_group__delete(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "getGroup")){ rc = dynsec_group__get(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "listGroups")){ rc = dynsec_group__list_all(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "addGroupRole")){ rc = dynsec_group__add_remove_role(argc-1, &argv[1], j_command, argv[0]); }else if(!strcasecmp(argv[0], "removeGroupRole")){ rc = dynsec_group__add_remove_role(argc-1, &argv[1], j_command, argv[0]); }else if(!strcasecmp(argv[0], "addGroupClient")){ rc = dynsec_group__add_remove_client(argc-1, &argv[1], j_command, argv[0]); }else if(!strcasecmp(argv[0], "removeGroupClient")){ rc = dynsec_group__add_remove_client(argc-1, &argv[1], j_command, argv[0]); }else if(!strcasecmp(argv[0], "setAnonymousGroup")){ rc = dynsec_group__set_anonymous(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "getAnonymousGroup")){ rc = dynsec_group__get_anonymous(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "createRole")){ rc = dynsec_role__create(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "deleteRole")){ rc = dynsec_role__delete(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "getRole")){ rc = dynsec_role__get(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "listRoles")){ rc = dynsec_role__list_all(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "addRoleACL")){ rc = dynsec_role__add_acl(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "removeRoleACL")){ rc = dynsec_role__remove_acl(argc-1, &argv[1], j_command); }else{ fprintf(stderr, "Command '%s' not recognised.\n", argv[0]); return MOSQ_ERR_UNKNOWN; } if(rc == MOSQ_ERR_SUCCESS){ ctrl->payload = cJSON_PrintUnformatted(j_tree); cJSON_Delete(j_tree); if(ctrl->payload == NULL){ fprintf(stderr, "Error: Out of memory.\n"); return MOSQ_ERR_NOMEM; } } return rc; } mosquitto-2.0.11/apps/mosquitto_ctrl/mosquitto_ctrl.c0000664000175000017500000000520614060132747022155 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include "lib_load.h" #include "mosquitto.h" #include "mosquitto_ctrl.h" static void print_version(void) { int major, minor, revision; mosquitto_lib_version(&major, &minor, &revision); printf("mosquitto_ctrl version %s running on libmosquitto %d.%d.%d.\n", VERSION, major, minor, revision); } static void print_usage(void) { printf("mosquitto_ctrl is a tool for administering certain Mosquitto features.\n"); print_version(); printf("\nGeneral usage: mosquitto_ctrl \n"); printf("For module specific help use: mosquitto_ctrl help\n"); printf("\nModules available: dynsec\n"); printf("\nFor more information see:\n"); printf(" https://mosquitto.org/man/mosquitto_ctrl-1.html\n\n"); } int main(int argc, char *argv[]) { struct mosq_ctrl ctrl; int rc = MOSQ_ERR_SUCCESS; FUNC_ctrl_main l_ctrl_main = NULL; void *lib = NULL; char lib_name[200]; if(argc == 1){ print_usage(); return 1; } memset(&ctrl, 0, sizeof(ctrl)); init_config(&ctrl.cfg); /* Shift program name out of args */ argc--; argv++; ctrl_config_parse(&ctrl.cfg, &argc, &argv); if(argc < 2){ print_usage(); return 1; } /* In built modules */ if(!strcasecmp(argv[0], "dynsec")){ l_ctrl_main = dynsec__main; }else{ /* Attempt external module */ snprintf(lib_name, sizeof(lib_name), "mosquitto_ctrl_%s.so", argv[0]); lib = LIB_LOAD(lib_name); if(lib){ l_ctrl_main = (FUNC_ctrl_main)LIB_SYM(lib, "ctrl_main"); } } if(l_ctrl_main == NULL){ fprintf(stderr, "Error: Module '%s' not supported.\n", argv[0]); rc = MOSQ_ERR_NOT_SUPPORTED; } if(l_ctrl_main){ rc = l_ctrl_main(argc-1, &argv[1], &ctrl); if(rc < 0){ /* Usage print */ rc = 0; }else if(rc == MOSQ_ERR_SUCCESS){ rc = client_request_response(&ctrl); }else if(rc == MOSQ_ERR_UNKNOWN){ /* Message printed already */ }else{ fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc)); } } client_config_cleanup(&ctrl.cfg); return rc; } mosquitto-2.0.11/apps/mosquitto_ctrl/client.c0000664000175000017500000001022614060132747020341 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include #include #include #include #include #include "mosquitto_ctrl.h" static int run = 1; static void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *properties) { struct mosq_ctrl *ctrl = obj; UNUSED(properties); if(ctrl->payload_callback){ ctrl->payload_callback(ctrl, msg->payloadlen, msg->payload); } mosquitto_disconnect_v5(mosq, 0, NULL); run = 0; } static void on_publish(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { UNUSED(obj); UNUSED(mid); UNUSED(properties); if(reason_code > 127){ fprintf(stderr, "Publish error: %s\n", mosquitto_reason_string(reason_code)); run = 0; mosquitto_disconnect_v5(mosq, 0, NULL); } } static void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos, const mosquitto_property *properties) { struct mosq_ctrl *ctrl = obj; UNUSED(mid); UNUSED(properties); if(qos_count == 1){ if(granted_qos[0] < 128){ /* Success */ mosquitto_publish(mosq, NULL, ctrl->request_topic, (int)strlen(ctrl->payload), ctrl->payload, ctrl->cfg.qos, 0); free(ctrl->request_topic); ctrl->request_topic = NULL; free(ctrl->payload); ctrl->payload = NULL; }else{ if(ctrl->cfg.protocol_version == MQTT_PROTOCOL_V5){ fprintf(stderr, "Subscribe error: %s\n", mosquitto_reason_string(granted_qos[0])); }else{ fprintf(stderr, "Subscribe error: Subscription refused.\n"); } run = 0; mosquitto_disconnect_v5(mosq, 0, NULL); } }else{ run = 0; mosquitto_disconnect_v5(mosq, 0, NULL); } } static void on_connect(struct mosquitto *mosq, void *obj, int reason_code, int flags, const mosquitto_property *properties) { struct mosq_ctrl *ctrl = obj; UNUSED(flags); UNUSED(properties); if(reason_code == 0){ if(ctrl->response_topic){ mosquitto_subscribe(mosq, NULL, ctrl->response_topic, ctrl->cfg.qos); free(ctrl->response_topic); ctrl->response_topic = NULL; } }else{ if(ctrl->cfg.protocol_version == MQTT_PROTOCOL_V5){ if(reason_code == MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION){ fprintf(stderr, "Connection error: %s. Try connecting to an MQTT v5 broker, or use MQTT v3.x mode.\n", mosquitto_reason_string(reason_code)); }else{ fprintf(stderr, "Connection error: %s\n", mosquitto_reason_string(reason_code)); } }else{ fprintf(stderr, "Connection error: %s\n", mosquitto_connack_string(reason_code)); } run = 0; mosquitto_disconnect_v5(mosq, 0, NULL); } } int client_request_response(struct mosq_ctrl *ctrl) { struct mosquitto *mosq; int rc; time_t start; if(ctrl->cfg.cafile == NULL && ctrl->cfg.capath == NULL){ fprintf(stderr, "Warning: You are running mosquitto_ctrl without encryption.\nThis means all of the configuration changes you are making are visible on the network, including passwords.\n\n"); } mosquitto_lib_init(); mosq = mosquitto_new(ctrl->cfg.id, true, ctrl); rc = client_opts_set(mosq, &ctrl->cfg); if(rc) goto cleanup; mosquitto_connect_v5_callback_set(mosq, on_connect); mosquitto_subscribe_v5_callback_set(mosq, on_subscribe); mosquitto_publish_v5_callback_set(mosq, on_publish); mosquitto_message_v5_callback_set(mosq, on_message); rc = client_connect(mosq, &ctrl->cfg); if(rc) goto cleanup; start = time(NULL); while(run && start+10 > time(NULL)){ mosquitto_loop(mosq, -1, 1); } cleanup: mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return rc; } mosquitto-2.0.11/apps/mosquitto_ctrl/options.c0000664000175000017500000005431114060132747020561 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause 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 "mosquitto_ctrl.h" #include "get_password.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 *argc, char **argvp[]); void init_config(struct mosq_config *cfg) { cfg->qos = 1; cfg->port = PORT_UNDEFINED; cfg->protocol_version = MQTT_PROTOCOL_V5; } void client_config_cleanup(struct mosq_config *cfg) { free(cfg->id); free(cfg->host); free(cfg->bind_address); free(cfg->username); free(cfg->password); free(cfg->options_file); #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 #ifdef WITH_SOCKS free(cfg->socks5_host); free(cfg->socks5_username); free(cfg->socks5_password); #endif } int ctrl_config_parse(struct mosq_config *cfg, int *argc, char **argv[]) { int rc; init_config(cfg); rc = client_config_load(cfg); if(rc) return rc; /* Deal with real argc/argv */ rc = client_config_line_proc(cfg, argc, argv); if(rc) return rc; #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->host){ cfg->host = strdup("localhost"); if(!cfg->host){ fprintf(stderr, "Error: Out of memory.\n"); return 1; } } return MOSQ_ERR_SUCCESS; } /* Process a tokenised single line from a file or set of real argc/argv */ static int client_config_line_proc(struct mosq_config *cfg, int *argc, char **argvp[]) { char **argv = *argvp; while((*argc) && argv[0][0] == '-'){ if(!strcmp(argv[0], "-A")){ if((*argc) == 1){ fprintf(stderr, "Error: -A argument given but no address specified.\n\n"); return 1; }else{ cfg->bind_address = strdup(argv[1]); } argv++; (*argc)--; #ifdef WITH_TLS }else if(!strcmp(argv[0], "--cafile")){ if((*argc) == 1){ fprintf(stderr, "Error: --cafile argument given but no file specified.\n\n"); return 1; }else{ cfg->cafile = strdup(argv[1]); } argv++; (*argc)--; }else if(!strcmp(argv[0], "--capath")){ if((*argc) == 1){ fprintf(stderr, "Error: --capath argument given but no directory specified.\n\n"); return 1; }else{ cfg->capath = strdup(argv[1]); } argv++; (*argc)--; }else if(!strcmp(argv[0], "--cert")){ if((*argc) == 1){ fprintf(stderr, "Error: --cert argument given but no file specified.\n\n"); return 1; }else{ cfg->certfile = strdup(argv[1]); } argv++; (*argc)--; }else if(!strcmp(argv[0], "--ciphers")){ if((*argc) == 1){ fprintf(stderr, "Error: --ciphers argument given but no ciphers specified.\n\n"); return 1; }else{ cfg->ciphers = strdup(argv[1]); } argv++; (*argc)--; #endif }else if(!strcmp(argv[0], "-d") || !strcmp(argv[0], "--debug")){ cfg->debug = true; }else if(!strcmp(argv[0], "--help")){ return 2; }else if(!strcmp(argv[0], "-h") || !strcmp(argv[0], "--host")){ if((*argc) == 1){ fprintf(stderr, "Error: -h argument given but no host specified.\n\n"); return 1; }else{ cfg->host = strdup(argv[1]); } argv++; (*argc)--; #ifdef WITH_TLS }else if(!strcmp(argv[0], "--insecure")){ cfg->insecure = true; #endif }else if(!strcmp(argv[0], "-i") || !strcmp(argv[0], "--id")){ if((*argc) == 1){ fprintf(stderr, "Error: -i argument given but no id specified.\n\n"); return 1; }else{ cfg->id = strdup(argv[1]); } argv++; (*argc)--; #ifdef WITH_TLS }else if(!strcmp(argv[0], "--key")){ if((*argc) == 1){ fprintf(stderr, "Error: --key argument given but no file specified.\n\n"); return 1; }else{ cfg->keyfile = strdup(argv[1]); } argv++; (*argc)--; }else if(!strcmp(argv[0], "--keyform")){ if((*argc) == 1){ fprintf(stderr, "Error: --keyform argument given but no keyform specified.\n\n"); return 1; }else{ cfg->keyform = strdup(argv[1]); } argv++; (*argc)--; #endif }else if(!strcmp(argv[0], "-L") || !strcmp(argv[0], "--url")){ if((*argc) == 1){ fprintf(stderr, "Error: -L argument given but no URL specified.\n\n"); return 1; } else { char *url = argv[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; 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); } argv++; (*argc)--; }else if(!strcmp(argv[0], "-o")){ if((*argc) == 1){ fprintf(stderr, "Error: -o argument given but no options file specified.\n\n"); return 1; }else{ cfg->options_file = strdup(argv[1]); } argv++; (*argc)--; }else if(!strcmp(argv[0], "-p") || !strcmp(argv[0], "--port")){ if((*argc) == 1){ fprintf(stderr, "Error: -p argument given but no port specified.\n\n"); return 1; }else{ cfg->port = atoi(argv[1]); if(cfg->port<0 || cfg->port>65535){ fprintf(stderr, "Error: Invalid port given: %d\n", cfg->port); return 1; } } argv++; (*argc)--; }else if(!strcmp(argv[0], "-P") || !strcmp(argv[0], "--pw")){ if((*argc) == 1){ fprintf(stderr, "Error: -P argument given but no password specified.\n\n"); return 1; }else{ cfg->password = strdup(argv[1]); } argv++; (*argc)--; #ifdef WITH_SOCKS }else if(!strcmp(argv[0], "--proxy")){ if((*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[1])){ return 1; } } argv++; (*argc)--; #endif #ifdef FINAL_WITH_TLS_PSK }else if(!strcmp(argv[0], "--psk")){ if((*argc) == 1){ fprintf(stderr, "Error: --psk argument given but no key specified.\n\n"); return 1; }else{ cfg->psk = strdup(argv[1]); } argv++; (*argc)--; }else if(!strcmp(argv[0], "--psk-identity")){ if((*argc) == 1){ fprintf(stderr, "Error: --psk-identity argument given but no identity specified.\n\n"); return 1; }else{ cfg->psk_identity = strdup(argv[1]); } argv++; (*argc)--; #endif }else if(!strcmp(argv[0], "-q") || !strcmp(argv[0], "--qos")){ if((*argc) == 1){ fprintf(stderr, "Error: -q argument given but no QoS specified.\n\n"); return 1; }else{ cfg->qos = atoi(argv[1]); if(cfg->qos<0 || cfg->qos>2){ fprintf(stderr, "Error: Invalid QoS given: %d\n", cfg->qos); return 1; } } argv++; (*argc)--; }else if(!strcmp(argv[0], "--quiet")){ cfg->quiet = true; #ifdef WITH_TLS }else if(!strcmp(argv[0], "--tls-alpn")){ if((*argc) == 1){ fprintf(stderr, "Error: --tls-alpn argument given but no protocol specified.\n\n"); return 1; }else{ cfg->tls_alpn = strdup(argv[1]); } argv++; (*argc)--; }else if(!strcmp(argv[0], "--tls-engine")){ if((*argc) == 1){ fprintf(stderr, "Error: --tls-engine argument given but no engine_id specified.\n\n"); return 1; }else{ cfg->tls_engine = strdup(argv[1]); } argv++; (*argc)--; }else if(!strcmp(argv[0], "--tls-engine-kpass-sha1")){ if((*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[1]); } argv++; (*argc)--; }else if(!strcmp(argv[0], "--tls-version")){ if((*argc) == 1){ fprintf(stderr, "Error: --tls-version argument given but no version specified.\n\n"); return 1; }else{ cfg->tls_version = strdup(argv[1]); } argv++; (*argc)--; #endif }else if(!strcmp(argv[0], "-u") || !strcmp(argv[0], "--username")){ if((*argc) == 1){ fprintf(stderr, "Error: -u argument given but no username specified.\n\n"); return 1; }else{ cfg->username = strdup(argv[1]); } argv++; (*argc)--; }else if(!strcmp(argv[0], "--unix")){ if((*argc) == 1){ fprintf(stderr, "Error: --unix argument given but no socket path specified.\n\n"); return 1; }else{ cfg->host = strdup(argv[1]); cfg->port = 0; } argv++; (*argc)--; }else if(!strcmp(argv[0], "-V") || !strcmp(argv[0], "--protocol-version")){ if((*argc) == 1){ fprintf(stderr, "Error: --protocol-version argument given but no version specified.\n\n"); return 1; }else{ if(!strcmp(argv[1], "mqttv31") || !strcmp(argv[1], "31")){ cfg->protocol_version = MQTT_PROTOCOL_V31; }else if(!strcmp(argv[1], "mqttv311") || !strcmp(argv[1], "311")){ cfg->protocol_version = MQTT_PROTOCOL_V311; }else if(!strcmp(argv[1], "mqttv5") || !strcmp(argv[1], "5")){ cfg->protocol_version = MQTT_PROTOCOL_V5; }else{ fprintf(stderr, "Error: Invalid protocol version argument given.\n\n"); return 1; } } argv++; (*argc)--; }else if(!strcmp(argv[0], "-v") || !strcmp(argv[0], "--verbose")){ cfg->verbose = 1; }else if(!strcmp(argv[0], "--version")){ return 3; }else{ goto unknown_option; } argv++; (*argc)--; } *argvp = argv; return MOSQ_ERR_SUCCESS; unknown_option: fprintf(stderr, "Error: Unknown option '%s'.\n",argv[0]); return 1; } static char *get_default_cfg_location(void) { char *loc = NULL; size_t len; #ifndef WIN32 char *env; #else char env[1024]; int rc; #endif #ifndef WIN32 env = getenv("XDG_CONFIG_HOME"); if(env){ len = strlen(env) + strlen("/mosquitto_ctrl") + 1; loc = malloc(len); if(!loc){ fprintf(stderr, "Error: Out of memory.\n"); return NULL; } snprintf(loc, len, "%s/mosquitto_ctrl", env); loc[len-1] = '\0'; }else{ env = getenv("HOME"); if(env){ len = strlen(env) + strlen("/.config/mosquitto_ctrl") + 1; loc = malloc(len); if(!loc){ fprintf(stderr, "Error: Out of memory.\n"); return NULL; } snprintf(loc, len, "%s/.config/mosquitto_ctrl", env); loc[len-1] = '\0'; } } #else rc = GetEnvironmentVariable("USERPROFILE", env, 1024); if(rc > 0 && rc < 1024){ len = strlen(env) + strlen("\\mosquitto_ctrl.conf") + 1; loc = malloc(len); if(!loc){ fprintf(stderr, "Error: Out of memory.\n"); return NULL; } snprintf(loc, len, "%s\\mosquitto_ctrl.conf", env); loc[len-1] = '\0'; } #endif return loc; } int client_config_load(struct mosq_config *cfg) { int rc; FILE *fptr = NULL; char line[1024]; int count; char **local_args, **args; char *default_cfg; if(cfg->options_file){ fptr = fopen(cfg->options_file, "rt"); }else{ default_cfg = get_default_cfg_location(); if(default_cfg){ fptr = fopen(default_cfg, "rt"); free(default_cfg); } } if(fptr){ local_args = malloc(3*sizeof(char *)); if(local_args == NULL){ fprintf(stderr, "Error: Out of memory.\n"); fclose(fptr); return 1; } 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; } local_args[0] = strtok(line, " "); if(local_args[0]){ local_args[1] = strtok(NULL, " "); if(local_args[1]){ count = 2; }else{ count = 1; } args = local_args; rc = client_config_line_proc(cfg, &count, &args); if(rc){ fclose(fptr); free(local_args); return rc; } } } fclose(fptr); free(local_args); } return 0; } int client_opts_set(struct mosquitto *mosq, struct mosq_config *cfg) { int rc; char prompt[1000]; char password[1000]; mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, cfg->protocol_version); if(cfg->username && cfg->password == NULL){ /* Ask for password */ snprintf(prompt, sizeof(prompt), "Password for %s: ", cfg->username); rc = get_password(prompt, NULL, false, password, sizeof(password)); if(rc){ fprintf(stderr, "Error getting password.\n"); mosquitto_lib_cleanup(); return 1; } cfg->password = strdup(password); if(cfg->password == NULL){ fprintf(stderr, "Error: Out of memory.\n"); mosquitto_lib_cleanup(); return 1; } } if((cfg->username || cfg->password) && mosquitto_username_pw_set(mosq, cfg->username, cfg->password)){ fprintf(stderr, "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){ fprintf(stderr, "Error: Problem setting TLS options: File not found.\n"); }else{ fprintf(stderr, "Error: Problem setting TLS options: %s.\n", mosquitto_strerror(rc)); } mosquitto_lib_cleanup(); return 1; } } if(cfg->insecure && mosquitto_tls_insecure_set(mosq, true)){ fprintf(stderr, "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)){ fprintf(stderr, "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)){ fprintf(stderr, "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)){ fprintf(stderr, "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)){ fprintf(stderr, "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)){ fprintf(stderr, "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)){ fprintf(stderr, "Error: Problem setting TLS options, check the options are valid.\n"); mosquitto_lib_cleanup(); return 1; } #endif #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_connect(struct mosquitto *mosq, struct mosq_config *cfg) { #ifndef WIN32 char *err; #else char err[1024]; #endif int rc; int port; if(cfg->port == PORT_UNDEFINED){ #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; } rc = mosquitto_connect_bind_v5(mosq, cfg->host, port, 60, cfg->bind_address, NULL); 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 fprintf(stderr, "Error: %s\n", err); }else{ fprintf(stderr, "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; size_t 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){ fprintf(stderr, "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){ fprintf(stderr, "Error: Out of memory.\n"); goto cleanup; } memcpy(port, &(str[start]), len); port[len] = '\0'; }else{ host = malloc(len + 1); if(!host){ fprintf(stderr, "Error: Out of memory.\n"); goto cleanup; } memcpy(host, &(str[start]), len); host[len] = '\0'; } } if(!host){ fprintf(stderr, "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){ fprintf(stderr, "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 mosquitto-2.0.11/apps/mosquitto_ctrl/dynsec_role.c0000664000175000017500000001123714060132747021374 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include "mosquitto.h" #include "mosquitto_ctrl.h" #include "password_mosq.h" int dynsec_role__create(int argc, char *argv[], cJSON *j_command) { char *rolename = NULL; if(argc == 1){ rolename = argv[0]; }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "createRole") == NULL || cJSON_AddStringToObject(j_command, "rolename", rolename) == NULL ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_role__delete(int argc, char *argv[], cJSON *j_command) { char *rolename = NULL; if(argc == 1){ rolename = argv[0]; }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "deleteRole") == NULL || cJSON_AddStringToObject(j_command, "rolename", rolename) == NULL ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_role__get(int argc, char *argv[], cJSON *j_command) { char *rolename = NULL; if(argc == 1){ rolename = argv[0]; }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "getRole") == NULL || cJSON_AddStringToObject(j_command, "rolename", rolename) == NULL ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_role__list_all(int argc, char *argv[], cJSON *j_command) { int count = -1, offset = -1; if(argc == 0){ /* All roles */ }else if(argc == 1){ count = atoi(argv[0]); }else if(argc == 2){ count = atoi(argv[0]); offset = atoi(argv[1]); }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "listRoles") == NULL || (count > 0 && cJSON_AddIntToObject(j_command, "count", count) == NULL) || (offset > 0 && cJSON_AddIntToObject(j_command, "offset", offset) == NULL) ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_role__add_acl(int argc, char *argv[], cJSON *j_command) { char *rolename, *acltype, *topic, *action; bool allow; int priority = -1; if(argc == 5){ rolename = argv[0]; acltype = argv[1]; topic = argv[2]; action = argv[3]; priority = atoi(argv[4]); }else if(argc == 4){ rolename = argv[0]; acltype = argv[1]; topic = argv[2]; action = argv[3]; }else{ return MOSQ_ERR_INVAL; } if(strcasecmp(acltype, "publishClientSend") && strcasecmp(acltype, "publishClientReceive") && strcasecmp(acltype, "subscribeLiteral") && strcasecmp(acltype, "subscribePattern") && strcasecmp(acltype, "unsubscribeLiteral") && strcasecmp(acltype, "unsubscribePattern")){ return MOSQ_ERR_INVAL; } if(!strcasecmp(action, "allow")){ allow = true; }else if(!strcasecmp(action, "deny")){ allow = false; }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "addRoleACL") == NULL || cJSON_AddStringToObject(j_command, "rolename", rolename) == NULL || cJSON_AddStringToObject(j_command, "acltype", acltype) == NULL || cJSON_AddStringToObject(j_command, "topic", topic) == NULL || cJSON_AddBoolToObject(j_command, "allow", allow) == NULL || (priority != -1 && cJSON_AddIntToObject(j_command, "priority", priority) == NULL) ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_role__remove_acl(int argc, char *argv[], cJSON *j_command) { char *rolename, *acltype, *topic; if(argc == 3){ rolename = argv[0]; acltype = argv[1]; topic = argv[2]; }else{ return MOSQ_ERR_INVAL; } if(strcasecmp(acltype, "publishClientSend") && strcasecmp(acltype, "publishClientReceive") && strcasecmp(acltype, "subscribeLiteral") && strcasecmp(acltype, "subscribePattern") && strcasecmp(acltype, "unsubscribeLiteral") && strcasecmp(acltype, "unsubscribePattern")){ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "removeRoleACL") == NULL || cJSON_AddStringToObject(j_command, "rolename", rolename) == NULL || cJSON_AddStringToObject(j_command, "acltype", acltype) == NULL || cJSON_AddStringToObject(j_command, "topic", topic) == NULL ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } mosquitto-2.0.11/apps/mosquitto_ctrl/dynsec_group.c0000664000175000017500000001102514060132747021562 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include "mosquitto.h" #include "mosquitto_ctrl.h" #include "password_mosq.h" int dynsec_group__create(int argc, char *argv[], cJSON *j_command) { char *groupname = NULL; if(argc == 1){ groupname = argv[0]; }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "createGroup") == NULL || cJSON_AddStringToObject(j_command, "groupname", groupname) == NULL ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_group__delete(int argc, char *argv[], cJSON *j_command) { char *groupname = NULL; if(argc == 1){ groupname = argv[0]; }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "deleteGroup") == NULL || cJSON_AddStringToObject(j_command, "groupname", groupname) == NULL ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_group__get_anonymous(int argc, char *argv[], cJSON *j_command) { UNUSED(argc); UNUSED(argv); if(cJSON_AddStringToObject(j_command, "command", "getAnonymousGroup") == NULL ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_group__set_anonymous(int argc, char *argv[], cJSON *j_command) { char *groupname = NULL; if(argc == 1){ groupname = argv[0]; }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "setAnonymousGroup") == NULL || cJSON_AddStringToObject(j_command, "groupname", groupname) == NULL ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_group__get(int argc, char *argv[], cJSON *j_command) { char *groupname = NULL; if(argc == 1){ groupname = argv[0]; }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "getGroup") == NULL || cJSON_AddStringToObject(j_command, "groupname", groupname) == NULL ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_group__add_remove_role(int argc, char *argv[], cJSON *j_command, const char *command) { char *groupname = NULL, *rolename = NULL; int priority = -1; if(argc == 2){ groupname = argv[0]; rolename = argv[1]; }else if(argc == 3){ groupname = argv[0]; rolename = argv[1]; priority = atoi(argv[2]); }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", command) == NULL || cJSON_AddStringToObject(j_command, "groupname", groupname) == NULL || cJSON_AddStringToObject(j_command, "rolename", rolename) == NULL || (priority != -1 && cJSON_AddIntToObject(j_command, "priority", priority) == NULL) ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_group__list_all(int argc, char *argv[], cJSON *j_command) { int count = -1, offset = -1; if(argc == 0){ /* All groups */ }else if(argc == 1){ count = atoi(argv[0]); }else if(argc == 2){ count = atoi(argv[0]); offset = atoi(argv[1]); }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", "listGroups") == NULL || (count > 0 && cJSON_AddIntToObject(j_command, "count", count) == NULL) || (offset > 0 && cJSON_AddIntToObject(j_command, "offset", offset) == NULL) ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } int dynsec_group__add_remove_client(int argc, char *argv[], cJSON *j_command, const char *command) { char *username, *groupname; int priority = -1; if(argc == 2){ groupname = argv[0]; username = argv[1]; }else if(argc == 3){ groupname = argv[0]; username = argv[1]; priority = atoi(argv[2]); }else{ return MOSQ_ERR_INVAL; } if(cJSON_AddStringToObject(j_command, "command", command) == NULL || cJSON_AddStringToObject(j_command, "username", username) == NULL || cJSON_AddStringToObject(j_command, "groupname", groupname) == NULL || (priority != -1 && cJSON_AddIntToObject(j_command, "priority", priority) == NULL) ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } mosquitto-2.0.11/apps/mosquitto_ctrl/example.c0000664000175000017500000000202214060132747020511 0ustar rogerroger/* Copyright (c) 2020 Roger Light All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include #include #include #include #include "mosquitto_ctrl.h" void ctrl_help(void) { printf("\nExample module\n"); printf("==============\n"); printf(" mosquitto_ctrl example help\n"); } int ctrl_main(int argc, char *argv[], struct mosq_ctrl *ctrl) { UNUSED(argc); UNUSED(ctrl); if(!strcasecmp(argv[0], "help")){ ctrl_help(); return -1; }else{ return MOSQ_ERR_INVAL; } } mosquitto-2.0.11/apps/mosquitto_ctrl/Makefile0000664000175000017500000000615014060132747020360 0ustar rogerrogerinclude ../../config.mk .PHONY: all install uninstall clean reallyclean ifeq ($(WITH_SHARED_LIBRARIES),yes) LIBMOSQ:=../../lib/libmosquitto.so.${SOVERSION} else ifeq ($(WITH_THREADING),yes) LIBMOSQ:=../../lib/libmosquitto.a -lpthread -lssl -lcrypto else LIBMOSQ:=../../lib/libmosquitto.a endif endif LOCAL_CPPFLAGS:=-I../mosquitto_passwd -DWITH_CJSON OBJS= mosquitto_ctrl.o \ client.o \ dynsec.o \ dynsec_client.o \ dynsec_group.o \ dynsec_role.o \ get_password.o \ memory_mosq.o \ memory_public.o \ options.o \ password_mosq.o EXAMPLE_OBJS= example.o ifeq ($(WITH_TLS),yes) ifeq ($(WITH_CJSON),yes) TARGET:=mosquitto_ctrl mosquitto_ctrl_example.so else TARGET:= endif else TARGET:= endif all : ${TARGET} mosquitto_ctrl : ${OBJS} ${LIBMOSQ} ${CROSS_COMPILE}${CC} ${APP_LDFLAGS} $^ -o $@ $(PASSWD_LDADD) $(LOCAL_LDFLAGS) $(LIBMOSQ) -lcjson -ldl mosquitto_ctrl_example.so : ${EXAMPLE_OBJS} $(CROSS_COMPILE)$(CC) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) $(PLUGIN_LDFLAGS) -shared $< -o $@ mosquitto_ctrl.o : mosquitto_ctrl.c mosquitto_ctrl.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ client.o : client.c mosquitto_ctrl.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ dynsec.o : dynsec.c mosquitto_ctrl.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ dynsec_client.o : dynsec_client.c mosquitto_ctrl.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ dynsec_group.o : dynsec_group.c mosquitto_ctrl.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ dynsec_role.o : dynsec_role.c mosquitto_ctrl.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ example.o : example.c mosquitto_ctrl.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(PLUGIN_CPPFLAGS) $(PLUGIN_CFLAGS) -c $< -o $@ get_password.o : ../mosquitto_passwd/get_password.c ../mosquitto_passwd/get_password.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ memory_mosq.o : ../../lib/memory_mosq.c ${CROSS_COMPILE}${CC} $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ memory_public.o : ../../src/memory_public.c ${CROSS_COMPILE}${CC} $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ options.o : options.c mosquitto_ctrl.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ misc_mosq.o : ../../lib/misc_mosq.c ../../lib/misc_mosq.h ${CROSS_COMPILE}${CC} $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ password_mosq.o : ../../src/password_mosq.c ../../src/password_mosq.h ${CROSS_COMPILE}${CC} $(APP_CPPFLAGS) $(APP_CFLAGS) -c $< -o $@ ../../lib/libmosquitto.so.${SOVERSION} : $(MAKE) -C ../../lib ../../lib/libmosquitto.a : $(MAKE) -C ../../lib libmosquitto.a install : all ifeq ($(WITH_TLS),yes) ifeq ($(WITH_CJSON),yes) $(INSTALL) -d "${DESTDIR}$(prefix)/bin" $(INSTALL) ${STRIP_OPTS} mosquitto_ctrl "${DESTDIR}${prefix}/bin/mosquitto_ctrl" endif endif uninstall : -rm -f "${DESTDIR}${prefix}/bin/mosquitto_ctrl" clean : -rm -f *.o mosquitto_ctrl *.gcda *.gcno *.so reallyclean : clean -rm -rf *.orig *.db mosquitto-2.0.11/apps/Makefile0000664000175000017500000000113114060132747015262 0ustar rogerrogerDIRS= \ db_dump \ mosquitto_ctrl \ mosquitto_passwd .PHONY : all binary check clean reallyclean test install uninstall all : set -e; for d in ${DIRS}; do $(MAKE) -C $${d}; done binary : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done clean : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done reallyclean : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done check : test test : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done install : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done uninstall : set -e; for d in ${DIRS}; do $(MAKE) -C $${d} $@; done mosquitto-2.0.11/README-letsencrypt.md0000664000175000017500000000165314060132747016521 0ustar rogerroger# Using Lets Encrypt with Mosquitto On Unix like operating systems, Mosquitto will attempt to drop root access as soon as it has loaded its configuration file, but before it has activated any of that configuration. This means that if you are using Lets Encrypt TLS certificates, it will be unable to access the certificates and private keys typically located in /etc/letsencrypt/live/ To help with this problem there is an example `deploy` renewal hook script in `misc/letsencrypt/mosquitto-copy.sh` which shows how the certificate and private key for a mosquitto broker can be copied to /etc/mosquitto/certs/ and given the correct ownership and permissions so the broker can access them, but no other user can. It then signals Mosquitto to reload the certificates. Use of this script allows you to happily use Lets Encrypt certificates with Mosquitto without needing root access for Mosquitto, and without having to restart Mosquitto. mosquitto-2.0.11/epl-v200000664000175000017500000003356614060132747014010 0ustar rogerrogerEclipse Public License - v 2.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 content 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 changes or additions to the Program that are not Modified Works. "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 or any Secondary License (as applicable), including Contributors. "Derivative Works" shall mean any work, whether in Source Code or other form, that is based on (or derived from) the Program and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. "Modified Works" shall mean any work in Source Code or other form that results from an addition to, deletion from, or modification of the contents of the Program, including, for purposes of clarity any new file in Source Code form that contains any contents of the Program. Modified Works shall not include works that contain only declarations, interfaces, types, classes, structures, or files of the Program solely in each case in order to link to, bind by name, or subclass the Program or Modified Works thereof. "Distribute" means the acts of a) distributing or b) making available in any manner that enables the transfer of a copy. "Source Code" means the form of a Program preferred for making modifications, including but not limited to software source code, documentation source, and configuration files. "Secondary License" means either the GNU General Public License, Version 2.0, or any later versions of that license, including any exceptions or additional permissions as identified by the initial Contributor. 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. 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 or other 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. e) Notwithstanding the terms of any Secondary License, no Contributor makes additional grants to any Recipient (other than those set forth in this Agreement) as a result of such Recipient's receipt of the Program under the terms of a Secondary License (if permitted under the terms of Section 3). 3. REQUIREMENTS 3.1 If a Contributor Distributes the Program in any form, then: a) the Program must also be made available as Source Code, in accordance with section 3.2, and the Contributor must accompany the Program with a statement that the Source Code for the Program is available under this Agreement, and informs Recipients how to obtain it in a reasonable manner on or through a medium customarily used for software exchange; and b) the Contributor may Distribute the Program under a license different than this Agreement, provided that such license: i) effectively disclaims on behalf of all other 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 other Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; iii) does not attempt to limit or alter the recipients' rights in the Source Code under section 3.2; and iv) requires any subsequent distribution of the Program by any party to be under a license that satisfies the requirements of this section 3. 3.2 When the Program is Distributed as Source Code: a) it must be made available under this Agreement, or if the Program (i) is combined with other material in a separate file or files made available under a Secondary License, and (ii) the initial Contributor attached to the Source Code the notice described in Exhibit A of this Agreement, then the Program may be made available under the terms of such Secondary Licenses, and b) a copy of this Agreement must be included with each copy of the Program. 3.3 Contributors may not remove or alter any copyright, patent, trademark, attribution notices, disclaimers of warranty, or limitations of liability ("notices") contained within the Program from any copy of the Program which they Distribute, provided that Contributors may add their own appropriate notices. 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, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, 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, AND TO THE EXTENT PERMITTED BY APPLICABLE LAW, 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. Nothing in this Agreement is intended to be enforceable by any entity that is not a Contributor or Recipient. No third-party beneficiary rights are created under this Agreement. Exhibit A - Form of Secondary Licenses Notice "This Source Code may also be made available under the following Secondary Licenses when the conditions for such availability set forth in the Eclipse Public License, v. 2.0 are satisfied: {name license(s), version(s), and exceptions or additional permissions here}." Simply including a copy of this Agreement, including this Exhibit A is not sufficient to license the Source Code under Secondary Licenses. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership.mosquitto-2.0.11/include/0000775000175000017500000000000014060132747014306 5ustar rogerrogermosquitto-2.0.11/include/mosquitto.h0000664000175000017500000036402714060132747016537 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef MOSQUITTO_H #define MOSQUITTO_H /* * File: mosquitto.h * * This header contains functions and definitions for use with libmosquitto, the Mosquitto client library. * * The definitions are also used in Mosquitto broker plugins, and some functions are available to plugins. */ #ifdef __cplusplus extern "C" { #endif #ifdef WIN32 # ifdef mosquitto_EXPORTS # define libmosq_EXPORT __declspec(dllexport) # else # ifndef LIBMOSQUITTO_STATIC # ifdef libmosquitto_EXPORTS # define libmosq_EXPORT __declspec(dllexport) # else # define libmosq_EXPORT __declspec(dllimport) # endif # else # define libmosq_EXPORT # endif # endif #else # define libmosq_EXPORT #endif #if defined(_MSC_VER) && _MSC_VER < 1900 && !defined(bool) # ifndef __cplusplus # define bool char # define true 1 # define false 0 # endif #else # ifndef __cplusplus # include # endif #endif #include #include #define LIBMOSQUITTO_MAJOR 2 #define LIBMOSQUITTO_MINOR 0 #define LIBMOSQUITTO_REVISION 11 /* 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, MOSQ_ERR_TIMEOUT = 27, MOSQ_ERR_RETAIN_NOT_SUPPORTED = 28, MOSQ_ERR_TOPIC_ALIAS_INVALID = 29, MOSQ_ERR_ADMINISTRATIVE_ACTION = 30, MOSQ_ERR_ALREADY_EXISTS = 31, }; /* 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, MOSQ_OPT_TCP_NODELAY = 11, MOSQ_OPT_BIND_ADDRESS = 12, MOSQ_OPT_TLS_USE_OS_CERTS = 13, }; /* 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 the library has been compiled without thread support it is *not* * guaranteed to be 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 - on success. * MOSQ_ERR_UNKNOWN - on Windows, if sockets couldn't be initialized. * * 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 . * * It is valid to use this function for clients using all MQTT protocol versions. * If you need to set MQTT v5 Will properties, use instead. * * 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 . * * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument * will be applied to the Will. For MQTT v3.1.1 and below, the `properties` * argument will be ignored. * * Set your client to use MQTT v5 immediately after it is created: * * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); * * 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. * * It is valid to use this function for clients using all MQTT protocol versions. * If you need to set MQTT v5 CONNECT properties, use * instead. * * 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, which could be any of: * * mosq == NULL * * host == NULL * * port < 0 * * keepalive < 5 * 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. If you do not want to bind to a specific interface, * set this to NULL. * * 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 * . * * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument * will be applied to the CONNECT message. For MQTT v3.1.1 and below, the * `properties` argument will be ignored. * * Set your client to use MQTT v5 immediately after it is created: * * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); * * 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. If you do not want to bind to a specific interface, * set this to NULL. * 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, which could be any of: * * mosq == NULL * * host == NULL * * port < 0 * * keepalive < 5 * 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. If you do not want to bind to a specific interface, * set this to NULL. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid, which could be any of: * * mosq == NULL * * host == NULL * * port < 0 * * keepalive < 5 * 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. If you do not want to bind to a specific interface, * set this to NULL. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_INVAL - if the input parameters were invalid, which could be any of: * * mosq == NULL * * host == NULL * * port < 0 * * keepalive < 5 * 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. * * It is valid to use this function for clients using all MQTT protocol versions. * If you need to set MQTT v5 DISCONNECT properties, use * instead. * * 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 * . * * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument * will be applied to the DISCONNECT message. For MQTT v3.1.1 and below, the * `properties` argument will be ignored. * * Set your client to use MQTT v5 immediately after it is created: * * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); * * 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. * * It is valid to use this function for clients using all MQTT protocol versions. * If you need to set MQTT v5 PUBLISH properties, use * instead. * * 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 * . * * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument * will be applied to the PUBLISH message. For MQTT v3.1.1 and below, the * `properties` argument will be ignored. * * Set your client to use MQTT v5 immediately after it is created: * * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); * * 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. * * It is valid to use this function for clients using all MQTT protocol versions. * If you need to set MQTT v5 SUBSCRIBE properties, use * instead. * * 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 * . * * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument * will be applied to the PUBLISH message. For MQTT v3.1.1 and below, the * `properties` argument will be ignored. * * Set your client to use MQTT v5 immediately after it is created: * * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); * * 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 list of * 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 list of * 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. * * It is valid to use this function for clients using all MQTT protocol versions. * If you need to set MQTT v5 UNSUBSCRIBE properties, use * instead. * * Use e.g. and similar to create a list of * properties, then attach them to this publish. Properties need freeing with * . * * If the mosquitto instance `mosq` is using MQTT v5, the `properties` argument * will be applied to the PUBLISH message. For MQTT v3.1.1 and below, the * `properties` argument will be ignored. * * Set your client to use MQTT v5 immediately after it is created: * * mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); * * 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_TCP_NODELAY - Set to 1 to 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. * Defaults to 0, which means Nagle remains enabled. * * 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. * * MOSQ_OPT_TLS_USE_OS_CERTS - Set to 1 to instruct the client to load and * trust OS provided CA certificates for use with TLS connections. * Set to 0 (the default) to only use manually specified CA certs. */ libmosq_EXPORT int mosquitto_int_option(struct mosquitto *mosq, enum mosq_opt_t option, int value); /* * 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. * * MOSQ_OPT_BIND_ADDRESS - Set the hostname or ip address of the local network * interface to bind to when connecting. */ libmosq_EXPORT int mosquitto_string_option(struct mosquitto *mosq, enum mosq_opt_t option, const char *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); /* * Function: mosquitto_ssl_get * * Retrieve a pointer to the SSL structure used for TLS connections in this * client. This can be used in e.g. the connect callback to carry out * additional verification steps. * * Parameters: * mosq - a valid mosquitto instance * * Returns: * A valid pointer to an openssl SSL structure - if the client is using TLS. * NULL - if the client is not using TLS, or TLS support is not compiled in. */ libmosq_EXPORT void *mosquitto_ssl_get(struct mosquitto *mosq); /* ====================================================================== * * Section: Callbacks * * ====================================================================== */ /* * Function: mosquitto_connect_callback_set * * Set the connect callback. This is called when the library receives 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. The values are defined by * the MQTT protocol version in use. * For MQTT v5.0, look at section 3.2.2.2 Connect Reason code: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html * For MQTT v3.1.1, look at section 3.2.2.3 Connect Return code: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html */ 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 library receives 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. The values are defined by * the MQTT protocol version in use. * For MQTT v5.0, look at section 3.2.2.2 Connect Reason code: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html * For MQTT v3.1.1, look at section 3.2.2.3 Connect Return code: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html * flags - the connect flags. */ 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 library receives a CONNACK * message in response to a connection. * * It is valid to set this callback for all MQTT protocol versions. If it is * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` * argument will always be NULL. * * 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. The values are defined by * the MQTT protocol version in use. * For MQTT v5.0, look at section 3.2.2.2 Connect Reason code: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html * For MQTT v3.1.1, look at section 3.2.2.3 Connect Return code: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html * 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. * * It is valid to set this callback for all MQTT protocol versions. If it is * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` * argument will always be NULL. * * 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 *props)); /* * Function: mosquitto_publish_callback_set * * Set the publish callback. This is called when a message initiated with * has been sent to the broker. "Sent" means different * things depending on the QoS of the message: * * QoS 0: The PUBLISH was passed to the local operating system for delivery, * there is no guarantee that it was delivered to the remote broker. * QoS 1: The PUBLISH was sent to the remote broker and the corresponding * PUBACK was received by the library. * QoS 2: The PUBLISH was sent to the remote broker and the corresponding * PUBCOMP was received by the library. * * 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. * "Sent" means different things depending on the QoS of the message: * * QoS 0: The PUBLISH was passed to the local operating system for delivery, * there is no guarantee that it was delivered to the remote broker. * QoS 1: The PUBLISH was sent to the remote broker and the corresponding * PUBACK was received by the library. * QoS 2: The PUBLISH was sent to the remote broker and the corresponding * PUBCOMP was received by the library. * * * It is valid to set this callback for all MQTT protocol versions. If it is * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` * argument will always be NULL. * * 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 *props)); /* * Function: mosquitto_message_callback_set * * Set the message callback. This is called when a message is received from the * broker and the required QoS flow has completed. * * 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 and the required QoS flow has completed. * * It is valid to set this callback for all MQTT protocol versions. If it is * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` * argument will always be NULL. * * 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 *props)); /* * Function: mosquitto_subscribe_callback_set * * Set the subscribe callback. This is called when the library receives a * SUBACK message in response to a SUBSCRIBE. * * 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 library receives a * SUBACK message in response to a SUBSCRIBE. * * It is valid to set this callback for all MQTT protocol versions. If it is * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` * argument will always be NULL. * * 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 *props)); /* * Function: mosquitto_unsubscribe_callback_set * * Set the unsubscribe callback. This is called when the library receives a * UNSUBACK message in response to an UNSUBSCRIBE. * * 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 library receives a * UNSUBACK message in response to an UNSUBSCRIBE. * * It is valid to set this callback for all MQTT protocol versions. If it is * used with MQTT clients that use MQTT v3.1.1 or earlier, then the `props` * argument will always be NULL. * * 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 *props)); /* * 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 *)); /* ============================================================================= * * 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: * (start code) * mosquitto_string_to_command("CONNECT", &cmd); * // cmd == CMD_CONNECT * (end) */ 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 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 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 * Greater than 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 * Greater than 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_identifier * * Return the property identifier for a single property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * A valid property identifier on success * 0 - on error */ libmosq_EXPORT int mosquitto_property_identifier(const mosquitto_property *property); /* * Function: mosquitto_property_next * * Return the next property in a property list. Use to iterate over a property * list, e.g.: * * (start code) * for(prop = proplist; prop != NULL; prop = mosquitto_property_next(prop)){ * if(mosquitto_property_identifier(prop) == MQTT_PROP_CONTENT_TYPE){ * ... * } * } * (end) * * Parameters: * proplist - pointer to mosquitto_property pointer, the list of properties * * Returns: * Pointer to the next item in the list * NULL, if proplist is NULL, or if there are no more items in the list. */ libmosq_EXPORT const mosquitto_property *mosquitto_property_next(const mosquitto_property *proplist); /* * 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: * * (start code) * 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); * (end) * * 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: * (start code) * // 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); * } * (end) */ 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_property_identifier_to_string * * Return the property name as a string for a property identifier. * The property name is as defined in the MQTT specification, with - as a * separator, for example: payload-format-indicator. * * Parameters: * identifier - valid MQTT property identifier integer * * Returns: * A const string to the property name on success * NULL on failure */ libmosq_EXPORT const char *mosquitto_property_identifier_to_string(int identifier); /* 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: * (start code) * mosquitto_string_to_property_info("response-topic", &id, &type); * // id == MQTT_PROP_RESPONSE_TOPIC * // type == MQTT_PROP_TYPE_STRING * (end) */ libmosq_EXPORT int mosquitto_string_to_property_info(const char *propname, int *identifier, int *type); #ifdef __cplusplus } #endif #endif mosquitto-2.0.11/include/mosquitto_broker.h0000664000175000017500000003700414060132747020073 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ /* * File: mosquitto_broker.h * * This header contains functions for use by plugins. */ #ifndef MOSQUITTO_BROKER_H #define MOSQUITTO_BROKER_H #ifdef __cplusplus extern "C" { #endif #if defined(WIN32) && defined(mosquitto_EXPORTS) # define mosq_EXPORT __declspec(dllexport) #else # define mosq_EXPORT #endif #include #include #include #include struct mosquitto; typedef struct mqtt5__property mosquitto_property; enum mosquitto_protocol { mp_mqtt, mp_mqttsn, mp_websockets }; /* ========================================================================= * * Section: Register callbacks. * * ========================================================================= */ /* Callback events */ enum mosquitto_plugin_event { MOSQ_EVT_RELOAD = 1, MOSQ_EVT_ACL_CHECK = 2, MOSQ_EVT_BASIC_AUTH = 3, MOSQ_EVT_EXT_AUTH_START = 4, MOSQ_EVT_EXT_AUTH_CONTINUE = 5, MOSQ_EVT_CONTROL = 6, MOSQ_EVT_MESSAGE = 7, MOSQ_EVT_PSK_KEY = 8, MOSQ_EVT_TICK = 9, MOSQ_EVT_DISCONNECT = 10, }; /* Data for the MOSQ_EVT_RELOAD event */ struct mosquitto_evt_reload { void *future; struct mosquitto_opt *options; int option_count; void *future2[4]; }; /* Data for the MOSQ_EVT_ACL_CHECK event */ struct mosquitto_evt_acl_check { void *future; struct mosquitto *client; const char *topic; const void *payload; mosquitto_property *properties; int access; uint32_t payloadlen; uint8_t qos; bool retain; void *future2[4]; }; /* Data for the MOSQ_EVT_BASIC_AUTH event */ struct mosquitto_evt_basic_auth { void *future; struct mosquitto *client; char *username; char *password; void *future2[4]; }; /* Data for the MOSQ_EVT_PSK_KEY event */ struct mosquitto_evt_psk_key { void *future; struct mosquitto *client; const char *hint; const char *identity; char *key; int max_key_len; void *future2[4]; }; /* Data for the MOSQ_EVT_EXTENDED_AUTH event */ struct mosquitto_evt_extended_auth { void *future; struct mosquitto *client; const void *data_in; void *data_out; uint16_t data_in_len; uint16_t data_out_len; const char *auth_method; void *future2[3]; }; /* Data for the MOSQ_EVT_CONTROL event */ struct mosquitto_evt_control { void *future; struct mosquitto *client; const char *topic; const void *payload; const mosquitto_property *properties; char *reason_string; uint32_t payloadlen; uint8_t qos; uint8_t reason_code; bool retain; void *future2[4]; }; /* Data for the MOSQ_EVT_MESSAGE event */ struct mosquitto_evt_message { void *future; struct mosquitto *client; char *topic; void *payload; mosquitto_property *properties; char *reason_string; uint32_t payloadlen; uint8_t qos; uint8_t reason_code; bool retain; void *future2[4]; }; /* Data for the MOSQ_EVT_TICK event */ struct mosquitto_evt_tick { void *future; long now_ns; long next_ns; time_t now_s; time_t next_s; void *future2[4]; }; /* Data for the MOSQ_EVT_DISCONNECT event */ struct mosquitto_evt_disconnect { void *future; struct mosquitto *client; int reason; void *future2[4]; }; /* Callback definition */ typedef int (*MOSQ_FUNC_generic_callback)(int, void *, void *); typedef struct mosquitto_plugin_id_t mosquitto_plugin_id_t; /* * Function: mosquitto_callback_register * * Register a callback for an event. * * Parameters: * identifier - the plugin identifier, as provided by . * event - the event to register a callback for. Can be one of: * * MOSQ_EVT_RELOAD * * MOSQ_EVT_ACL_CHECK * * MOSQ_EVT_BASIC_AUTH * * MOSQ_EVT_EXT_AUTH_START * * MOSQ_EVT_EXT_AUTH_CONTINUE * * MOSQ_EVT_CONTROL * * MOSQ_EVT_MESSAGE * * MOSQ_EVT_PSK_KEY * * MOSQ_EVT_TICK * * MOSQ_EVT_DISCONNECT * cb_func - the callback function * event_data - event specific data * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if cb_func is NULL * MOSQ_ERR_NOMEM - on out of memory * MOSQ_ERR_ALREADY_EXISTS - if cb_func has already been registered for this event * MOSQ_ERR_NOT_SUPPORTED - if the event is not supported */ mosq_EXPORT int mosquitto_callback_register( mosquitto_plugin_id_t *identifier, int event, MOSQ_FUNC_generic_callback cb_func, const void *event_data, void *userdata); /* * Function: mosquitto_callback_unregister * * Unregister a previously registered callback function. * * Parameters: * identifier - the plugin identifier, as provided by . * event - the event to register a callback for. Can be one of: * * MOSQ_EVT_RELOAD * * MOSQ_EVT_ACL_CHECK * * MOSQ_EVT_BASIC_AUTH * * MOSQ_EVT_EXT_AUTH_START * * MOSQ_EVT_EXT_AUTH_CONTINUE * * MOSQ_EVT_CONTROL * * MOSQ_EVT_MESSAGE * * MOSQ_EVT_PSK_KEY * * MOSQ_EVT_TICK * * MOSQ_EVT_DISCONNECT * cb_func - the callback function * event_data - event specific data * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if cb_func is NULL * MOSQ_ERR_NOT_FOUND - if cb_func was not registered for this event * MOSQ_ERR_NOT_SUPPORTED - if the event is not supported */ mosq_EXPORT int mosquitto_callback_unregister( mosquitto_plugin_id_t *identifier, int event, MOSQ_FUNC_generic_callback cb_func, const void *event_data); /* ========================================================================= * * Section: Memory allocation. * * Use these functions when allocating or freeing memory to have your memory * included in the memory tracking on the broker. * * ========================================================================= */ /* * Function: mosquitto_calloc */ mosq_EXPORT void *mosquitto_calloc(size_t nmemb, size_t size); /* * Function: mosquitto_free */ mosq_EXPORT void mosquitto_free(void *mem); /* * Function: mosquitto_malloc */ mosq_EXPORT void *mosquitto_malloc(size_t size); /* * Function: mosquitto_realloc */ mosq_EXPORT void *mosquitto_realloc(void *ptr, size_t size); /* * Function: mosquitto_strdup */ mosq_EXPORT char *mosquitto_strdup(const char *s); /* ========================================================================= * * Section: Utility Functions * * Use these functions from within your plugin. * * ========================================================================= */ /* * 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. */ mosq_EXPORT 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. */ mosq_EXPORT const char *mosquitto_client_address(const struct mosquitto *client); /* * Function: mosquitto_client_clean_session * * Retrieve the clean session flag value for a client. */ mosq_EXPORT bool mosquitto_client_clean_session(const struct mosquitto *client); /* * Function: mosquitto_client_id * * Retrieve the client id associated with a client. */ mosq_EXPORT const char *mosquitto_client_id(const struct mosquitto *client); /* * Function: mosquitto_client_keepalive * * Retrieve the keepalive value for a client. */ mosq_EXPORT 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. * * When you have finished with the x509 pointer, it must be freed using * X509_free(). * * If TLS is not supported, this function will always return NULL. */ mosq_EXPORT 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) */ mosq_EXPORT int mosquitto_client_protocol(const struct mosquitto *client); /* * Function: mosquitto_client_protocol_version * * Retrieve the MQTT protocol version with which the client has connected. Can be one of: * * Returns: * 3 - for MQTT v3 / v3.1 * 4 - for MQTT v3.1.1 * 5 - for MQTT v5 */ mosq_EXPORT int mosquitto_client_protocol_version(const struct mosquitto *client); /* * Function: mosquitto_client_sub_count * * Retrieve the number of subscriptions that have been made by a client. */ mosq_EXPORT int mosquitto_client_sub_count(const struct mosquitto *client); /* * Function: mosquitto_client_username * * Retrieve the username associated with a client. */ mosq_EXPORT 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 */ mosq_EXPORT int mosquitto_set_username(struct mosquitto *client, const char *username); /* ========================================================================= * * Section: Client control * * ========================================================================= */ /* Function: mosquitto_kick_client_by_clientid * * Forcefully disconnect a client from the broker. * * If clientid != NULL, then the client with the matching client id is * disconnected from the broker. * If clientid == NULL, then all clients are disconnected from the broker. * * If with_will == true, then if the client has a Last Will and Testament * defined then this will be sent. If false, the LWT will not be sent. */ mosq_EXPORT int mosquitto_kick_client_by_clientid(const char *clientid, bool with_will); /* Function: mosquitto_kick_client_by_username * * Forcefully disconnect a client from the broker. * * If username != NULL, then all clients with a matching username are kicked * from the broker. * If username == NULL, then all clients that do not have a username are * kicked. * * If with_will == true, then if the client has a Last Will and Testament * defined then this will be sent. If false, the LWT will not be sent. */ mosq_EXPORT int mosquitto_kick_client_by_username(const char *username, bool with_will); /* ========================================================================= * * Section: Publishing functions * * ========================================================================= */ /* Function: mosquitto_broker_publish * * Publish a message from within a plugin. * * This function allows a plugin to publish a message. Messages published in * this way are treated as coming from the broker and so will not be passed to * `mosquitto_auth_acl_check(, MOSQ_ACL_WRITE, , )` for checking. Read access * will be enforced as normal for individual clients when they are due to * receive the message. * * It can be used to send messages to all clients that have a matching * subscription, or to a single client whether or not it has a matching * subscription. * * Parameters: * clientid - optional string. If set to NULL, the message is delivered to all * clients. If non-NULL, the message is delivered only to the * client with the corresponding client id. If the client id * specified is not connected, the message will be dropped. * topic - message topic * payloadlen - payload length in bytes. Can be 0 for an empty payload. * payload - payload bytes. If payloadlen > 0 this must not be NULL. Must * be allocated on the heap. Will be freed by mosquitto after use if the * function returns success. * qos - message QoS to use. * retain - should retain be set on the message. This does not apply if * clientid is non-NULL. * properties - MQTT v5 properties to attach to the message. If the function * returns success, then properties is owned by the broker and * will be freed at a later point. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if topic is NULL, if payloadlen < 0, if payloadlen > 0 * and payload is NULL, if qos is not 0, 1, or 2. * MOSQ_ERR_NOMEM - on out of memory */ mosq_EXPORT int mosquitto_broker_publish( const char *clientid, const char *topic, int payloadlen, void *payload, int qos, bool retain, mosquitto_property *properties); /* Function: mosquitto_broker_publish_copy * * Publish a message from within a plugin. * * This function is identical to mosquitto_broker_publish, except that a copy * of `payload` is taken. * * Parameters: * clientid - optional string. If set to NULL, the message is delivered to all * clients. If non-NULL, the message is delivered only to the * client with the corresponding client id. If the client id * specified is not connected, the message will be dropped. * topic - message topic * payloadlen - payload length in bytes. Can be 0 for an empty payload. * payload - payload bytes. If payloadlen > 0 this must not be NULL. * Memory remains the property of the calling function. * qos - message QoS to use. * retain - should retain be set on the message. This does not apply if * clientid is non-NULL. * properties - MQTT v5 properties to attach to the message. If the function * returns success, then properties is owned by the broker and * will be freed at a later point. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if topic is NULL, if payloadlen < 0, if payloadlen > 0 * and payload is NULL, if qos is not 0, 1, or 2. * MOSQ_ERR_NOMEM - on out of memory */ mosq_EXPORT int mosquitto_broker_publish_copy( const char *clientid, const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties); #ifdef __cplusplus } #endif #endif mosquitto-2.0.11/include/mosquitto_plugin.h0000664000175000017500000003604514060132747020111 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef MOSQUITTO_PLUGIN_H #define MOSQUITTO_PLUGIN_H /* * File: mosquitto_plugin.h * * This header contains function declarations for use when writing a Mosquitto plugin. */ #ifdef __cplusplus extern "C" { #endif /* The generic plugin interface starts at version 5 */ #define MOSQ_PLUGIN_VERSION 5 /* The old auth only interface stopped at version 4 */ #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 #define MOSQ_ACL_UNSUBSCRIBE 0x08 #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; }; #ifdef WIN32 # define mosq_plugin_EXPORT __declspec(dllexport) #else # define mosq_plugin_EXPORT #endif /* * 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. */ /* ========================================================================= * * Section: Plugin Functions v5 * * This is the plugin version 5 interface, which covers authentication, access * control, the $CONTROL topic space handling, and message inspection and * modification. * * This interface is available from v2.0 onwards. * * There are just three functions to implement in your plugin. You should * register callbacks to handle different events in your * mosquitto_plugin_init() function. See mosquitto_broker.h for the events and * callback registering functions. * * ========================================================================= */ /* * Function: mosquitto_plugin_version * * The broker will attempt to call this function immediately after loading the * plugin to check it is a supported plugin version. Your code must simply * return the plugin interface version you support, i.e. 5. * * The supported_versions array tells you which plugin versions the broker supports. * * If the broker does not support the version that you require, return -1 to * indicate failure. */ mosq_plugin_EXPORT int mosquitto_plugin_version(int supported_version_count, const int *supported_versions); /* * Function: mosquitto_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: * * identifier - This is a pointer to an opaque structure which you must * save and use when registering/unregistering callbacks. * 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. */ mosq_plugin_EXPORT int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **userdata, struct mosquitto_opt *options, int option_count); /* * Function: mosquitto_plugin_cleanup * * Called when the broker is shutting down. This will only ever be called once * per plugin. * * 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. */ mosq_plugin_EXPORT int mosquitto_plugin_cleanup(void *userdata, struct mosquitto_opt *options, int option_count); /* ========================================================================= * * Section: Plugin Functions v4 * * This is the plugin version 4 interface, which is exclusively for * authentication and access control, and which is still supported for existing * plugins. If you are developing a new plugin, please use the v5 interface. * * 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 * the version of the plugin interface you support, i.e. 4. */ mosq_plugin_EXPORT 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. */ mosq_plugin_EXPORT 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. */ mosq_plugin_EXPORT 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. */ mosq_plugin_EXPORT 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. */ mosq_plugin_EXPORT 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. */ mosq_plugin_EXPORT 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. */ mosq_plugin_EXPORT 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. */ mosq_plugin_EXPORT 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. */ mosq_plugin_EXPORT 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); mosq_plugin_EXPORT 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-2.0.11/include/mqtt_protocol.h0000664000175000017500000002702214060132747017370 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 2.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at https://www.eclipse.org/legal/epl-2.0/ and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause Contributors: Roger Light - initial implementation and documentation. */ #ifndef MQTT_PROTOCOL_H #define MQTT_PROTOCOL_H /* * File: mqtt_protocol.h * * This header contains definitions of MQTT values as defined in the specifications. */ #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 0x10U #define CMD_CONNACK 0x20U #define CMD_PUBLISH 0x30U #define CMD_PUBACK 0x40U #define CMD_PUBREC 0x50U #define CMD_PUBREL 0x60U #define CMD_PUBCOMP 0x70U #define CMD_SUBSCRIBE 0x80U #define CMD_SUBACK 0x90U #define CMD_UNSUBSCRIBE 0xA0U #define CMD_UNSUBACK 0xB0U #define CMD_PINGREQ 0xC0U #define CMD_PINGRESP 0xD0U #define CMD_DISCONNECT 0xE0U #define CMD_AUTH 0xF0U /* Mosquitto only: for distinguishing CONNECT and WILL properties */ #define CMD_WILL 0x100 /* Enum: mqtt311_connack_codes * * The CONNACK results for MQTT v3.1.1, and v3.1. * * Values: * 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 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 * The reason codes returned in various MQTT commands. * * Values: * MQTT_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 */ 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 * Options for use with MQTTv5 properties. * Options: * * MQTT_PROP_PAYLOAD_FORMAT_INDICATOR - property option. * MQTT_PROP_MESSAGE_EXPIRY_INTERVAL - property option. * MQTT_PROP_CONTENT_TYPE - property option. * MQTT_PROP_RESPONSE_TOPIC - property option. * MQTT_PROP_CORRELATION_DATA - property option. * MQTT_PROP_SUBSCRIPTION_IDENTIFIER - property option. * MQTT_PROP_SESSION_EXPIRY_INTERVAL - property option. * MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER - property option. * MQTT_PROP_SERVER_KEEP_ALIVE - property option. * MQTT_PROP_AUTHENTICATION_METHOD - property option. * MQTT_PROP_AUTHENTICATION_DATA - property option. * MQTT_PROP_REQUEST_PROBLEM_INFORMATION - property option. * MQTT_PROP_WILL_DELAY_INTERVAL - property option. * MQTT_PROP_REQUEST_RESPONSE_INFORMATION - property option. * MQTT_PROP_RESPONSE_INFORMATION - property option. * MQTT_PROP_SERVER_REFERENCE - property option. * MQTT_PROP_REASON_STRING - property option. * MQTT_PROP_RECEIVE_MAXIMUM - property option. * MQTT_PROP_TOPIC_ALIAS_MAXIMUM - property option. * MQTT_PROP_TOPIC_ALIAS - property option. * MQTT_PROP_MAXIMUM_QOS - property option. * MQTT_PROP_RETAIN_AVAILABLE - property option. * MQTT_PROP_USER_PROPERTY - property option. * MQTT_PROP_MAXIMUM_PACKET_SIZE - property option. * MQTT_PROP_WILDCARD_SUB_AVAILABLE - property option. * MQTT_PROP_SUBSCRIPTION_ID_AVAILABLE - property option. * MQTT_PROP_SHARED_SUB_AVAILABLE - property option. */ 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 * Options for use with MQTTv5 subscriptions. * * 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. */ 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-2.0.11/libmosquittopp.pc.in0000664000175000017500000000037414060132747016713 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-2.0.11/CONTRIBUTING.md0000664000175000017500000000751214060132747015121 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-2.0.11/pwfile.example0000664000175000017500000000054314060132747015530 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-2.0.11/logo/0000775000175000017500000000000014060132747013623 5ustar rogerrogermosquitto-2.0.11/logo/mosquitto.ico0000664000175000017500000010341414060132747016366 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-2.0.11/logo/legacy/mosquitto-14x14.png0000664000175000017500000000100114060132747020410 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-2.0.11/logo/legacy/mosquitto-16x16.png0000664000175000017500000000106614060132747020427 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-2.0.11/logo/mosquitto-logo-min.svg0000664000175000017500000000712314060132747020132 0ustar rogerroger image/svg+xmlmosquitto-2.0.11/logo/mosquitto-logo-only.svg0000664000175000017500000001027314060132747020330 0ustar rogerroger image/svg+xmlmosquitto-2.0.11/logo/mosquitto-text-below.svg0000664000175000017500000002344014060132747020503 0ustar rogerroger image/svg+xmlmosquitto-2.0.11/logo/mosquitto-text-side.svg0000664000175000017500000002330114060132747020313 0ustar rogerroger image/svg+xmlmosquitto-2.0.11/NOTICE.md0000664000175000017500000000353614060132747014175 0ustar rogerroger# Notices for Mosquitto This content is produced and maintained by the Eclipse Mosquitto project. * Project home: https://projects.eclipse.org/projects/iot.mosquitto ## Trademarks Eclipse Mosquitto trademarks of the Eclipse Foundation. Eclipse, and the Eclipse Logo are registered trademarks of the Eclipse Foundation. ## Copyright All content is the property of the respective authors or their employers. For more information regarding authorship of content, please consult the listed source code repository logs. ## Declared Project Licenses This program and the accompanying materials are made available under the terms of the Eclipse Public License v2.0 which is available at http://www.eclipse.org/legal/epl-v10.html, or the BSD 3 Clause license. SPDX-License-Identifier: EPL-2.0 or BSD-3-Clause ## Source Code The project maintains the following source code repositories: * https://github.com/eclipse/mosquitto ## Third-party Content This project makes use of the follow third party projects. cJSON (1.7.x) * License: MIT * Project: https://github.com/DaveGamble/cJSON libwebsockets (4.x) * License: MIT * Project: https://github.com/warmcat/libwebsockets openssl (1.1.1) * License: OpenSSL License and SSLeay License * Project: https://openssl.org * Source: https://github.com/openssl/openssl uthash (2.1.0) * License: BSD revised (https://troydhanson.github.io/uthash/license.html) * Project: https://github.com/troydhanson/uthash ## 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. mosquitto-2.0.11/README-compiling.md0000664000175000017500000000213314060132747016120 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 2.4 and above) * cJSON (optional but recommended, for dynamic-security plugin support, and JSON output from mosquitto_sub/mosquitto_rr) * libsystemd-dev (optional, if building with systemd support on Linux) * On Windows, a pthreads library is required if threading support is to be included. * xsltproc (only if building from git) * docbook-xsl (only if building from git) 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) then please get in touch using the details in README.md. mosquitto-2.0.11/Makefile0000664000175000017500000000641014060132747014324 0ustar rogerrogerinclude config.mk DIRS=lib apps client plugins src DOCDIRS=man DISTDIRS=man DISTFILES= \ apps/ \ client/ \ cmake/ \ deps/ \ examples/ \ include/ \ installer/ \ lib/ \ logo/ \ man/ \ misc/ \ plugins/ \ security/ \ service/ \ snap/ \ src/ \ test/ \ \ CMakeLists.txt \ CONTRIBUTING.md \ ChangeLog.txt \ LICENSE.txt \ Makefile \ about.html \ aclfile.example \ config.h \ config.mk \ edl-v10 \ epl-v20 \ libmosquitto.pc.in \ libmosquittopp.pc.in \ mosquitto.conf \ NOTICE.md \ pskfile.example \ pwfile.example \ README-compiling.md \ README-letsencrypt.md \ 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 : all 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/ 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 . -t eclipse-mosquitto:local mosquitto-2.0.11/edl-v100000664000175000017500000000304114060132747013754 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.