Repository: eclipse-mosquitto/mosquitto Branch: master Commit: b3b4d77ef3fa Files: 1864 Total size: 7.2 MB Directory structure: gitextract_o5h0yyj5/ ├── .editorconfig ├── .github/ │ ├── issue_template.md │ ├── labeler.yml │ ├── pull_request_template.md │ └── workflows/ │ ├── build-variants.yml │ ├── cifuzz.yml │ ├── codeql-analysis.yml │ ├── coverage.yml │ ├── coverity-scan-develop.yml │ ├── coverity-scan-fixes.yml │ ├── delete-old-workflow-runs.yml │ ├── issue-labler.yml │ ├── lock.yml │ ├── macos.yml │ ├── mosquitto-cmake.yml │ ├── mosquitto-make-asan.yml │ ├── mosquitto-make.yml │ ├── windows-x86.yml │ └── windows.yml ├── .gitignore ├── .uncrustify.cfg ├── CITATION.cff ├── CMakeLists.txt ├── CONTRIBUTING.md ├── ChangeLog.txt ├── LICENSE.txt ├── Makefile ├── NOTICE.md ├── README-compiling.md ├── README-letsencrypt.md ├── README-tests.md ├── README-windows.txt ├── README.md ├── SECURITY.md ├── THANKS.txt ├── about.html ├── aclfile.example ├── apps/ │ ├── CMakeLists.txt │ ├── Makefile │ ├── db_dump/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── db_dump.c │ │ ├── db_dump.h │ │ ├── json.c │ │ ├── print.c │ │ └── stubs.c │ ├── mosquitto_ctrl/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── broker.c │ │ ├── client.c │ │ ├── ctrl_shell.c │ │ ├── ctrl_shell.h │ │ ├── ctrl_shell_broker.c │ │ ├── ctrl_shell_client.c │ │ ├── ctrl_shell_completion_tree.c │ │ ├── ctrl_shell_dynsec.c │ │ ├── ctrl_shell_internal.h │ │ ├── ctrl_shell_io.c │ │ ├── ctrl_shell_post_connect.c │ │ ├── ctrl_shell_pre_connect.c │ │ ├── ctrl_shell_printf.c │ │ ├── dynsec.c │ │ ├── dynsec_client.c │ │ ├── dynsec_group.c │ │ ├── dynsec_role.c │ │ ├── example.c │ │ ├── mosquitto_ctrl.c │ │ ├── mosquitto_ctrl.h │ │ ├── options.c │ │ └── test/ │ │ └── Makefile │ ├── mosquitto_passwd/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── get_password.c │ │ ├── get_password.h │ │ └── mosquitto_passwd.c │ └── mosquitto_signal/ │ ├── CMakeLists.txt │ ├── Makefile │ ├── mosquitto_signal.c │ ├── mosquitto_signal.h │ ├── signal_unix.c │ └── signal_windows.c ├── buildtest.py ├── client/ │ ├── CMakeLists.txt │ ├── Makefile │ ├── args.txt │ ├── client_props.c │ ├── client_shared.c │ ├── client_shared.h │ ├── pub_client.c │ ├── pub_shared.c │ ├── pub_shared.h │ ├── pub_test_properties │ ├── rr_client.c │ ├── sub_client.c │ ├── sub_client_output.c │ ├── sub_client_output.h │ ├── sub_test_fixed_width │ └── sub_test_properties ├── cmake/ │ ├── FindCUnit.cmake │ ├── FindLineEditing.cmake │ ├── Findargon2.cmake │ └── FindcJSON.cmake ├── codecov.yml ├── common/ │ ├── json_help.c │ ├── json_help.h │ └── lib_load.h ├── config.h ├── config.mk ├── dashboard/ │ ├── README.md │ └── src/ │ ├── app/ │ │ ├── consts.js │ │ ├── dashboard.js │ │ ├── index.js │ │ ├── listeners.js │ │ └── sidebar.js │ ├── css/ │ │ └── styles.css │ ├── index.html │ ├── lib/ │ │ └── chart.umd.js │ ├── listeners.html │ ├── tailwind/ │ │ └── styles.css │ ├── tailwind.config.js │ └── utils/ │ ├── assert.js │ ├── queue.js │ └── utils.js ├── deps/ │ ├── picohttpparser/ │ │ ├── README.md │ │ ├── picohttpparser.c │ │ └── picohttpparser.h │ ├── uthash.h │ └── utlist.h ├── doc/ │ ├── historical/ │ │ ├── old-regex.txt │ │ └── topic-match.kds │ └── joss-paper/ │ ├── codemeta.json │ ├── paper.bib │ └── paper.md ├── docker/ │ ├── 1.6-openssl/ │ │ ├── Dockerfile │ │ ├── README.md │ │ └── docker-entrypoint.sh │ ├── 2.0-openssl/ │ │ ├── Dockerfile │ │ ├── README.md │ │ ├── docker-entrypoint.sh │ │ └── mosquitto-no-auth.conf │ ├── 2.1-alpine/ │ │ ├── Dockerfile │ │ ├── README.md │ │ ├── docker-entrypoint.sh │ │ └── mosquitto.conf │ ├── 2.1-ubuntu/ │ │ ├── Dockerfile │ │ ├── README.md │ │ ├── docker-entrypoint.sh │ │ └── mosquitto.conf │ ├── README.md │ ├── generic/ │ │ ├── Dockerfile │ │ ├── README.md │ │ ├── docker-entrypoint.sh │ │ └── mosquitto-no-auth.conf │ └── local/ │ ├── Dockerfile │ ├── README.md │ ├── docker-entrypoint.sh │ └── mosquitto.conf ├── edl-v10 ├── epl-v20 ├── examples/ │ ├── mysql_log/ │ │ ├── Makefile │ │ └── mysql_log.c │ ├── publish/ │ │ ├── Makefile │ │ ├── basic-1.c │ │ └── basic-websockets-1.c │ ├── subscribe/ │ │ └── basic-1.c │ ├── subscribe_simple/ │ │ ├── Makefile │ │ ├── callback.c │ │ ├── multiple.c │ │ └── single.c │ └── temperature_conversion/ │ ├── Makefile │ ├── main.cpp │ ├── readme.txt │ ├── temperature_conversion.cpp │ └── temperature_conversion.h ├── format.sh ├── fuzzing/ │ ├── Makefile │ ├── apps/ │ │ ├── Makefile │ │ ├── db_dump/ │ │ │ ├── Makefile │ │ │ ├── db_dump_fuzz_load.cpp │ │ │ ├── db_dump_fuzz_load_client_stats.cpp │ │ │ └── db_dump_fuzz_load_stats.cpp │ │ └── mosquitto_passwd/ │ │ ├── Makefile │ │ └── mosquitto_passwd_fuzz_load.cpp │ ├── broker/ │ │ ├── Makefile │ │ ├── broker_fuzz.cpp │ │ ├── broker_fuzz.h │ │ ├── broker_fuzz_acl_file.cpp │ │ ├── broker_fuzz_handle_auth.cpp │ │ ├── broker_fuzz_handle_connect.cpp │ │ ├── broker_fuzz_handle_publish.cpp │ │ ├── broker_fuzz_handle_subscribe.cpp │ │ ├── broker_fuzz_handle_unsubscribe.cpp │ │ ├── broker_fuzz_password_file.cpp │ │ ├── broker_fuzz_proxy_v1.cpp │ │ ├── broker_fuzz_proxy_v2.cpp │ │ ├── broker_fuzz_psk_file.cpp │ │ ├── broker_fuzz_queue_msg.cpp │ │ ├── broker_fuzz_read_handle.cpp │ │ ├── broker_fuzz_test_config.cpp │ │ ├── broker_fuzz_with_init.cpp │ │ ├── fuzz_packet_read_base.c │ │ └── fuzz_packet_read_base.h │ ├── config.mk │ ├── corpora/ │ │ ├── broker_acl_file.dict │ │ └── broker_conf.dict │ ├── generate_packet_corpora.py │ ├── libcommon/ │ │ ├── Makefile │ │ ├── libcommon_fuzz_property.cpp │ │ ├── libcommon_fuzz_property.proto │ │ ├── libcommon_fuzz_pub_topic_check2.cpp │ │ ├── libcommon_fuzz_sub_topic_check2.cpp │ │ ├── libcommon_fuzz_topic_matching.cpp │ │ ├── libcommon_fuzz_topic_matching.proto │ │ ├── libcommon_fuzz_topic_tokenise.cpp │ │ └── libcommon_fuzz_utf8.cpp │ ├── plugins/ │ │ ├── Makefile │ │ └── dynamic-security/ │ │ ├── Makefile │ │ └── dynsec_fuzz_load.cpp │ └── scripts/ │ ├── oss-fuzz-build.sh │ └── oss-fuzz-dependencies.sh ├── include/ │ ├── mosquitto/ │ │ ├── broker.h │ │ ├── broker_control.h │ │ ├── broker_plugin.h │ │ ├── defs.h │ │ ├── libcommon.h │ │ ├── libcommon_base64.h │ │ ├── libcommon_cjson.h │ │ ├── libcommon_file.h │ │ ├── libcommon_memory.h │ │ ├── libcommon_password.h │ │ ├── libcommon_properties.h │ │ ├── libcommon_random.h │ │ ├── libcommon_string.h │ │ ├── libcommon_time.h │ │ ├── libcommon_topic.h │ │ ├── libcommon_utf8.h │ │ ├── libmosquitto.h │ │ ├── libmosquitto_auth.h │ │ ├── libmosquitto_callbacks.h │ │ ├── libmosquitto_connect.h │ │ ├── libmosquitto_create_delete.h │ │ ├── libmosquitto_helpers.h │ │ ├── libmosquitto_loop.h │ │ ├── libmosquitto_message.h │ │ ├── libmosquitto_options.h │ │ ├── libmosquitto_publish.h │ │ ├── libmosquitto_socks.h │ │ ├── libmosquitto_subscribe.h │ │ ├── libmosquitto_tls.h │ │ ├── libmosquitto_unsubscribe.h │ │ ├── libmosquitto_will.h │ │ ├── libmosquittopp.h │ │ └── mqtt_protocol.h │ ├── mosquitto.h │ ├── mosquitto_broker.h │ ├── mosquitto_plugin.h │ ├── mosquittopp.h │ └── mqtt_protocol.h ├── installer/ │ ├── mosquitto.nsi │ └── mosquitto64.nsi ├── lib/ │ ├── CMakeLists.txt │ ├── Makefile │ ├── actions_publish.c │ ├── actions_subscribe.c │ ├── actions_unsubscribe.c │ ├── alias_mosq.c │ ├── alias_mosq.h │ ├── callbacks.c │ ├── callbacks.h │ ├── connect.c │ ├── cpp/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ └── mosquittopp.cpp │ ├── extended_auth.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 │ ├── http_client.c │ ├── http_client.h │ ├── libmosquitto.c │ ├── linker.version │ ├── logging_mosq.c │ ├── logging_mosq.h │ ├── loop.c │ ├── messages_mosq.c │ ├── messages_mosq.h │ ├── mosquitto_internal.h │ ├── net_mosq.c │ ├── net_mosq.h │ ├── net_mosq_ocsp.c │ ├── net_ws.c │ ├── options.c │ ├── packet_datatypes.c │ ├── packet_mosq.c │ ├── packet_mosq.h │ ├── property_mosq.c │ ├── property_mosq.h │ ├── pthread_compat.h │ ├── read_handle.c │ ├── read_handle.h │ ├── send_connect.c │ ├── send_disconnect.c │ ├── send_mosq.c │ ├── send_mosq.h │ ├── send_publish.c │ ├── send_subscribe.c │ ├── send_unsubscribe.c │ ├── socks_mosq.c │ ├── socks_mosq.h │ ├── srv_mosq.c │ ├── thread_mosq.c │ ├── tls_mosq.c │ ├── tls_mosq.h │ ├── util_mosq.c │ ├── util_mosq.h │ ├── will_mosq.c │ └── will_mosq.h ├── libcommon/ │ ├── CMakeLists.txt │ ├── Makefile │ ├── base64_common.c │ ├── cjson_common.c │ ├── file_common.c │ ├── linker.version │ ├── memory_common.c │ ├── mqtt_common.c │ ├── password_common.c │ ├── property_common.c │ ├── property_common.h │ ├── random_common.c │ ├── strings_common.c │ ├── time_common.c │ ├── topic_common.c │ └── utf8_common.c ├── libmosquitto.pc.in ├── libmosquittopp.pc.in ├── make/ │ ├── broker.mk │ └── unit-test.mk ├── man/ │ ├── CMakeLists.txt │ ├── Makefile │ ├── common/ │ │ ├── env-var-mosquitto-unsafe-allow-symlinks.xml │ │ ├── option-bind.xml │ │ ├── option-clean-session.xml │ │ ├── option-clientid-prefix.xml │ │ ├── option-clientid.xml │ │ ├── option-config-file.xml │ │ ├── option-debug.xml │ │ ├── option-format-no-eol.xml │ │ ├── option-format-pretty.xml │ │ ├── option-format-verbose.xml │ │ ├── option-format.xml │ │ ├── option-help.xml │ │ ├── option-hide-retain.xml │ │ ├── option-host.xml │ │ ├── option-keepalive.xml │ │ ├── option-no-tls.xml │ │ ├── option-nodelay.xml │ │ ├── option-password.xml │ │ ├── option-payload-file.xml │ │ ├── option-payload-message.xml │ │ ├── option-payload-null.xml │ │ ├── option-payload-stdin-file.xml │ │ ├── option-port.xml │ │ ├── option-property.xml │ │ ├── option-protocol-version.xml │ │ ├── option-proxy.xml │ │ ├── option-qos-incoming.xml │ │ ├── option-quiet.xml │ │ ├── option-retain-handling.xml │ │ ├── option-session-expiry-interval.xml │ │ ├── option-srv.xml │ │ ├── option-timeout.xml │ │ ├── option-tls-alpn.xml │ │ ├── option-tls-cafile.xml │ │ ├── option-tls-capath.xml │ │ ├── option-tls-cert.xml │ │ ├── option-tls-ciphers.xml │ │ ├── option-tls-engine-kpass-sha1.xml │ │ ├── option-tls-engine.xml │ │ ├── option-tls-insecure.xml │ │ ├── option-tls-key.xml │ │ ├── option-tls-keyform.xml │ │ ├── option-tls-keylog.xml │ │ ├── option-tls-psk-identity.xml │ │ ├── option-tls-psk.xml │ │ ├── option-tls-use-os-certs.xml │ │ ├── option-tls-version.xml │ │ ├── option-unix-socket.xml │ │ ├── option-url.xml │ │ ├── option-username.xml │ │ ├── option-websockets.xml │ │ ├── option-will-payload.xml │ │ ├── option-will-qos.xml │ │ ├── option-will-retain.xml │ │ ├── option-will-topic.xml │ │ ├── options-intro.xml │ │ ├── section-bugs.xml │ │ ├── section-encrypted-connections.xml │ │ ├── section-exit-status.xml │ │ ├── section-output-format.xml │ │ ├── section-properties-connect.xml │ │ ├── section-properties-disconnect.xml │ │ ├── section-properties-publish.xml │ │ ├── section-properties-subscribe.xml │ │ ├── section-properties-unsubscribe.xml │ │ ├── section-properties-will.xml │ │ ├── section-wills.xml │ │ ├── synopsis-tls-certificate-options.xml │ │ ├── synopsis-tls-psk-options.xml │ │ ├── synopsis-will.xml │ │ └── version-2.1.xml │ ├── html.xsl │ ├── libmosquitto.3.meta │ ├── libmosquitto.3.xml │ ├── manpage.xsl │ ├── mosquitto-tls.7.meta │ ├── mosquitto-tls.7.xml │ ├── mosquitto.7.meta │ ├── mosquitto.7.xml │ ├── mosquitto.8.meta │ ├── mosquitto.8.xml │ ├── mosquitto.conf.5.meta │ ├── mosquitto.conf.5.xml │ ├── mosquitto_ctrl.1.meta │ ├── mosquitto_ctrl.1.xml │ ├── mosquitto_ctrl_dynsec.1.meta │ ├── mosquitto_ctrl_dynsec.1.xml │ ├── mosquitto_ctrl_shell.1.meta │ ├── mosquitto_ctrl_shell.1.xml │ ├── mosquitto_passwd.1.meta │ ├── mosquitto_passwd.1.xml │ ├── mosquitto_pub.1.meta │ ├── mosquitto_pub.1.xml │ ├── mosquitto_rr.1.meta │ ├── mosquitto_rr.1.xml │ ├── mosquitto_signal.1.meta │ ├── mosquitto_signal.1.xml │ ├── mosquitto_sub.1.meta │ ├── mosquitto_sub.1.xml │ ├── mqtt.7.meta │ └── mqtt.7.xml ├── misc/ │ ├── currentcost/ │ │ ├── cc128_log_mysql.pl │ │ ├── cc128_parse.pl │ │ ├── cc128_read.pl │ │ ├── cc128_read.py │ │ └── gnome-panel/ │ │ ├── CurrentCostMQTT.py │ │ └── CurrentCostMQTT.server │ └── letsencrypt/ │ └── mosquitto-copy.sh ├── mosquitto.conf ├── plugins/ │ ├── CMakeLists.txt │ ├── Makefile │ ├── README.md │ ├── acl-file/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── acl_check.c │ │ ├── acl_parse.c │ │ ├── plugin.c │ │ ├── test.conf │ │ └── test.sh │ ├── dynamic-security/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── README.md │ │ ├── acl.c │ │ ├── auth.c │ │ ├── clientlist.c │ │ ├── clients.c │ │ ├── config.c │ │ ├── config_init.c │ │ ├── control.c │ │ ├── default_acl.c │ │ ├── details.c │ │ ├── dynamic_security.h │ │ ├── grouplist.c │ │ ├── groups.c │ │ ├── kicklist.c │ │ ├── migrate_to_dynsec.py │ │ ├── plugin.c │ │ ├── rolelist.c │ │ ├── roles.c │ │ ├── test.conf │ │ ├── test.sh │ │ └── tick.c │ ├── examples/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── add-properties/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_add_properties.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── auth-by-env/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ └── mosquitto_auth_by_env.c │ │ ├── auth-by-ip/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_auth_by_ip.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── client-lifetime-stats/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_client_lifetime_stats.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── client-properties/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_client_properties.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── connection-state/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_connection_state.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── delayed-auth/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_delayed_auth.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── deny-protocol-version/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_deny_protocol_version.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── force-retain/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_force_retain.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── limit-subscription-qos/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_limit_subscription_qos.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── message-timestamp/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_message_timestamp.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── payload-ban/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_payload_ban.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── payload-modification/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_payload_modification.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── payload-size-stats/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_payload_size_stats.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── plugin-event-stats/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_plugin_event_stats.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── print-ip-on-publish/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_print_ip_on_publish.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── tick-interval/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_tick_interval.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── topic-hierarchy-flatten/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_topic_hierarchy_flatten.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── topic-jail/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_topic_jail.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ ├── topic-modification/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosquitto_topic_modification.c │ │ │ ├── test.conf │ │ │ └── test.sh │ │ └── wildcard-temp/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── mosquitto_wildcard_temp.c │ │ ├── test.conf │ │ └── test.sh │ ├── password-file/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── password_check.c │ │ ├── password_parse.c │ │ ├── plugin.c │ │ ├── test.conf │ │ ├── test.pwfile │ │ └── test.sh │ ├── persist-sqlite/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── base_msgs.c │ │ ├── client_msgs.c │ │ ├── clients.c │ │ ├── common.c │ │ ├── init.c │ │ ├── migrate_to_persist_sqlite.py │ │ ├── persist_sqlite.h │ │ ├── plugin.c │ │ ├── restore.c │ │ ├── retain_msgs.c │ │ ├── subscriptions.c │ │ ├── test.conf │ │ ├── test.sh │ │ ├── tick.c │ │ ├── util.h │ │ └── will.c │ ├── plugin.mk │ └── sparkplug-aware/ │ ├── CMakeLists.txt │ ├── Makefile │ ├── README.md │ ├── on_message.c │ ├── plugin.c │ ├── plugin_global.h │ ├── test.conf │ └── test.sh ├── pskfile.example ├── pwfile.example ├── run_tests.py ├── security/ │ └── mosquitto.apparmor ├── service/ │ ├── monit/ │ │ └── mosquitto.monit │ ├── svscan/ │ │ └── run │ ├── systemd/ │ │ ├── README │ │ ├── mosquitto.service.notify │ │ └── mosquitto.service.simple │ └── upstart/ │ └── mosquitto.conf ├── set-version.sh ├── snap/ │ ├── local/ │ │ ├── default_config.conf │ │ └── launcher.sh │ └── snapcraft.yaml ├── src/ │ ├── CMakeLists.txt │ ├── Makefile │ ├── acl_file.c │ ├── acl_file.h │ ├── bridge.c │ ├── bridge_topic.c │ ├── broker_control.c │ ├── conf.c │ ├── conf_includedir.c │ ├── context.c │ ├── control.c │ ├── control_common.c │ ├── database.c │ ├── handle_auth.c │ ├── handle_connack.c │ ├── handle_connect.c │ ├── handle_disconnect.c │ ├── handle_publish.c │ ├── handle_subscribe.c │ ├── handle_unsubscribe.c │ ├── http_api.c │ ├── http_serv.c │ ├── keepalive.c │ ├── linker-aix.syms │ ├── linker-macosx.syms │ ├── linker.syms │ ├── listeners.c │ ├── logging.c │ ├── loop.c │ ├── mosquitto.c │ ├── mosquitto_broker_internal.h │ ├── mux.c │ ├── mux.h │ ├── mux_epoll.c │ ├── mux_kqueue.c │ ├── mux_poll.c │ ├── net.c │ ├── password_file.c │ ├── password_file.h │ ├── persist.h │ ├── persist_read.c │ ├── persist_read_v234.c │ ├── persist_read_v5.c │ ├── persist_write.c │ ├── persist_write_v5.c │ ├── plugin_acl_check.c │ ├── plugin_basic_auth.c │ ├── plugin_callbacks.c │ ├── plugin_cleanup.c │ ├── plugin_client_offline.c │ ├── plugin_connect.c │ ├── plugin_disconnect.c │ ├── plugin_extended_auth.c │ ├── plugin_init.c │ ├── plugin_message.c │ ├── plugin_persist.c │ ├── plugin_psk_key.c │ ├── plugin_public.c │ ├── plugin_reload.c │ ├── plugin_subscribe.c │ ├── plugin_tick.c │ ├── plugin_unsubscribe.c │ ├── plugin_v2.c │ ├── plugin_v3.c │ ├── plugin_v4.c │ ├── plugin_v5.c │ ├── property_broker.c │ ├── proxy_v1.c │ ├── proxy_v2.c │ ├── psk_file.c │ ├── read_handle.c │ ├── retain.c │ ├── security_default.c │ ├── send_auth.c │ ├── send_connack.c │ ├── send_suback.c │ ├── send_unsuback.c │ ├── service.c │ ├── session_expiry.c │ ├── signals.c │ ├── subs.c │ ├── sys_tree.c │ ├── sys_tree.h │ ├── topic_tok.c │ ├── watchdog.c │ ├── websockets.c │ ├── will_delay.c │ └── xtreport.c ├── test/ │ ├── CMakeLists.txt │ ├── Makefile │ ├── __init__.py │ ├── apps/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── TODO.md │ │ ├── ctrl/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── ctrl-args.py │ │ │ ├── ctrl-broker.py │ │ │ ├── ctrl-dynsec.py │ │ │ ├── ctrl_shell_broker_test.cpp │ │ │ ├── ctrl_shell_completion_test.cpp │ │ │ ├── ctrl_shell_dynsec_test.cpp │ │ │ ├── ctrl_shell_help_test.cpp │ │ │ ├── ctrl_shell_options_test.cpp │ │ │ ├── ctrl_shell_pre_connect_test.cpp │ │ │ ├── ctrl_shell_test.cpp │ │ │ ├── mosq_test_helper.py │ │ │ └── test.py │ │ ├── db_dump/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── data/ │ │ │ │ ├── bad-chunk.test-db │ │ │ │ ├── bad-dbid-size.test-db │ │ │ │ ├── bad-magic.test-db │ │ │ │ ├── short.test-db │ │ │ │ ├── v3-corrupt.test-db │ │ │ │ ├── v3-empty.test-db │ │ │ │ ├── v4-corrupt.test-db │ │ │ │ ├── v4-empty.test-db │ │ │ │ ├── v4-single-client.test-db │ │ │ │ ├── v4-single-cmsg.test-db │ │ │ │ ├── v4-single-retain.test-db │ │ │ │ ├── v4-single-sub.test-db │ │ │ │ ├── v5-corrupt.test-db │ │ │ │ ├── v5-empty.test-db │ │ │ │ ├── v6-corrupt-client.test-db │ │ │ │ ├── v6-corrupt-cmsg.test-db │ │ │ │ ├── v6-corrupt-retain.test-db │ │ │ │ ├── v6-corrupt-sub.test-db │ │ │ │ ├── v6-corrupt.test-db │ │ │ │ ├── v6-empty.test-db │ │ │ │ ├── v6-mqtt-v5-props.test-db │ │ │ │ ├── v6-single-all.test-db │ │ │ │ ├── v6-single-client.test-db │ │ │ │ ├── v6-single-cmsg.test-db │ │ │ │ ├── v6-single-retain.test-db │ │ │ │ └── v6-single-sub.test-db │ │ │ ├── db-dump-client-stats.py │ │ │ ├── db-dump-corrupt.py │ │ │ ├── db-dump-json-v6-mqtt-v5-props.py │ │ │ ├── db-dump-print-empty.py │ │ │ ├── db-dump-print-v6-all.py │ │ │ ├── db-dump-print-v6-mqtt-v5-props.py │ │ │ ├── db-dump-stats-current.py │ │ │ ├── db-dump-stats.py │ │ │ ├── mosq_test_helper.py │ │ │ └── test.py │ │ ├── mosq_test_helper.py │ │ ├── passwd/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── mosq_test_helper.py │ │ │ ├── passwd-args.py │ │ │ ├── passwd-changes.py │ │ │ ├── passwd-stdout.py │ │ │ └── test.py │ │ └── signal/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── mosq_test_helper.py │ │ ├── signal-args.py │ │ └── test.py │ ├── broker/ │ │ ├── 01-bad-initial-packets.py │ │ ├── 01-connect-575314.py │ │ ├── 01-connect-accept-protocol.py │ │ ├── 01-connect-allow-anonymous.py │ │ ├── 01-connect-auto-id.py │ │ ├── 01-connect-disconnect-v5.py │ │ ├── 01-connect-global-max-clients.py │ │ ├── 01-connect-global-max-connections.py │ │ ├── 01-connect-listener-allow-anonymous.py │ │ ├── 01-connect-max-connections.py │ │ ├── 01-connect-max-keepalive.py │ │ ├── 01-connect-take-over.py │ │ ├── 01-connect-uname-no-password-denied.pwfile │ │ ├── 01-connect-uname-no-password-denied.py │ │ ├── 01-connect-uname-or-anon.pwfile │ │ ├── 01-connect-uname-or-anon.py │ │ ├── 01-connect-uname-password-denied-no-will.py │ │ ├── 01-connect-uname-password-denied.pwfile │ │ ├── 01-connect-uname-password-denied.py │ │ ├── 01-connect-uname-password-success-no-tls.pwfile │ │ ├── 01-connect-uname-password-success-no-tls.py │ │ ├── 01-connect-unix-socket.py │ │ ├── 01-connect-windows-line-endings.py │ │ ├── 01-connect-zero-length-id.py │ │ ├── 01-plugin-connect-uname-password-denied.pwfile │ │ ├── 01-plugin-connect-uname-password-denied.py │ │ ├── 02-shared-nolocal.py │ │ ├── 02-shared-qos0-v5.py │ │ ├── 02-subhier-crash.py │ │ ├── 02-subpub-b2c-topic-alias.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-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-max-inflight-bytes.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-subpub-recover-subscriptions.py │ │ ├── 02-subscribe-dollar-v5.py │ │ ├── 02-subscribe-invalid-utf8.py │ │ ├── 02-subscribe-long-topic.py │ │ ├── 02-subscribe-persistence-flipflop.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-bad-flags.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-max-inflight.py │ │ ├── 03-publish-qos1-no-subscribers-v5.py │ │ ├── 03-publish-qos1-queued-bytes.conf │ │ ├── 03-publish-qos1-queued-bytes.py │ │ ├── 03-publish-qos1-retain-disabled.py │ │ ├── 03-publish-qos1.py │ │ ├── 03-publish-qos2-dup.py │ │ ├── 03-publish-qos2-max-inflight-exceeded.py │ │ ├── 03-publish-qos2-max-inflight.py │ │ ├── 03-publish-qos2-reuse-mid.py │ │ ├── 03-publish-qos2.py │ │ ├── 04-retain-check-source-persist-diff-port.py │ │ ├── 04-retain-check-source-persist.py │ │ ├── 04-retain-check-source.py │ │ ├── 04-retain-clear-multiple.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-clean-session-qos1.py │ │ ├── 05-session-expiry-kick.py │ │ ├── 05-session-expiry-v5.py │ │ ├── 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-core.py │ │ ├── 06-bridge-clean-session-csF-lcsF.py │ │ ├── 06-bridge-clean-session-csF-lcsN.py │ │ ├── 06-bridge-clean-session-csF-lcsT.py │ │ ├── 06-bridge-clean-session-csT-lcsF.py │ │ ├── 06-bridge-clean-session-csT-lcsN.py │ │ ├── 06-bridge-clean-session-csT-lcsT.py │ │ ├── 06-bridge-config-reload.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 │ │ ├── 06-bridge-remap-receive-wildcard.py │ │ ├── 06-bridge-remote-shutdown.py │ │ ├── 07-will-control.py │ │ ├── 07-will-delay-invalid-573191.py │ │ ├── 07-will-delay-reconnect.py │ │ ├── 07-will-delay-recover.py │ │ ├── 07-will-delay-session-expiry-0.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-per-listener.py │ │ ├── 07-will-properties.py │ │ ├── 07-will-qos0.py │ │ ├── 07-will-reconnect-1273.py │ │ ├── 07-will-takeover.py │ │ ├── 08-ssl-bridge-helper.py │ │ ├── 08-ssl-bridge.py │ │ ├── 08-ssl-connect-cert-auth-crl.py │ │ ├── 08-ssl-connect-cert-auth-expired-allowed.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-dhparam.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 │ │ ├── 08-tls-psk-bridge.psk │ │ ├── 08-tls-psk-bridge.py │ │ ├── 08-tls-psk-pub.psk │ │ ├── 08-tls-psk-pub.py │ │ ├── 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-reauth.py │ │ ├── 09-extended-auth-single.py │ │ ├── 09-extended-auth-single2.py │ │ ├── 09-plugin-acl-access-variants.py │ │ ├── 09-plugin-acl-change.py │ │ ├── 09-plugin-auth-acl-pub-prop.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-auth-v3-unpwd-fail.py │ │ ├── 09-plugin-auth-v3-unpwd-success.py │ │ ├── 09-plugin-auth-v4-unpwd-fail.py │ │ ├── 09-plugin-auth-v4-unpwd-success.py │ │ ├── 09-plugin-auth-v5-unpwd-fail.py │ │ ├── 09-plugin-auth-v5-unpwd-success.py │ │ ├── 09-plugin-bad.py │ │ ├── 09-plugin-change-id.py │ │ ├── 09-plugin-delayed-auth.py │ │ ├── 09-plugin-evt-client-offline.py │ │ ├── 09-plugin-evt-message-in.py │ │ ├── 09-plugin-evt-message-out.py │ │ ├── 09-plugin-evt-psk-key.py │ │ ├── 09-plugin-evt-reload.py │ │ ├── 09-plugin-evt-subscribe.py │ │ ├── 09-plugin-evt-tick.py │ │ ├── 09-plugin-evt-unsubscribe.py │ │ ├── 09-plugin-load-acl.py │ │ ├── 09-plugin-load-basic-auth.py │ │ ├── 09-plugin-load-extended-auth.py │ │ ├── 09-plugin-publish.py │ │ ├── 09-plugin-unsupported.py │ │ ├── 09-pwfile-parse-invalid.py │ │ ├── 10-listener-mount-point.py │ │ ├── 11-message-expiry.py │ │ ├── 11-persistence-autosave-changes.py │ │ ├── 11-persistent-subscription-no-local.py │ │ ├── 11-persistent-subscription.py │ │ ├── 11-pub-props.py │ │ ├── 11-subscription-id.py │ │ ├── 12-prop-assigned-client-identifier.py │ │ ├── 12-prop-maximum-packet-size-broker.py │ │ ├── 12-prop-maximum-packet-size-publish-qos1.py │ │ ├── 12-prop-maximum-packet-size-publish-qos2.py │ │ ├── 12-prop-response-topic-correlation-data.py │ │ ├── 12-prop-response-topic.py │ │ ├── 12-prop-server-keepalive.py │ │ ├── 12-prop-subpub-content-type.py │ │ ├── 12-prop-subpub-payload-format.py │ │ ├── 13-websocket-bad-origin.py │ │ ├── 14-dynsec-acl.py │ │ ├── 14-dynsec-allow-wildcard.py │ │ ├── 14-dynsec-anon-group.py │ │ ├── 14-dynsec-auth.py │ │ ├── 14-dynsec-client-invalid.py │ │ ├── 14-dynsec-client.py │ │ ├── 14-dynsec-config-init-env.py │ │ ├── 14-dynsec-config-init-file.py │ │ ├── 14-dynsec-config-init-random.py │ │ ├── 14-dynsec-default-access.py │ │ ├── 14-dynsec-disable-client.py │ │ ├── 14-dynsec-group-invalid.py │ │ ├── 14-dynsec-group.py │ │ ├── 14-dynsec-modify-client.py │ │ ├── 14-dynsec-modify-group.py │ │ ├── 14-dynsec-modify-role.py │ │ ├── 14-dynsec-plugin-invalid.py │ │ ├── 14-dynsec-role-invalid.py │ │ ├── 14-dynsec-role.py │ │ ├── 15-persist-bridge-queue.py │ │ ├── 15-persist-client-drop-expired-messages.py │ │ ├── 15-persist-client-expired-session.py │ │ ├── 15-persist-client-msg-in-v3-1-1.py │ │ ├── 15-persist-client-msg-in-v5-0.py │ │ ├── 15-persist-client-msg-modify-acl.py │ │ ├── 15-persist-client-msg-out-clear-v3-1-1.py │ │ ├── 15-persist-client-msg-out-dup-v3-1-1.py │ │ ├── 15-persist-client-msg-out-queue-v3-1-1.py │ │ ├── 15-persist-client-msg-out-v3-1-1-db.py │ │ ├── 15-persist-client-msg-out-v3-1-1.py │ │ ├── 15-persist-client-msg-out-v5-0.py │ │ ├── 15-persist-client-v3-1-1.py │ │ ├── 15-persist-client-v5-0.py │ │ ├── 15-persist-client-will.py │ │ ├── 15-persist-migrate-db.py │ │ ├── 15-persist-publish-properties-v5-0.py │ │ ├── 15-persist-retain-clear.py │ │ ├── 15-persist-retain-v3-1-1.py │ │ ├── 15-persist-retain-v5-0.py │ │ ├── 15-persist-subscription-v3-1-1.py │ │ ├── 15-persist-subscription-v5-0.py │ │ ├── 16-cmd-args.py │ │ ├── 16-config-huge.py │ │ ├── 16-config-includedir.py │ │ ├── 16-config-missing.py │ │ ├── 16-config-parse-errors-tls-psk.py │ │ ├── 16-config-parse-errors-tls.py │ │ ├── 16-config-parse-errors-without-tls.py │ │ ├── 17-control-list-listeners.py │ │ ├── 17-control-list-plugins.py │ │ ├── 17-control-missing-endpoint.py │ │ ├── 20-sparkplug-aware.py │ │ ├── 20-sparkplug-compliance.py │ │ ├── 21-proxy-bad-version.py │ │ ├── 21-proxy-v1-bad.py │ │ ├── 21-proxy-v1-success.py │ │ ├── 21-proxy-v2-bad-config.py │ │ ├── 21-proxy-v2-bad-header.py │ │ ├── 21-proxy-v2-ipv4.py │ │ ├── 21-proxy-v2-ipv6.py │ │ ├── 21-proxy-v2-local.py │ │ ├── 21-proxy-v2-long-tlv.py │ │ ├── 21-proxy-v2-lost-connection.py │ │ ├── 21-proxy-v2-ssl-cipher.py │ │ ├── 21-proxy-v2-ssl-common-name-failure.py │ │ ├── 21-proxy-v2-ssl-common-name-success.py │ │ ├── 21-proxy-v2-ssl-require-cert-failure.py │ │ ├── 21-proxy-v2-ssl-require-cert-success.py │ │ ├── 21-proxy-v2-ssl-require-tls-failure.py │ │ ├── 21-proxy-v2-ssl-require-tls-success.py │ │ ├── 21-proxy-v2-unix.py │ │ ├── 21-proxy-v2-websockets.py │ │ ├── 22-http-api-acl.py │ │ ├── 22-http-api-api.py │ │ ├── 22-http-api-auth.pwfile │ │ ├── 22-http-api-auth.py │ │ ├── 22-http-api-file.py │ │ ├── 22-http-api-tls.py │ │ ├── 23-security-acl-file-reload.py │ │ ├── 23-security-password-file-reload.py │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── c/ │ │ │ ├── 08-tls-psk-bridge.c │ │ │ ├── 08-tls-psk-pub.c │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── auth_plugin_acl.c │ │ │ ├── auth_plugin_acl_change.c │ │ │ ├── auth_plugin_acl_sub_denied.c │ │ │ ├── auth_plugin_context_params.c │ │ │ ├── auth_plugin_delayed.c │ │ │ ├── auth_plugin_extended_multiple.c │ │ │ ├── auth_plugin_extended_reauth.c │ │ │ ├── auth_plugin_extended_single.c │ │ │ ├── auth_plugin_extended_single2.c │ │ │ ├── auth_plugin_id_change.c │ │ │ ├── auth_plugin_msg_params.c │ │ │ ├── auth_plugin_publish.c │ │ │ ├── auth_plugin_pwd.c │ │ │ ├── auth_plugin_v2.c │ │ │ ├── auth_plugin_v3.c │ │ │ ├── auth_plugin_v4.c │ │ │ ├── auth_plugin_v5.c │ │ │ ├── auth_plugin_v5_control.c │ │ │ ├── bad_v1.c │ │ │ ├── bad_v2_1.c │ │ │ ├── bad_v2_2.c │ │ │ ├── bad_v2_3.c │ │ │ ├── bad_v2_4.c │ │ │ ├── bad_v2_5.c │ │ │ ├── bad_v2_6.c │ │ │ ├── bad_v2_7.c │ │ │ ├── bad_v3_1.c │ │ │ ├── bad_v3_2.c │ │ │ ├── bad_v3_3.c │ │ │ ├── bad_v3_4.c │ │ │ ├── bad_v3_5.c │ │ │ ├── bad_v3_6.c │ │ │ ├── bad_v3_7.c │ │ │ ├── bad_v4_1.c │ │ │ ├── bad_v4_2.c │ │ │ ├── bad_v4_3.c │ │ │ ├── bad_v4_4.c │ │ │ ├── bad_v5_1.c │ │ │ ├── bad_v6.c │ │ │ ├── bad_vnone_1.c │ │ │ ├── kick_last_client.c │ │ │ ├── mosquitto_plugin_v2.h │ │ │ ├── plugin_control.c │ │ │ ├── plugin_evt_client_offline.c │ │ │ ├── plugin_evt_message_in.c │ │ │ ├── plugin_evt_message_out.c │ │ │ ├── plugin_evt_persist_client_update.c │ │ │ ├── plugin_evt_psk_key.c │ │ │ ├── plugin_evt_reload.c │ │ │ ├── plugin_evt_subscribe.c │ │ │ ├── plugin_evt_tick.c │ │ │ ├── plugin_evt_unsubscribe.c │ │ │ ├── plugin_load_acl.c │ │ │ └── plugin_load_extended_auth.c │ │ ├── data/ │ │ │ ├── AUTH.json │ │ │ ├── CONNACK.json │ │ │ ├── CONNECT.json │ │ │ ├── DISCONNECT.json │ │ │ ├── FLOW.json │ │ │ ├── FORBIDDEN.json │ │ │ ├── PINGREQ.json │ │ │ ├── PINGRESP.json │ │ │ ├── PUBACK.json │ │ │ ├── PUBCOMP.json │ │ │ ├── PUBLISH.json │ │ │ ├── PUBREC.json │ │ │ ├── PUBREL.json │ │ │ ├── REGRESSION.json │ │ │ ├── SUBACK.json │ │ │ ├── SUBSCRIBE.json │ │ │ ├── UNSUBACK.json │ │ │ ├── UNSUBSCRIBE.json │ │ │ └── ZZ-broker-check.json │ │ ├── dynamic-security-init.json │ │ ├── dynsec_helper.py │ │ ├── mosq_test_helper.py │ │ ├── msg_sequence_test.py │ │ ├── ntest.py │ │ ├── persist_module_helper.py │ │ ├── persist_sqlite.py │ │ ├── prop_subpub_helper.py │ │ ├── proxy_helper.py │ │ ├── readme.txt │ │ ├── test.py │ │ └── test.supp │ ├── client/ │ │ ├── 02-subscribe-argv-errors-tls-psk.py │ │ ├── 02-subscribe-argv-errors-tls.py │ │ ├── 02-subscribe-argv-errors-without-tls.py │ │ ├── 02-subscribe-env.py │ │ ├── 02-subscribe-filter-out.py │ │ ├── 02-subscribe-format-json-properties.py │ │ ├── 02-subscribe-format-json-qos0.py │ │ ├── 02-subscribe-format-json-qos1.py │ │ ├── 02-subscribe-format-json-retain.py │ │ ├── 02-subscribe-format.py │ │ ├── 02-subscribe-null.py │ │ ├── 02-subscribe-qos1-ws.py │ │ ├── 02-subscribe-qos1.py │ │ ├── 02-subscribe-retain-handling.py │ │ ├── 02-subscribe-verbose.py │ │ ├── 03-publish-argv-errors-tls-psk.py │ │ ├── 03-publish-argv-errors-tls.py │ │ ├── 03-publish-argv-errors-without-tls.py │ │ ├── 03-publish-env.py │ │ ├── 03-publish-file-empty.py │ │ ├── 03-publish-file.py │ │ ├── 03-publish-options-file.py │ │ ├── 03-publish-qos0-empty.py │ │ ├── 03-publish-qos1-properties.py │ │ ├── 03-publish-qos1-ws-large.py │ │ ├── 03-publish-qos1-ws.py │ │ ├── 03-publish-qos1.py │ │ ├── 03-publish-repeat.py │ │ ├── 03-publish-socks-auth-failed.py │ │ ├── 03-publish-socks-no-auth.py │ │ ├── 03-publish-socks.py │ │ ├── 03-publish-stdin-file.py │ │ ├── 03-publish-stdin-line.py │ │ ├── 03-publish-tls.py │ │ ├── 03-publish-url.py │ │ ├── 04-rr-argv-errors-tls-psk.py │ │ ├── 04-rr-argv-errors-tls.py │ │ ├── 04-rr-argv-errors-without-tls.py │ │ ├── 04-rr-env.py │ │ ├── 04-rr-qos1-ws.py │ │ ├── 04-rr-qos1.py │ │ ├── 04-rr-retain-handling.py │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── data/ │ │ │ └── .config/ │ │ │ ├── mosquitto_pub │ │ │ └── mosquitto_sub │ │ ├── mosq_test_helper.py │ │ ├── test-ws.sh │ │ ├── test.py │ │ ├── test.sh │ │ └── ws.conf │ ├── lib/ │ │ ├── 01-con-discon-success-v5.py │ │ ├── 01-con-discon-success.py │ │ ├── 01-con-discon-will-clear.py │ │ ├── 01-con-discon-will-v5.py │ │ ├── 01-con-discon-will.py │ │ ├── 01-extended-auth-continue.py │ │ ├── 01-extended-auth-failure.py │ │ ├── 01-keepalive-pingreq.py │ │ ├── 01-no-clean-session.py │ │ ├── 01-pre-connect-callback.py │ │ ├── 01-server-keepalive-pingreq.py │ │ ├── 01-unpwd-set.py │ │ ├── 01-will-set.py │ │ ├── 01-will-unpwd-set.py │ │ ├── 02-subscribe-helper-qos2.py │ │ ├── 02-subscribe-qos0.py │ │ ├── 02-subscribe-qos1.py │ │ ├── 02-subscribe-qos2.py │ │ ├── 02-unsubscribe-multiple-v5.py │ │ ├── 02-unsubscribe-v5.py │ │ ├── 02-unsubscribe.py │ │ ├── 03-publish-b2c-qos1-unexpected-puback.py │ │ ├── 03-publish-b2c-qos1.py │ │ ├── 03-publish-b2c-qos2-len.py │ │ ├── 03-publish-b2c-qos2-unexpected-pubcomp.py │ │ ├── 03-publish-b2c-qos2-unexpected-pubrel.py │ │ ├── 03-publish-b2c-qos2.py │ │ ├── 03-publish-c2b-qos1-disconnect.py │ │ ├── 03-publish-c2b-qos1-len.py │ │ ├── 03-publish-c2b-qos1-receive-maximum.py │ │ ├── 03-publish-c2b-qos2-disconnect.py │ │ ├── 03-publish-c2b-qos2-len.py │ │ ├── 03-publish-c2b-qos2-maximum-qos-0.py │ │ ├── 03-publish-c2b-qos2-maximum-qos-1.py │ │ ├── 03-publish-c2b-qos2-pubrec-error.py │ │ ├── 03-publish-c2b-qos2-receive-maximum-1.py │ │ ├── 03-publish-c2b-qos2-receive-maximum-2.py │ │ ├── 03-publish-c2b-qos2.py │ │ ├── 03-publish-loop.py │ │ ├── 03-publish-qos0-no-payload.py │ │ ├── 03-publish-qos0.py │ │ ├── 03-request-response-correlation.py │ │ ├── 03-request-response.py │ │ ├── 04-retain-qos0.py │ │ ├── 08-ssl-bad-cacert.py │ │ ├── 08-ssl-connect-cert-auth-enc.py │ │ ├── 08-ssl-connect-cert-auth.py │ │ ├── 08-ssl-connect-no-auth.py │ │ ├── 08-ssl-connect-san.py │ │ ├── 08-ssl-fake-cacert.py │ │ ├── 09-util-topic-tokenise.py │ │ ├── 11-prop-oversize-packet.py │ │ ├── 11-prop-recv-qos0.py │ │ ├── 11-prop-recv-qos1.py │ │ ├── 11-prop-recv-qos2.py │ │ ├── 11-prop-send-content-type.py │ │ ├── 11-prop-send-payload-format.py │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── c/ │ │ │ ├── 01-con-discon-success-v5.c │ │ │ ├── 01-con-discon-success.c │ │ │ ├── 01-con-discon-will-clear.c │ │ │ ├── 01-con-discon-will-v5.c │ │ │ ├── 01-con-discon-will.c │ │ │ ├── 01-extended-auth-continue.c │ │ │ ├── 01-extended-auth-failure.c │ │ │ ├── 01-keepalive-pingreq.c │ │ │ ├── 01-no-clean-session.c │ │ │ ├── 01-pre-connect-callback.c │ │ │ ├── 01-server-keepalive-pingreq.c │ │ │ ├── 01-unpwd-set.c │ │ │ ├── 01-will-set.c │ │ │ ├── 01-will-unpwd-set.c │ │ │ ├── 02-subscribe-helper-callback-qos2.c │ │ │ ├── 02-subscribe-helper-simple-qos2.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 │ │ │ ├── 02-unsubscribe2-v5.c │ │ │ ├── 03-publish-b2c-qos1-unexpected-puback.c │ │ │ ├── 03-publish-b2c-qos1.c │ │ │ ├── 03-publish-b2c-qos2-len.c │ │ │ ├── 03-publish-b2c-qos2-unexpected-pubcomp.c │ │ │ ├── 03-publish-b2c-qos2-unexpected-pubrel.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.c │ │ │ ├── 03-publish-c2b-qos2.c │ │ │ ├── 03-publish-loop-forever.c │ │ │ ├── 03-publish-loop-manual.c │ │ │ ├── 03-publish-loop-start.c │ │ │ ├── 03-publish-loop.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-custom-ssl-ctx-default.c │ │ │ ├── 08-ssl-connect-cert-auth-custom-ssl-ctx.c │ │ │ ├── 08-ssl-connect-cert-auth-enc.c │ │ │ ├── 08-ssl-connect-cert-auth.c │ │ │ ├── 08-ssl-connect-no-auth.c │ │ │ ├── 08-ssl-connect-san.c │ │ │ ├── 08-ssl-fake-cacert.c │ │ │ ├── 09-util-topic-tokenise.c │ │ │ ├── 11-prop-oversize-packet.c │ │ │ ├── 11-prop-recv.c │ │ │ ├── 11-prop-send-content-type.c │ │ │ ├── 11-prop-send-payload-format.c │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ └── fuzzish.c │ │ ├── cpp/ │ │ │ ├── 01-con-discon-success-v5.cpp │ │ │ ├── 01-con-discon-success.cpp │ │ │ ├── 01-con-discon-will-clear.cpp │ │ │ ├── 01-con-discon-will-v5.cpp │ │ │ ├── 01-con-discon-will.cpp │ │ │ ├── 01-extended-auth-continue.cpp │ │ │ ├── 01-extended-auth-failure.cpp │ │ │ ├── 01-keepalive-pingreq.cpp │ │ │ ├── 01-no-clean-session.cpp │ │ │ ├── 01-pre-connect-callback.cpp │ │ │ ├── 01-server-keepalive-pingreq.cpp │ │ │ ├── 01-unpwd-set.cpp │ │ │ ├── 01-will-set.cpp │ │ │ ├── 01-will-unpwd-set.cpp │ │ │ ├── 02-subscribe-helper-callback-qos2.cpp │ │ │ ├── 02-subscribe-helper-simple-qos2.cpp │ │ │ ├── 02-subscribe-qos0.cpp │ │ │ ├── 02-subscribe-qos1-async1.cpp │ │ │ ├── 02-subscribe-qos1-async2.cpp │ │ │ ├── 02-subscribe-qos1.cpp │ │ │ ├── 02-subscribe-qos2.cpp │ │ │ ├── 02-unsubscribe-v5.cpp │ │ │ ├── 02-unsubscribe.cpp │ │ │ ├── 03-publish-b2c-qos1-unexpected-puback.cpp │ │ │ ├── 03-publish-b2c-qos1.cpp │ │ │ ├── 03-publish-b2c-qos2-len.cpp │ │ │ ├── 03-publish-b2c-qos2-unexpected-pubcomp.cpp │ │ │ ├── 03-publish-b2c-qos2-unexpected-pubrel.cpp │ │ │ ├── 03-publish-b2c-qos2.cpp │ │ │ ├── 03-publish-c2b-qos1-disconnect.cpp │ │ │ ├── 03-publish-c2b-qos1-len.cpp │ │ │ ├── 03-publish-c2b-qos1-receive-maximum.cpp │ │ │ ├── 03-publish-c2b-qos2-disconnect.cpp │ │ │ ├── 03-publish-c2b-qos2-len.cpp │ │ │ ├── 03-publish-c2b-qos2-maximum-qos-0.cpp │ │ │ ├── 03-publish-c2b-qos2-maximum-qos-1.cpp │ │ │ ├── 03-publish-c2b-qos2-pubrec-error.cpp │ │ │ ├── 03-publish-c2b-qos2-receive-maximum.cpp │ │ │ ├── 03-publish-c2b-qos2.cpp │ │ │ ├── 03-publish-loop-forever.cpp │ │ │ ├── 03-publish-loop-manual.cpp │ │ │ ├── 03-publish-loop-start.cpp │ │ │ ├── 03-publish-loop.cpp │ │ │ ├── 03-publish-qos0-no-payload.cpp │ │ │ ├── 03-publish-qos0.cpp │ │ │ ├── 03-request-response-1.cpp │ │ │ ├── 03-request-response-2.cpp │ │ │ ├── 03-request-response-correlation-1.cpp │ │ │ ├── 04-retain-qos0.cpp │ │ │ ├── 08-ssl-bad-cacert.cpp │ │ │ ├── 08-ssl-connect-cert-auth-custom-ssl-ctx-default.cpp │ │ │ ├── 08-ssl-connect-cert-auth-custom-ssl-ctx.cpp │ │ │ ├── 08-ssl-connect-cert-auth-enc.cpp │ │ │ ├── 08-ssl-connect-cert-auth.cpp │ │ │ ├── 08-ssl-connect-no-auth.cpp │ │ │ ├── 08-ssl-connect-san.cpp │ │ │ ├── 08-ssl-fake-cacert.cpp │ │ │ ├── 09-util-topic-tokenise.cpp │ │ │ ├── 11-prop-oversize-packet.cpp │ │ │ ├── 11-prop-recv.cpp │ │ │ ├── 11-prop-send-content-type.cpp │ │ │ ├── 11-prop-send-payload-format.cpp │ │ │ ├── CMakeLists.txt │ │ │ └── Makefile │ │ ├── data/ │ │ │ ├── AUTH.json │ │ │ ├── CONNACK.json │ │ │ ├── CONNECT.json │ │ │ ├── DISCONNECT.json │ │ │ ├── FORBIDDEN.json │ │ │ ├── PINGREQ.json │ │ │ ├── PINGRESP.json │ │ │ ├── PUBACK.json │ │ │ ├── PUBLISH.json │ │ │ ├── PUBREC.json │ │ │ ├── SUBSCRIBE.json │ │ │ ├── UNSUBACK.json │ │ │ └── UNSUBSCRIBE.json │ │ ├── mosq_test_helper.py │ │ ├── msg_sequence_test.py │ │ └── test.py │ ├── mock/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── apps/ │ │ │ ├── CMakeLists.txt │ │ │ └── mosquitto_ctrl/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── ctrl_shell_mock.cpp │ │ │ └── ctrl_shell_mock.hpp │ │ ├── c_function_mock.hpp │ │ ├── editline_mock.cpp │ │ ├── editline_mock.hpp │ │ ├── lib/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── actions_publish_mock.cpp │ │ │ ├── actions_subscribe_mock.cpp │ │ │ ├── actions_unsubscribe_mock.cpp │ │ │ ├── callbacks_mock.cpp │ │ │ ├── connect_mock.cpp │ │ │ ├── extended_auth_mock.cpp │ │ │ ├── helpers_mock.cpp │ │ │ ├── libmosquitto_mock.cpp │ │ │ ├── libmosquitto_mock.hpp │ │ │ ├── loop_mock.cpp │ │ │ ├── messages_mosq_mock.cpp │ │ │ ├── net_mosq_mock.cpp │ │ │ ├── options_mock.cpp │ │ │ ├── socks_mosq_mock.cpp │ │ │ ├── srv_mosq_mock.cpp │ │ │ └── thread_mosq_mock.cpp │ │ ├── libcommon/ │ │ │ ├── CMakeLists.txt │ │ │ ├── Makefile │ │ │ ├── base64_common_mock.cpp │ │ │ ├── cjson_common.cpp │ │ │ ├── file_common_mock.cpp │ │ │ ├── libmosquitto_common_mock.cpp │ │ │ ├── libmosquitto_common_mock.hpp │ │ │ ├── memory_common_mock.cpp │ │ │ ├── mqtt_common_mock.cpp │ │ │ ├── password_common_mock.cpp │ │ │ ├── property_common_mock.cpp │ │ │ ├── random_common_mock.cpp │ │ │ ├── strings_common_mock.cpp │ │ │ ├── time_common_mock.cpp │ │ │ ├── topic_common_mock.cpp │ │ │ └── utf8_common_mock.cpp │ │ ├── pthread_mock.cpp │ │ └── pthread_mock.hpp │ ├── mosq_test.py │ ├── mqtt5_opts.py │ ├── mqtt5_props.py │ ├── mqtt5_rc.py │ ├── old/ │ │ ├── Makefile │ │ ├── msgsps_common.h │ │ ├── msgsps_pub.c │ │ └── msgsps_sub.c │ ├── path_helper.h │ ├── ptest.py │ ├── random/ │ │ ├── Makefile │ │ ├── auth_plugin.c │ │ ├── pwfile │ │ ├── random.conf │ │ ├── random_client.py │ │ └── test.py │ ├── ssl/ │ │ ├── all-ca.crt │ │ ├── client-encrypted.crt │ │ ├── client-encrypted.key │ │ ├── client-expired.crt │ │ ├── client-expired.key │ │ ├── client-revoked.crt │ │ ├── client-revoked.key │ │ ├── client.crt │ │ ├── client.key │ │ ├── crl-empty.pem │ │ ├── crl.pem │ │ ├── dhparam │ │ ├── gen.sh │ │ ├── openssl.cnf │ │ ├── readme.txt │ │ ├── server-expired.crt │ │ ├── server-expired.key │ │ ├── server-san.crt │ │ ├── server-san.key │ │ ├── server.crt │ │ ├── server.key │ │ ├── test-alt-ca.crt │ │ ├── test-alt-ca.key │ │ ├── test-bad-root-ca.crt │ │ ├── test-bad-root-ca.key │ │ ├── test-fake-root-ca.crt │ │ ├── test-fake-root-ca.key │ │ ├── test-root-ca.crt │ │ ├── test-root-ca.key │ │ ├── test-signing-ca.crt │ │ └── test-signing-ca.key │ └── unit/ │ ├── CMakeLists.txt │ ├── Makefile │ ├── broker/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── bridge_topic_test.c │ │ ├── files/ │ │ │ ├── persist_read/ │ │ │ │ ├── corrupt-header-long.test-db │ │ │ │ ├── corrupt-header-short.test-db │ │ │ │ ├── empty.test-db │ │ │ │ ├── unsupported-version.test-db │ │ │ │ ├── v3-bad-chunk.test-db │ │ │ │ ├── v3-cfg-bad-dbid.test-db │ │ │ │ ├── v3-cfg-truncated.test-db │ │ │ │ ├── v3-cfg.test-db │ │ │ │ ├── v3-client-message.test-db │ │ │ │ ├── v3-client.test-db │ │ │ │ ├── v3-message-store.test-db │ │ │ │ ├── v3-retain.test-db │ │ │ │ ├── v3-sub.test-db │ │ │ │ ├── v4-cfg.test-db │ │ │ │ ├── v4-message-store.test-db │ │ │ │ ├── v5-bad-chunk.test-db │ │ │ │ ├── v5-cfg-truncated.test-db │ │ │ │ ├── v5-client.test-db │ │ │ │ ├── v6-base-msg-topic-0.test-db │ │ │ │ ├── v6-cfg.test-db │ │ │ │ ├── v6-client-message-props.test-db │ │ │ │ ├── v6-client-message.test-db │ │ │ │ ├── v6-client.test-db │ │ │ │ ├── v6-message-store-props.test-db │ │ │ │ ├── v6-message-store.test-db │ │ │ │ ├── v6-retain.test-db │ │ │ │ └── v6-sub.test-db │ │ │ └── persist_write/ │ │ │ ├── empty.test-db │ │ │ ├── v4-full.test-db │ │ │ └── v6-message-store-no-ref.test-db │ │ ├── keepalive_stubs.c │ │ ├── keepalive_test.c │ │ ├── persist_read_stubs.c │ │ ├── persist_read_test.c │ │ ├── persist_write_stubs.c │ │ ├── persist_write_test.c │ │ ├── stubs.c │ │ ├── subs_stubs.c │ │ └── subs_test.c │ ├── lib/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── datatype_read.c │ │ ├── datatype_write.c │ │ ├── property_read.c │ │ ├── property_user_read.c │ │ ├── property_write.c │ │ ├── publish_test.c │ │ ├── stubs.c │ │ └── test.c │ ├── libcommon/ │ │ ├── CMakeLists.txt │ │ ├── Makefile │ │ ├── base64_test.c │ │ ├── file_test.c │ │ ├── property_add.c │ │ ├── property_value.c │ │ ├── strings_test.c │ │ ├── test.c │ │ ├── topic_test.c │ │ ├── trim_test.c │ │ └── utf8.c │ ├── tls_stubs.c │ └── tls_test.c ├── vcpkg.json └── www/ ├── README.md ├── conf.py ├── files/ │ ├── manifest.json │ └── stickers/ │ └── index.html ├── pages/ │ ├── documentation/ │ │ ├── authentication-methods.md │ │ ├── dynamic-security.md │ │ ├── listeners/ │ │ │ ├── haproxy.md │ │ │ └── per_listener_settings.md │ │ ├── migrating-to-2-0.md │ │ ├── persistence/ │ │ │ └── sqlite.md │ │ ├── plugins/ │ │ │ ├── acl-file.md │ │ │ ├── password-file.md │ │ │ └── sparkplug-aware.md │ │ └── using-the-snap.md │ ├── documentation.md │ ├── download.md │ ├── index.html │ ├── roadmap.md │ └── security.md ├── plugins/ │ ├── __init__.py │ └── docbookmanpage/ │ ├── docbookmanpage.plugin │ ├── docbookmanpage.py │ └── html.xsl ├── posts/ │ ├── 2009/ │ │ └── 12/ │ │ ├── version-0-2-released.md │ │ └── version-0-3-released.md │ ├── 2010/ │ │ ├── 01/ │ │ │ ├── mailing-list-irc.md │ │ │ ├── version-0-4-1-released.md │ │ │ └── version-0-4-released.md │ │ ├── 02/ │ │ │ └── version-0-4-2-released.md │ │ ├── 03/ │ │ │ ├── google-powermeter.md │ │ │ ├── upgrading-to-0-5-1.md │ │ │ ├── version-0-5-1-released.md │ │ │ ├── version-0-5-2-released.md │ │ │ ├── version-0-5-3-released.md │ │ │ └── version-0-5-4-released.md │ │ ├── 04/ │ │ │ ├── help-wanted-rpm-packaging.md │ │ │ ├── mind-control-mqtt.md │ │ │ └── oggcamp.md │ │ ├── 05/ │ │ │ ├── fedora-packages-available.md │ │ │ ├── gentoo-ebuilds-available.md │ │ │ ├── mosquitto-org.md │ │ │ ├── mqtt-push-on-android.md │ │ │ ├── mqtt-wiki.md │ │ │ ├── version-0-6-1-released.md │ │ │ └── version-0-6-released.md │ │ ├── 06/ │ │ │ ├── automation-has-the-oven-warmed-up-yet.md │ │ │ ├── google-powermeter-step-by-step.attachments.json │ │ │ ├── google-powermeter-step-by-step.md │ │ │ ├── mosquitto-0-7rc1.md │ │ │ └── version-0-7-released.md │ │ ├── 07/ │ │ │ ├── mosquitto-on-opensuse-11-3.md │ │ │ └── mqtt-client-library.md │ │ ├── 08/ │ │ │ ├── compiling-mosquitto-on-mac-os-x.md │ │ │ ├── mosquitto-running-on-mac-os-x.md │ │ │ ├── mqtt-v3-1.md │ │ │ ├── version-0-8-1-released.md │ │ │ ├── version-0-8-2.md │ │ │ └── version-0-8-released.md │ │ ├── 09/ │ │ │ ├── debian-packages.md │ │ │ └── mqtt-with-php.md │ │ ├── 10/ │ │ │ ├── man-page-translations.md │ │ │ ├── one-year-old.md │ │ │ └── version-0-8-3-released.md │ │ ├── 11/ │ │ │ ├── distro-packaging.md │ │ │ ├── mosquitto-0-9test2.md │ │ │ └── version-0-9-released.md │ │ └── 12/ │ │ └── version-0-9-1-released.md │ ├── 2011/ │ │ ├── 01/ │ │ │ ├── mosquitto-for-slackware.md │ │ │ └── mqtt-news.md │ │ ├── 02/ │ │ │ ├── lightweight-messaging-and-linux.md │ │ │ ├── mosquitto-on-maemo.md │ │ │ ├── mqtt-on-android.md │ │ │ └── version-0-9-2-released.md │ │ ├── 03/ │ │ │ ├── api-documentation.md │ │ │ ├── mosquitto-in-mac-homebrew.md │ │ │ └── version-0-9-3-released.md │ │ ├── 04/ │ │ │ └── version-0-10-released.md │ │ ├── 05/ │ │ │ ├── mqtt-ontology.md │ │ │ └── version-0-10-1-released.md │ │ ├── 06/ │ │ │ ├── nanode-a-cheap-networked-arduino-clone.md │ │ │ ├── version-0-10-2-released.md │ │ │ ├── version-0-11-1-released.md │ │ │ ├── version-0-11-2-released.md │ │ │ └── version-0-11-released.md │ │ ├── 07/ │ │ │ ├── debian-and-ubuntu-packaging.md │ │ │ ├── lua-mqtt-client.md │ │ │ ├── mosquitto-on-qnx.md │ │ │ ├── version-0-11-3-released.md │ │ │ ├── version-0-12-released.md │ │ │ └── wireshark-mqtt-decoder.md │ │ ├── 08/ │ │ │ ├── arch-linux-package.md │ │ │ ├── facebook-using-mqtt.attachments.json │ │ │ ├── facebook-using-mqtt.md │ │ │ ├── mosquitto-on-openwrt.md │ │ │ └── mqtt-standardisation.md │ │ ├── 09/ │ │ │ └── version-0-13-released.md │ │ ├── 10/ │ │ │ ├── mqtt-power-usage-on-android.md │ │ │ └── two.md │ │ ├── 11/ │ │ │ ├── android-mqtt-example-project.md │ │ │ ├── ibm-java-and-c-clients-to-be-open-source.md │ │ │ ├── new-linux-repositories.md │ │ │ ├── version-0-14-1-released.md │ │ │ ├── version-0-14-2-released.md │ │ │ └── version-0-14-released.md │ │ └── 12/ │ │ ├── mqtt-on-nanode.md │ │ └── version-0-14-3-released.md │ ├── 2012/ │ │ ├── 01/ │ │ │ ├── challenge-web-based-mqtt-graphing.md │ │ │ ├── do-you-use-mqtt.md │ │ │ ├── mosquitto-test-server.md │ │ │ └── version-0-14-4-released.md │ │ ├── 02/ │ │ │ ├── mqtt2pachube.md │ │ │ └── version-0-15-released.md │ │ ├── 03/ │ │ │ ├── quick-start-guide-for-mqtt-with-pachube.md │ │ │ └── upcoming-incompatible-library-changes.md │ │ ├── 05/ │ │ │ └── python-client-module-available-for-testing.md │ │ ├── 06/ │ │ │ ├── ipv6-on-test-server.md │ │ │ └── ssl-support-on-test-server.md │ │ ├── 07/ │ │ │ └── upcoming-release.md │ │ ├── 08/ │ │ │ ├── baby.attachments.json │ │ │ ├── baby.md │ │ │ ├── bugfix-coming-soon.md │ │ │ ├── version-1-0-1-released.md │ │ │ ├── version-1-0-2-released.md │ │ │ └── version-1-0-released.md │ │ ├── 09/ │ │ │ ├── updating-password-files.md │ │ │ └── version-1-0-3-released.md │ │ ├── 10/ │ │ │ └── version-1-0-4-released.md │ │ ├── 11/ │ │ │ ├── making-mosquitto-packages-for-debian-yourself.md │ │ │ └── version-1-0-5-released.md │ │ └── 12/ │ │ ├── libmosquitto-go-bindings.md │ │ └── version-1-1-released.md │ ├── 2013/ │ │ ├── 01/ │ │ │ ├── mosquitto-debian-repository.md │ │ │ ├── version-1-1-1-released.md │ │ │ └── version-1-1-2-released.md │ │ ├── 02/ │ │ │ ├── mqtt-standardisation-oasis-call-for-participation.md │ │ │ └── version-1-1-3-released.md │ │ ├── 04/ │ │ │ └── some-interesting-mqtt-things.md │ │ ├── 05/ │ │ │ └── mosquitto-javascript-client-deprecated.md │ │ ├── 07/ │ │ │ ├── authentication-plugins.md │ │ │ └── version-1-2-near-complete.md │ │ ├── 08/ │ │ │ ├── mosquitto-on-fedora.md │ │ │ ├── mqtt-watchdir.md │ │ │ └── version-1-2-released.md │ │ ├── 09/ │ │ │ └── version-1-2-1-released.md │ │ ├── 10/ │ │ │ └── version-1-2-2-released.md │ │ └── 12/ │ │ ├── paho-mqtt-python-client.md │ │ └── version-1-2-3-released.md │ ├── 2014/ │ │ ├── 03/ │ │ │ ├── version-1-3-1-released.md │ │ │ └── version-1-3-released.md │ │ ├── 05/ │ │ │ ├── new-arrival.attachments.json │ │ │ └── new-arrival.md │ │ ├── 07/ │ │ │ └── version-1-3-2-released.md │ │ ├── 08/ │ │ │ ├── version-1-3-3-released.md │ │ │ └── version-1-3-4-released.md │ │ └── 10/ │ │ ├── mosquitto-and-poodle.md │ │ ├── unintended-change-of-behaviour-in-1-3-4.md │ │ └── version-1-3-5-released.md │ ├── 2015/ │ │ ├── 01/ │ │ │ └── seeking-sponsorship.md │ │ ├── 02/ │ │ │ └── version-1-4-released.md │ │ ├── 04/ │ │ │ └── version-1-4-1-released.md │ │ ├── 05/ │ │ │ ├── mosquitto-and-current-unreleased-libwebsockets-branch.md │ │ │ └── version-1-4-2-released.md │ │ ├── 08/ │ │ │ └── version-1-4-3-released.md │ │ ├── 09/ │ │ │ └── version-1-4-4-released.md │ │ ├── 11/ │ │ │ └── version-1-4-5-released.md │ │ └── 12/ │ │ ├── using-lets-encrypt-certificates-with-mosquitto.md │ │ └── version-1-4-7-released.md │ ├── 2016/ │ │ ├── 01/ │ │ │ └── test6-mosquitto-org.md │ │ ├── 02/ │ │ │ └── version-1-4-8-released.md │ │ ├── 03/ │ │ │ ├── logo-contest-results-for-shortlisting.md │ │ │ ├── logo-contest.md │ │ │ └── repository-moved-to-github.md │ │ ├── 05/ │ │ │ ├── stickers.attachments.json │ │ │ └── stickers.md │ │ ├── 06/ │ │ │ └── version-1-4-9-released.md │ │ ├── 08/ │ │ │ ├── mqtt-v5-draft-features.md │ │ │ └── version-1-4-10-released.md │ │ └── 12/ │ │ └── pre-christmas-update.md │ ├── 2017/ │ │ ├── 02/ │ │ │ └── version-1-4-11-released.md │ │ ├── 03/ │ │ │ ├── for-the-final-time.attachments.json │ │ │ └── for-the-final-time.md │ │ ├── 05/ │ │ │ └── security-advisory-cve-2017-7650.md │ │ ├── 06/ │ │ │ ├── citing-eclipse-mosquitto.md │ │ │ └── security-advisory-cve-2017-9868.md │ │ └── 07/ │ │ ├── version-1-4-13-released.md │ │ └── version-1-4-14-released.md │ ├── 2018/ │ │ ├── 01/ │ │ │ └── mosquitto-debian-repo-key-updated.md │ │ ├── 02/ │ │ │ └── security-advisory-cve-2017-7651-cve-2017-7652.md │ │ ├── 05/ │ │ │ ├── press-release.md │ │ │ └── version-1-5-released.md │ │ ├── 08/ │ │ │ ├── updated-debian-repository-backend.md │ │ │ └── version-151-released.md │ │ ├── 09/ │ │ │ ├── security-advisory-cve-2018-12543.md │ │ │ └── version-152-released.md │ │ ├── 11/ │ │ │ ├── mqtt5-progress.md │ │ │ └── version-154-released.md │ │ └── 12/ │ │ └── version-155-released.md │ ├── 2019/ │ │ ├── 02/ │ │ │ ├── mqtt5-test-release.md │ │ │ ├── version-1-5-6-released.md │ │ │ ├── version-1-5-7-released.md │ │ │ └── version-1-5-8-released.md │ │ ├── 04/ │ │ │ ├── version-1-6-1-released.md │ │ │ ├── version-1-6-2-released.md │ │ │ └── version-1-6-released.md │ │ ├── 06/ │ │ │ └── version-1-6-3-released.md │ │ ├── 08/ │ │ │ └── version-1-6-4-released.md │ │ ├── 09/ │ │ │ ├── version-1-6-5-released.md │ │ │ ├── version-1-6-6-released.md │ │ │ └── version-1-6-7-released.md │ │ └── 11/ │ │ └── version-1-6-8-released.md │ ├── 2020/ │ │ ├── 02/ │ │ │ └── version-1-6-9-released.md │ │ ├── 05/ │ │ │ └── version-1-6-10-released.md │ │ ├── 06/ │ │ │ ├── mosquitto-ubuntu-appliance.md │ │ │ └── test-mosquitto-org-cert-updated.md │ │ ├── 08/ │ │ │ ├── version-1-6-11-released.md │ │ │ └── version-1-6-12-released.md │ │ └── 12/ │ │ ├── version-2-0-0-released.md │ │ ├── version-2-0-2-released.md │ │ ├── version-2-0-3-released.md │ │ └── version-2-0-4-released.md │ ├── 2021/ │ │ ├── 01/ │ │ │ ├── version-2-0-5-released.md │ │ │ └── version-2-0-6-released.md │ │ ├── 02/ │ │ │ ├── version-2-0-7-released.md │ │ │ └── version-2-0-8-released.md │ │ ├── 03/ │ │ │ └── version-2-0-9-released.md │ │ ├── 04/ │ │ │ └── version-2-0-10-released.md │ │ ├── 06/ │ │ │ └── version-2-0-11-released.md │ │ ├── 08/ │ │ │ └── version-2-0-12-released.md │ │ ├── 10/ │ │ │ └── version-2-0-13-released.md │ │ └── 11/ │ │ └── version-2-0-14-released.md │ ├── 2022/ │ │ └── 08/ │ │ └── version-2-0-15-released.md │ ├── 2023/ │ │ ├── 08/ │ │ │ ├── version-2-0-16-released.md │ │ │ └── version-2-0-17-released.md │ │ └── 09/ │ │ └── version-2-0-18-released.md │ ├── 2024/ │ │ └── 10/ │ │ ├── version-2-0-19-released.md │ │ └── version-2-0-20-released.md │ ├── 2025/ │ │ ├── 03/ │ │ │ └── version-2-0-21-released.md │ │ └── 07/ │ │ └── version-2-0-22-released.md │ └── 2026/ │ ├── 01/ │ │ ├── rc-2.1.0rc1-available.md │ │ └── version-2-1-0-released.md │ └── 02/ │ ├── version-2-1-1-released.md │ └── version-2-1-2-released.md ├── templates/ │ └── book.tmpl └── themes/ └── mosquitto/ ├── assets/ │ └── css/ │ ├── bulma.css │ ├── local.css │ └── man.css ├── engine ├── parent └── templates/ ├── base.tmpl ├── base_footer.tmpl ├── base_header.tmpl ├── base_helper.tmpl ├── index.tmpl ├── post.tmpl ├── post_header.tmpl └── story.tmpl ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true [*.{c,h,cpp,hpp}] indent_style = tab indent_size = 4 [*.py] indent_style = space indent_size = 4 [Makefile] indent_style = tab [*.{yml,yaml}] indent_style = space indent_size = 2 ================================================ FILE: .github/issue_template.md ================================================ ================================================ FILE: .github/labeler.yml ================================================ 'Status: Available': - '/.*/' ================================================ FILE: .github/pull_request_template.md ================================================ Thank you for contributing your time to the Mosquitto project! Before you go any further, please note that we cannot accept contributions if you haven't signed the [Eclipse Contributor Agreement](https://www.eclipse.org/legal/ECA.php). If you aren't able to do that, or just don't want to, please describe your bug fix/feature change in an issue. For simple bug fixes it is can be just as easy for us to be told about the problem and then go fix it directly. Then please check the following list of things we ask for in your pull request: - [ ] Have you signed the [Eclipse Contributor Agreement](https://www.eclipse.org/legal/ECA.php), using the same email address as you used in your commits? - [ ] Do each of your commits have a "Signed-off-by" line, with the correct email address? Use "git commit -s" to generate this line for you. - [ ] If you are contributing a new feature, is your work based off the develop branch? - [ ] If you are contributing a bugfix, is your work based off the fixes branch? - [ ] Have you added an explanation of what your changes do and why you'd like us to include them? - [ ] Have you successfully run `make test` with your changes locally? ----- ================================================ FILE: .github/workflows/build-variants.yml ================================================ name: Mosquitto - Build variants on: push: branches: - master - develop - fixes - release/* pull_request: branches: - master - develop - fixes - release/* jobs: build: runs-on: ubuntu-latest steps: - name: Install third party dependencies run: | sudo apt-get update sudo apt-get install -y \ docbook-xsl \ libargon2-dev \ libc-ares-dev \ libcjson-dev \ libcunit1-dev \ libedit-dev \ libgmock-dev \ libmicrohttpd-dev \ libssl-dev \ libsystemd-dev \ libwrap0-dev \ python3-all \ uthash-dev \ xsltproc - uses: actions/checkout@v6 with: submodules: 'true' - name: build run: ./buildtest.py ================================================ FILE: .github/workflows/cifuzz.yml ================================================ name: CIFuzz on: workflow_dispatch: pull_request: branches: - master - develop paths: - '**.c' - '**.cpp' - '**.h' permissions: {} jobs: Fuzzing: runs-on: ubuntu-latest permissions: security-events: write steps: - name: Build Fuzzers id: build uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master with: oss-fuzz-project-name: 'mosquitto' - name: Run Fuzzers uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master with: oss-fuzz-project-name: 'mosquitto' fuzz-seconds: 600 output-sarif: true - name: Upload Crash uses: actions/upload-artifact@v6 if: failure() && steps.build.outcome == 'success' with: name: artifacts path: ./out/artifacts - name: Upload Sarif if: always() && steps.build.outcome == 'success' uses: github/codeql-action/upload-sarif@v3 with: # Path to SARIF file relative to the root of the repository sarif_file: cifuzz-sarif/results.sarif checkout_path: cifuzz-sarif ================================================ FILE: .github/workflows/codeql-analysis.yml ================================================ # For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: workflow_dispatch: push: branches: [ master, fixes, develop ] pull_request: # The branches below must be a subset of the branches above branches: [ master ] schedule: - cron: '44 18 * * 1' jobs: analyze: name: Analyze runs-on: ubuntu-latest strategy: fail-fast: false matrix: language: [ 'cpp', 'python' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] # Learn more: # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed steps: - name: Checkout repository uses: actions/checkout@v6 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl - run: sudo apt-get update && sudo apt-get install -y gcc g++ git libssl-dev libargon2-dev libedit-dev libmicrohttpd-dev # Install cJSON - run: git clone https://github.com/DaveGamble/cJSON /tmp/cJSON - run: wget https://github.com/DaveGamble/cJSON/archive/v1.7.19.tar.gz -O /tmp/cjson.tar.gz - run: mkdir -p /tmp/build/cjson - run: tar --strip=1 -xf /tmp/cjson.tar.gz -C /tmp/build/cjson - run: rm /tmp/cjson.tar.gz - run: cd /tmp/build/cjson && cmake . -DCMAKE_BUILD_TYPE=MinSizeRel -DCJSON_BUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX=/usr - run: sudo make -C /tmp/build/cjson install # Now build Mosquitto - run: make binary - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 ================================================ FILE: .github/workflows/coverage.yml ================================================ name: Coverage on: workflow_dispatch: push: branches: - master - develop - fixes - release/* pull_request: branches: - master - develop - fixes - release/* jobs: coverage: runs-on: ubuntu-22.04 steps: - run: | sudo apt-get update sudo apt-get install -y \ docbook-xsl \ lcov \ libargon2-dev \ libc-ares-dev \ libcjson-dev \ libcjson1 \ libcunit1-dev \ libedit-dev \ libgmock-dev \ libmicrohttpd-dev \ libssl-dev \ libwrap0-dev \ microsocks \ python3-all \ python3-paho-mqtt \ python3-psutil \ uthash-dev \ xsltproc - uses: actions/checkout@v6 - run: | make \ WITH_COVERAGE=yes \ CFLAGS="-O0 -Wall -ggdb -fprofile-arcs" \ -j $(nproc) \ binary make \ WITH_COVERAGE=yes \ CFLAGS="-O0 -Wall -ggdb -fprofile-arcs" \ -j $(nproc) \ test-compile - run: | make -C test test - run: | lcov --capture --directory . --output-file coverage.info --no-external - uses: codecov/codecov-action@v4 with: token: ${{ secrets.CODECOV_TOKEN }} fail_ci_if_error: true files: ./coverage.info verbose: true ================================================ FILE: .github/workflows/coverity-scan-develop.yml ================================================ name: Coverity Scan develop branch on a weekly basis on: workflow_dispatch: schedule: - cron: "7 3 * * 0" jobs: coverity: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 with: ref: develop - name: Dependencies run: | sudo apt-get update sudo apt-get install -y \ docbook-xsl \ google-mock \ googletest \ lcov \ libc-ares-dev \ libcjson-dev \ libcjson1 \ libcunit1-dev \ libedit-dev \ libgmock-dev \ libmicrohttpd-dev \ libssl-dev \ libwrap0-dev \ microsocks \ python3-all \ python3-paho-mqtt \ python3-psutil \ uthash-dev \ xsltproc - uses: vapier/coverity-scan-action@v1 with: build_language: 'cxx' project: "eclipse/mosquitto" token: ${{ secrets.COVERITY_SCAN_TOKEN }} email: ${{ secrets.COVERITY_SCAN_EMAIL }} command: "make binary-all" ================================================ FILE: .github/workflows/coverity-scan-fixes.yml ================================================ name: Coverity Scan fixes branch on a weekly basis on: workflow_dispatch: schedule: - cron: "7 3 * * 3" jobs: coverity: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 with: ref: fixes - name: Dependencies run: | sudo apt-get update sudo apt-get install -y \ docbook-xsl \ lcov \ libc-ares-dev \ libcjson-dev \ libcjson1 \ libcunit1-dev \ libedit-dev \ libmicrohttpd-dev \ libssl-dev \ libwrap0-dev \ microsocks \ python3-all \ python3-paho-mqtt \ python3-psutil \ uthash-dev \ xsltproc - uses: vapier/coverity-scan-action@v1 with: build_language: 'cxx' project: "eclipse/mosquitto" token: ${{ secrets.COVERITY_SCAN_TOKEN }} email: ${{ secrets.COVERITY_SCAN_EMAIL }} command: "make binary-all" ================================================ FILE: .github/workflows/delete-old-workflow-runs.yml ================================================ name: Delete old workflow runs on: workflow_dispatch: schedule: - cron: '0 0 1 * *' # Run monthly, at 00:00 on the 1st day of month. jobs: del_runs: runs-on: ubuntu-latest steps: - name: Delete workflow runs uses: Mattraks/delete-workflow-runs@v2 with: token: ${{ github.token }} repository: ${{ github.repository }} retain_days: 30 keep_minimum_runs: 6 ================================================ FILE: .github/workflows/issue-labler.yml ================================================ name: "Issue Labeler" on: issues: types: [opened] permissions: issues: write contents: read jobs: triage: runs-on: ubuntu-latest steps: - uses: github/issue-labeler@v3.4 with: configuration-path: .github/labeler.yml not-before: 2024-11-03T00:00:00Z enable-versioned-regex: 0 repo-token: ${{ github.token }} ================================================ FILE: .github/workflows/lock.yml ================================================ name: 'Lock Threads' on: schedule: - cron: '0 0 * * 0' workflow_dispatch: permissions: issues: write pull-requests: write concurrency: group: lock-threads jobs: action: runs-on: ubuntu-latest steps: - uses: dessant/lock-threads@v6 with: issue-inactive-days: '90' ================================================ FILE: .github/workflows/macos.yml ================================================ name: Mac OS build on: workflow_dispatch: push: branches: - master - fixes - develop - release/* tags: - 'v[0-9]+.*' pull_request: branches: - master - fixes - develop - release/* env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) BUILD_TYPE: Release jobs: mosquitto: runs-on: macos-latest steps: - uses: actions/checkout@v6 - name: pin cmake to 3.x series uses: jwlawson/actions-setup-cmake@09fd9b0fb3b239b4b68d9256cd65adf8d6b91da0 with: cmake-version: '3.31.6' - name: Python test dependencies uses: actions/setup-python@v6 with: cache: 'pip' - name: Install Homebrew dependencies run: | brew update brew list cmake || brew install cmake brew install \ argon2 \ cjson \ cunit \ docbook-xsl \ gcc \ googletest \ libedit \ libmicrohttpd \ make \ openssl \ uthash - name: Configure CMake run: | EDITLINE_DIR=$(brew --prefix libedit) HOMEBREW_PREFIX=$(brew --prefix) cmake -B ${{github.workspace}}/build64 \ -G Ninja \ -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} \ -DCMAKE_PREFIX_PATH="$HOMEBREW_PREFIX" \ -DWITH_DOCS=OFF \ -DOPENSSL_ROOT_DIR=$(brew --prefix openssl@3) - name: Build run: | cmake --build ${{github.workspace}}/build64 \ --config ${{env.BUILD_TYPE}} - name: Test working-directory: build64/ run: | python3 -m venv venv source venv/bin/activate python3 -m pip install --upgrade pip python3 -m pip install psutil ctest --output-on-failure --repeat until-pass:5 ================================================ FILE: .github/workflows/mosquitto-cmake.yml ================================================ name: Mosquitto - CMake on: workflow_dispatch: push: branches: - master - fixes - develop - release/* tags: - 'v[0-9]+.*' pull_request: branches: - master - fixes - develop - release/* jobs: build: runs-on: ubuntu-latest steps: - name: Install third party dependencies run: | sudo apt-get update sudo apt-get install -y \ docbook-xsl \ lcov \ libargon2-dev \ libc-ares-dev \ libcjson-dev \ libcjson1 \ libcunit1-dev \ libedit-dev \ libgmock-dev \ libmicrohttpd-dev \ libssl-dev \ libwrap0-dev \ microsocks \ python3-all \ python3-paho-mqtt \ python3-psutil \ uthash-dev \ xsltproc - uses: actions/checkout@v6 - run: cmake -E make_directory build - run: | cmake \ -DCMAKE_BUILD_TYPE=Debug \ -S . \ -B build - run: cmake --build build --parallel $(nproc) - working-directory: build/ run: ctest --output-on-failure --repeat until-pass:5 ================================================ FILE: .github/workflows/mosquitto-make-asan.yml ================================================ name: Mosquitto - Make ASAN on: push: branches: - master - develop - fixes - release/* pull_request: branches: - master - develop - fixes - release/* jobs: build: runs-on: ubuntu-latest steps: - name: Install third party dependencies run: | sudo apt-get update sudo apt-get install -y \ clang \ docbook-xsl \ lcov \ libargon2-dev \ libc-ares-dev \ libcjson-dev \ libcjson1 \ libcunit1-dev \ libedit-dev \ libgmock-dev \ libmicrohttpd-dev \ libssl-dev \ libwrap0-dev \ microsocks \ python3-all \ python3-paho-mqtt \ python3-psutil \ uthash-dev \ xsltproc - uses: actions/checkout@v6 with: submodules: 'true' - name: make run: make WITH_ASAN=yes - name: make test run: | make WITH_ASAN=yes ptest ================================================ FILE: .github/workflows/mosquitto-make.yml ================================================ name: Mosquitto - Make on: workflow_dispatch: push: branches: - master - fixes - develop - release/* tags: - 'v[0-9]+.*' pull_request: branches: - master - fixes - develop - release/* jobs: build: runs-on: ubuntu-latest steps: - name: Install third party dependencies run: | sudo apt-get update sudo apt-get install -y \ docbook-xsl \ lcov \ libargon2-dev \ libc-ares-dev \ libcjson-dev \ libcjson1 \ libcunit1-dev \ libedit-dev \ libgmock-dev \ libmicrohttpd-dev \ libssl-dev \ libwrap0-dev \ microsocks \ python3-all \ python3-paho-mqtt \ python3-psutil \ uthash-dev \ xsltproc - uses: actions/checkout@v6 with: submodules: 'true' - name: make run: make - name: make test run: | make ptest ================================================ FILE: .github/workflows/windows-x86.yml ================================================ name: Windows x86 build on: workflow_dispatch: push: branches: - master - fixes - develop - release/* tags: - 'v[0-9]+.*' pull_request: branches: - master - fixes - develop - release/* env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) BUILD_TYPE: Release jobs: mosquitto: runs-on: windows-2022 steps: - uses: actions/checkout@v6 - name: vcpkg build uses: johnwason/vcpkg-action@v7 id: vcpkg with: manifest-dir: ${{ github.workspace }} triplet: x86-windows token: ${{ github.token }} - name: Configure CMake run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DWITH_WEBSOCKETS=ON -DWITH_TESTS=OFF -DCMAKE_GENERATOR_PLATFORM=WIN32 -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x86-windows -DVCPKG_MANIFEST_MODE=ON -DWITH_HTTP_API=ON -DHTTP_API_DIR="C:\\Program Files (x86)\\Mosquitto\\dashboard" - name: Build run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} - uses: suisei-cn/actions-download-file@v1.6.1 id: vcredist name: Download VC redistributable with: url: https://aka.ms/vs/17/release/vc_redist.x86.exe target: ${{github.workspace}}/installer/ - name: Installer uses: joncloud/makensis-action@v5.0 with: script-file: ${{github.workspace}}/installer/mosquitto.nsi - name: Upload installer to artifacts uses: actions/upload-artifact@v6 with: name: installer path: ${{ github.workspace }}/installer/mosquitto*.exe ================================================ FILE: .github/workflows/windows.yml ================================================ name: Windows build on: workflow_dispatch: push: branches: - master - fixes - develop - release/* tags: - 'v[0-9]+.*' pull_request: branches: - master - fixes - develop - release/* env: # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) BUILD_TYPE: Release jobs: mosquitto: runs-on: windows-2022 steps: - uses: actions/checkout@v6 - name: pin cmake to 3.x series uses: jwlawson/actions-setup-cmake@09fd9b0fb3b239b4b68d9256cd65adf8d6b91da0 with: cmake-version: '3.31.6' - name: vcpkg build uses: johnwason/vcpkg-action@v7 id: vcpkg with: manifest-dir: ${{ github.workspace }} triplet: x64-windows-release token: ${{ github.token }} - name: Configure CMake run: cmake -B ${{github.workspace}}/build64 -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DWITH_WEBSOCKETS=ON -DWITH_TESTS=OFF -DCMAKE_GENERATOR_PLATFORM=x64 -DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-release -DVCPKG_MANIFEST_MODE=ON -DWITH_HTTP_API=ON -DHTTP_API_DIR="C:\\Program Files\\Mosquitto\\dashboard" - name: Build run: cmake --build ${{github.workspace}}/build64 --config ${{env.BUILD_TYPE}} - uses: suisei-cn/actions-download-file@v1.6.1 id: vcredist name: Download VC redistributable with: url: https://aka.ms/vs/17/release/vc_redist.x64.exe target: ${{github.workspace}}/installer/ - name: Installer uses: joncloud/makensis-action@v5.0 with: script-file: ${{github.workspace}}/installer/mosquitto64.nsi - name: Upload installer to artifacts uses: actions/upload-artifact@v6 with: name: installer path: ${{ github.workspace }}/installer/mosquitto*.exe ================================================ FILE: .gitignore ================================================ # .gitignore *.a *.db *.gcda *.gcno *.exe *.o *.old *.pyc *.so *.vglog callgrind.out.* coverage.info dhat.out.* massif.out.* vglog* c/*.test cpp/*.test apps/db_dump/mosquitto_db_dump apps/db_dump/mosquitto_db_dump.a apps/mosquitto_ctrl/mosquitto_ctrl apps/mosquitto_passwd/mosquitto_passwd apps/mosquitto_passwd/mosquitto_passwd.a apps/mosquitto_signal/mosquitto_signal build/ build64/ client/mosquitto_pub client/mosquitto_pub.a client/mosquitto_rr client/mosquitto_rr.a client/mosquitto_sub client/mosquitto_sub.a client/testing client/testing.c cov-int/ dist/ docker/local/mosq.tar.gz examples/mysql_log/mosquitto_mysql_log examples/temperature_conversion/mqtt_temperature_conversion examples/publish/basic-1 examples/publish/basic-websockets-1 fuzzing/apps/db_dump/db_dump_fuzz_load fuzzing/apps/db_dump/db_dump_fuzz_load_client_stats fuzzing/apps/db_dump/db_dump_fuzz_load_stats fuzzing/apps/mosquitto_passwd/mosquitto_passwd_fuzz_load fuzzing/broker/broker_fuzz_acl_file fuzzing/broker/broker_fuzz_handle_auth fuzzing/broker/broker_fuzz_handle_connect fuzzing/broker/broker_fuzz_handle_publish fuzzing/broker/broker_fuzz_handle_subscribe fuzzing/broker/broker_fuzz_handle_unsubscribe fuzzing/broker/broker_fuzz_initial_packet fuzzing/broker/broker_fuzz_initial_packet_with_init fuzzing/broker/broker_fuzz_password_file fuzzing/broker/broker_fuzz_proxy_v1 fuzzing/broker/broker_fuzz_proxy_v2 fuzzing/broker/broker_fuzz_psk_file fuzzing/broker/broker_fuzz_queue_msg fuzzing/broker/broker_fuzz_read_handle fuzzing/broker/broker_fuzz_second_packet fuzzing/broker/broker_fuzz_second_packet_with_init fuzzing/broker/broker_fuzz_test_config fuzzing/corpora/broker/* fuzzing/corpora/broker_packet_seed_corpus.zip fuzzing/corpora/client/* fuzzing/corpora/client_packet_seed_corpus.zip fuzzing/corpora/db_dump_seed_corpus.zip fuzzing/lib/lib_fuzz_pub_topic_check2 fuzzing/lib/lib_fuzz_sub_topic_check2 fuzzing/lib/lib_fuzz_utf8 fuzzing/libcommon/libcommon_fuzz_property fuzzing/libcommon/libcommon_fuzz_property.pb.cc fuzzing/libcommon/libcommon_fuzz_property.pb.h fuzzing/libcommon/libcommon_fuzz_pub_topic_check2 fuzzing/libcommon/libcommon_fuzz_sub_topic_check2 fuzzing/libcommon/libcommon_fuzz_topic_matching fuzzing/libcommon/libcommon_fuzz_topic_matching.pb.cc fuzzing/libcommon/libcommon_fuzz_topic_matching.pb.h fuzzing/libcommon/libcommon_fuzz_topic_tokenise fuzzing/libcommon/libcommon_fuzz_utf8 fuzzing/plugins/dynamic-security/dynsec_fuzz_load lib/cpp/libmosquittopp.so* lib/cpp/libmosquittopp.a lib/libmosquitto.so* lib/libmosquitto.a man/libmosquitto.3 man/mosquitto-tls.7 man/mosquitto.7 man/mosquitto.8 man/mosquitto.conf.5 man/mosquitto_ctrl.1 man/mosquitto_ctrl_dynsec.1 man/mosquitto_ctrl_shell.1 man/mosquitto_passwd.1 man/mosquitto_pub.1 man/mosquitto_rr.1 man/mosquitto_signal.1 man/mosquitto_sub.1 man/mqtt.7 out/ src/mosquitto src/mosquitto_broker.a test/apps/ctrl/ctrl_shell_broker_test test/apps/ctrl/ctrl_shell_completion_test test/apps/ctrl/ctrl_shell_dynsec_test test/apps/ctrl/ctrl_shell_help_test test/apps/ctrl/ctrl_shell_options_test test/apps/ctrl/ctrl_shell_pre_connect_test test/apps/ctrl/ctrl_shell_test test/broker/broker.pid test/test_client test/fake_user test/msgsps_pub test/msgsps_sub test/msgsps_pub.dat test/msgsps_sub.dat test/broker/c/auth_plugin.so test/broker/c/*.test test/ssl/*.csr test/ssl/rootCA/ test/ssl/signingCA/ test/lib/c/*.test test/lib/cpp/*.test test/unit/broker/bridge_topic_test test/unit/broker/keepalive_test test/unit/broker/persist_read_test test/unit/broker/persist_write_test test/unit/broker/subs_test test/unit/coverage.info test/unit/lib/lib_test test/unit/libcommon/libcommon_test test/unit/tls_test www/cache/ __pycache__ *.sync-conflict-* # Debian generated files debian/.debhelper/ debian/debhelper-build-stamp debian/files debian/*.log debian/*.substvars debian/*mosquitto*/ debian/*.debhelper debian/tmp/ obj-*/ # Emacs generated files *~ # clangd .cache/ # VSCode generated files .vscode/ # Others tmp/ failed-tests.json ================================================ FILE: .uncrustify.cfg ================================================ # Uncrustify_d-0.80.1-109-229eb1c05 # # General options # set FOR HASH_ITER set FOR DL_FOREACH set FOR DL_FOREACH_SAFE set FOR DL_FOREACH_SAFE2 set FOR LL_FOREACH set FOR LL_FOREACH_SAFE set FOR cJSON_ArrayForEach # The type of line endings. # # Default: auto newlines = auto # lf/crlf/cr/auto # The original size of tabs in the input. # # Default: 8 input_tab_size = 4 # unsigned number # The size of tabs in the output (only used if align_with_tabs=true). # # Default: 8 output_tab_size = 4 # unsigned number # The ASCII value of the string escape char, usually 92 (\) or (Pawn) 94 (^). # # Default: 92 string_escape_char = 92 # unsigned number # Alternate string escape char (usually only used for Pawn). # Only works right before the quote char. string_escape_char2 = 0 # unsigned number # Replace tab characters found in string literals with the escape sequence \t # instead. string_replace_tab_chars = false # true/false # Allow interpreting '>=' and '>>=' as part of a template in code like # 'void f(list>=val);'. If true, 'assert(x<0 && y>=3)' will be broken. # Improvements to template detection may make this option obsolete. tok_split_gte = false # true/false # Disable formatting of NL_CONT ('\\n') ended lines (e.g. multi-line macros). disable_processing_nl_cont = false # true/false # Specify the marker used in comments to disable processing of part of the # file. # # Default: *INDENT-OFF* disable_processing_cmt = " *INDENT-OFF*" # string # Specify the marker used in comments to (re)enable processing in a file. # # Default: *INDENT-ON* enable_processing_cmt = " *INDENT-ON*" # string # Enable parsing of digraphs. enable_digraphs = false # true/false # Option to allow both disable_processing_cmt and enable_processing_cmt # strings, if specified, to be interpreted as ECMAScript regular expressions. # If true, a regex search will be performed within comments according to the # specified patterns in order to disable/enable processing. processing_cmt_as_regex = false # true/false # Add or remove the UTF-8 BOM (recommend 'remove'). utf8_bom = remove # ignore/add/remove/force # If the file contains bytes with values between 128 and 255, but is not # UTF-8, then output as UTF-8. utf8_byte = false # true/false # Force the output encoding to UTF-8. utf8_force = true # true/false # # Spacing options # # Add or remove space around non-assignment symbolic operators ('+', '/', '%', # '<<', and so forth). sp_arith = ignore # ignore/add/remove/force # Add or remove space around arithmetic operators '+' and '-'. # # Overrides sp_arith. sp_arith_additive = ignore # ignore/add/remove/force # Add or remove space around assignment operator '=', '+=', etc. sp_assign = ignore # ignore/add/remove/force # Add or remove space around '=' in C++11 lambda capture specifications. # # Overrides sp_assign. sp_cpp_lambda_assign = ignore # ignore/add/remove/force # Add or remove space after the capture specification of a C++11 lambda when # an argument list is present, as in '[] (int x){ ... }'. sp_cpp_lambda_square_paren = ignore # ignore/add/remove/force # Add or remove space after the capture specification of a C++11 lambda with # no argument list is present, as in '[] { ... }'. sp_cpp_lambda_square_brace = ignore # ignore/add/remove/force # Add or remove space after the opening parenthesis and before the closing # parenthesis of a argument list of a C++11 lambda, as in # '[]( ){ ... }' # with an empty list. sp_cpp_lambda_argument_list_empty = ignore # ignore/add/remove/force # Add or remove space after the opening parenthesis and before the closing # parenthesis of a argument list of a C++11 lambda, as in # '[]( int x ){ ... }'. sp_cpp_lambda_argument_list = ignore # ignore/add/remove/force # Add or remove space after the argument list of a C++11 lambda, as in # '[](int x) { ... }'. sp_cpp_lambda_paren_brace = ignore # ignore/add/remove/force # Add or remove space between a lambda body and its call operator of an # immediately invoked lambda, as in '[]( ... ){ ... } ( ... )'. sp_cpp_lambda_fparen = ignore # ignore/add/remove/force # Add or remove space around assignment operator '=' in a prototype. # # If set to ignore, use sp_assign. sp_assign_default = ignore # ignore/add/remove/force # Add or remove space before assignment operator '=', '+=', etc. # # Overrides sp_assign. sp_before_assign = ignore # ignore/add/remove/force # Add or remove space after assignment operator '=', '+=', etc. # # Overrides sp_assign. sp_after_assign = ignore # ignore/add/remove/force # Add or remove space in 'enum {'. # # Default: add sp_enum_brace = remove # ignore/add/remove/force # Add or remove space in 'NS_ENUM ('. sp_enum_paren = ignore # ignore/add/remove/force # Add or remove space around assignment '=' in enum. sp_enum_assign = ignore # ignore/add/remove/force # Add or remove space before assignment '=' in enum. # # Overrides sp_enum_assign. sp_enum_before_assign = ignore # ignore/add/remove/force # Add or remove space after assignment '=' in enum. # # Overrides sp_enum_assign. sp_enum_after_assign = ignore # ignore/add/remove/force # Add or remove space around assignment ':' in enum. sp_enum_colon = ignore # ignore/add/remove/force # Add or remove space around preprocessor '##' concatenation operator. # # Default: add sp_pp_concat = add # ignore/add/remove/force # Add or remove space after preprocessor '#' stringify operator. # Also affects the '#@' charizing operator. sp_pp_stringify = ignore # ignore/add/remove/force # Add or remove space before preprocessor '#' stringify operator # as in '#define x(y) L#y'. sp_before_pp_stringify = ignore # ignore/add/remove/force # Add or remove space around boolean operators '&&' and '||'. sp_bool = ignore # ignore/add/remove/force # Add or remove space around compare operator '<', '>', '==', etc. sp_compare = ignore # ignore/add/remove/force # Add or remove space inside '(' and ')'. sp_inside_paren = remove # ignore/add/remove/force # Add or remove space between nested parentheses, i.e. '((' vs. ') )'. sp_paren_paren = remove # ignore/add/remove/force # Add or remove space between back-to-back parentheses, i.e. ')(' vs. ') ('. sp_cparen_oparen = ignore # ignore/add/remove/force # Add or remove space between ')' and '{'. sp_paren_brace = remove # ignore/add/remove/force # Add or remove space between nested braces, i.e. '{{' vs. '{ {'. sp_brace_brace = remove # ignore/add/remove/force # Add or remove space before pointer star '*'. sp_before_ptr_star = add # ignore/add/remove/force # Add or remove space before pointer star '*' that isn't followed by a # variable name. If set to ignore, sp_before_ptr_star is used instead. sp_before_unnamed_ptr_star = add # ignore/add/remove/force # Add or remove space before pointer star '*' that is followed by a qualifier. # If set to ignore, sp_before_unnamed_ptr_star is used instead. sp_before_qualifier_ptr_star = add # ignore/add/remove/force # Add or remove space before pointer star '*' that is followed by 'operator' keyword. # If set to ignore, sp_before_unnamed_ptr_star is used instead. sp_before_operator_ptr_star = ignore # ignore/add/remove/force # Add or remove space before pointer star '*' that is followed by # a class scope (as in 'int *MyClass::method()') or namespace scope # (as in 'int *my_ns::func()'). # If set to ignore, sp_before_unnamed_ptr_star is used instead. sp_before_scope_ptr_star = ignore # ignore/add/remove/force # Add or remove space before pointer star '*' that is followed by '::', # as in 'int *::func()'. # If set to ignore, sp_before_unnamed_ptr_star is used instead. sp_before_global_scope_ptr_star = ignore # ignore/add/remove/force # Add or remove space between a qualifier and a pointer star '*' that isn't # followed by a variable name, as in '(char const *)'. If set to ignore, # sp_before_ptr_star is used instead. sp_qualifier_unnamed_ptr_star = ignore # ignore/add/remove/force # Add or remove space between pointer stars '*', as in 'int ***a;'. sp_between_ptr_star = remove # ignore/add/remove/force # Add or remove space between pointer star '*' and reference '&', as in 'int *& a;'. sp_between_ptr_ref = ignore # ignore/add/remove/force # Add or remove space after pointer star '*', if followed by a word. # # Overrides sp_type_func. sp_after_ptr_star = remove # ignore/add/remove/force # Add or remove space after pointer caret '^', if followed by a word. sp_after_ptr_block_caret = ignore # ignore/add/remove/force # Add or remove space after pointer star '*', if followed by a qualifier. sp_after_ptr_star_qualifier = ignore # ignore/add/remove/force # Add or remove space after a pointer star '*', if followed by a function # prototype or function definition. # # Overrides sp_after_ptr_star and sp_type_func. sp_after_ptr_star_func = remove # ignore/add/remove/force # Add or remove space after a pointer star '*' in the trailing return of a # function prototype or function definition. sp_after_ptr_star_trailing = ignore # ignore/add/remove/force # Add or remove space between the pointer star '*' and the name of the variable # in a function pointer definition. sp_ptr_star_func_var = remove # ignore/add/remove/force # Add or remove space between the pointer star '*' and the name of the type # in a function pointer type definition. sp_ptr_star_func_type = ignore # ignore/add/remove/force # Add or remove space after a pointer star '*', if followed by an open # parenthesis, as in 'void* (*)()'. sp_ptr_star_paren = ignore # ignore/add/remove/force # Add or remove space before a pointer star '*', if followed by a function # prototype or function definition. If set to ignore, sp_before_ptr_star is # used instead. sp_before_ptr_star_func = ignore # ignore/add/remove/force # Add or remove space between a qualifier and a pointer star '*' followed by # the name of the function in a function prototype or definition, as in # 'char const *foo()`. If set to ignore, sp_before_ptr_star is used instead. sp_qualifier_ptr_star_func = ignore # ignore/add/remove/force # Add or remove space before a pointer star '*' in the trailing return of a # function prototype or function definition. sp_before_ptr_star_trailing = ignore # ignore/add/remove/force # Add or remove space between a qualifier and a pointer star '*' in the # trailing return of a function prototype or function definition, as in # 'auto foo() -> char const *'. sp_qualifier_ptr_star_trailing = ignore # ignore/add/remove/force # Add or remove space before a reference sign '&'. sp_before_byref = ignore # ignore/add/remove/force # Add or remove space before a reference sign '&' that isn't followed by a # variable name. If set to ignore, sp_before_byref is used instead. sp_before_unnamed_byref = ignore # ignore/add/remove/force # Add or remove space after reference sign '&', if followed by a word. # # Overrides sp_type_func. sp_after_byref = ignore # ignore/add/remove/force # Add or remove space after a reference sign '&', if followed by a function # prototype or function definition. # # Overrides sp_after_byref and sp_type_func. sp_after_byref_func = ignore # ignore/add/remove/force # Add or remove space before a reference sign '&', if followed by a function # prototype or function definition. sp_before_byref_func = ignore # ignore/add/remove/force # Add or remove space after a reference sign '&', if followed by an open # parenthesis, as in 'char& (*)()'. sp_byref_paren = ignore # ignore/add/remove/force # Add or remove space between type and word. In cases where total removal of # whitespace would be a syntax error, a value of 'remove' is treated the same # as 'force'. # # This also affects some other instances of space following a type that are # not covered by other options; for example, between the return type and # parenthesis of a function type template argument, between the type and # parenthesis of an array parameter, or between 'decltype(...)' and the # following word. # # Default: force sp_after_type = force # ignore/add/remove/force # Add or remove space between 'decltype(...)' and word, # brace or function call. sp_after_decltype = ignore # ignore/add/remove/force # (D) Add or remove space before the parenthesis in the D constructs # 'template Foo(' and 'class Foo('. sp_before_template_paren = ignore # ignore/add/remove/force # Add or remove space between 'template' and '<'. # If set to ignore, sp_before_angle is used. sp_template_angle = ignore # ignore/add/remove/force # Add or remove space before '<'. sp_before_angle = ignore # ignore/add/remove/force # Add or remove space inside '<' and '>'. sp_inside_angle = ignore # ignore/add/remove/force # Add or remove space inside '<>'. # if empty. sp_inside_angle_empty = ignore # ignore/add/remove/force # Add or remove space between '>' and ':'. sp_angle_colon = ignore # ignore/add/remove/force # Add or remove space after '>'. sp_after_angle = ignore # ignore/add/remove/force # Add or remove space between '>' and '(' as found in 'new List(foo);'. sp_angle_paren = ignore # ignore/add/remove/force # Add or remove space between '>' and '()' as found in 'new List();'. sp_angle_paren_empty = ignore # ignore/add/remove/force # Add or remove space between '>' and a word as in 'List m;' or # 'template static ...'. sp_angle_word = ignore # ignore/add/remove/force # Add or remove space between '>' and '>' in '>>' (template stuff). # # Default: add sp_angle_shift = add # ignore/add/remove/force # (C++11) Permit removal of the space between '>>' in 'foo >'. Note # that sp_angle_shift cannot remove the space without this option. sp_permit_cpp11_shift = false # true/false # Add or remove space before '(' of control statements ('if', 'for', 'switch', # 'while', etc.). sp_before_sparen = remove # ignore/add/remove/force # Add or remove space inside '(' and ')' of control statements other than # 'for'. sp_inside_sparen = remove # ignore/add/remove/force # Add or remove space after '(' of control statements other than 'for'. # # Overrides sp_inside_sparen. sp_inside_sparen_open = ignore # ignore/add/remove/force # Add or remove space before ')' of control statements other than 'for'. # # Overrides sp_inside_sparen. sp_inside_sparen_close = ignore # ignore/add/remove/force # Add or remove space inside '(' and ')' of 'for' statements. sp_inside_for = ignore # ignore/add/remove/force # Add or remove space after '(' of 'for' statements. # # Overrides sp_inside_for. sp_inside_for_open = ignore # ignore/add/remove/force # Add or remove space before ')' of 'for' statements. # # Overrides sp_inside_for. sp_inside_for_close = ignore # ignore/add/remove/force # Add or remove space between '((' or '))' of control statements. sp_sparen_paren = remove # ignore/add/remove/force # Add or remove space after ')' of control statements. sp_after_sparen = ignore # ignore/add/remove/force # Add or remove space between ')' and '{' of control statements. sp_sparen_brace = remove # ignore/add/remove/force # Add or remove space between 'do' and '{'. sp_do_brace_open = remove # ignore/add/remove/force # Add or remove space between '}' and 'while'. sp_brace_close_while = remove # ignore/add/remove/force # Add or remove space between 'while' and '('. Overrides sp_before_sparen. sp_while_paren_open = remove # ignore/add/remove/force # (D) Add or remove space between 'invariant' and '('. sp_invariant_paren = ignore # ignore/add/remove/force # (D) Add or remove space after the ')' in 'invariant (C) c'. sp_after_invariant_paren = ignore # ignore/add/remove/force # Add or remove space before empty statement ';' on 'if', 'for' and 'while'. # examples: # if (b) ; # for (a=1; a<10; a++) ; # while (*p++ = ' ') ; sp_special_semi = ignore # ignore/add/remove/force # Add or remove space before ';'. # # Default: remove sp_before_semi = remove # ignore/add/remove/force # Add or remove space before ';' in non-empty 'for' statements. sp_before_semi_for = ignore # ignore/add/remove/force # Add or remove space before a semicolon of an empty left part of a for # statement, as in 'for ( ; ; )'. sp_before_semi_for_empty = ignore # ignore/add/remove/force # Add or remove space between the semicolons of an empty middle part of a for # statement, as in 'for ( ; ; )'. sp_between_semi_for_empty = ignore # ignore/add/remove/force # Add or remove space after ';', except when followed by a comment. # # Default: add sp_after_semi = add # ignore/add/remove/force # Add or remove space after ';' in non-empty 'for' statements. # # Default: force sp_after_semi_for = force # ignore/add/remove/force # Add or remove space after the final semicolon of an empty part of a for # statement, as in 'for ( ; ; )'. sp_after_semi_for_empty = ignore # ignore/add/remove/force # Add or remove space before '[' (except '[]'). sp_before_square = ignore # ignore/add/remove/force # Add or remove space before '[' for a variable definition. # # Default: remove sp_before_vardef_square = remove # ignore/add/remove/force # Add or remove space before '[' for asm block. sp_before_square_asm_block = ignore # ignore/add/remove/force # Add or remove space before '[]'. sp_before_squares = ignore # ignore/add/remove/force # Add or remove space before C++17 structured bindings # after byref. sp_cpp_before_struct_binding_after_byref = ignore # ignore/add/remove/force # Add or remove space before C++17 structured bindings. sp_cpp_before_struct_binding = ignore # ignore/add/remove/force # Add or remove space inside a non-empty '[' and ']'. sp_inside_square = ignore # ignore/add/remove/force # Add or remove space inside '[]'. # if empty. sp_inside_square_empty = ignore # ignore/add/remove/force # (OC) Add or remove space inside a non-empty Objective-C boxed array '@[' and # ']'. If set to ignore, sp_inside_square is used. sp_inside_square_oc_array = ignore # ignore/add/remove/force # Add or remove space after ',', i.e. 'a,b' vs. 'a, b'. sp_after_comma = add # ignore/add/remove/force # Add or remove space before ',', i.e. 'a,b' vs. 'a ,b'. # # Default: remove sp_before_comma = remove # ignore/add/remove/force # (C#, Vala) Add or remove space between ',' and ']' in multidimensional array type # like 'int[,,]'. sp_after_mdatype_commas = ignore # ignore/add/remove/force # (C#, Vala) Add or remove space between '[' and ',' in multidimensional array type # like 'int[,,]'. sp_before_mdatype_commas = ignore # ignore/add/remove/force # (C#, Vala) Add or remove space between ',' in multidimensional array type # like 'int[,,]'. sp_between_mdatype_commas = ignore # ignore/add/remove/force # Add or remove space between an open parenthesis and comma, # i.e. '(,' vs. '( ,'. # # Default: force sp_paren_comma = force # ignore/add/remove/force # Add or remove space between a type and ':'. sp_type_colon = ignore # ignore/add/remove/force # Add or remove space after the variadic '...' when preceded by a # non-punctuator. # The value REMOVE will be overridden with FORCE sp_after_ellipsis = ignore # ignore/add/remove/force # Add or remove space before the variadic '...' when preceded by a # non-punctuator. # The value REMOVE will be overridden with FORCE sp_before_ellipsis = ignore # ignore/add/remove/force # Add or remove space between a type and '...'. sp_type_ellipsis = ignore # ignore/add/remove/force # Add or remove space between a '*' and '...'. sp_ptr_type_ellipsis = ignore # ignore/add/remove/force # Add or remove space between ')' and '...'. sp_paren_ellipsis = ignore # ignore/add/remove/force # Add or remove space between '&&' and '...'. sp_byref_ellipsis = ignore # ignore/add/remove/force # Add or remove space between ')' and a qualifier such as 'const'. sp_paren_qualifier = ignore # ignore/add/remove/force # Add or remove space between ')' and 'noexcept'. sp_paren_noexcept = ignore # ignore/add/remove/force # Add or remove space after class ':'. sp_after_class_colon = ignore # ignore/add/remove/force # Add or remove space before class ':'. sp_before_class_colon = ignore # ignore/add/remove/force # Add or remove space after class constructor ':'. # # Default: add sp_after_constr_colon = add # ignore/add/remove/force # Add or remove space before class constructor ':'. # # Default: add sp_before_constr_colon = add # ignore/add/remove/force # Add or remove space before case ':'. # # Default: remove sp_before_case_colon = remove # ignore/add/remove/force # Add or remove space between 'operator' and operator sign. sp_after_operator = ignore # ignore/add/remove/force # Add or remove space between the operator symbol and the open parenthesis, as # in 'operator ++('. sp_after_operator_sym = ignore # ignore/add/remove/force # Overrides sp_after_operator_sym when the operator has no arguments, as in # 'operator *()'. sp_after_operator_sym_empty = ignore # ignore/add/remove/force # Add or remove space after C/D cast, i.e. 'cast(int)a' vs. 'cast(int) a' or # '(int)a' vs. '(int) a'. sp_after_cast = remove # ignore/add/remove/force # Add or remove spaces inside cast parentheses. sp_inside_paren_cast = ignore # ignore/add/remove/force # Add or remove space between the type and open parenthesis in a C++ cast, # i.e. 'int(exp)' vs. 'int (exp)'. sp_cpp_cast_paren = ignore # ignore/add/remove/force # Add or remove space between 'sizeof' and '('. sp_sizeof_paren = ignore # ignore/add/remove/force # Add or remove space between 'sizeof' and '...'. sp_sizeof_ellipsis = ignore # ignore/add/remove/force # Add or remove space between 'sizeof...' and '('. sp_sizeof_ellipsis_paren = ignore # ignore/add/remove/force # Add or remove space between '...' and a parameter pack. sp_ellipsis_parameter_pack = ignore # ignore/add/remove/force # Add or remove space between a parameter pack and '...'. sp_parameter_pack_ellipsis = ignore # ignore/add/remove/force # Add or remove space between 'decltype' and '('. sp_decltype_paren = ignore # ignore/add/remove/force # (Pawn) Add or remove space after the tag keyword. sp_after_tag = ignore # ignore/add/remove/force # Add or remove space inside enum '{' and '}'. sp_inside_braces_enum = ignore # ignore/add/remove/force # Add or remove space inside struct/union '{' and '}'. sp_inside_braces_struct = ignore # ignore/add/remove/force # (OC) Add or remove space inside Objective-C boxed dictionary '{' and '}' sp_inside_braces_oc_dict = ignore # ignore/add/remove/force # Add or remove space after open brace in an unnamed temporary # direct-list-initialization # if statement is a brace_init_lst # works only if sp_brace_brace is set to ignore. sp_after_type_brace_init_lst_open = ignore # ignore/add/remove/force # Add or remove space before close brace in an unnamed temporary # direct-list-initialization # if statement is a brace_init_lst # works only if sp_brace_brace is set to ignore. sp_before_type_brace_init_lst_close = ignore # ignore/add/remove/force # Add or remove space inside an unnamed temporary direct-list-initialization # if statement is a brace_init_lst # works only if sp_brace_brace is set to ignore # works only if sp_before_type_brace_init_lst_close is set to ignore. sp_inside_type_brace_init_lst = ignore # ignore/add/remove/force # Add or remove space inside '{' and '}'. sp_inside_braces = ignore # ignore/add/remove/force # Add or remove space inside '{}'. # if empty. sp_inside_braces_empty = remove # ignore/add/remove/force # Add or remove space around trailing return operator '->'. sp_trailing_return = ignore # ignore/add/remove/force # Add or remove space between return type and function name. A minimum of 1 # is forced except for pointer return types. sp_type_func = ignore # ignore/add/remove/force # Add or remove space between type and open brace of an unnamed temporary # direct-list-initialization. sp_type_brace_init_lst = ignore # ignore/add/remove/force # Add or remove space between function name and '(' on function declaration. sp_func_proto_paren = remove # ignore/add/remove/force # Add or remove space between function name and '()' on function declaration # if empty. sp_func_proto_paren_empty = remove # ignore/add/remove/force # Add or remove space between function name and '(' with a typedef specifier. sp_func_type_paren = ignore # ignore/add/remove/force # Add or remove space between alias name and '(' of a non-pointer function type typedef. sp_func_def_paren = ignore # ignore/add/remove/force # Add or remove space between function name and '()' on function definition # if empty. sp_func_def_paren_empty = ignore # ignore/add/remove/force # Add or remove space inside empty function '()'. # Overrides sp_after_angle unless use_sp_after_angle_always is set to true. sp_inside_fparens = remove # ignore/add/remove/force # Add or remove space inside function '(' and ')'. sp_inside_fparen = remove # ignore/add/remove/force # Add or remove space inside user functor '(' and ')'. sp_func_call_user_inside_rparen = ignore # ignore/add/remove/force # Add or remove space inside empty functor '()'. # Overrides sp_after_angle unless use_sp_after_angle_always is set to true. sp_inside_rparens = ignore # ignore/add/remove/force # Add or remove space inside functor '(' and ')'. sp_inside_rparen = ignore # ignore/add/remove/force # Add or remove space inside the first parentheses in a function type, as in # 'void (*x)(...)'. sp_inside_tparen = ignore # ignore/add/remove/force # Add or remove space between the ')' and '(' in a function type, as in # 'void (*x)(...)'. sp_after_tparen_close = ignore # ignore/add/remove/force # Add or remove space between ']' and '(' when part of a function call. sp_square_fparen = ignore # ignore/add/remove/force # Add or remove space between ')' and '{' of function. sp_fparen_brace = remove # ignore/add/remove/force # Add or remove space between ')' and '{' of a function call in object # initialization. # # Overrides sp_fparen_brace. sp_fparen_brace_initializer = remove # ignore/add/remove/force # (Java) Add or remove space between ')' and '{{' of double brace initializer. sp_fparen_dbrace = ignore # ignore/add/remove/force # Add or remove space between function name and '(' on function calls. sp_func_call_paren = remove # ignore/add/remove/force # Add or remove space between function name and '()' on function calls without # parameters. If set to ignore (the default), sp_func_call_paren is used. sp_func_call_paren_empty = ignore # ignore/add/remove/force # Add or remove space between the user function name and '(' on function # calls. You need to set a keyword to be a user function in the config file, # like: # set func_call_user tr _ i18n sp_func_call_user_paren = ignore # ignore/add/remove/force # Add or remove space inside user function '(' and ')'. sp_func_call_user_inside_fparen = ignore # ignore/add/remove/force # Add or remove space between nested parentheses with user functions, # i.e. '((' vs. '( ('. sp_func_call_user_paren_paren = ignore # ignore/add/remove/force # Add or remove space between a constructor/destructor and the open # parenthesis. sp_func_class_paren = ignore # ignore/add/remove/force # Add or remove space between a constructor without parameters or destructor # and '()'. sp_func_class_paren_empty = ignore # ignore/add/remove/force # Add or remove space after 'return'. # # Default: force sp_return = force # ignore/add/remove/force # Add or remove space between 'return' and '('. sp_return_paren = ignore # ignore/add/remove/force # Add or remove space between 'return' and '{'. sp_return_brace = ignore # ignore/add/remove/force # Add or remove space between '__attribute__' and '('. sp_attribute_paren = ignore # ignore/add/remove/force # Add or remove space between 'defined' and '(' in '#if defined (FOO)'. sp_defined_paren = ignore # ignore/add/remove/force # Add or remove space between 'throw' and '(' in 'throw (something)'. sp_throw_paren = ignore # ignore/add/remove/force # Add or remove space between 'throw' and anything other than '(' as in # '@throw [...];'. sp_after_throw = ignore # ignore/add/remove/force # Add or remove space between 'catch' and '(' in 'catch (something) { }'. # If set to ignore, sp_before_sparen is used. sp_catch_paren = ignore # ignore/add/remove/force # (OC) Add or remove space between '@catch' and '(' # in '@catch (something) { }'. If set to ignore, sp_catch_paren is used. sp_oc_catch_paren = ignore # ignore/add/remove/force # (OC) Add or remove space before Objective-C protocol list # as in '@protocol Protocol' or '@interface MyClass : NSObject'. sp_before_oc_proto_list = ignore # ignore/add/remove/force # (OC) Add or remove space between class name and '(' # in '@interface className(categoryName):BaseClass' sp_oc_classname_paren = ignore # ignore/add/remove/force # (D) Add or remove space between 'version' and '(' # in 'version (something) { }'. If set to ignore, sp_before_sparen is used. sp_version_paren = ignore # ignore/add/remove/force # (D) Add or remove space between 'scope' and '(' # in 'scope (something) { }'. If set to ignore, sp_before_sparen is used. sp_scope_paren = ignore # ignore/add/remove/force # Add or remove space between 'super' and '(' in 'super (something)'. # # Default: remove sp_super_paren = remove # ignore/add/remove/force # Add or remove space between 'this' and '(' in 'this (something)'. # # Default: remove sp_this_paren = remove # ignore/add/remove/force # Add or remove space between a macro name and its definition. sp_macro = ignore # ignore/add/remove/force # Add or remove space between a macro function ')' and its definition. sp_macro_func = ignore # ignore/add/remove/force # Add or remove space between 'else' and '{' if on the same line. sp_else_brace = remove # ignore/add/remove/force # Add or remove space between '}' and 'else' if on the same line. sp_brace_else = remove # ignore/add/remove/force # Add or remove space between '}' and the name of a typedef on the same line. sp_brace_typedef = ignore # ignore/add/remove/force # Add or remove space before the '{' of a 'catch' statement, if the '{' and # 'catch' are on the same line, as in 'catch (decl) {'. sp_catch_brace = ignore # ignore/add/remove/force # (OC) Add or remove space before the '{' of a '@catch' statement, if the '{' # and '@catch' are on the same line, as in '@catch (decl) {'. # If set to ignore, sp_catch_brace is used. sp_oc_catch_brace = ignore # ignore/add/remove/force # Add or remove space between '}' and 'catch' if on the same line. sp_brace_catch = ignore # ignore/add/remove/force # (OC) Add or remove space between '}' and '@catch' if on the same line. # If set to ignore, sp_brace_catch is used. sp_oc_brace_catch = ignore # ignore/add/remove/force # Add or remove space between 'finally' and '{' if on the same line. sp_finally_brace = ignore # ignore/add/remove/force # Add or remove space between '}' and 'finally' if on the same line. sp_brace_finally = ignore # ignore/add/remove/force # Add or remove space between 'try' and '{' if on the same line. sp_try_brace = ignore # ignore/add/remove/force # Add or remove space between get/set and '{' if on the same line. sp_getset_brace = ignore # ignore/add/remove/force # Add or remove space between a variable and '{' for C++ uniform # initialization. sp_word_brace_init_lst = ignore # ignore/add/remove/force # Add or remove space between a variable and '{' for a namespace. # # Default: add sp_word_brace_ns = remove # ignore/add/remove/force # Add or remove space before the '::' operator. sp_before_dc = ignore # ignore/add/remove/force # Add or remove space after the '::' operator. sp_after_dc = ignore # ignore/add/remove/force # (D) Add or remove around the D named array initializer ':' operator. sp_d_array_colon = ignore # ignore/add/remove/force # Add or remove space after the '!' (not) unary operator. # # Default: remove sp_not = remove # ignore/add/remove/force # Add or remove space between two '!' (not) unary operators. # If set to ignore, sp_not will be used. sp_not_not = ignore # ignore/add/remove/force # Add or remove space after the '~' (invert) unary operator. # # Default: remove sp_inv = remove # ignore/add/remove/force # Add or remove space after the '&' (address-of) unary operator. This does not # affect the spacing after a '&' that is part of a type. # # Default: remove sp_addr = remove # ignore/add/remove/force # Add or remove space around the '.' or '->' operators. # also the c-sharp null-conditional operator '?.' # # Default: remove sp_member = remove # ignore/add/remove/force # Add or remove space after the '*' (dereference) unary operator. This does # not affect the spacing after a '*' that is part of a type. # # Default: remove sp_deref = remove # ignore/add/remove/force # Add or remove space after '+' or '-', as in 'x = -5' or 'y = +7'. # # Default: remove sp_sign = remove # ignore/add/remove/force # Add or remove space between '++' and '--' the word to which it is being # applied, as in '(--x)' or 'y++;'. # # Default: remove sp_incdec = remove # ignore/add/remove/force # Add or remove space before a backslash-newline at the end of a line. # # Default: add sp_before_nl_cont = add # ignore/add/remove/force # (OC) Add or remove space after the scope '+' or '-', as in '-(void) foo;' # or '+(int) bar;'. sp_after_oc_scope = ignore # ignore/add/remove/force # (OC) Add or remove space after the colon in message specs, # i.e. '-(int) f:(int) x;' vs. '-(int) f: (int) x;'. sp_after_oc_colon = ignore # ignore/add/remove/force # (OC) Add or remove space before the colon in message specs, # i.e. '-(int) f: (int) x;' vs. '-(int) f : (int) x;'. sp_before_oc_colon = ignore # ignore/add/remove/force # (OC) Add or remove space after the colon in immutable dictionary expression # 'NSDictionary *test = @{@"foo" :@"bar"};'. sp_after_oc_dict_colon = ignore # ignore/add/remove/force # (OC) Add or remove space before the colon in immutable dictionary expression # 'NSDictionary *test = @{@"foo" :@"bar"};'. sp_before_oc_dict_colon = ignore # ignore/add/remove/force # (OC) Add or remove space after the colon in message specs, # i.e. '[object setValue:1];' vs. '[object setValue: 1];'. sp_after_send_oc_colon = ignore # ignore/add/remove/force # (OC) Add or remove space before the colon in message specs, # i.e. '[object setValue:1];' vs. '[object setValue :1];'. sp_before_send_oc_colon = ignore # ignore/add/remove/force # (OC) Add or remove space after the (type) in message specs, # i.e. '-(int)f: (int) x;' vs. '-(int)f: (int)x;'. sp_after_oc_type = ignore # ignore/add/remove/force # (OC) Add or remove space after the first (type) in message specs, # i.e. '-(int) f:(int)x;' vs. '-(int)f:(int)x;'. sp_after_oc_return_type = ignore # ignore/add/remove/force # (OC) Add or remove space between '@selector' and '(', # i.e. '@selector(msgName)' vs. '@selector (msgName)'. # Also applies to '@protocol()' constructs. sp_after_oc_at_sel = ignore # ignore/add/remove/force # (OC) Add or remove space between '@selector(x)' and the following word, # i.e. '@selector(foo) a:' vs. '@selector(foo)a:'. sp_after_oc_at_sel_parens = ignore # ignore/add/remove/force # (OC) Add or remove space inside '@selector' parentheses, # i.e. '@selector(foo)' vs. '@selector( foo )'. # Also applies to '@protocol()' constructs. sp_inside_oc_at_sel_parens = ignore # ignore/add/remove/force # (OC) Add or remove space before a block pointer caret, # i.e. '^int (int arg){...}' vs. ' ^int (int arg){...}'. sp_before_oc_block_caret = ignore # ignore/add/remove/force # (OC) Add or remove space after a block pointer caret, # i.e. '^int (int arg){...}' vs. '^ int (int arg){...}'. sp_after_oc_block_caret = ignore # ignore/add/remove/force # (OC) Add or remove space between the receiver and selector in a message, # as in '[receiver selector ...]'. sp_after_oc_msg_receiver = ignore # ignore/add/remove/force # (OC) Add or remove space after '@property'. sp_after_oc_property = ignore # ignore/add/remove/force # (OC) Add or remove space between '@synchronized' and the open parenthesis, # i.e. '@synchronized(foo)' vs. '@synchronized (foo)'. sp_after_oc_synchronized = ignore # ignore/add/remove/force # Add or remove space around the ':' in 'b ? t : f'. sp_cond_colon = ignore # ignore/add/remove/force # Add or remove space before the ':' in 'b ? t : f'. # # Overrides sp_cond_colon. sp_cond_colon_before = ignore # ignore/add/remove/force # Add or remove space after the ':' in 'b ? t : f'. # # Overrides sp_cond_colon. sp_cond_colon_after = ignore # ignore/add/remove/force # Add or remove space around the '?' in 'b ? t : f'. sp_cond_question = ignore # ignore/add/remove/force # Add or remove space before the '?' in 'b ? t : f'. # # Overrides sp_cond_question. sp_cond_question_before = ignore # ignore/add/remove/force # Add or remove space after the '?' in 'b ? t : f'. # # Overrides sp_cond_question. sp_cond_question_after = ignore # ignore/add/remove/force # In the abbreviated ternary form '(a ?: b)', add or remove space between '?' # and ':'. # # Overrides all other sp_cond_* options. sp_cond_ternary_short = ignore # ignore/add/remove/force # Fix the spacing between 'case' and the label. Only 'ignore' and 'force' make # sense here. sp_case_label = ignore # ignore/add/remove/force # (D) Add or remove space around the D '..' operator. sp_range = ignore # ignore/add/remove/force # Add or remove space after ':' in a Java/C++11 range-based 'for', # as in 'for (Type var : expr)'. sp_after_for_colon = ignore # ignore/add/remove/force # Add or remove space before ':' in a Java/C++11 range-based 'for', # as in 'for (Type var : expr)'. sp_before_for_colon = ignore # ignore/add/remove/force # (D) Add or remove space between 'extern' and '(' as in 'extern (C)'. sp_extern_paren = ignore # ignore/add/remove/force # Add or remove space after the opening of a C++ comment, as in '// A'. sp_cmt_cpp_start = ignore # ignore/add/remove/force # remove space after the '//' and the pvs command '-V1234', # only works with sp_cmt_cpp_start set to add or force. sp_cmt_cpp_pvs = false # true/false # remove space after the '//' and the command 'lint', # only works with sp_cmt_cpp_start set to add or force. sp_cmt_cpp_lint = false # true/false # Add or remove space in a C++ region marker comment, as in '// BEGIN'. # A region marker is defined as a comment which is not preceded by other text # (i.e. the comment is the first non-whitespace on the line), and which starts # with either 'BEGIN' or 'END'. # # Overrides sp_cmt_cpp_start. sp_cmt_cpp_region = ignore # ignore/add/remove/force # If true, space added with sp_cmt_cpp_start will be added after Doxygen # sequences like '///', '///<', '//!' and '//!<'. sp_cmt_cpp_doxygen = false # true/false # If true, space added with sp_cmt_cpp_start will be added after Qt translator # or meta-data comments like '//:', '//=', and '//~'. sp_cmt_cpp_qttr = false # true/false # Add or remove space between #else or #endif and a trailing comment. sp_endif_cmt = ignore # ignore/add/remove/force # Add or remove space after 'new', 'delete' and 'delete[]'. sp_after_new = ignore # ignore/add/remove/force # Add or remove space between 'new' and '(' in 'new()'. sp_between_new_paren = ignore # ignore/add/remove/force # Add or remove space between ')' and type in 'new(foo) BAR'. sp_after_newop_paren = ignore # ignore/add/remove/force # Add or remove space inside parentheses of the new operator # as in 'new(foo) BAR'. sp_inside_newop_paren = ignore # ignore/add/remove/force # Add or remove space after the open parenthesis of the new operator, # as in 'new(foo) BAR'. # # Overrides sp_inside_newop_paren. sp_inside_newop_paren_open = ignore # ignore/add/remove/force # Add or remove space before the close parenthesis of the new operator, # as in 'new(foo) BAR'. # # Overrides sp_inside_newop_paren. sp_inside_newop_paren_close = ignore # ignore/add/remove/force # Add or remove space before a trailing comment. sp_before_tr_cmt = ignore # ignore/add/remove/force # Number of spaces before a trailing comment. sp_num_before_tr_cmt = 0 # unsigned number # Add or remove space before an embedded comment. # # Default: force sp_before_emb_cmt = force # ignore/add/remove/force # Number of spaces before an embedded comment. # # Default: 1 sp_num_before_emb_cmt = 1 # unsigned number # Add or remove space after an embedded comment. # # Default: force sp_after_emb_cmt = force # ignore/add/remove/force # Number of spaces after an embedded comment. # # Default: 1 sp_num_after_emb_cmt = 1 # unsigned number # Embedded comment spacing options have higher priority (== override) # than other spacing options (comma, parenthesis, braces, ...) sp_emb_cmt_priority = false # true/false # (Java) Add or remove space between an annotation and the open parenthesis. sp_annotation_paren = ignore # ignore/add/remove/force # If true, vbrace tokens are dropped to the previous token and skipped. sp_skip_vbrace_tokens = false # true/false # Add or remove space after 'noexcept'. sp_after_noexcept = ignore # ignore/add/remove/force # Add or remove space after '_'. sp_vala_after_translation = ignore # ignore/add/remove/force # Add or remove space before a bit colon ':'. sp_before_bit_colon = ignore # ignore/add/remove/force # Add or remove space after a bit colon ':'. sp_after_bit_colon = ignore # ignore/add/remove/force # If true, a is inserted after #define. force_tab_after_define = false # true/false # Add or remove space between two strings. sp_string_string = ignore # ignore/add/remove/force # Add or remove space 'struct' and a type. sp_struct_type = ignore # ignore/add/remove/force # # Indenting options # # The number of columns to indent per level. Usually 2, 3, 4, or 8. # # Default: 8 indent_columns = 4 # unsigned number # Whether to ignore indent for the first continuation line. Subsequent # continuation lines will still be indented to match the first. indent_ignore_first_continue = false # true/false # The continuation indent. If non-zero, this overrides the indent of '(', '[' # and '=' continuation indents. Negative values are OK; negative value is # absolute and not increased for each '(' or '[' level. # # For FreeBSD, this is set to 4. # Requires indent_ignore_first_continue=false. indent_continue = 8 # number # The continuation indent, only for class header line(s). If non-zero, this # overrides the indent of 'class' continuation indents. # Requires indent_ignore_first_continue=false. indent_continue_class_head = 0 # unsigned number # Whether to indent empty lines (i.e. lines which contain only spaces before # the newline character). indent_single_newlines = false # true/false # The continuation indent for func_*_param if they are true. If non-zero, this # overrides the indent. indent_param = 0 # unsigned number # How to use tabs when indenting code. # # 0: Spaces only # 1: Indent with tabs to brace level, align with spaces (default) # 2: Indent and align with tabs, using spaces when not on a tabstop # # Default: 1 indent_with_tabs = 2 # unsigned number # Whether to indent comments that are not at a brace level with tabs on a # tabstop. Requires indent_with_tabs=2. If false, will use spaces. indent_cmt_with_tabs = false # true/false # Whether to indent strings broken by '\' so that they line up. indent_align_string = false # true/false # The number of spaces to indent multi-line XML strings. # Requires indent_align_string=true. indent_xml_string = 0 # unsigned number # Spaces to indent '{' from level. indent_brace = 0 # unsigned number # Whether braces are indented to the body level. indent_braces = false # true/false # Whether to disable indenting function braces if indent_braces=true. indent_braces_no_func = false # true/false # Whether to disable indenting class braces if indent_braces=true. indent_braces_no_class = false # true/false # Whether to disable indenting struct braces if indent_braces=true. indent_braces_no_struct = false # true/false # Whether to indent based on the size of the brace parent, # i.e. 'if' => 3 spaces, 'for' => 4 spaces, etc. indent_brace_parent = false # true/false # Whether to indent based on the open parenthesis instead of the open brace # in '({\n'. indent_paren_open_brace = false # true/false # (C#) Whether to indent the brace of a C# delegate by another level. indent_cs_delegate_brace = false # true/false # (C#) Whether to indent a C# delegate (to handle delegates with no brace) by # another level. indent_cs_delegate_body = false # true/false # Whether to indent the body of a 'namespace'. indent_namespace = false # true/false # Whether to indent only the first namespace, and not any nested namespaces. # Requires indent_namespace=true. indent_namespace_single_indent = false # true/false # The number of spaces to indent a namespace block. # If set to zero, use the value indent_columns indent_namespace_level = 0 # unsigned number # If the body of the namespace is longer than this number, it won't be # indented. Requires indent_namespace=true. 0 means no limit. indent_namespace_limit = 0 # unsigned number # Whether to indent only in inner namespaces (nested in other namespaces). # Requires indent_namespace=true. indent_namespace_inner_only = false # true/false # Whether the 'extern "C"' body is indented. indent_extern = false # true/false # Whether the 'class' body is indented. indent_class = true # true/false # Whether to ignore indent for the leading base class colon. indent_ignore_before_class_colon = false # true/false # Additional indent before the leading base class colon. # Negative values decrease indent down to the first column. # Requires indent_ignore_before_class_colon=false and a newline break before # the colon (see pos_class_colon and nl_class_colon) indent_before_class_colon = 0 # number # Whether to indent the stuff after a leading base class colon. indent_class_colon = false # true/false # Whether to indent based on a class colon instead of the stuff after the # colon. Requires indent_class_colon=true. indent_class_on_colon = false # true/false # Whether to ignore indent for a leading class initializer colon. indent_ignore_before_constr_colon = false # true/false # Whether to indent the stuff after a leading class initializer colon. indent_constr_colon = false # true/false # Virtual indent from the ':' for leading member initializers. # # Default: 2 indent_ctor_init_leading = 2 # unsigned number # Virtual indent from the ':' for following member initializers. # # Default: 2 indent_ctor_init_following = 2 # unsigned number # Additional indent for constructor initializer list. # Negative values decrease indent down to the first column. indent_ctor_init = 0 # number # Whether to indent 'if' following 'else' as a new block under the 'else'. # If false, 'else\nif' is treated as 'else if' for indenting purposes. indent_else_if = false # true/false # Amount to indent variable declarations after a open brace. # # <0: Relative # >=0: Absolute indent_var_def_blk = 0 # number # Whether to indent continued variable declarations instead of aligning. indent_var_def_cont = true # true/false # How to indent continued shift expressions ('<<' and '>>'). # Set align_left_shift=false when using this. # 0: Align shift operators instead of indenting them (default) # 1: Indent by one level # -1: Preserve original indentation indent_shift = 0 # number # Whether to force indentation of function definitions to start in column 1. indent_func_def_force_col1 = false # true/false # Whether to indent continued function call parameters one indent level, # rather than aligning parameters under the open parenthesis. indent_func_call_param = true # true/false # Whether to indent continued function definition parameters one indent level, # rather than aligning parameters under the open parenthesis. indent_func_def_param = true # true/false # for function definitions, only if indent_func_def_param is false # Allows to align params when appropriate and indent them when not # behave as if it was true if paren position is more than this value # if paren position is more than the option value indent_func_def_param_paren_pos_threshold = 0 # unsigned number # Whether to indent continued function call prototype one indent level, # rather than aligning parameters under the open parenthesis. indent_func_proto_param = true # true/false # Whether to indent continued function call declaration one indent level, # rather than aligning parameters under the open parenthesis. indent_func_class_param = true # true/false # Whether to indent continued class variable constructors one indent level, # rather than aligning parameters under the open parenthesis. indent_func_ctor_var_param = true # true/false # Whether to indent continued template parameter list one indent level, # rather than aligning parameters under the open parenthesis. indent_template_param = true # true/false # Double the indent for indent_func_xxx_param options. # Use both values of the options indent_columns and indent_param. indent_func_param_double = true # true/false # Indentation column for standalone 'const' qualifier on a function # prototype. indent_func_const = 0 # unsigned number # Indentation column for standalone 'throw' qualifier on a function # prototype. indent_func_throw = 0 # unsigned number # How to indent within a macro followed by a brace on the same line # This allows reducing the indent in macros that have (for example) # `do { ... } while (0)` blocks bracketing them. # # true: add an indent for the brace on the same line as the macro # false: do not add an indent for the brace on the same line as the macro # # Default: true indent_macro_brace = true # true/false # The number of spaces to indent a continued '->' or '.'. # Usually set to 0, 1, or indent_columns. indent_member = indent_columns # unsigned number # Whether lines broken at '.' or '->' should be indented by a single indent. # The indent_member option will not be effective if this is set to true. indent_member_single = false # true/false # Spaces to indent single line ('//') comments on lines before code. indent_single_line_comments_before = 0 # unsigned number # Spaces to indent single line ('//') comments on lines after code. indent_single_line_comments_after = 0 # unsigned number # When opening a paren for a control statement (if, for, while, etc), increase # the indent level by this value. Negative values decrease the indent level. indent_sparen_extra = 0 # number # Whether to indent trailing single line ('//') comments relative to the code # instead of trying to keep the same absolute column. indent_relative_single_line_comments = false # true/false # Spaces to indent 'case' from 'switch'. Usually 0 or indent_columns. # It might be wise to choose the same value for the option indent_case_brace. indent_switch_case = indent_columns # unsigned number # Spaces to indent the body of a 'switch' before any 'case'. # Usually the same as indent_columns or indent_switch_case. indent_switch_body = 0 # unsigned number # Whether to ignore indent for '{' following 'case'. indent_ignore_case_brace = false # true/false # Spaces to indent '{' from 'case'. By default, the brace will appear under # the 'c' in case. Usually set to 0 or indent_columns. Negative values are OK. # It might be wise to choose the same value for the option indent_switch_case. indent_case_brace = indent_columns # number # indent 'break' with 'case' from 'switch'. indent_switch_break_with_case = false # true/false # Whether to indent preprocessor statements inside of switch statements. # # Default: true indent_switch_pp = true # true/false # Spaces to shift the 'case' line, without affecting any other lines. # Usually 0. indent_case_shift = 0 # unsigned number # Whether to align comments before 'case' with the 'case'. # # Default: true indent_case_comment = true # true/false # Whether to indent comments not found in first column. # # Default: true indent_comment = true # true/false # Whether to indent comments found in first column. indent_col1_comment = false # true/false # Whether to indent multi string literal in first column. indent_col1_multi_string_literal = false # true/false # Align comments on adjacent lines that are this many columns apart or less. # # Default: 3 indent_comment_align_thresh = 3 # unsigned number # Whether to ignore indent for goto labels. indent_ignore_label = false # true/false # How to indent goto labels. Requires indent_ignore_label=false. # # >0: Absolute column where 1 is the leftmost column # <=0: Subtract from brace indent # # Default: 1 indent_label = 1 # number # How to indent access specifiers that are followed by a # colon. # # >0: Absolute column where 1 is the leftmost column # <=0: Subtract from brace indent # # Default: 1 indent_access_spec = 1 # number # Whether to indent the code after an access specifier by one level. # If true, this option forces 'indent_access_spec=0'. indent_access_spec_body = false # true/false # If an open parenthesis is followed by a newline, whether to indent the next # line so that it lines up after the open parenthesis (not recommended). indent_paren_nl = false # true/false # How to indent a close parenthesis after a newline. # # 0: Indent to body level (default) # 1: Align under the open parenthesis # 2: Indent to the brace level # -1: Preserve original indentation indent_paren_close = 0 # number # Whether to indent the open parenthesis of a function definition, # if the parenthesis is on its own line. indent_paren_after_func_def = false # true/false # Whether to indent the open parenthesis of a function declaration, # if the parenthesis is on its own line. indent_paren_after_func_decl = false # true/false # Whether to indent the open parenthesis of a function call, # if the parenthesis is on its own line. indent_paren_after_func_call = false # true/false # How to indent a comma when inside braces. # 0: Indent by one level (default) # 1: Align under the open brace # -1: Preserve original indentation indent_comma_brace = 0 # number # How to indent a comma when inside parentheses. # 0: Indent by one level (default) # 1: Align under the open parenthesis # -1: Preserve original indentation indent_comma_paren = 0 # number # How to indent a Boolean operator when inside parentheses. # 0: Indent by one level (default) # 1: Align under the open parenthesis # -1: Preserve original indentation indent_bool_paren = 0 # number # Whether to ignore the indentation of a Boolean operator when outside # parentheses. indent_ignore_bool = false # true/false # Whether to indent lines that are nested in boolean expression one more level for each nesting indent_bool_nested_all = false # true/false # Whether to ignore the indentation of an arithmetic operator. indent_ignore_arith = false # true/false # Whether to indent a semicolon when inside a for parenthesis. # If true, aligns under the open for parenthesis. indent_semicolon_for_paren = false # true/false # Whether to ignore the indentation of a semicolon outside of a 'for' # statement. indent_ignore_semicolon = false # true/false # Whether to align the first expression to following ones # if indent_bool_paren=1. indent_first_bool_expr = false # true/false # Whether to align the first expression to following ones # if indent_semicolon_for_paren=true. indent_first_for_expr = false # true/false # If an open square is followed by a newline, whether to indent the next line # so that it lines up after the open square (not recommended). indent_square_nl = false # true/false # (ESQL/C) Whether to preserve the relative indent of 'EXEC SQL' bodies. indent_preserve_sql = false # true/false # Whether to ignore the indentation of an assignment operator. indent_ignore_assign = false # true/false # Whether to align continued statements at the '='. If false or if the '=' is # followed by a newline, the next line is indent one tab. # # Default: true indent_align_assign = true # true/false # If true, the indentation of the chunks after a '=' sequence will be set at # LHS token indentation column before '='. indent_off_after_assign = false # true/false # Whether to align continued statements at the '('. If false or the '(' is # followed by a newline, the next line indent is one tab. # # Default: true indent_align_paren = true # true/false # (OC) Whether to indent Objective-C code inside message selectors. indent_oc_inside_msg_sel = false # true/false # (OC) Whether to indent Objective-C blocks at brace level instead of usual # rules. indent_oc_block = false # true/false # (OC) Indent for Objective-C blocks in a message relative to the parameter # name. # # =0: Use indent_oc_block rules # >0: Use specified number of spaces to indent indent_oc_block_msg = 0 # unsigned number # (OC) Minimum indent for subsequent parameters indent_oc_msg_colon = 0 # unsigned number # (OC) Whether to prioritize aligning with initial colon (and stripping spaces # from lines, if necessary). # # Default: true indent_oc_msg_prioritize_first_colon = true # true/false # (OC) Whether to indent blocks the way that Xcode does by default # (from the keyword if the parameter is on its own line; otherwise, from the # previous indentation level). Requires indent_oc_block_msg=true. indent_oc_block_msg_xcode_style = false # true/false # (OC) Whether to indent blocks from where the brace is, relative to a # message keyword. Requires indent_oc_block_msg=true. indent_oc_block_msg_from_keyword = false # true/false # (OC) Whether to indent blocks from where the brace is, relative to a message # colon. Requires indent_oc_block_msg=true. indent_oc_block_msg_from_colon = false # true/false # (OC) Whether to indent blocks from where the block caret is. # Requires indent_oc_block_msg=true. indent_oc_block_msg_from_caret = false # true/false # (OC) Whether to indent blocks from where the brace caret is. # Requires indent_oc_block_msg=true. indent_oc_block_msg_from_brace = false # true/false # When indenting after virtual brace open and newline add further spaces to # reach this minimum indent. indent_min_vbrace_open = 0 # unsigned number # Whether to add further spaces after regular indent to reach next tabstop # when indenting after virtual brace open and newline. indent_vbrace_open_on_tabstop = false # true/false # How to indent after a brace followed by another token (not a newline). # true: indent all contained lines to match the token # false: indent all contained lines to match the brace # # Default: true indent_token_after_brace = true # true/false # Whether to indent the body of a C++11 lambda. indent_cpp_lambda_body = false # true/false # How to indent compound literals that are being returned. # true: add both the indent from return & the compound literal open brace # (i.e. 2 indent levels) # false: only indent 1 level, don't add the indent for the open brace, only # add the indent for the return. # # Default: true indent_compound_literal_return = true # true/false # (C#) Whether to indent a 'using' block if no braces are used. # # Default: true indent_using_block = true # true/false # How to indent the continuation of ternary operator. # # 0: Off (default) # 1: When the `if_false` is a continuation, indent it under the `if_true` branch # 2: When the `:` is a continuation, indent it under `?` indent_ternary_operator = 0 # unsigned number # Whether to indent the statements inside ternary operator. indent_inside_ternary_operator = false # true/false # If true, the indentation of the chunks after a `return` sequence will be set at return indentation column. indent_off_after_return = false # true/false # If true, the indentation of the chunks after a `return new` sequence will be set at return indentation column. indent_off_after_return_new = false # true/false # If true, the tokens after return are indented with regular single indentation. By default (false) the indentation is after the return token. indent_single_after_return = false # true/false # Whether to ignore indent and alignment for 'asm' blocks (i.e. assume they # have their own indentation). indent_ignore_asm_block = false # true/false # Don't indent the close parenthesis of a function definition, # if the parenthesis is on its own line. donot_indent_func_def_close_paren = false # true/false # # Newline adding and removing options # # Whether to collapse empty blocks between '{' and '}' except for functions. # Use nl_collapse_empty_body_functions to specify how empty function braces # should be formatted. nl_collapse_empty_body = false # true/false # Whether to collapse empty blocks between '{' and '}' for functions only. # If true, overrides nl_inside_empty_func. nl_collapse_empty_body_functions = false # true/false # Don't split one-line braced assignments, as in 'foo_t f = { 1, 2 };'. nl_assign_leave_one_liners = true # true/false # Don't split one-line braced statements inside a 'class xx { }' body. nl_class_leave_one_liners = true # true/false # Don't split one-line enums, as in 'enum foo { BAR = 15 };' nl_enum_leave_one_liners = true # true/false # Don't split one-line get or set functions. nl_getset_leave_one_liners = true # true/false # (C#) Don't split one-line property get or set functions. nl_cs_property_leave_one_liners = false # true/false # Don't split one-line function definitions, as in 'int foo() { return 0; }'. # might modify nl_func_type_name nl_func_leave_one_liners = false # true/false # Don't split one-line C++11 lambdas, as in '[]() { return 0; }'. nl_cpp_lambda_leave_one_liners = false # true/false # Don't split one-line if/else statements, as in 'if(...) b++;'. nl_if_leave_one_liners = false # true/false # Don't split one-line while statements, as in 'while(...) b++;'. nl_while_leave_one_liners = false # true/false # Don't split one-line do statements, as in 'do { b++; } while(...);'. nl_do_leave_one_liners = false # true/false # Don't split one-line for statements, as in 'for(...) b++;'. nl_for_leave_one_liners = false # true/false # (OC) Don't split one-line Objective-C messages. nl_oc_msg_leave_one_liner = false # true/false # (OC) Add or remove newline between method declaration and '{'. nl_oc_mdef_brace = ignore # ignore/add/remove/force # (OC) Add or remove newline between Objective-C block signature and '{'. nl_oc_block_brace = ignore # ignore/add/remove/force # (OC) Add or remove blank line before '@interface' statement. nl_oc_before_interface = ignore # ignore/add/remove/force # (OC) Add or remove blank line before '@implementation' statement. nl_oc_before_implementation = ignore # ignore/add/remove/force # (OC) Add or remove blank line before '@end' statement. nl_oc_before_end = ignore # ignore/add/remove/force # (OC) Add or remove newline between '@interface' and '{'. nl_oc_interface_brace = ignore # ignore/add/remove/force # (OC) Add or remove newline between '@implementation' and '{'. nl_oc_implementation_brace = ignore # ignore/add/remove/force # Add or remove newlines at the start of the file. nl_start_of_file = ignore # ignore/add/remove/force # The minimum number of newlines at the start of the file (only used if # nl_start_of_file is 'add' or 'force'). nl_start_of_file_min = 0 # unsigned number # Add or remove newline at the end of the file. nl_end_of_file = ignore # ignore/add/remove/force # The minimum number of newlines at the end of the file (only used if # nl_end_of_file is 'add' or 'force'). nl_end_of_file_min = 0 # unsigned number # Add or remove newline between '=' and '{'. nl_assign_brace = remove # ignore/add/remove/force # (D) Add or remove newline between '=' and '['. nl_assign_square = ignore # ignore/add/remove/force # Add or remove newline between '[]' and '{'. nl_tsquare_brace = ignore # ignore/add/remove/force # (D) Add or remove newline after '= ['. Will also affect the newline before # the ']'. nl_after_square_assign = ignore # ignore/add/remove/force # Add or remove newline between a function call's ')' and '{', as in # 'list_for_each(item, &list) { }'. nl_fcall_brace = add # ignore/add/remove/force # Add or remove newline between 'enum' and '{'. nl_enum_brace = remove # ignore/add/remove/force # Add or remove newline between 'enum' and 'class'. nl_enum_class = ignore # ignore/add/remove/force # Add or remove newline between 'enum class' and the identifier. nl_enum_class_identifier = ignore # ignore/add/remove/force # Add or remove newline between 'enum class' type and ':'. nl_enum_identifier_colon = ignore # ignore/add/remove/force # Add or remove newline between 'enum class identifier :' and type. nl_enum_colon_type = ignore # ignore/add/remove/force # Add or remove newline between 'struct and '{'. nl_struct_brace = remove # ignore/add/remove/force # Add or remove newline between 'union' and '{'. nl_union_brace = remove # ignore/add/remove/force # Add or remove newline between 'if' and '{'. nl_if_brace = remove # ignore/add/remove/force # Add or remove newline between '}' and 'else'. nl_brace_else = remove # ignore/add/remove/force # Add or remove newline between 'else if' and '{'. If set to ignore, # nl_if_brace is used instead. nl_elseif_brace = remove # ignore/add/remove/force # Add or remove newline between 'else' and '{'. nl_else_brace = remove # ignore/add/remove/force # Add or remove newline between 'else' and 'if'. nl_else_if = remove # ignore/add/remove/force # Add or remove newline before '{' opening brace nl_before_opening_brace_func_class_def = ignore # ignore/add/remove/force # Add or remove newline before 'if'/'else if' closing parenthesis. nl_before_if_closing_paren = ignore # ignore/add/remove/force # Add or remove newline between '}' and 'finally'. nl_brace_finally = ignore # ignore/add/remove/force # Add or remove newline between 'finally' and '{'. nl_finally_brace = ignore # ignore/add/remove/force # Add or remove newline between 'try' and '{'. nl_try_brace = ignore # ignore/add/remove/force # Add or remove newline between get/set and '{'. nl_getset_brace = ignore # ignore/add/remove/force # Add or remove newline between 'for' and '{'. nl_for_brace = remove # ignore/add/remove/force # Add or remove newline before the '{' of a 'catch' statement, as in # 'catch (decl) {'. nl_catch_brace = ignore # ignore/add/remove/force # (OC) Add or remove newline before the '{' of a '@catch' statement, as in # '@catch (decl) {'. If set to ignore, nl_catch_brace is used. nl_oc_catch_brace = ignore # ignore/add/remove/force # Add or remove newline between '}' and 'catch'. nl_brace_catch = ignore # ignore/add/remove/force # (OC) Add or remove newline between '}' and '@catch'. If set to ignore, # nl_brace_catch is used. nl_oc_brace_catch = ignore # ignore/add/remove/force # Add or remove newline between '}' and ']'. nl_brace_square = ignore # ignore/add/remove/force # Add or remove newline between '}' and ')' in a function invocation. nl_brace_fparen = ignore # ignore/add/remove/force # Add or remove newline between 'while' and '{'. nl_while_brace = remove # ignore/add/remove/force # (D) Add or remove newline between 'scope (x)' and '{'. nl_scope_brace = ignore # ignore/add/remove/force # (D) Add or remove newline between 'unittest' and '{'. nl_unittest_brace = ignore # ignore/add/remove/force # (D) Add or remove newline between 'version (x)' and '{'. nl_version_brace = ignore # ignore/add/remove/force # (C#) Add or remove newline between 'using' and '{'. nl_using_brace = ignore # ignore/add/remove/force # Add or remove newline between two open or close braces. Due to general # newline/brace handling, REMOVE may not work. nl_brace_brace = ignore # ignore/add/remove/force # Add or remove newline between 'do' and '{'. nl_do_brace = remove # ignore/add/remove/force # Add or remove newline between '}' and 'while' of 'do' statement. nl_brace_while = remove # ignore/add/remove/force # Add or remove newline between 'switch' and '{'. nl_switch_brace = remove # ignore/add/remove/force # Add or remove newline between 'synchronized' and '{'. nl_synchronized_brace = remove # ignore/add/remove/force # Add a newline between ')' and '{' if the ')' is on a different line than the # if/for/etc. # # Overrides nl_for_brace, nl_if_brace, nl_switch_brace, nl_while_switch and # nl_catch_brace. nl_multi_line_cond = false # true/false # Add a newline after '(' if an if/for/while/switch condition spans multiple # lines nl_multi_line_sparen_open = ignore # ignore/add/remove/force # Add a newline before ')' if an if/for/while/switch condition spans multiple # lines. Overrides nl_before_if_closing_paren if both are specified. nl_multi_line_sparen_close = ignore # ignore/add/remove/force # Force a newline in a define after the macro name for multi-line defines. nl_multi_line_define = false # true/false # Whether to add a newline before 'case', and a blank line before a 'case' # statement that follows a ';' or '}'. nl_before_case = false # true/false # Whether to add a newline after a 'case' statement. nl_after_case = false # true/false # Add or remove newline between a case ':' and '{'. # # Overrides nl_after_case. nl_case_colon_brace = ignore # ignore/add/remove/force # Add or remove newline between ')' and 'throw'. nl_before_throw = ignore # ignore/add/remove/force # Add or remove newline between 'namespace' and '{'. nl_namespace_brace = ignore # ignore/add/remove/force # Add or remove newline after 'template<...>' of a template class. nl_template_class = ignore # ignore/add/remove/force # Add or remove newline after 'template<...>' of a template class declaration. # # Overrides nl_template_class. nl_template_class_decl = ignore # ignore/add/remove/force # Add or remove newline after 'template<>' of a specialized class declaration. # # Overrides nl_template_class_decl. nl_template_class_decl_special = ignore # ignore/add/remove/force # Add or remove newline after 'template<...>' of a template class definition. # # Overrides nl_template_class. nl_template_class_def = ignore # ignore/add/remove/force # Add or remove newline after 'template<>' of a specialized class definition. # # Overrides nl_template_class_def. nl_template_class_def_special = ignore # ignore/add/remove/force # Add or remove newline after 'template<...>' of a template function. nl_template_func = ignore # ignore/add/remove/force # Add or remove newline after 'template<...>' of a template function # declaration. # # Overrides nl_template_func. nl_template_func_decl = ignore # ignore/add/remove/force # Add or remove newline after 'template<>' of a specialized function # declaration. # # Overrides nl_template_func_decl. nl_template_func_decl_special = ignore # ignore/add/remove/force # Add or remove newline after 'template<...>' of a template function # definition. # # Overrides nl_template_func. nl_template_func_def = ignore # ignore/add/remove/force # Add or remove newline after 'template<>' of a specialized function # definition. # # Overrides nl_template_func_def. nl_template_func_def_special = ignore # ignore/add/remove/force # Add or remove newline after 'template<...>' of a template variable. nl_template_var = ignore # ignore/add/remove/force # Add or remove newline between 'template<...>' and 'using' of a templated # type alias. nl_template_using = ignore # ignore/add/remove/force # Add or remove newline between 'class' and '{'. nl_class_brace = ignore # ignore/add/remove/force # Add or remove newline before or after (depending on pos_class_comma, # may not be IGNORE) each',' in the base class list. nl_class_init_args = ignore # ignore/add/remove/force # Add or remove newline after each ',' in the constructor member # initialization. Related to nl_constr_colon, pos_constr_colon and # pos_constr_comma. nl_constr_init_args = ignore # ignore/add/remove/force # Add or remove newline before first element, after comma, and after last # element, in 'enum'. nl_enum_own_lines = ignore # ignore/add/remove/force # Add or remove newline between return type and function name in a function # definition. # might be modified by nl_func_leave_one_liners nl_func_type_name = ignore # ignore/add/remove/force # Add or remove newline between return type and function name inside a class # definition. If set to ignore, nl_func_type_name or nl_func_proto_type_name # is used instead. nl_func_type_name_class = ignore # ignore/add/remove/force # Add or remove newline between class specification and '::' # in 'void A::f() { }'. Only appears in separate member implementation (does # not appear with in-line implementation). nl_func_class_scope = ignore # ignore/add/remove/force # Add or remove newline between function scope and name, as in # 'void A :: f() { }'. nl_func_scope_name = ignore # ignore/add/remove/force # Add or remove newline between return type and function name in a prototype. nl_func_proto_type_name = ignore # ignore/add/remove/force # Add or remove newline between a function name and the opening '(' in the # declaration. nl_func_paren = remove # ignore/add/remove/force # Overrides nl_func_paren for functions with no parameters. nl_func_paren_empty = remove # ignore/add/remove/force # Add or remove newline between a function name and the opening '(' in the # definition. nl_func_def_paren = remove # ignore/add/remove/force # Overrides nl_func_def_paren for functions with no parameters. nl_func_def_paren_empty = remove # ignore/add/remove/force # Add or remove newline between a function name and the opening '(' in the # call. nl_func_call_paren = remove # ignore/add/remove/force # Overrides nl_func_call_paren for functions with no parameters. nl_func_call_paren_empty = remove # ignore/add/remove/force # Add or remove newline after '(' in a function declaration. nl_func_decl_start = ignore # ignore/add/remove/force # Add or remove newline after '(' in a function definition. nl_func_def_start = ignore # ignore/add/remove/force # Overrides nl_func_decl_start when there is only one parameter. nl_func_decl_start_single = ignore # ignore/add/remove/force # Overrides nl_func_def_start when there is only one parameter. nl_func_def_start_single = ignore # ignore/add/remove/force # Whether to add a newline after '(' in a function declaration if '(' and ')' # are in different lines. If false, nl_func_decl_start is used instead. nl_func_decl_start_multi_line = false # true/false # Whether to add a newline after '(' in a function definition if '(' and ')' # are in different lines. If false, nl_func_def_start is used instead. nl_func_def_start_multi_line = false # true/false # Add or remove newline after each ',' in a function declaration. nl_func_decl_args = ignore # ignore/add/remove/force # Add or remove newline after each ',' in a function definition. nl_func_def_args = ignore # ignore/add/remove/force # Add or remove newline after each ',' in a function call. nl_func_call_args = ignore # ignore/add/remove/force # Whether to add a newline after each ',' in a function declaration if '(' # and ')' are in different lines. If false, nl_func_decl_args is used instead. nl_func_decl_args_multi_line = false # true/false # Whether to add a newline after each ',' in a function definition if '(' # and ')' are in different lines. If false, nl_func_def_args is used instead. nl_func_def_args_multi_line = false # true/false # Add or remove newline before the ')' in a function declaration. nl_func_decl_end = ignore # ignore/add/remove/force # Add or remove newline before the ')' in a function definition. nl_func_def_end = ignore # ignore/add/remove/force # Overrides nl_func_decl_end when there is only one parameter. nl_func_decl_end_single = ignore # ignore/add/remove/force # Overrides nl_func_def_end when there is only one parameter. nl_func_def_end_single = ignore # ignore/add/remove/force # Whether to add a newline before ')' in a function declaration if '(' and ')' # are in different lines. If false, nl_func_decl_end is used instead. nl_func_decl_end_multi_line = false # true/false # Whether to add a newline before ')' in a function definition if '(' and ')' # are in different lines. If false, nl_func_def_end is used instead. nl_func_def_end_multi_line = false # true/false # Add or remove newline between '()' in a function declaration. nl_func_decl_empty = ignore # ignore/add/remove/force # Add or remove newline between '()' in a function definition. nl_func_def_empty = ignore # ignore/add/remove/force # Add or remove newline between '()' in a function call. nl_func_call_empty = ignore # ignore/add/remove/force # Whether to add a newline after '(' in a function call, # has preference over nl_func_call_start_multi_line. nl_func_call_start = ignore # ignore/add/remove/force # Whether to add a newline before ')' in a function call. nl_func_call_end = ignore # ignore/add/remove/force # Whether to add a newline after '(' in a function call if '(' and ')' are in # different lines. nl_func_call_start_multi_line = false # true/false # Whether to add a newline after each ',' in a function call if '(' and ')' # are in different lines. nl_func_call_args_multi_line = false # true/false # Whether to add a newline before ')' in a function call if '(' and ')' are in # different lines. nl_func_call_end_multi_line = false # true/false # Whether to respect nl_func_call_XXX option in case of closure args. nl_func_call_args_multi_line_ignore_closures = false # true/false # Whether to add a newline after '<' of a template parameter list. nl_template_start = false # true/false # Whether to add a newline after each ',' in a template parameter list. nl_template_args = false # true/false # Whether to add a newline before '>' of a template parameter list. nl_template_end = false # true/false # (OC) Whether to put each Objective-C message parameter on a separate line. # See nl_oc_msg_leave_one_liner. nl_oc_msg_args = false # true/false # (OC) Minimum number of Objective-C message parameters before applying nl_oc_msg_args. nl_oc_msg_args_min_params = 0 # unsigned number # (OC) Max code width of Objective-C message before applying nl_oc_msg_args. nl_oc_msg_args_max_code_width = 0 # unsigned number # (OC) Whether to apply nl_oc_msg_args if some of the parameters are already # on new lines. Overrides nl_oc_msg_args_min_params and nl_oc_msg_args_max_code_width. nl_oc_msg_args_finish_multi_line = false # true/false # Add or remove newline between function signature and '{'. nl_fdef_brace = add # ignore/add/remove/force # Add or remove newline between function signature and '{', # if signature ends with ')'. Overrides nl_fdef_brace. nl_fdef_brace_cond = ignore # ignore/add/remove/force # Add or remove newline between C++11 lambda signature and '{'. nl_cpp_ldef_brace = ignore # ignore/add/remove/force # Add or remove newline between 'return' and the return expression. nl_return_expr = ignore # ignore/add/remove/force # Add or remove newline between 'throw' and the throw expression. nl_throw_expr = ignore # ignore/add/remove/force # Whether to add a newline after semicolons, except in 'for' statements. nl_after_semicolon = false # true/false # (Java) Add or remove newline between the ')' and '{{' of the double brace # initializer. nl_paren_dbrace_open = ignore # ignore/add/remove/force # Whether to add a newline after the type in an unnamed temporary # direct-list-initialization, better: # before a direct-list-initialization. nl_type_brace_init_lst = ignore # ignore/add/remove/force # Whether to add a newline after the open brace in an unnamed temporary # direct-list-initialization. nl_type_brace_init_lst_open = ignore # ignore/add/remove/force # Whether to add a newline before the close brace in an unnamed temporary # direct-list-initialization. nl_type_brace_init_lst_close = ignore # ignore/add/remove/force # Whether to add a newline before '{'. nl_before_brace_open = false # true/false # Whether to add a newline after '{'. nl_after_brace_open = false # true/false # Whether to add a newline between the open brace and a trailing single-line # comment. Requires nl_after_brace_open=true. nl_after_brace_open_cmt = false # true/false # Whether to add a newline after a virtual brace open with a non-empty body. # These occur in un-braced if/while/do/for statement bodies. nl_after_vbrace_open = false # true/false # Whether to add a newline after a virtual brace open with an empty body. # These occur in un-braced if/while/do/for statement bodies. nl_after_vbrace_open_empty = false # true/false # Whether to add a newline after '}'. Does not apply if followed by a # necessary ';'. nl_after_brace_close = false # true/false # Whether to add a newline after a virtual brace close, # as in 'if (foo) a++; return;'. nl_after_vbrace_close = false # true/false # Add or remove newline between the close brace and identifier, # as in 'struct { int a; } b;'. Affects enumerations, unions and # structures. If set to ignore, uses nl_after_brace_close. nl_brace_struct_var = ignore # ignore/add/remove/force # Whether to add a newline before/after each '&&' or `||` on the same # nesting level in a boolean expression if boolean expression will not # fit on a line. code_width needs to be positive and pos_bool needs # to be 'lead' or 'trail' for this option to have any effect. nl_bool_expr_hierarchical = false # true/false # Whether to alter newlines in '#define' macros. nl_define_macro = false # true/false # Whether to alter newlines between consecutive parenthesis closes. The number # of closing parentheses in a line will depend on respective open parenthesis # lines. nl_squeeze_paren_close = false # true/false # Whether to remove blanks after '#ifxx' and '#elxx', or before '#elxx' and # '#endif'. Does not affect top-level #ifdefs. nl_squeeze_ifdef = false # true/false # Makes the nl_squeeze_ifdef option affect the top-level #ifdefs as well. nl_squeeze_ifdef_top_level = false # true/false # Add or remove blank line before 'if'. nl_before_if = ignore # ignore/add/remove/force # Add or remove blank line after 'if' statement. Add/Force work only if the # next token is not a closing brace. nl_after_if = ignore # ignore/add/remove/force # Add or remove blank line before 'for'. nl_before_for = ignore # ignore/add/remove/force # Add or remove blank line after 'for' statement. nl_after_for = ignore # ignore/add/remove/force # Add or remove blank line before 'while'. nl_before_while = ignore # ignore/add/remove/force # Add or remove blank line after 'while' statement. nl_after_while = ignore # ignore/add/remove/force # Add or remove blank line before 'switch'. nl_before_switch = ignore # ignore/add/remove/force # Add or remove blank line after 'switch' statement. nl_after_switch = ignore # ignore/add/remove/force # Add or remove blank line before 'synchronized'. nl_before_synchronized = ignore # ignore/add/remove/force # Add or remove blank line after 'synchronized' statement. nl_after_synchronized = ignore # ignore/add/remove/force # Add or remove blank line before 'do'. nl_before_do = ignore # ignore/add/remove/force # Add or remove blank line after 'do/while' statement. nl_after_do = ignore # ignore/add/remove/force # Ignore nl_before_{if,for,switch,do,synchronized} if the control # statement is immediately after a case statement. # if nl_before_{if,for,switch,do} is set to remove, this option # does nothing. nl_before_ignore_after_case = false # true/false # Whether to put a blank line before 'return' statements, unless after an open # brace. nl_before_return = false # true/false # Whether to put a blank line after 'return' statements, unless followed by a # close brace. nl_after_return = false # true/false # Whether to put a blank line before a member '.' or '->' operators. nl_before_member = ignore # ignore/add/remove/force # (Java) Whether to put a blank line after a member '.' or '->' operators. nl_after_member = ignore # ignore/add/remove/force # Whether to double-space commented-entries in 'struct'/'union'/'enum'. nl_ds_struct_enum_cmt = false # true/false # Whether to force a newline before '}' of a 'struct'/'union'/'enum'. # (Lower priority than eat_blanks_before_close_brace.) nl_ds_struct_enum_close_brace = false # true/false # Add or remove newline before or after (depending on pos_class_colon) a class # colon, as in 'class Foo : public Bar'. nl_class_colon = ignore # ignore/add/remove/force # Add or remove newline around a class constructor colon. The exact position # depends on nl_constr_init_args, pos_constr_colon and pos_constr_comma. nl_constr_colon = ignore # ignore/add/remove/force # Whether to collapse a two-line namespace, like 'namespace foo\n{ decl; }' # into a single line. If true, prevents other brace newline rules from turning # such code into four lines. If true, it also preserves one-liner namespaces. nl_namespace_two_to_one_liner = false # true/false # Whether to remove a newline in simple unbraced if statements, turning them # into one-liners, as in 'if(b)\n i++;' => 'if(b) i++;'. nl_create_if_one_liner = false # true/false # Whether to remove a newline in simple unbraced for statements, turning them # into one-liners, as in 'for (...)\n stmt;' => 'for (...) stmt;'. nl_create_for_one_liner = false # true/false # Whether to remove a newline in simple unbraced while statements, turning # them into one-liners, as in 'while (expr)\n stmt;' => 'while (expr) stmt;'. nl_create_while_one_liner = false # true/false # Whether to collapse a function definition whose body (not counting braces) # is only one line so that the entire definition (prototype, braces, body) is # a single line. nl_create_func_def_one_liner = false # true/false # Whether to split one-line simple list definitions into three lines by # adding newlines, as in 'int a[12] = { 0 };'. nl_create_list_one_liner = false # true/false # Whether to split one-line simple unbraced if statements into two lines by # adding a newline, as in 'if(b) i++;'. nl_split_if_one_liner = true # true/false # Whether to split one-line simple unbraced for statements into two lines by # adding a newline, as in 'for (...) stmt;'. nl_split_for_one_liner = true # true/false # Whether to split one-line simple unbraced while statements into two lines by # adding a newline, as in 'while (expr) stmt;'. nl_split_while_one_liner = true # true/false # Don't add a newline before a cpp-comment in a parameter list of a function # call. donot_add_nl_before_cpp_comment = false # true/false # # Blank line options # # The maximum number of consecutive newlines (3 = 2 blank lines). nl_max = 0 # unsigned number # The maximum number of consecutive newlines in a function. nl_max_blank_in_func = 0 # unsigned number # The number of newlines inside an empty function body. # This option overrides eat_blanks_after_open_brace and # eat_blanks_before_close_brace, but is ignored when # nl_collapse_empty_body_functions=true nl_inside_empty_func = 0 # unsigned number # The number of newlines before a function prototype. nl_before_func_body_proto = 0 # unsigned number # The number of newlines before a multi-line function definition. Where # applicable, this option is overridden with eat_blanks_after_open_brace=true nl_before_func_body_def = 3 # unsigned number # The number of newlines before a class constructor/destructor prototype. nl_before_func_class_proto = 0 # unsigned number # The number of newlines before a class constructor/destructor definition. nl_before_func_class_def = 0 # unsigned number # The number of newlines after a function prototype. nl_after_func_proto = 0 # unsigned number # The number of newlines after a function prototype, if not followed by # another function prototype. nl_after_func_proto_group = 0 # unsigned number # The number of newlines after a class constructor/destructor prototype. nl_after_func_class_proto = 0 # unsigned number # The number of newlines after a class constructor/destructor prototype, # if not followed by another constructor/destructor prototype. nl_after_func_class_proto_group = 0 # unsigned number # Whether one-line method definitions inside a class body should be treated # as if they were prototypes for the purposes of adding newlines. # # Requires nl_class_leave_one_liners=true. Overrides nl_before_func_body_def # and nl_before_func_class_def for one-liners. nl_class_leave_one_liner_groups = false # true/false # The number of newlines after '}' of a multi-line function body. # # Overrides nl_min_after_func_body and nl_max_after_func_body. nl_after_func_body = 0 # unsigned number # The minimum number of newlines after '}' of a multi-line function body. # # Only works when nl_after_func_body is 0. nl_min_after_func_body = 0 # unsigned number # The maximum number of newlines after '}' of a multi-line function body. # # Only works when nl_after_func_body is 0. # Takes precedence over nl_min_after_func_body. nl_max_after_func_body = 0 # unsigned number # The number of newlines after '}' of a multi-line function body in a class # declaration. Also affects class constructors/destructors. # # Overrides nl_after_func_body. nl_after_func_body_class = 0 # unsigned number # The number of newlines after '}' of a single line function body. Also # affects class constructors/destructors. # # Overrides nl_after_func_body and nl_after_func_body_class. nl_after_func_body_one_liner = 0 # unsigned number # The number of newlines before a block of typedefs. If nl_after_access_spec # is non-zero, that option takes precedence. # # 0: No change (default). nl_typedef_blk_start = 0 # unsigned number # The number of newlines after a block of typedefs. # # 0: No change (default). nl_typedef_blk_end = 0 # unsigned number # The maximum number of consecutive newlines within a block of typedefs. # # 0: No change (default). nl_typedef_blk_in = 0 # unsigned number # The minimum number of blank lines after a block of variable definitions # at the top of a function body. If any preprocessor directives appear # between the opening brace of the function and the variable block, then # it is considered as not at the top of the function.Newlines are added # before trailing preprocessor directives, if any exist. # # 0: No change (default). nl_var_def_blk_end_func_top = 0 # unsigned number # The minimum number of empty newlines before a block of variable definitions # not at the top of a function body. If nl_after_access_spec is non-zero, # that option takes precedence. Newlines are not added at the top of the # file or just after an opening brace. Newlines are added above any # preprocessor directives before the block. # # 0: No change (default). nl_var_def_blk_start = 0 # unsigned number # The minimum number of empty newlines after a block of variable definitions # not at the top of a function body. Newlines are not added if the block # is at the bottom of the file or just before a preprocessor directive. # # 0: No change (default). nl_var_def_blk_end = 0 # unsigned number # The maximum number of consecutive newlines within a block of variable # definitions. # # 0: No change (default). nl_var_def_blk_in = 0 # unsigned number # The minimum number of newlines before a multi-line comment. # Doesn't apply if after a brace open or another multi-line comment. nl_before_block_comment = 0 # unsigned number # The minimum number of newlines before a single-line C comment. # Doesn't apply if after a brace open or other single-line C comments. nl_before_c_comment = 0 # unsigned number # The minimum number of newlines before a CPP comment. # Doesn't apply if after a brace open or other CPP comments. nl_before_cpp_comment = 0 # unsigned number # Whether to force a newline after a multi-line comment. nl_after_multiline_comment = false # true/false # Whether to force a newline after a label's colon. nl_after_label_colon = false # true/false # The number of newlines before a struct definition. nl_before_struct = 0 # unsigned number # The number of newlines after '}' or ';' of a struct/enum/union definition. nl_after_struct = 0 # unsigned number # The number of newlines before a class definition. nl_before_class = 0 # unsigned number # The number of newlines after '}' or ';' of a class definition. nl_after_class = 0 # unsigned number # The number of newlines before a namespace. nl_before_namespace = 0 # unsigned number # The number of newlines after '{' of a namespace. This also adds newlines # before the matching '}'. # # 0: Apply eat_blanks_after_open_brace or eat_blanks_before_close_brace if # applicable, otherwise no change. # # Overrides eat_blanks_after_open_brace and eat_blanks_before_close_brace. nl_inside_namespace = 0 # unsigned number # The number of newlines after '}' of a namespace. nl_after_namespace = 0 # unsigned number # The number of newlines before an access specifier label. This also includes # the Qt-specific 'signals:' and 'slots:'. Will not change the newline count # if after a brace open. # # 0: No change (default). nl_before_access_spec = 0 # unsigned number # The number of newlines after an access specifier label. This also includes # the Qt-specific 'signals:' and 'slots:'. Will not change the newline count # if after a brace open. # # 0: No change (default). # # Overrides nl_typedef_blk_start and nl_var_def_blk_start. nl_after_access_spec = 0 # unsigned number # The number of newlines between a function definition and the function # comment, as in '// comment\n void foo() {...}'. # # 0: No change (default). nl_comment_func_def = 0 # unsigned number # The number of newlines after a try-catch-finally block that isn't followed # by a brace close. # # 0: No change (default). nl_after_try_catch_finally = 0 # unsigned number # (C#) The number of newlines before and after a property, indexer or event # declaration. # # 0: No change (default). nl_around_cs_property = 0 # unsigned number # (C#) The number of newlines between the get/set/add/remove handlers. # # 0: No change (default). nl_between_get_set = 0 # unsigned number # (C#) Add or remove newline between property and the '{'. nl_property_brace = ignore # ignore/add/remove/force # Whether to remove blank lines after '{'. eat_blanks_after_open_brace = false # true/false # Whether to remove blank lines before '}'. eat_blanks_before_close_brace = false # true/false # How aggressively to remove extra newlines not in preprocessor. # # 0: No change (default) # 1: Remove most newlines not handled by other config # 2: Remove all newlines and reformat completely by config nl_remove_extra_newlines = 0 # unsigned number # (Java) Add or remove newline after an annotation statement. Only affects # annotations that are after a newline. nl_after_annotation = ignore # ignore/add/remove/force # (Java) Add or remove newline between two annotations. nl_between_annotation = ignore # ignore/add/remove/force # The number of newlines before a whole-file #ifdef. # # 0: No change (default). nl_before_whole_file_ifdef = 0 # unsigned number # The number of newlines after a whole-file #ifdef. # # 0: No change (default). nl_after_whole_file_ifdef = 0 # unsigned number # The number of newlines before a whole-file #endif. # # 0: No change (default). nl_before_whole_file_endif = 0 # unsigned number # The number of newlines after a whole-file #endif. # # 0: No change (default). nl_after_whole_file_endif = 0 # unsigned number # # Positioning options # # The position of arithmetic operators in wrapped expressions. pos_arith = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # The position of assignment in wrapped expressions. Do not affect '=' # followed by '{'. pos_assign = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # The position of Boolean operators in wrapped expressions. pos_bool = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # The position of comparison operators in wrapped expressions. pos_compare = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # The position of conditional operators, as in the '?' and ':' of # 'expr ? stmt : stmt', in wrapped expressions. pos_conditional = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # The position of the comma in wrapped expressions. pos_comma = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # The position of the comma in enum entries. pos_enum_comma = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # The position of the comma in the base class list if there is more than one # line. Affects nl_class_init_args. pos_class_comma = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # The position of the comma in the constructor initialization list. # Related to nl_constr_colon, nl_constr_init_args and pos_constr_colon. pos_constr_comma = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # The position of trailing/leading class colon, between class and base class # list. Affects nl_class_colon. pos_class_colon = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # The position of colons between constructor and member initialization. # Related to nl_constr_colon, nl_constr_init_args and pos_constr_comma. pos_constr_colon = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # The position of shift operators in wrapped expressions. pos_shift = ignore # ignore/break/force/lead/trail/join/lead_break/lead_force/trail_break/trail_force # # Line splitting options # # Try to limit code width to N columns. code_width = 0 # unsigned number # Whether to fully split long 'for' statements at semi-colons. ls_for_split_full = false # true/false # Whether to fully split long function prototypes/calls at commas. # The option ls_code_width has priority over the option ls_func_split_full. ls_func_split_full = false # true/false # Whether to split lines as close to code_width as possible and ignore some # groupings. # The option ls_code_width has priority over the option ls_func_split_full. ls_code_width = false # true/false # # Code alignment options (not left column spaces/tabs) # # Whether to keep non-indenting tabs. align_keep_tabs = false # true/false # Whether to use tabs for aligning. align_with_tabs = false # true/false # Whether to bump out to the next tab when aligning. align_on_tabstop = false # true/false # Whether to right-align numbers. align_number_right = false # true/false # Whether to keep whitespace not required for alignment. align_keep_extra_space = false # true/false # Whether to align variable definitions in prototypes and functions. align_func_params = false # true/false # The span for aligning parameter definitions in function on parameter name. # # 0: Don't align (default). align_func_params_span = 0 # unsigned number # The threshold for aligning function parameter definitions. # Use a negative number for absolute thresholds. # # 0: No limit (default). align_func_params_thresh = 0 # number # The gap for aligning function parameter definitions. align_func_params_gap = 0 # unsigned number # The span for aligning constructor value. # # 0: Don't align (default). align_constr_value_span = 0 # unsigned number # The threshold for aligning constructor value. # Use a negative number for absolute thresholds. # # 0: No limit (default). align_constr_value_thresh = 0 # number # The gap for aligning constructor value. align_constr_value_gap = 0 # unsigned number # Whether to align parameters in single-line functions that have the same # name. The function names must already be aligned with each other. align_same_func_call_params = false # true/false # The span for aligning function-call parameters for single line functions. # # 0: Don't align (default). align_same_func_call_params_span = 0 # unsigned number # The threshold for aligning function-call parameters for single line # functions. # Use a negative number for absolute thresholds. # # 0: No limit (default). align_same_func_call_params_thresh = 0 # number # The span for aligning variable definitions. # # 0: Don't align (default). align_var_def_span = 0 # unsigned number # How to consider (or treat) the '*' in the alignment of variable definitions. # # 0: Part of the type 'void * foo;' (default) # 1: Part of the variable 'void *foo;' # 2: Dangling 'void *foo;' # Dangling: the '*' will not be taken into account when aligning. align_var_def_star_style = 0 # unsigned number # How to consider (or treat) the '&' in the alignment of variable definitions. # # 0: Part of the type 'long & foo;' (default) # 1: Part of the variable 'long &foo;' # 2: Dangling 'long &foo;' # Dangling: the '&' will not be taken into account when aligning. align_var_def_amp_style = 0 # unsigned number # The threshold for aligning variable definitions. # Use a negative number for absolute thresholds. # # 0: No limit (default). align_var_def_thresh = 0 # number # The gap for aligning variable definitions. align_var_def_gap = 0 # unsigned number # Whether to align the colon in struct bit fields. align_var_def_colon = false # true/false # The gap for aligning the colon in struct bit fields. align_var_def_colon_gap = 0 # unsigned number # Whether to align any attribute after the variable name. align_var_def_attribute = false # true/false # Whether to align inline struct/enum/union variable definitions. align_var_def_inline = false # true/false # The span for aligning on '=' in assignments. # # 0: Don't align (default). align_assign_span = 0 # unsigned number # The span for aligning on '=' in function prototype modifier. # # 0: Don't align (default). align_assign_func_proto_span = 0 # unsigned number # The threshold for aligning on '=' in assignments. # Use a negative number for absolute thresholds. # # 0: No limit (default). align_assign_thresh = 0 # number # Whether to align on the left most assignment when multiple # definitions are found on the same line. # Depends on 'align_assign_span' and 'align_assign_thresh' settings. align_assign_on_multi_var_defs = false # true/false # The span for aligning on '{' in braced init list. # # 0: Don't align (default). align_braced_init_list_span = 0 # unsigned number # The threshold for aligning on '{' in braced init list. # Use a negative number for absolute thresholds. # # 0: No limit (default). align_braced_init_list_thresh = 0 # number # How to apply align_assign_span to function declaration "assignments", i.e. # 'virtual void foo() = 0' or '~foo() = {default|delete}'. # # 0: Align with other assignments (default) # 1: Align with each other, ignoring regular assignments # 2: Don't align align_assign_decl_func = 0 # unsigned number # The span for aligning on '=' in enums. # # 0: Don't align (default). align_enum_equ_span = 0 # unsigned number # The threshold for aligning on '=' in enums. # Use a negative number for absolute thresholds. # # 0: no limit (default). align_enum_equ_thresh = 0 # number # The span for aligning class member definitions. # # 0: Don't align (default). align_var_class_span = 0 # unsigned number # The threshold for aligning class member definitions. # Use a negative number for absolute thresholds. # # 0: No limit (default). align_var_class_thresh = 0 # number # The gap for aligning class member definitions. align_var_class_gap = 0 # unsigned number # The span for aligning struct/union member definitions. # # 0: Don't align (default). align_var_struct_span = 0 # unsigned number # The threshold for aligning struct/union member definitions. # Use a negative number for absolute thresholds. # # 0: No limit (default). align_var_struct_thresh = 0 # number # The gap for aligning struct/union member definitions. align_var_struct_gap = 0 # unsigned number # The span for aligning struct initializer values. # # 0: Don't align (default). align_struct_init_span = 0 # unsigned number # The span for aligning single-line typedefs. # # 0: Don't align (default). align_typedef_span = 0 # unsigned number # The minimum space between the type and the synonym of a typedef. align_typedef_gap = 0 # unsigned number # How to align typedef'd functions with other typedefs. # # 0: Don't mix them at all (default) # 1: Align the open parenthesis with the types # 2: Align the function type name with the other type names align_typedef_func = 0 # unsigned number # How to consider (or treat) the '*' in the alignment of typedefs. # # 0: Part of the typedef type, 'typedef int * pint;' (default) # 1: Part of type name: 'typedef int *pint;' # 2: Dangling: 'typedef int *pint;' # Dangling: the '*' will not be taken into account when aligning. align_typedef_star_style = 0 # unsigned number # How to consider (or treat) the '&' in the alignment of typedefs. # # 0: Part of the typedef type, 'typedef int & intref;' (default) # 1: Part of type name: 'typedef int &intref;' # 2: Dangling: 'typedef int &intref;' # Dangling: the '&' will not be taken into account when aligning. align_typedef_amp_style = 0 # unsigned number # The span for aligning comments that end lines. # # 0: Don't align (default). align_right_cmt_span = 0 # unsigned number # Minimum number of columns between preceding text and a trailing comment in # order for the comment to qualify for being aligned. Must be non-zero to have # an effect. align_right_cmt_gap = 0 # unsigned number # If aligning comments, whether to mix with comments after '}' and #endif with # less than three spaces before the comment. align_right_cmt_mix = false # true/false # Whether to only align trailing comments that are at the same brace level. align_right_cmt_same_level = false # true/false # Minimum column at which to align trailing comments. Comments which are # aligned beyond this column, but which can be aligned in a lesser column, # may be "pulled in". # # 0: Ignore (default). align_right_cmt_at_col = 0 # unsigned number # The span for aligning function prototypes. # # 0: Don't align (default). align_func_proto_span = 0 # unsigned number # Whether to ignore continuation lines when evaluating the number of # new lines for the function prototype alignment's span. # # false: continuation lines are part of the newlines count # true: continuation lines are not counted align_func_proto_span_ignore_cont_lines = false # true/false # How to consider (or treat) the '*' in the alignment of function prototypes. # # 0: Part of the type 'void * foo();' (default) # 1: Part of the function 'void *foo();' # 2: Dangling 'void *foo();' # Dangling: the '*' will not be taken into account when aligning. align_func_proto_star_style = 0 # unsigned number # How to consider (or treat) the '&' in the alignment of function prototypes. # # 0: Part of the type 'long & foo();' (default) # 1: Part of the function 'long &foo();' # 2: Dangling 'long &foo();' # Dangling: the '&' will not be taken into account when aligning. align_func_proto_amp_style = 0 # unsigned number # The threshold for aligning function prototypes. # Use a negative number for absolute thresholds. # # 0: No limit (default). align_func_proto_thresh = 0 # number # Minimum gap between the return type and the function name. align_func_proto_gap = 0 # unsigned number # Whether to align function prototypes on the 'operator' keyword instead of # what follows. align_on_operator = false # true/false # Whether to mix aligning prototype and variable declarations. If true, # align_var_def_XXX options are used instead of align_func_proto_XXX options. align_mix_var_proto = false # true/false # Whether to align single-line functions with function prototypes. # Uses align_func_proto_span. align_single_line_func = false # true/false # Whether to align the open brace of single-line functions. # Requires align_single_line_func=true. Uses align_func_proto_span. align_single_line_brace = false # true/false # Gap for align_single_line_brace. align_single_line_brace_gap = 0 # unsigned number # (OC) The span for aligning Objective-C message specifications. # # 0: Don't align (default). align_oc_msg_spec_span = 0 # unsigned number # Whether and how to align backslashes that split a macro onto multiple lines. # This will not work right if the macro contains a multi-line comment. # # 0: Do nothing (default) # 1: Align the backslashes in the column at the end of the longest line # 2: Align with the backslash that is farthest to the left, or, if that # backslash is farther left than the end of the longest line, at the end of # the longest line # 3: Align with the backslash that is farthest to the right align_nl_cont = 0 # unsigned number # The minimum number of spaces between the end of a line and its continuation # backslash. Requires align_nl_cont. # # Default: 1 align_nl_cont_spaces = 1 # unsigned number # Whether to align macro functions and variables together. align_pp_define_together = false # true/false # The span for aligning on '#define' bodies. # # =0: Don't align (default) # >0: Number of lines (including comments) between blocks align_pp_define_span = 0 # unsigned number # The minimum space between label and value of a preprocessor define. align_pp_define_gap = 0 # unsigned number # Whether to align lines that start with '<<' with previous '<<'. # # Default: true align_left_shift = true # true/false # Whether to align comma-separated statements following '<<' (as used to # initialize Eigen matrices). align_eigen_comma_init = false # true/false # Whether to align text after 'asm volatile ()' colons. align_asm_colon = false # true/false # (OC) Span for aligning parameters in an Objective-C message call # on the ':'. # # 0: Don't align. align_oc_msg_colon_span = 0 # unsigned number # (OC) Whether to always align with the first parameter, even if it is too # short. align_oc_msg_colon_first = false # true/false # (OC) Whether to align parameters in an Objective-C '+' or '-' declaration # on the ':'. align_oc_decl_colon = false # true/false # (OC) Whether to not align parameters in an Objectve-C message call if first # colon is not on next line of the message call (the same way Xcode does # alignment) align_oc_msg_colon_xcode_like = false # true/false # # Comment modification options # # Try to wrap comments at N columns. cmt_width = 0 # unsigned number # How to reflow comments. # # 0: No reflowing (apart from the line wrapping due to cmt_width) (default) # 1: No touching at all # 2: Full reflow (enable cmt_indent_multi for indent with line wrapping due to cmt_width) cmt_reflow_mode = 0 # unsigned number # Path to a file that contains regular expressions describing patterns for # which the end of one line and the beginning of the next will be folded into # the same sentence or paragraph during full comment reflow. The regular # expressions are described using ECMAScript syntax. The syntax for this # specification is as follows, where "..." indicates the custom regular # expression and "n" indicates the nth end_of_prev_line_regex and # beg_of_next_line_regex regular expression pair: # # end_of_prev_line_regex[1] = "...$" # beg_of_next_line_regex[1] = "^..." # end_of_prev_line_regex[2] = "...$" # beg_of_next_line_regex[2] = "^..." # . # . # . # end_of_prev_line_regex[n] = "...$" # beg_of_next_line_regex[n] = "^..." # # Note that use of this option overrides the default reflow fold regular # expressions, which are internally defined as follows: # # end_of_prev_line_regex[1] = "[\w,\]\)]$" # beg_of_next_line_regex[1] = "^[\w,\[\(]" # end_of_prev_line_regex[2] = "\.$" # beg_of_next_line_regex[2] = "^[A-Z]" cmt_reflow_fold_regex_file = "" # string # Whether to indent wrapped lines to the start of the encompassing paragraph # during full comment reflow (cmt_reflow_mode = 2). Overrides the value # specified by cmt_sp_after_star_cont. # # Note that cmt_align_doxygen_javadoc_tags overrides this option for # paragraphs associated with javadoc tags cmt_reflow_indent_to_paragraph_start = false # true/false # Whether to convert all tabs to spaces in comments. If false, tabs in # comments are left alone, unless used for indenting. cmt_convert_tab_to_spaces = false # true/false # Whether to apply changes to multi-line comments, including cmt_width, # keyword substitution and leading chars. # # Default: true cmt_indent_multi = false # true/false # Whether to align doxygen javadoc-style tags ('@param', '@return', etc.) # and corresponding fields such that groups of consecutive block tags, # parameter names, and descriptions align with one another. Overrides that # which is specified by the cmt_sp_after_star_cont. If cmt_width > 0, it may # be necessary to enable cmt_indent_multi and set cmt_reflow_mode = 2 # in order to achieve the desired alignment for line-wrapping. cmt_align_doxygen_javadoc_tags = false # true/false # The number of spaces to insert after the star and before doxygen # javadoc-style tags (@param, @return, etc). Requires enabling # cmt_align_doxygen_javadoc_tags. Overrides that which is specified by the # cmt_sp_after_star_cont. # # Default: 1 cmt_sp_before_doxygen_javadoc_tags = 1 # unsigned number # Whether to change trailing, single-line c-comments into cpp-comments. cmt_trailing_single_line_c_to_cpp = false # true/false # Whether to group c-comments that look like they are in a block. cmt_c_group = false # true/false # Whether to put an empty '/*' on the first line of the combined c-comment. cmt_c_nl_start = false # true/false # Whether to add a newline before the closing '*/' of the combined c-comment. cmt_c_nl_end = false # true/false # Whether to change cpp-comments into c-comments. cmt_cpp_to_c = false # true/false # Whether to group cpp-comments that look like they are in a block. Only # meaningful if cmt_cpp_to_c=true. cmt_cpp_group = false # true/false # Whether to put an empty '/*' on the first line of the combined cpp-comment # when converting to a c-comment. # # Requires cmt_cpp_to_c=true and cmt_cpp_group=true. cmt_cpp_nl_start = false # true/false # Whether to add a newline before the closing '*/' of the combined cpp-comment # when converting to a c-comment. # # Requires cmt_cpp_to_c=true and cmt_cpp_group=true. cmt_cpp_nl_end = false # true/false # Whether to put a star on subsequent comment lines. cmt_star_cont = false # true/false # The number of spaces to insert at the start of subsequent comment lines. cmt_sp_before_star_cont = 0 # unsigned number # The number of spaces to insert after the star on subsequent comment lines. cmt_sp_after_star_cont = 0 # unsigned number # For multi-line comments with a '*' lead, remove leading spaces if the first # and last lines of the comment are the same length. # # Default: true cmt_multi_check_last = true # true/false # For multi-line comments with a '*' lead, remove leading spaces if the first # and last lines of the comment are the same length AND if the length is # bigger as the first_len minimum. # # Default: 4 cmt_multi_first_len_minimum = 4 # unsigned number # Path to a file that contains text to insert at the beginning of a file if # the file doesn't start with a C/C++ comment. If the inserted text contains # '$(filename)', that will be replaced with the current file's name. cmt_insert_file_header = "" # string # Path to a file that contains text to insert at the end of a file if the # file doesn't end with a C/C++ comment. If the inserted text contains # '$(filename)', that will be replaced with the current file's name. cmt_insert_file_footer = "" # string # Path to a file that contains text to insert before a function definition if # the function isn't preceded by a C/C++ comment. If the inserted text # contains '$(function)', '$(javaparam)' or '$(fclass)', these will be # replaced with, respectively, the name of the function, the javadoc '@param' # and '@return' stuff, or the name of the class to which the member function # belongs. cmt_insert_func_header = "" # string # Path to a file that contains text to insert before a class if the class # isn't preceded by a C/C++ comment. If the inserted text contains '$(class)', # that will be replaced with the class name. cmt_insert_class_header = "" # string # Path to a file that contains text to insert before an Objective-C message # specification, if the method isn't preceded by a C/C++ comment. If the # inserted text contains '$(message)' or '$(javaparam)', these will be # replaced with, respectively, the name of the function, or the javadoc # '@param' and '@return' stuff. cmt_insert_oc_msg_header = "" # string # Whether a comment should be inserted if a preprocessor is encountered when # stepping backwards from a function name. # # Applies to cmt_insert_oc_msg_header, cmt_insert_func_header and # cmt_insert_class_header. cmt_insert_before_preproc = false # true/false # Whether a comment should be inserted if a function is declared inline to a # class definition. # # Applies to cmt_insert_func_header. # # Default: true cmt_insert_before_inlines = true # true/false # Whether a comment should be inserted if the function is a class constructor # or destructor. # # Applies to cmt_insert_func_header. cmt_insert_before_ctor_dtor = false # true/false # # Code modifying options (non-whitespace) # # Add or remove braces on a single-line 'do' statement. mod_full_brace_do = add # ignore/add/remove/force # Add or remove braces on a single-line 'for' statement. mod_full_brace_for = add # ignore/add/remove/force # (Pawn) Add or remove braces on a single-line function definition. mod_full_brace_function = ignore # ignore/add/remove/force # Add or remove braces on a single-line 'if' statement. Braces will not be # removed if the braced statement contains an 'else'. mod_full_brace_if = add # ignore/add/remove/force # Whether to enforce that all blocks of an 'if'/'else if'/'else' chain either # have, or do not have, braces. Overrides mod_full_brace_if. # # 0: Don't override mod_full_brace_if # 1: Add braces to all blocks if any block needs braces and remove braces if # they can be removed from all blocks # 2: Add braces to all blocks if any block already has braces, regardless of # whether it needs them # 3: Add braces to all blocks if any block needs braces and remove braces if # they can be removed from all blocks, except if all blocks have braces # despite none needing them mod_full_brace_if_chain = 0 # unsigned number # Whether to add braces to all blocks of an 'if'/'else if'/'else' chain. # If true, mod_full_brace_if_chain will only remove braces from an 'if' that # does not have an 'else if' or 'else'. mod_full_brace_if_chain_only = false # true/false # Add or remove braces on single-line 'while' statement. mod_full_brace_while = add # ignore/add/remove/force # Add or remove braces on single-line 'using ()' statement. mod_full_brace_using = ignore # ignore/add/remove/force # Don't remove braces around statements that span N newlines mod_full_brace_nl = 0 # unsigned number # Whether to prevent removal of braces from 'if'/'for'/'while'/etc. blocks # which span multiple lines. # # Affects: # mod_full_brace_for # mod_full_brace_if # mod_full_brace_if_chain # mod_full_brace_if_chain_only # mod_full_brace_while # mod_full_brace_using # # Does not affect: # mod_full_brace_do # mod_full_brace_function mod_full_brace_nl_block_rem_mlcond = false # true/false # Add or remove unnecessary parentheses on 'return' statement. mod_paren_on_return = ignore # ignore/add/remove/force # Add or remove unnecessary parentheses on 'throw' statement. mod_paren_on_throw = ignore # ignore/add/remove/force # (Pawn) Whether to change optional semicolons to real semicolons. mod_pawn_semicolon = false # true/false # Whether to fully parenthesize Boolean expressions in 'while' and 'if' # statement, as in 'if (a && b > c)' => 'if (a && (b > c))'. mod_full_paren_if_bool = false # true/false # Whether to fully parenthesize Boolean expressions after '=' # statement, as in 'x = a && b > c;' => 'x = (a && (b > c));'. mod_full_paren_assign_bool = false # true/false # Whether to fully parenthesize Boolean expressions after '=' # statement, as in 'return a && b > c;' => 'return (a && (b > c));'. mod_full_paren_return_bool = false # true/false # Whether to remove superfluous semicolons. mod_remove_extra_semicolon = false # true/false # Whether to remove duplicate include. mod_remove_duplicate_include = false # true/false # the following options (mod_XX_closebrace_comment) use different comment, # depending of the setting of the next option. # false: Use the c comment (default) # true : Use the cpp comment mod_add_force_c_closebrace_comment = false # true/false # If a function body exceeds the specified number of newlines and doesn't have # a comment after the close brace, a comment will be added. mod_add_long_function_closebrace_comment = 0 # unsigned number # If a namespace body exceeds the specified number of newlines and doesn't # have a comment after the close brace, a comment will be added. mod_add_long_namespace_closebrace_comment = 0 # unsigned number # If a class body exceeds the specified number of newlines and doesn't have a # comment after the close brace, a comment will be added. mod_add_long_class_closebrace_comment = 0 # unsigned number # If a switch body exceeds the specified number of newlines and doesn't have a # comment after the close brace, a comment will be added. mod_add_long_switch_closebrace_comment = 0 # unsigned number # If an #ifdef body exceeds the specified number of newlines and doesn't have # a comment after the #endif, a comment will be added. mod_add_long_ifdef_endif_comment = 0 # unsigned number # If an #ifdef or #else body exceeds the specified number of newlines and # doesn't have a comment after the #else, a comment will be added. mod_add_long_ifdef_else_comment = 0 # unsigned number # Whether to take care of the case by the mod_sort_xx options. mod_sort_case_sensitive = false # true/false # Whether to sort consecutive single-line 'import' statements. mod_sort_import = false # true/false # (C#) Whether to sort consecutive single-line 'using' statements. mod_sort_using = false # true/false # Whether to sort consecutive single-line '#include' statements (C/C++) and # '#import' statements (Objective-C). Be aware that this has the potential to # break your code if your includes/imports have ordering dependencies. mod_sort_include = false # true/false # Whether to prioritize '#include' and '#import' statements that contain # filename without extension when sorting is enabled. mod_sort_incl_import_prioritize_filename = false # true/false # Whether to prioritize '#include' and '#import' statements that does not # contain extensions when sorting is enabled. mod_sort_incl_import_prioritize_extensionless = false # true/false # Whether to prioritize '#include' and '#import' statements that contain # angle over quotes when sorting is enabled. mod_sort_incl_import_prioritize_angle_over_quotes = false # true/false # Whether to ignore file extension in '#include' and '#import' statements # for sorting comparison. mod_sort_incl_import_ignore_extension = false # true/false # Whether to group '#include' and '#import' statements when sorting is enabled. mod_sort_incl_import_grouping_enabled = false # true/false # Whether to move a 'break' that appears after a fully braced 'case' before # the close brace, as in 'case X: { ... } break;' => 'case X: { ... break; }'. mod_move_case_break = false # true/false # Whether to move a 'return' that appears after a fully braced 'case' before # the close brace, as in 'case X: { ... } return;' => 'case X: { ... return; }'. mod_move_case_return = false # true/false # Add or remove braces around a fully braced case statement. Will only remove # braces if there are no variable declarations in the block. mod_case_brace = ignore # ignore/add/remove/force # Whether to remove a void 'return;' that appears as the last statement in a # function. mod_remove_empty_return = false # true/false # Add or remove the comma after the last value of an enumeration. mod_enum_last_comma = add # ignore/add/remove/force # Syntax to use for infinite loops. # # 0: Leave syntax alone (default) # 1: Rewrite as `for(;;)` # 2: Rewrite as `while(true)` # 3: Rewrite as `do`...`while(true);` # 4: Rewrite as `while(1)` # 5: Rewrite as `do`...`while(1);` # # Infinite loops that do not already match one of these syntaxes are ignored. # Other options that affect loop formatting will be applied after transforming # the syntax. mod_infinite_loop = 0 # unsigned number # Add or remove the 'int' keyword in 'int short'. mod_int_short = ignore # ignore/add/remove/force # Add or remove the 'int' keyword in 'short int'. mod_short_int = ignore # ignore/add/remove/force # Add or remove the 'int' keyword in 'int long'. mod_int_long = ignore # ignore/add/remove/force # Add or remove the 'int' keyword in 'long int'. mod_long_int = ignore # ignore/add/remove/force # Add or remove the 'int' keyword in 'int signed'. mod_int_signed = ignore # ignore/add/remove/force # Add or remove the 'int' keyword in 'signed int'. mod_signed_int = ignore # ignore/add/remove/force # Add or remove the 'int' keyword in 'int unsigned'. mod_int_unsigned = ignore # ignore/add/remove/force # Add or remove the 'int' keyword in 'unsigned int'. mod_unsigned_int = ignore # ignore/add/remove/force # If there is a situation where mod_int_* and mod_*_int would result in # multiple int keywords, whether to keep the rightmost int (the default) or the # leftmost int. mod_int_prefer_int_on_left = false # true/false # (OC) Whether to organize the properties. If true, properties will be # rearranged according to the mod_sort_oc_property_*_weight factors. mod_sort_oc_properties = false # true/false # (OC) Weight of a class property modifier. mod_sort_oc_property_class_weight = 0 # number # (OC) Weight of 'atomic' and 'nonatomic'. mod_sort_oc_property_thread_safe_weight = 0 # number # (OC) Weight of 'readwrite' when organizing properties. mod_sort_oc_property_readwrite_weight = 0 # number # (OC) Weight of a reference type specifier ('retain', 'copy', 'assign', # 'weak', 'strong') when organizing properties. mod_sort_oc_property_reference_weight = 0 # number # (OC) Weight of getter type ('getter=') when organizing properties. mod_sort_oc_property_getter_weight = 0 # number # (OC) Weight of setter type ('setter=') when organizing properties. mod_sort_oc_property_setter_weight = 0 # number # (OC) Weight of nullability type ('nullable', 'nonnull', 'null_unspecified', # 'null_resettable') when organizing properties. mod_sort_oc_property_nullability_weight = 0 # number # # Preprocessor options # # How to use tabs when indenting preprocessor code. # # -1: Use 'indent_with_tabs' setting (default) # 0: Spaces only # 1: Indent with tabs to brace level, align with spaces # 2: Indent and align with tabs, using spaces when not on a tabstop # # Default: -1 pp_indent_with_tabs = -1 # number # Add or remove indentation of preprocessor directives inside #if blocks # at brace level 0 (file-level). pp_indent = remove # ignore/add/remove/force # Whether to indent #if/#else/#endif at the brace level. If false, these are # indented from column 1. pp_indent_at_level = false # true/false # Whether to indent #if/#else/#endif at the parenthesis level if the brace # level is 0. If false, these are indented from column 1. pp_indent_at_level0 = false # true/false # Specifies the number of columns to indent preprocessors per level # at brace level 0 (file-level). If pp_indent_at_level=false, also specifies # the number of columns to indent preprocessors per level # at brace level > 0 (function-level). # # Default: 1 pp_indent_count = 1 # unsigned number # Add or remove space after # based on pp level of #if blocks. pp_space_after = ignore # ignore/add/remove/force # Sets the number of spaces per level added with pp_space_after. pp_space_count = 0 # unsigned number # The indent for '#region' and '#endregion' in C# and '#pragma region' in # C/C++. Negative values decrease indent down to the first column. pp_indent_region = 0 # number # Whether to indent the code between #region and #endregion. pp_region_indent_code = false # true/false # If pp_indent_at_level=true, sets the indent for #if, #else and #endif when # not at file-level. Negative values decrease indent down to the first column. # # =0: Indent preprocessors using output_tab_size # >0: Column at which all preprocessors will be indented pp_indent_if = 0 # number # Whether to indent the code between #if, #else and #endif. pp_if_indent_code = false # true/false # Whether to indent the body of an #if that encompasses all the code in the file. pp_indent_in_guard = false # true/false # Whether to indent '#define' at the brace level. If false, these are # indented from column 1. pp_define_at_level = false # true/false # Whether to indent '#include' at the brace level. pp_include_at_level = false # true/false # Whether to ignore the '#define' body while formatting. pp_ignore_define_body = false # true/false # An offset value that controls the indentation of the body of a multiline #define. # 'body' refers to all the lines of a multiline #define except the first line. # Requires 'pp_ignore_define_body = false'. # # <0: Absolute column: the body indentation starts off at the specified column # (ex. -3 ==> the body is indented starting from column 3) # >=0: Relative to the column of the '#' of '#define' # (ex. 3 ==> the body is indented starting 3 columns at the right of '#') # # Default: 8 pp_multiline_define_body_indent = 8 # number # Whether to indent case statements between #if, #else, and #endif. # Only applies to the indent of the preprocessor that the case statements # directly inside of. # # Default: true pp_indent_case = true # true/false # Whether to indent whole function definitions between #if, #else, and #endif. # Only applies to the indent of the preprocessor that the function definition # is directly inside of. # # Default: true pp_indent_func_def = true # true/false # Whether to indent extern C blocks between #if, #else, and #endif. # Only applies to the indent of the preprocessor that the extern block is # directly inside of. # # Default: true pp_indent_extern = true # true/false # How to indent braces directly inside #if, #else, and #endif. # Requires pp_if_indent_code=true and only applies to the indent of the # preprocessor that the braces are directly inside of. # 0: No extra indent # 1: Indent by one level # -1: Preserve original indentation # # Default: 1 pp_indent_brace = 1 # number # Action to perform when unbalanced #if and #else blocks are found. # 0: do nothing # 1: print a warning message # 2: terminate the program with an error (EX_SOFTWARE) # # The action will be triggered in the following cases: # - if an #ifdef block ends on a different indent level than # where it started from. Example: # # #ifdef TEST # int i; # { # int j; # #endif # # - an #elif/#else block ends on a different indent level than # the corresponding #ifdef block. Example: # # #ifdef TEST # int i; # #else # } # int j; # #endif pp_unbalanced_if_action = 0 # unsigned number # # Sort includes options # # The regex for include category with priority 0. include_category_0 = "" # string # The regex for include category with priority 1. include_category_1 = "" # string # The regex for include category with priority 2. include_category_2 = "" # string # # Use or Do not Use options # # true: indent_func_call_param will be used (default) # false: indent_func_call_param will NOT be used # # Default: true use_indent_func_call_param = true # true/false # The value of the indentation for a continuation line is calculated # differently if the statement is: # - a declaration: your case with QString fileName ... # - an assignment: your case with pSettings = new QSettings( ... # # At the second case the indentation value might be used twice: # - at the assignment # - at the function call (if present) # # To prevent the double use of the indentation value, use this option with the # value 'true'. # # true: indent_continue will be used only once # false: indent_continue will be used every time (default) # # Requires indent_ignore_first_continue=false. use_indent_continue_only_once = false # true/false # The indentation can be: # - after the assignment, at the '[' character # - at the beginning of the lambda body # # true: indentation will be at the beginning of the lambda body # false: indentation will be after the assignment (default) indent_cpp_lambda_only_once = false # true/false # Whether sp_after_angle takes precedence over sp_inside_fparen. This was the # historic behavior, but is probably not the desired behavior, so this is off # by default. use_sp_after_angle_always = false # true/false # Whether to apply special formatting for Qt SIGNAL/SLOT macros. Essentially, # this tries to format these so that they match Qt's normalized form (i.e. the # result of QMetaObject::normalizedSignature), which can slightly improve the # performance of the QObject::connect call, rather than how they would # otherwise be formatted. # # See options_for_QT.cpp for details. # # Default: true use_options_overriding_for_qt_macros = true # true/false # If true: the form feed character is removed from the list of whitespace # characters. See https://en.cppreference.com/w/cpp/string/byte/isspace. use_form_feed_no_more_as_whitespace_character = false # true/false # # Warn levels - 1: error, 2: warning (default), 3: note # # (C#) Warning is given if doing tab-to-\t replacement and we have found one # in a C# verbatim string literal. # # Default: 2 warn_level_tabs_found_in_verbatim_string_literals = 2 # unsigned number # Limit the number of loops. # Used by uncrustify.cpp to exit from infinite loop. # 0: no limit. debug_max_number_of_loops = 0 # number # Set the number of the line to protocol; # Used in the function prot_the_line if the 2. parameter is zero. # 0: nothing protocol. debug_line_number_to_protocol = 0 # number # Set the number of second(s) before terminating formatting the current file, # 0: no timeout. # only for linux debug_timeout = 0 # number # Set the number of characters to be printed if the text is too long, # 0: do not truncate. debug_truncate = 0 # unsigned number # sort (or not) the tracking info. # # Default: true debug_sort_the_tracks = true # true/false # decode (or not) the flags as a new line. # only if the -p option is set. debug_decode_the_flags = false # true/false # use (or not) the exit(EX_SOFTWARE) function. # # Default: true debug_use_the_exit_function_pop = true # true/false # print (or not) the version in the file defined at the command option -o. debug_print_version = false # true/false # insert the number of the line at the beginning of each line set_numbering_for_html_output = false # true/false # Meaning of the settings: # Ignore - do not do any changes # Add - makes sure there is 1 or more space/brace/newline/etc # Force - makes sure there is exactly 1 space/brace/newline/etc, # behaves like Add in some contexts # Remove - removes space/brace/newline/etc # # # - Token(s) can be treated as specific type(s) with the 'set' option: # `set tokenType tokenString [tokenString...]` # # Example: # `set BOOL __AND__ __OR__` # # tokenTypes are defined in src/token_enum.h, use them without the # 'CT_' prefix: 'CT_BOOL' => 'BOOL' # # # - Token(s) can be treated as type(s) with the 'type' option. # `type tokenString [tokenString...]` # # Example: # `type int c_uint_8 Rectangle` # # This can also be achieved with `set TYPE int c_uint_8 Rectangle` # # # To embed whitespace in tokenStrings use the '\' escape character, or quote # the tokenStrings. These quotes are supported: "'` # # # - Support for the auto detection of languages through the file ending can be # added using the 'file_ext' command. # `file_ext langType langString [langString..]` # # Example: # `file_ext CPP .ch .cxx .cpp.in` # # langTypes are defined in uncrusify_types.h in the lang_flag_e enum, use # them without the 'LANG_' prefix: 'LANG_CPP' => 'CPP' # # # - Custom macro-based indentation can be set up using 'macro-open', # 'macro-else' and 'macro-close'. # `(macro-open | macro-else | macro-close) tokenString` # # Example: # `macro-open BEGIN_TEMPLATE_MESSAGE_MAP` # `macro-open BEGIN_MESSAGE_MAP` # `macro-close END_MESSAGE_MAP` # # # option(s) with 'not default' value: 0 # ================================================ FILE: CITATION.cff ================================================ cff-version: 1.2.0 message: "If you use this software, please cite it as below." authors: - family-names: "Light" given-names: "Roger A." orcid: "https://orcid.org/0000-0001-9218-7797" title: "My Research Software" version: 2.0.21 doi: 10.21105/joss.00265 url: "https://github.com/eclise-mosquitto/mosquitto" preferred-citation: type: article authors: - family-names: "Light" given-names: "Roger A." orcid: "https://orcid.org/0000-0001-9218-7797" doi: "10.21105/joss.00265" journal: "Journal of Open Source Software" start: 265 title: "Mosquitto: server and client implementation of the MQTT protocol" issue: 13 volume: 2 year: 2017 ================================================ FILE: CMakeLists.txt ================================================ # 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.18) set (VERSION 2.1.2) project(mosquitto VERSION ${VERSION} DESCRIPTION "Eclipse Mosquitto" LANGUAGES C ) set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_STANDARD_REQUIRED ON) list(APPEND CMAKE_MODULE_PATH "${PROJECT_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() if(APPLE) set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -undefined dynamic_lookup") endif() add_library(common-options INTERFACE) if(NOT WIN32) target_compile_options(common-options INTERFACE -Wall -Wextra -Wconversion) endif() include(CMakePushCheckState) include(CheckIncludeFiles) include(CheckLibraryExists) include(CheckSourceCompiles) include(GNUInstallDirs) include(CMakePushCheckState) include(CheckSourceCompiles) option(WITH_BUNDLED_DEPS "Build with bundled dependencies?" ON) option(WITH_LIB_CPP "Build C++ library?" ON) option(WITH_TLS "Include SSL/TLS support?" ON) option(WITH_TLS_PSK "Include TLS-PSK support (requires WITH_TLS)?" ON) option(WITH_TESTS "Enable tests" ON) option(INC_MEMTRACK "Include memory tracking support?" ON) if (WITH_LIB_CPP OR WITH_TESTS) ENABLE_LANGUAGE(CXX) endif() if (WITH_TLS) find_package(OpenSSL REQUIRED) add_definitions("-DWITH_TLS") # mosquitto uses OpenSSL 1.1 API, so set OPENSSL_API_COMPAT accordingly: # https://www.openssl.org/docs/manmaster/man7/OPENSSL_API_COMPAT.html # TODO: migrate off ENGINE API (deprecated since OpenSSL 3.0), see: # https://www.openssl.org/docs/manmaster/man7/migration_guide.html#Engines-and-METHOD-APIs add_definitions("-DOPENSSL_API_COMPAT=0x10100000L") if (WITH_TLS_PSK) add_definitions("-DWITH_TLS_PSK") endif (WITH_TLS_PSK) else() set (OPENSSL_INCLUDE_DIR "") endif() option(WITH_UNIX_SOCKETS "Include Unix Domain Socket support?" ON) if(WITH_UNIX_SOCKETS) add_definitions("-DWITH_UNIX_SOCKETS") endif() option(WITH_SOCKS "Include SOCKS5 support?" ON) if(WITH_SOCKS) add_definitions("-DWITH_SOCKS") endif() option(WITH_WEBSOCKETS "Include websockets support?" ON) option(WITH_WEBSOCKETS_BUILTIN "Websockets support uses builtin library? Set OFF to use libwebsockets" ON) if(WITH_WEBSOCKETS AND NOT WITH_TLS) message(FATAL_ERROR "WITH_WEBSOCKETS support requires WITH_TLS.") endif() 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 threading support?" ON) if(WITH_THREADING) add_definitions("-DWITH_THREADING") if(WIN32) find_package(PThreads4W REQUIRED) endif() endif() option(WITH_DLT "Include DLT support?" OFF) message(STATUS "WITH_DLT = ${WITH_DLT}") if(WITH_DLT) find_package(PkgConfig) pkg_check_modules(DLT "automotive-dlt >= 2.11" REQUIRED) endif() find_package(cJSON REQUIRED) find_package(argon2) option(WITH_CTRL_SHELL "Include mosquitto_ctrl interactive shell support?" ON) if(WITH_CTRL_SHELL) find_package(LineEditing) endif() if(ARGON2_FOUND) # Disable until separate password handling thread is implemented #add_definitions("-DWITH_ARGON2") endif() option(WITH_LTO "Build with link time optimizations (IPO) / interprocedural optimization (IPO) enabled." ON) if(WITH_LTO) include(CheckIPOSupported) check_ipo_supported(RESULT is_ipo_supported OUTPUT output) if(is_ipo_supported) set_property(TARGET common-options PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE) else() message(WARNING "LTO/IPO is not supported: ${output}") endif() 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(WITH_DOCS "Build documentation?" ON) target_sources(common-options INTERFACE config.h) target_include_directories(common-options INTERFACE ${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/include ) if(WITH_TLS) target_include_directories(common-options INTERFACE "${OPENSSL_INCLUDE_DIR}" ) endif() if(WITH_BUNDLED_DEPS) target_include_directories(common-options INTERFACE "${mosquitto_SOURCE_DIR}/deps" ) endif() add_subdirectory(libcommon) add_subdirectory(lib) if(WITH_CLIENTS) add_subdirectory(client) endif() if(WITH_BROKER) add_subdirectory(src) endif() if(WITH_APPS) add_subdirectory(apps) endif() if(WITH_PLUGINS) add_subdirectory(plugins) endif() if(WITH_DOCS) add_subdirectory(man) endif() # ======================================== # Install config file # ======================================== if(WITH_BROKER) install(FILES mosquitto.conf RENAME mosquitto.conf.example DESTINATION "${CMAKE_INSTALL_SYSCONFDIR}/mosquitto") install(FILES aclfile.example pskfile.example pwfile.example DESTINATION "${CMAKE_INSTALL_SYSCONFDIR}/mosquitto") endif() # ======================================== # 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") # ======================================== # Install headers # ======================================== install( FILES ${mosquitto_SOURCE_DIR}/include/mosquitto.h ${mosquitto_SOURCE_DIR}/include/mosquitto_broker.h ${mosquitto_SOURCE_DIR}/include/mosquitto_plugin.h ${mosquitto_SOURCE_DIR}/include/mosquittopp.h ${mosquitto_SOURCE_DIR}/include/mqtt_protocol.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" ) install( FILES ${mosquitto_SOURCE_DIR}/include/mosquitto/broker.h ${mosquitto_SOURCE_DIR}/include/mosquitto/broker_control.h ${mosquitto_SOURCE_DIR}/include/mosquitto/broker_plugin.h ${mosquitto_SOURCE_DIR}/include/mosquitto/defs.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_base64.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_cjson.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_file.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_memory.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_password.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_properties.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_random.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_string.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_time.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_topic.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_utf8.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_auth.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_callbacks.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_connect.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_create_delete.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_helpers.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_loop.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_message.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_options.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_publish.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_socks.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_subscribe.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_tls.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_unsubscribe.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquitto_will.h ${mosquitto_SOURCE_DIR}/include/mosquitto/libmosquittopp.h ${mosquitto_SOURCE_DIR}/include/mosquitto/mqtt_protocol.h DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/mosquitto" ) # ======================================== # Testing # ======================================== if(WITH_TESTS) find_package(GTest REQUIRED) include(GoogleTest) enable_testing() add_subdirectory(test) endif() ================================================ FILE: CONTRIBUTING.md ================================================ Contributing 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) ================================================ FILE: ChangeLog.txt ================================================ 2.1.3 - 2026-02-xx ================== # Broker - Fix MOSQ_EVT_DISCONNECT being called before MOSQ_EVT_ACL_CHECK for the will of that client. Closes #3487. - Fix password length not being passed to MOSQ_EVT_BASIC_AUTH events. Closes #3490. - Fix incorrect maximum-packet-size restriction for outgoing packets. Closes #3503. - Fix incorrect maximum-packet-size restriction for incoming packets. Closes #3515. - Fix will messages being incorrectly delayed if a client set session-expiry-interval=0 when using will-delay-interval>0. Closes #3505. # Common lib: - Fix potential crash if reading a file in restricted mode and the group id does not have an entry in /etc/groups. Closes #3498. - Fix missing SONAME. Closes #3483. # Lib - Fix mosquitto_loop_start() leaving the mosq struct in an invalid state if thread creation fails. Closes #3496. # Plugins - Fix migrate_to_persist_sqlite.py not base64 decoding message payloads when migrating. Closes #3492. # Build: - Fix test when nbuilding with WITH_EDITLINE=no. Closes #3484. - Fix tests when building with WITH_WEBSOCKETS=no. Closes #3502. - Fix libmosquitto_static cmake build. - Enable WITH_UNIX_SOCKETS on Windows. 2.1.2 - 2026-02-09 ================== # Broker - Forbid running with `persistence true` and with a persistence plugin at the same time. # Build - Build fixes for OpenBSD. Closes #3474. - Add missing libedit to docker builds. Closes #3476. - Fix static/shared linking of libwebsockets under cmake. 2.1.1 - 2026-02-04 ================== # Broker - Fix PUID/PGID checking for docker - Add MOSQUITTO_UNSAFE_ALLOW_SYMLINKS environment variable to allow the restrictions on reading files through symlinks to be lifted in safe environments like kubernetes. Closes #3461. - Fix inconsistent disconnect log message format, and add address:port. - Fix `plugin`/`global_plugin` option not allowing space characters. - Fix $SYS load values not being published initially. Closes #3459. - Fix max_connections not being honoured on libwebsockets listeners. This does not affect the built-in websockets support. Closes #3455. - Don't enforce receive-maximum, just log a warning. This allows badly behaving clients to be fixed. Closes #3471. # Plugins - Fix incorrect linking of libmosquitto_common.so for the acl and password file plugins. Closes #3460. # Build - Fix building with WITH_TLS=no 2.1.0 - 2026-01-29 ================== # Broker ## Deprecations - The acl_file option is deprecated in favour of the acl-file plugin, which is the same code but moved into a plugin. The acl_file option will be removed in 3.0. - The password_file option is deprecated in favour of the password-file plugin, which is the same code but moved into a plugin. The password_file option will be removed in 3.0. - The per_listener_settings option is deprecated in favour of the new listener specific options. The per_listener_settings option will be removed in 3.0. ## Behaviour changes - max_packet_size now defaults to 2,000,000 bytes instead of the 256MB MQTT limit. If you are using payloads that will result in a packet larger than this, you need to manually set the option to a value that suits your application. - acl_file and password_file will produce an error on invalid input when reloading the config, causing the broker to quit. ## Protocol related - Add support for broker created topic aliases. Topics are allocated on a first come first serve basis. - Add support for bridges to allow remote brokers to create topic aliases when running in MQTT v5 mode. - Enforce receive maximum on MQTT v5. - Return protocol error if a client attemps to subscribe to a shared subscription and also sets no-local. - Protocol version numbers reported in the log when a client connects now match the MQTT protocol version numbers, not internal Mosquitto values. - Send DISCONNECT With session-takeover return code to MQTT v5 clients when a client connects with the same client id. Closes #2340. - The `allow_duplicate_messages` now defaults to `true`. - Add `accept_protocol_versions` option to allow limiting which MQTT protocol versions are allowed for a particular listener. ## TLS related - Add `--tls-keylog` option which can be used to generate a file that can be used by wireshark to decrypt TLS traffic for debugging purposes. Closes #1818. - Add `disable_client_cert_date_checks` option to allow expired client certificate to be considered valid. - Add `bridge_tls_use_os_certs` option to allow bridges to be easily configured to trust default CA certificates. Closes #2473. - Remove support for TLS v1.1 (clients only - it remains available in the broker but is now undocumented) - Use openssl provided function for x509 certificate hostname verification, rather than own function. ## Bridge related - Add `bridge_receive_maximum` option for MQTT v5.0 bridges. - Add `bridge_session_expiry_interval` option for MQTT v5.0 bridges. - Bridge reconnection backoff improvements. ## Transport related - Add the `websockets_origin` option to allow optional enforcement of origin when a connection attempts an upgrade to WebSockets. - Add built-in websockets support that doesn't use libwebsockets. This is the preferred websockets implementation. - Add support for X-Forwarded-For header for built in websockets. - Add suport for PROXY protocol v1 and v2. ## Platform specific - Increase maximum connection count on Windows from 2048 to 8192 where supported. Closes #2122. - Allow multiple instances of mosquitto to run as services on Windows. See README-windows.txt. - Add kqueue support. - Add support for systemd watchdog. ## General - Report on what compile time options are enabled. Closes #2193. - Performance: reduce memory allocations when sending packets. - Log protocol version and ciphers that a client negotiates when connecting. - Password salts are now 64 bytes long. - Add the `global_plugin` option, which gives global plugin loaded regardless of `per_listener_settings`. - Add `global_max_clients` option to allow limiting client sessions globally on the broker. - Add `global_max_connections` option to allow limiting client connections globally on the broker. - Improve idle performance. The broker now calculates when the next event of interest is, and uses that as the timeout for e.g. `epoll_wait()`. This can reduce the number of process wakeups by 100x on an idle broker. - Add more efficient keepalive check. - Add support for sending the SIGRTMIN signal to trigger log rotation. Closes #2337. - Add `--test-config` option which can be used to test a configuration file before trying to use it in a live broker. Closes #2521. - Add support for PUID/PGID environment variables for setting the user/group to drop privileges to. Closes #2441. - Report persistence stats when starting. - $SYS updates are now aligned to `sys_interval` seconds, meaning that if set to 10, for example, updates will be sent at times matching x0 seconds. Previously update intervals were aligned to the time the broker was started. - Add `log_dest android` for logging to the Android logd daemon. - Fix some retained topic memory not being cleared immediately after used. - Add -q option to allow logging to be disabled at the command line. - Log message if a client attempts to connect with TLS to a non-TLS listener. - Add `listener_allow_anonymous` option. - Add `listener_auto_id_prefix` option. - Allow seconds when defining `persistent_client_expiration`. ## Plugin interface - Add `mosquitto_topic_matches_sub_with_pattern()`, which can match against subscriptions with `%c` and `%u` patterns for client id / username substitution. - Add support for modifying outgoing messages using `MOSQ_EVT_MESSAGE_OUT`. - Add `mosquitto_client()` function for retrieving a client struct if that client is connected. - Add `MOSQ_ERR_PLUGIN_IGNORE` to allow plugins to register basic auth or acl check callbacks, but still act as though they are not registered. A plugin that wanted to act as a blocklist for certain usernames, but wasn't carrying out authentication could return `MOSQ_ERR_PLUGIN_IGNORE` for usernames not on its blocklist. If no other plugins were configured, the client would be authenticated. Using `MOSQ_ERR_PLUGIN_DEFER` instead would mean the clients would be denied if no other plugins were configured. - Add `mosquitto_client_port()` function for plugins. - Add `MOSQ_EVT_CONNECT`, to allow plugins to know when a client has successfully authenticated to the broker. - Add connection-state example plugin to demonstrate `MOSQ_EVT_CONNECT`. - Add `MOSQ_EVT_CLIENT_OFFLINE`, to allow plugins to know when a client with a non-zero session expiry interval has gone offline. - Plugins on non-Windows platforms now no longer make their symbols globally available, which means they are self contained. - Add support for delayed basic authentication in plugins. - Plugins using the `MOSQ_EVT_MESSAGE_WRITE` callback can now return `MOSQ_ERR_QUOTA_EXCEEDED` to have the message be rejected. MQTT v5 clients using QoS 1 or 2 will receive the quota-exceeded reason code in the corresponding PUBACK/PUBREC. - `MOSQ_EVT_TICK` is now passed to plugins when `per_listener_settings` is true. - Add `mosquitto_sub_matches_acl()`, which can match one topic filter (a subscription) against another topic filter (an ACL). - Registration of the `MOSQ_EVT_CONTROL` plugin event is now handled globally across the broker, so only a single plugin can register for a given $CONTROL topic. - Add `mosquitto_plugin_set_info()` to allow plugins to tell the broker their name and version. - Add builtin $CONTROL/broker/v1 control topic with the `listPlugins` command. This is disabled by default, but can be enabled with the `enable_control_api` option. - Plugins no longer need to define `mosquitto_plugin_cleanup()` if they do not need to do any of their own cleanup. Callbacks will be unregistered automatically. - Add `mosquitto_set_clientid()` to allow plugins to force a client id for a client. - Add `MOSQ_EVT_SUBSCRIBE` and `MOSQ_EVT_UNSUBSCRIBE` events that are called when subscribe/unsubscribes actually succeed. Allow modifying topic and qos. - Add `mosquitto_persistence_location()` for plugins to use to find a valid location for storing persistent data. - Plugins can now use the `next_s` and `next_ms` members of the tick event data struct to set a minimum interval that the broker will wait before calling the tick callback again. - MOSQ_EVT_ACL_CHECK event is now passed message properties where possible. # Plugins - Add acl-file plugin. - Add password-file plugin. - Add persist-sqlite plugin. - Add sparkplug-aware plugin. # Dynamic security plugin - Add ability to deny wildcard subscriptions for a role to the dynsec plugin. - The dynamic security plugin now only kicks clients at the start of the next network loop, to give chance for PUBACK/PUBREC to be sent. Closes #2474. - The dynamic security plugin now reports client connections in getClient and listClients. - The dynamic security plugin now generates an initial configuration if none is present, including a set of default roles. - The dynamic security plugin now supports `%c` and `%u` patterns for substituting client id and username respectively, in all ACLs except for subscribeLiteral and unsubscribeLiteral. - The dynamic security plugin now supports multiple ways to initialise the first configuration file. # Client library - Add `MOSQ_OPT_DISABLE_SOCKETPAIR` to allow the disabling of the socketpair feature that allows the network thread to be woken from select() by another thread when e.g. `mosquitto_publish()` is called. This reduces the number of sockets used by each client by two. - Add `on_pre_connect()` callback to allow clients to update username/password/TLS parameters before an automatic reconnection. - Callbacks no longer block other callbacks, and can be set from within a callback. Closes #2127. - Add support for MQTT v5 broker to client topic aliases. - Add `mosquitto_topic_matches_sub_with_pattern()`, which can match against subscriptions with `%c` and `%u` patterns for client id / username substitution. - Add `mosquitto_sub_matches_acl()`, which can match one topic filter (a subscription) against another topic filter (an ACL). - Add `mosquitto_sub_matches_acl_with_pattern()`, which can match one topic filter (a subscription) against another topic filter (an ACL), with `%c` and `%u` patterns for client id / username substitution. - Performance: reduce memory allocations when sending packets. - Reintroduce threading support for Windows. Closes #1509. - `mosquitto_subscribe*()` now returns `MOSQ_ERR_INVAL` if an empty string is passed as a topic filter. - `mosquitto_unsubscribe*()` now returns `MOSQ_ERR_INVAL` if an empty string is passed as a topic filter. - Add websockets support. - `mosquitto_property_read_binary/string/string_pair` will now set the name/value parameter to NULL if the binary/string is empty. This aligns the behaviour with other property functions. Closes #2648. - Add `mosquitto_unsubscribe2_v5_callback_set`, which provides a callback that gives access to reason codes for each of the unsubscription requests. - Add `mosquitto_property_remove`, for removing properties from property lists. - Add `on_ext_auth()` callback to allow handling MQTT v5 extended authentication. - Add `mosquitto_ext_auth_continue()` function to continue an MQTT v5 extended authentication. - Remove support for TLS v1.1. - Use openssl provided function for x509 certificate hostname verification, rather than own function. # Clients ## General - Add `-W` timeout support to Windows. - The `--insecure` option now disables all server certificate verification. - Add websockets support. - Using `-x` now sets the clients to use MQTT v5.0. - Fix parsing of IPv6 addresses in socks proxy urls. - Add `--tls-keylog` option which can be used to generate a file that can be used by wireshark to decrypt TLS traffic for debugging purposes. - Remove support for TLS v1.1. - Add `-o` option for all clients loading options from a specific file. - Add `--no-tls` option for all clients which disables all TLS options for that instance. This is useful for negating TLS options provided in a config file, or to disable the automatic use of TLS when using port 8883. Closes #2180. ## mosquitto_rr - Fix `-f` and `-s` options in mosquitto_rr. - Add `--latency` option to mosquitto_rr, for printing the request/response latency. - Add `--retain-handling` option. ## mosquitto_sub - Fix incorrect output formatting in mosquitto_sub when using field widths with `%x` and `%X` for printing the payload in hex. - Add float printing option to mosquitto_sub. - mosquitto_sub payload hex output can now be split by fixed field length. - Add `--message-rate` option to mosquitto_sub, for printing the count of messages received each second. - Add `--retain-handling` option. - Add `-w`/`--watch` to mosquitto_sub which means messages will be printed on a fixed line number based on the topic and order in which messages were received. Requires ANSI escape code support in the terminal. - mosquitto_sub now only needs `-t` or `-U` to run - this means that `-t` is not required in all situations. # Apps ## mosquitto_signal - Add `mosquitto_signal` for helping send signals to mosquitto on Windows. ## mosquitto_ctrl - Add interactive shell mode to mosquitto_ctrl. - Add support for `listPlugins` to mosquitto_ctrl. - Allow mosquitto_ctrl dynsec module to update passwords in files rather than having to connect to a broker. ## mosquitto_passwd - Print messages in mosquitto_passwd when adding/updating passwords. Closes #2544. - When creating a new file with `-c`, setting the output filename to a dash `-` will output the result to stdout. ## mosquitto_db_dump - Add `--json` output mode do mosquitto_db_dump. # Build - Increased CMake minimal required version to 3.14, which is required for the preinstalled SQLite3 find module. - Add an CMake option `WITH_LTO` to enable/disable link time optimization. - Set C99 as the explicit, rather than implicit, build standard. - cJSON is now a required dependency. - Refactored headers for easier discovery. - Support for openssl < 3.0 removed. 2.0.23 - 2026-01-14 =================== Broker: - Fix handling of disconnected sessions for `per_listener_settings true` - Check return values of openssl *_get_ex_data() and *_set_ex_data() to prevent possible crash. This could occur only in extremely unlikely situations. See https://github.com/eclipse-mosquitto/mosquitto/issues/3389 Closes #3389. - Check return value of openssl ASN1_string_[get0_]data() functions for NULL. This prevents a crash in case of incorrect certificate handling in openssl. Closes #3390. - Fix potential crash on startup if a malicious/corrupt persistence file from mosquitto 1.5 or earlier is loaded. Closes #3439. - Limit auto_id_prefix to 50 characters. Closes #3440. 2.0.22 - 2025-07-11 =================== # Broker - Windows: Fix broker crash on startup if using `log_dest stdout` - Bridge: Fix idle_timeout never occurring for lazy bridges. - Fix case where max_queued_messages = 0 was not treated as unlimited. Closes #3244. - Fix `--version` exit code and output. Closes #3267. - Fix crash on receiving a $CONTROL message over a bridge, if per_listener_settings is set true and the bridge is carrying out topic remapping. Closes #3261. - Fix incorrect reference clock being selected on startup on Linux. Closes #3238. - Fix reporting of client disconnections being incorrectly attributed to "out of memory". Closes #3253. - Fix compilation when using `WITH_OLD_KEEPALIVE`. Closes #3250. - Add Windows linker file for the broker to the installer. Closes #3269. - Fix Websockets PING not being sent on Windows. Closes #3272. - Fix problems with secure websockets. Closes #1211. - Fix crash on exit when using WITH_EPOLL=no. Closes #3302. - Fix clients being incorrectly expired when they have keepalive == max_keepalive. Closes #3226, #3286. # Dynamic security plugin - Fix mismatch memory free when saving config which caused memory tracking to be incorrect. # Client library - Fix C++ symbols being removed when compiled with link time optimisation. Closes #3259. - TLS error handling was incorrectly setting a protocol error for non-TLS errors. This would cause the mosquitto_loop_start() thread to exit if no broker was available on the first connection attempt. This has been fixed. Closes #3258. - Fix linker errors on some architectures using cmake. Closes #3167. # Tests - Fix 08-ssl-connect-cert-auth-expired and 08-ssl-connect-cert-auth-revoked tests when running on a single CPU system. Closes #3230. 2.0.21 - 2025-03-06 =================== # Security - Fix leak on malicious SUBSCRIBE by authenticated client. Closes eclipse #248. - Further fix for CVE-2023-28366. # Broker - Fix clients sending a RESERVED packet not being quickly disconnected. Closes #2325. - Fix `bind_interface` producing an error when used with an interface that has an IPv6 link-local address and no other IPv6 addresses. Closes #2696. - Fix mismatched wrapped/unwrapped memory alloc/free in properties. Closes #3192. - Fix `allow_anonymous false` not being applied in local only mode. Closes #3198. - Add `retain_expiry_interval` option to fix expired retained message not being removed from memory if they are not subscribed to. Closes #3221. - Produce an error if invalid combinations of cafile/capath/certfile/keyfile are used. Closes #1836. Closes #3130. - Backport keepalive checking from develop to fix problems in current implementation. Closes #3138. # Client library - Fix potential deadlock in mosquitto_sub if `-W` is used. Closes #3175. # Apps - mosquitto_ctrl dynsec now also allows `-i` to specify a clientid as well as `-c`. This matches the documentation which states `-i`. Closes #3219. # Client library - Fix threads linking on Windows for static libmosquitto library Closes #3143 # Build - Fix Windows builds not having websockets enabled. - Add tzdata to docker images # Tests - Fix 08-ssl-connect-cert-auth-expired and 08-ssl-connect-cert-auth-revoked tests when under load. Closes #3208. 2.0.20 - 2024-10-16 =================== # Broker - Fix QoS 1 / QoS 2 publish incorrectly returning "no subscribers". Closes #3128. - Open files with appropriate access on Windows. Closes #3119. - Don't allow invalid response topic values. - Fix some strict protocol compliance issues. Closes #3052. # Client library - Fix cmake build on OS X. Closes #3125. # Build - Fix build on NetBSD 2.0.19 - 2024-10-02 =================== # Security - Fix mismatched subscribe/unsubscribe with normal/shared topics. - Fix crash on bridge using remapped topic being sent a crafted packet. # Broker - Fix assert failure when loading a persistence file that contains subscriptions with no client id. - Fix local bridges being incorrectly expired when persistent_client_expiration is in use. - Fix use of CLOCK_BOOTTIME for getting time. Closes #3089. - Fix mismatched subscribe/unsubscribe with normal/shared topics. - Fix crash on bridge using remapped topic being sent a crafted packet. # Client library - Fix some error codes being converted to string as "unknown". Closes #2579. - Clear SSL error state to avoid spurious error reporting. Closes #3054. - Fix "payload format invalid" not being allowed as a PUBREC reason code. - Don't allow SUBACK with missing reason codes. # Build - Thread support is re-enabled on Windows. 2.0.18 - 2023-09-18 =================== # Broker - Fix crash on subscribe under certain unlikely conditions. Closes #2885. Closes #2881. # Clients - Fix mosquitto_rr not honouring `-R`. Closes #2893. # Windows - Installer will start/stop the mosquitto service when installing and uninstalling, to prevent problems with not being able to overwrite or remove mosquitto.exe. 2.0.17 - 2023-08-22 =================== # Broker - Fix `max_queued_messages 0` stopping clients from receiving messages. Closes #2879. - Fix `max_inflight_messages` not being set correctly. Closes #2876. # Apps - Fix `mosquitto_passwd -U` backup file creation. Closes #2873. 2.0.16 - 2023-08-16 =================== # Security - CVE-2023-28366: Fix memory leak in broker when clients send multiple QoS 2 messages with the same message ID, but then never respond to the PUBREC commands. - CVE-2023-0809: Fix excessive memory being allocated based on malicious initial packets that are not CONNECT packets. - CVE-2023-3592: Fix memory leak when clients send v5 CONNECT packets with a will message that contains invalid property types. - Broker will now reject Will messages that attempt to publish to $CONTROL/. - Broker now validates usernames provided in a TLS certificate or TLS-PSK identity are valid UTF-8. - Fix potential crash when loading invalid persistence file. - Library will no longer allow single level wildcard certificates, e.g. *.com # Broker - Fix $SYS messages being expired after 60 seconds and hence unchanged values disappearing. - Fix some retained topic memory not being cleared immediately after used. - Fix error handling related to the `bind_interface` option. - Fix std* files not being redirected when daemonising, when built with assertions removed. Closes #2708. - Fix default settings incorrectly allowing TLS v1.1. Closes #2722. - Use line buffered mode for stdout. Closes #2354. Closes #2749. - Fix bridges with non-matching cleansession/local_cleansession being expired on start after restoring from persistence. Closes #2634. - Fix connections being limited to 2048 on Windows. The limit is now 8192, where supported. Closes #2732. - Broker will log warnings if sensitive files are world readable/writable, or if the owner/group is not the same as the user/group the broker is running as. In future versions the broker will refuse to open these files. - mosquitto_memcmp_const is now more constant time. - Only register with DLT if DLT logging is enabled. - Fix any possible case where a json string might be incorrectly loaded. This could have caused a crash if a textname or textdescription field of a role was not a string, when loading the dynsec config from file only. - Dynsec plugin will not allow duplicate clients/groups/roles when loading config from file, which matches the behaviour for when creating them. - Fix heap overflow when reading corrupt config with "log_dest file". # Client library - Use CLOCK_BOOTTIME when available, to keep track of time. This solves the problem of the client OS sleeping and the client hence not being able to calculate the actual time for keepalive purposes. Closes #2760. - Fix default settings incorrectly allowing TLS v1.1. Closes #2722. - Fix high CPU use on slow TLS connect. Closes #2794. # Clients - Fix incorrect topic-alias property value in mosquitto_sub json output. - Fix confusing message on TLS certificate verification. Closes #2746. # Apps - mosquitto_passwd uses mkstemp() for backup files. - `mosquitto_ctrl dynsec init` will refuse to overwrite an existing file, without a race-condition. 2.0.15 - 2022-08-16 =================== # Security - Deleting the group configured as the anonymous group in the Dynamic Security plugin, would leave a dangling pointer that could lead to a single crash. This is considered a minor issue - only administrative users should have access to dynsec, the impact on availability is one-off, and there is no associated loss of data. It is now forbidden to delete the group configured as the anonymous group. # Broker - Fix memory leak when a plugin modifies the topic of a message in MOSQ_EVT_MESSAGE. - Fix bridge `restart_timeout` not being honoured. - Fix potential memory leaks if a plugin modifies the message in the MOSQ_EVT_MESSAGE event. - Fix unused flags in CONNECT command being forced to be 0, which is not required for MQTT v3.1. Closes #2522. - Improve documentation of `persistent_client_expiration` option. Closes #2404. - Add clients to session expiry check list when restarting and reloading from persistence. Closes #2546. - Fix bridges not sending failure notification messages to the local broker if the remote bridge connection fails. Closes #2467. Closes #1488. - Fix some PUBLISH messages not being counted in $SYS stats. Closes #2448. - Fix incorrect return code being sent in DISCONNECT when a client session is taken over. Closes #2607. - Fix confusing "out of memory" error when a client is kicked in the dynamic security plugin. Closes #2525. - Fix confusing error message when dynamic security config file was a directory. Closes #2520. - Fix bridge queued messages not being persisted when local_cleansession is set to false and cleansession is set to true. Closes #2604. - Dynamic security: Fix modifyClient and modifyGroup commands to not modify the client/group if a new group/client being added is not valid. Closes #2598. - Dynamic security: Fix the plugin being able to be loaded twice. Currently only a single plugin can interact with a unique $CONTROL topic. Using multiple instances of the plugin would produce duplicate entries in the config file. Closes #2601. Closes #2470. - Fix case where expired messages were causing queued messages not to be delivered. Closes #2609. - Fix websockets not passing on the X-Forwarded-For header. # Client library - Fix threads library detection on Windows under cmake. Bumps the minimum cmake version to 3.1, which is still ancient. - Fix use of `MOSQ_OPT_TLS_ENGINE` being unable to be used due to the openssl ctx not being initialised until starting to connect. Closes #2537. - Fix incorrect use of SSL_connect. Closes #2594. - Don't set SIGPIPE to ignore, use MSG_NOSIGNAL instead. Closes #2564. - Add documentation of struct mosquitto_message to header. Closes #2561. - Fix documentation omission around mosquitto_reinitialise. Closes #2489. - Fix use of MOSQ_OPT_SSL_CTX when used in conjunction with MOSQ_OPT_SSL_CTX_DEFAULTS. Closes #2463. - Fix failure to close thread in some situations. Closes #2545. # Clients - Fix mosquitto_pub incorrectly reusing topic aliases when reconnecting. Closes #2494. # Apps - Fix `-o` not working in `mosquitto_ctrl`, and typo in related documentation. Closes #2471. 2.0.14 - 2021-11-17 =================== # Broker - Fix bridge not respecting receive-maximum when reconnecting with MQTT v5. # Client library - Fix mosquitto_topic_matches_sub2() not using the length parameters. Closes #2364. - Fix incorrect subscribe_callback in mosquittopp.h. Closes #2367. 2.0.13 - 2021-10-27 =================== # Broker - Fix `max_keepalive` option not being able to be set to 0. - Fix LWT messages not being delivered if `per_listener_settings` was set to true. Closes #2314. - Various fixes around inflight quota management. Closes #2306. - Fix problem parsing config files with Windows line endings. Closes #2297. - Don't send retained messages when a shared subscription is made. - Fix log being truncated in Windows. - Fix client id not showing in log on failed connections, where possible. - Fix broker sending duplicate CONNACK on failed MQTT v5 reauthentication. Closes #2339. - Fix mosquitto_plugin.h not including mosquitto_broker.h. Closes #2350. - Fix unlimited message quota not being properly checked for incoming messages. Closes #2593. - Fixed build for openssl compiled with OPENSSL_NO_ENGINE. Closes #2589. # Client library - Initialise sockpairR/W to invalid in `mosquitto_reinitialise()` to avoid closing invalid sockets in `mosquitto_destroy()` on error. Closes #2326. # Clients - Fix date format in mosquitto_sub output. Closes #2353. 2.0.12 - 2021-08-31 =================== # Security - An MQTT v5 client connecting with a large number of user-property properties could cause excessive CPU usage, leading to a loss of performance and possible denial of service. This has been fixed. - Fix `max_keepalive` not applying to MQTT v3.1.1 and v3.1 connections. These clients are now rejected if their keepalive value exceeds max_keepalive. This option allows CVE-2020-13849, which is for the MQTT v3.1.1 protocol itself rather than an implementation, to be addressed. - Using certain listener related configuration options e.g. `cafile`, that apply to the default listener without defining any listener would cause a remotely accessible listener to be opened that was not confined to the local machine but did have anonymous access enabled, contrary to the documentation. This has been fixed. Closes #2283. - CVE-2021-34434: If a plugin had granted ACL subscription access to a durable/non-clean-session client, then removed that access, the client would keep its existing subscription. This has been fixed. - Incoming QoS 2 messages that had not completed the QoS flow were not being checked for ACL access when a clean session=False client was reconnecting. This has been fixed. # Broker - Fix possible out of bounds memory reads when reading a corrupt/crafted configuration file. Unless your configuration file is writable by untrusted users this is not a risk. Closes #567213. - Fix `max_connections` option not being correctly counted. - Fix TLS certificates and TLS-PSK not being able to be configured at the same time. - Disable TLS v1.3 when using TLS-PSK, because it isn't correctly configured. - Fix `max_keepalive` not applying to MQTT v3.1.1 and v3.1 connections. These clients are now rejected if their keepalive value exceeds max_keepalive. This option allows CVE-2020-13849, which is for the MQTT v3.1.1 protocol itself rather than an implementation, to be addressed. - Fix broker not quitting if e.g. the `password_file` is specified as a directory. Closes #2241. - Fix listener mount_point not being removed on outgoing messages. Closes #2244. - Strict protocol compliance fixes, plus test suite. - Fix $share subscriptions not being recovered for durable clients that reconnect. - Update plugin configuration documentation. Closes #2286. # Client library - If a client uses TLS-PSK then force the default cipher list to use "PSK" ciphers only. This means that a client connecting to a broker configured with x509 certificates only will now fail. Prior to this, the client would connect successfully without verifying certificates, because they were not configured. - Disable TLS v1.3 when using TLS-PSK, because it isn't correctly configured. - Threaded mode is deconfigured when the mosquitto_loop_start() thread ends, which allows mosquitto_loop_start() to be called again. Closes #2242. - Fix MOSQ_OPT_SSL_CTX not being able to be set to NULL. Closes #2289. - Fix reconnecting failing when MOSQ_OPT_TLS_USE_OS_CERTS was in use, but none of capath, cafile, psk, nor MOSQ_OPT_SSL_CTX were set, and MOSQ_OPT_SSL_CTX_WITH_DEFAULTS was set to the default value of true. Closes #2288. # Apps - Fix `mosquitto_ctrl dynsec setDefaultACLAccess` command not working. # Clients - mosquitto_sub and mosquitto_rr now open stdout in binary mode on Windows so binary payloads are not modified when printing. - Document TLS certificate behaviour when using `-p 8883`. # Build - Fix installation using WITH_TLS=no. Closes #2281. - Fix builds with libressl 3.4.0. Closes #2198. - Remove some unnecessary code guards related to libressl. - Fix printf format build warning on MIPS. Closes #2271. 2.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. - Fix openssl not being linked to dynamic security plugin. Closes #2277. # 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-28166: 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-2021-28166. 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 minimum 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 incorrectly 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 quitting 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. CVE-2017-7654. 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 uninitialised 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 noticeable 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 truly 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 syntax 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). ================================================ FILE: LICENSE.txt ================================================ This project is dual licensed under the Eclipse Public License 2.0 OR the Eclipse Distribution License 1.0 as described in the epl-v20 and edl-v10 files. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause ================================================ FILE: Makefile ================================================ include config.mk DIRS=libcommon lib apps client plugins src DOCDIRS=man DISTDIRS=man DISTFILES= \ apps/ \ client/ \ cmake/ \ common/ \ dashboard/ \ deps/ \ doc/ \ docker/ \ examples/ \ fuzzing/ \ include/ \ installer/ \ libcommon/ \ lib/ \ logo/ \ make/ \ man/ \ misc/ \ plugins/ \ security/ \ service/ \ snap/ \ src/ \ test/ \ www/ \ .github \ \ .editorconfig \ .gitignore \ .uncrustify.cfg \ buildtest.py \ codecov.yml \ CMakeLists.txt \ CITATION.cff \ CONTRIBUTING.md \ ChangeLog.txt \ format.sh \ 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-tests.md \ README-windows.txt \ README.md \ run_tests.py \ set-version.sh \ SECURITY.md \ THANKS.txt \ vcpkg.json .PHONY : all mosquitto api docs binary check clean reallyclean test test-compile install uninstall dist sign copy localdocker all : $(MAKE_ALL) api : mkdir -p api p naturaldocs -o HTML api -i include -p p rm -rf p docs : set -e; for d in ${DOCDIRS}; do $(MAKE) -C $${d}; done binary : mosquitto binary-all : mosquitto test-compile 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 fuzzing : mosquitto $(MAKE) -C fuzzing 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 $(MAKE) -C fuzzing 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-compile: mosquitto lib $(MAKE) -C test test-compile $(MAKE) -C plugins test-compile test : mosquitto lib apps test-compile $(MAKE) -C test test $(MAKE) -C plugins 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" $(INSTALL) -d "${DESTDIR}$(prefix)/include/mosquitto" $(INSTALL) include/mosquitto/*.h "${DESTDIR}${prefix}/include/mosquitto/" $(INSTALL) include/mosquitto.h "${DESTDIR}${prefix}/include/mosquitto.h" $(INSTALL) include/mosquitto_broker.h "${DESTDIR}${prefix}/include/mosquitto_broker.h" $(INSTALL) include/mosquitto_plugin.h "${DESTDIR}${prefix}/include/mosquitto_plugin.h" $(INSTALL) include/mosquittopp.h "${DESTDIR}${prefix}/include/mosquittopp.h" $(INSTALL) include/mqtt_protocol.h "${DESTDIR}${prefix}/include/mqtt_protocol.h" 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" rm -f "${DESTDIR}${prefix}/include/mosquitto.h" rm -f "${DESTDIR}${prefix}/include/mosquitto/broker.h" rm -f "${DESTDIR}${prefix}/include/mosquitto/broker_control.h" rm -f "${DESTDIR}${prefix}/include/mosquitto/broker_plugin.h" rm -f "${DESTDIR}${prefix}/include/mosquitto/libmosquittopp.h" rm -f "${DESTDIR}${prefix}/include/mosquitto/mqtt_protocol.h" rm -f "${DESTDIR}${prefix}/include/mosquitto_broker.h" rm -f "${DESTDIR}${prefix}/include/mosquitto_plugin.h" rm -f "${DESTDIR}${prefix}/include/mosquittopp.h" rm -f "${DESTDIR}${prefix}/include/mqtt_protocol.h" 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 -d apps -d client -d lib -d plugins -d src --output-file coverage.info --no-external --ignore-errors empty genhtml --ignore-errors inconsistent 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 --build-arg VERSION=${VERSION} ================================================ FILE: NOTICE.md ================================================ # 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/mosquitto ## Third-party Content This project makes use of the follow third party projects. c-ares * License: MIT * Project: https://c-ares.org/ * Source: https://github.com/c-ares/c-ares cJSON (1.7.x) * License: MIT * Project: https://github.com/DaveGamble/cJSON googletest * License: BSD-3-Clause * Project: https://github.com/google/googletest libedit (3.1) * License: BSD-3-Clause * Project: https://thrysoee.dk/editline/ * Source: https://thrysoee.dk/editline/libedit-20250104-3.1.tar.gz libwebsockets (4.x) * License: MIT * Project: https://github.com/warmcat/libwebsockets microhttpd * License: GNU LGPL v2.1+ * Project: https://www.gnu.org/software/libmicrohttpd/ * Source: git://git.gnunet.org/libmicrohttpd2.git openssl (3.x.x) * License: Apache 2.0 * Project: https://openssl.org * Source: https://github.com/openssl/openssl picohttpparser * License: MIT * Project: github.com/h2o/picohttpparser uthash (2.3.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. ================================================ FILE: README-compiling.md ================================================ The following packages can be used to add features to mosquitto. * cJSON - required * c-ares (libc-ares-dev on Debian based systems) - optional, enable with `WITH_SRV=yes` * libedit - for mosquitto_ctrl interactive shell - optional, disable with `WITH_EDITLINE=no` * libmicrohttpd - for broker http api support - optional, disable with `WITH_HTTP_API=no` * openssl (libssl-dev on Debian based systems) - optional, disable with `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. * sqlite3 - for persistence support in the broker - optional, disable with `WITH_SQLITE=no` * uthash / utlist - bundled versions of these headers are provided, disable their use with `WITH_BUNDLED_DEPS=no` * xsltproc (xsltproc and docbook-xsl on Debian based systems) - only needed when building from git sources - disable with `WITH_DOCS=no` For testing, the following packages are required: * cunit * googletest / gmock * microsocks * python To compile you may either use CMake, or on Linux look in the file `config.mk` for compile options and use plain `make`. Up to version 2.1, the recommendation was to use CMake for Windows and Mac, and to use make everywhere else. The recommendation now is to use cmake in all cases, and that the plain makefiles will be removed in version 3.0. 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. ================================================ FILE: README-letsencrypt.md ================================================ # 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. ================================================ FILE: README-tests.md ================================================ # Tests ## Running The Mosquitto test suite can be invoked using either of ``` make test make check ``` The tests run in series and due to the nature of some of the tests being made can take a while. ## Parallel Tests To run the tests with some parallelism, use ``` make ptest ``` This runs up to 20 tests in parallel at once, yielding much faster overall run time at the expense of having up to 20 instances of Python running at once. This is not a particularly CPU intensive option, but does require more memory and may be unsuitable on e.g. a Raspberry Pi. ## Dependencies The tests require Python 3 and CUnit to be installed. ================================================ FILE: README-windows.txt ================================================ Mosquitto for Windows ===================== Mosquitto for Windows comes in 64-bit and 32-bit flavours. All dependencies are provided in the installer. Installing ---------- Running the installer will present the normal type of graphical installer. If you want to install without starting the graphical part of the installer, you can do so by running it from a cmd prompt with the `/S` switch: ``` mosquitto-2.0.12-install-windows-x64.exe /S ``` You can override the installation directory with the `/D` switch: ``` mosquitto-2.0.12-install-windows-x64.exe /S /D=:\mosquitto ``` 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, this limit is 2048 connections. 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 defined by the %MOSQUITTO_DIR% environment variable. This will be set to the directory that you installed to by default. 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 It is possible to install and run multiple instances of a Mosquitto service, as of version 2.1. To do this, copy the mosquitto executable to a new *name* and run the service install as above. The service will load a configuration file mosquitto.conf from the directory defined by the environment variable "_DIR". For this reason it is suggested to keep the executable name consisting of alphanumeric and '_' characters. Any other character will be replaced with '_'. For example, if you copy mosquitto.exe to eclipse_mosquitto.exe, you would run these commands to install/uninstall: C:\Program Files\mosquitto\eclipse_mosquitto install C:\Program Files\mosquitto\eclipse_mosquitto uninstall And the service would try to load the config file at %ECLIPSE_MOSQUITTO_DIR%/mosquitto.conf The new service will appear in the service list as "Mosquitto Broker (eclipse_mosquitto.exe)". 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. Signals ------- Starting with version 2.1, it is possible to use the mosquitto_signal command to send signals to the broker, in a similar way to sending signals on a posix based system. See https://mosquitto.org/man/mosquitto_signal-1.html for more details. ================================================ FILE: README.md ================================================ Eclipse 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, the `mosquitto_pub` `mosquitto_rr`, and `mosquitto_sub` utilities for publishing and subscribing, and the `mosquitto_ctrl`, `mosquitto_signal`, and `mosquitto_passwd` applications for helping administer the broker. ## 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 very 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' Note that starting the broker like this allows anonymous/unauthenticated access but only from the local computer, so it's only really useful for initial testing. If you want to have clients from another computer connect, you will need to provide a configuration file. If you have installed from a binary package, you will probably already have a configuration file at somewhere like `/etc/mosquitto/mosquitto.conf`. If you've compiled from source, you can write your config file then run as `mosquitto -c /path/to/mosquitto.conf`. To start your config file you define a listener and you will need to think about what authentication you require. It is not advised to run your broker with anonymous access when it is publicly available. For details on how to do this, look at the [authentication methods](https://mosquitto.org/documentation/authentication-methods/) available and the [dynamic security plugin](https://mosquitto.org/documentation/dynamic-security/). ## 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 * cJSON - required * c-ares (libc-ares-dev on Debian based systems) - optional, enable with `WITH_SRV=yes` * libedit - for mosquitto_ctrl interactive shell - optional, disable with `WITH_EDITLINE=no` * libmicrohttpd - for broker http api support - optional, disable with `WITH_HTTP_API=no` * openssl (libssl-dev on Debian based systems) - optional, disable with `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. * sqlite3 - for persistence support in the broker - optional, disable with `WITH_SQLITE=no` * uthash / utlist - bundled versions of these headers are provided, disable their use with `WITH_BUNDLED_DEPS=no` * xsltproc (xsltproc and docbook-xsl on Debian based systems) - only needed when building from git sources - disable with `WITH_DOCS=no` Equivalent options for enabling/disabling features are available when using the CMake build. It is also possible to enable/disable building of specific plugins in the CMake build. ### Building mosquitto - Using vcpkg You can download and install mosquitto using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install mosquitto The mosquitto port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. ## Credits Mosquitto was written by Roger Light . There have been substantial contributions by other people in the community both in terms of code and other help. ================================================ FILE: SECURITY.md ================================================ # Security Policy ## Reporting a Vulnerability If you think you have found a security vulnerability in Mosquitto, please follow the steps on [Eclipse Security](https://www.eclipse.org/security/) page to report it. ================================================ FILE: THANKS.txt ================================================ These people have reported bugs / provided patches / done something else to aid the mosquitto project. Thanks to you all! If you think I've missed you off the list, please rest assured that it wasn't intentional and get in touch and I'll fix it. Adam Rudd Alexandre Zia Andrew Elwell Andy Piper Andy Stanford-Clark Anton Prokofiev Axel Busch Bart Van Der Meerssche BD Walker Ben Tobin Bob Blackrock Brad Stancel Brett Francis Chris Willing Christian Sampaio Christoph Krey Craig Hollabaugh Cristian Manuel Vertiz Fernandez Dan Anderson Daniel Deadwyler Daniel O'Conner Dariusz Suchojad Darren Oliver David Huang David Monro Dirk O. Kaar Dominik Obermaier Dominik Zajac Ed Morris Fabian Ruff Fang Chong Frank Hansen Gary Koh Gianfranco Costamagna Guido Hinderberger Hiram van Paassen Jan-Piet Mens Joan Zapata Joe McIlvain Karl Palsson Larry Lendo Martin Assarsson Martin Rauscher Martin van Wingerden Marty Lee Matt Daubney Michael C Michael Frisch Michael Hekel Michael Laing Michael Rushton Mike Bush Milan Tucic Neil Bothwick Nicholas Humfrey Nicholas O'Leary Nithin Kumar Patrick Geary Paul Diston Peter Magnusson Pryce Jones Peter George Richard Eagland Rob Pridham Robin Gingras Roland de Boo Sebastian Kroll Sergio Rubio Sharon Ben-Asher sskaje Stefan Hudelmaier Stefano Costa Stephen Owens Stephen Woods Steven Lougheed Surendra Reddy Szymon Kochanski Tammo Besemann Thomas Hilbig Tobias Assarsson Toby Jaffey Tomas Novotny Vicente Ruiz Wayne Ingram Yun Wu Yuvraaj Kelkar 賴 冠廷 ================================================ FILE: about.html ================================================ 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.

================================================ FILE: aclfile.example ================================================ # 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. # Note that this is the only topic it is possible to grant access to writing to # the $SYS tree. All other topics are always denied. pattern write $SYS/broker/connection/%c/state ================================================ FILE: apps/CMakeLists.txt ================================================ add_subdirectory(db_dump) add_subdirectory(mosquitto_ctrl) add_subdirectory(mosquitto_passwd) add_subdirectory(mosquitto_signal) ================================================ FILE: apps/Makefile ================================================ R=.. include ${R}/config.mk DIRS= \ mosquitto_ctrl \ mosquitto_passwd \ mosquitto_signal ifeq ($(WITH_PERSISTENCE),yes) DIRS+=db_dump endif .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 ================================================ FILE: apps/db_dump/CMakeLists.txt ================================================ add_executable(mosquitto_db_dump db_dump.c db_dump.h json.c print.c stubs.c ../../common/json_help.c ../../common/json_help.h ../../lib/packet_datatypes.c ../../lib/property_mosq.c ../../src/persist_read.c ../../src/persist_read_v234.c ../../src/persist_read_v5.c ../../src/topic_tok.c ) target_compile_definitions(mosquitto_db_dump PRIVATE WITH_BROKER WITH_PERSISTENCE ) target_include_directories(mosquitto_db_dump PRIVATE "${mosquitto_SOURCE_DIR}/common" "${mosquitto_SOURCE_DIR}/lib" "${mosquitto_SOURCE_DIR}/libcommon" "${mosquitto_SOURCE_DIR}/src" "${OPENSSL_INCLUDE_DIR}" "${CJSON_INCLUDE_DIRS}" ) if(WITH_TLS) target_link_libraries(mosquitto_db_dump PRIVATE OpenSSL::SSL) endif() if(WIN32) target_link_libraries(mosquitto_db_dump PRIVATE ws2_32) endif() target_link_libraries(mosquitto_db_dump PRIVATE common-options libmosquitto_common) install(TARGETS mosquitto_db_dump RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ) ================================================ FILE: apps/db_dump/Makefile ================================================ R=../.. include ${R}/config.mk LOCAL_CFLAGS+= LOCAL_CPPFLAGS+=-I${R} -I${R}/lib -I${R}/src -I${R}/common -DWITH_BROKER LOCAL_LDFLAGS+= LOCAL_LDADD+=-lcjson -lm ${LIBMOSQ_COMMON} # ------------------------------------------ # Compile time options # ------------------------------------------ include ${R}/make/broker.mk # ------------------------------------------ # Targets # ------------------------------------------ OBJS = \ db_dump.o \ json.o \ print.o \ stubs.o BROKER_OBJS = \ ${R}/src/packet_datatypes.o \ ${R}/src/persist_read.o \ ${R}/src/persist_read_v234.o \ ${R}/src/persist_read_v5.o \ ${R}/src/property_mosq.o \ ${R}/src/topic_tok.o OBJS_EXTERNAL = \ json_help.o ifeq ($(UNAME),Linux) LIBS:=$(LIBS) -lrt endif .PHONY: all clean reallyclean ifeq ($(WITH_FUZZING),yes) all : mosquitto_db_dump.a else all : mosquitto_db_dump endif mosquitto_db_dump : ${OBJS} ${BROKER_OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}${CC} $^ -o $@ ${LOCAL_LDFLAGS} ${LOCAL_LDADD} mosquitto_db_dump.a : ${OBJS} ${BROKER_OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}$(AR) cr $@ $^ ${OBJS} : %.o:%.c db_dump.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ ${BROKER_OBJS} : $(MAKE) -C ${R}/src $(notdir $@) json_help.o : ${R}/common/json_help.c ${R}/common/json_help.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ reallyclean: clean clean : -rm -f $(OBJS) $(OBJS_EXTERNAL) $(BROKER_OBJS) mosquitto_db_dump mosquitto_db_dump.a *.gcda *.gcno install: $(INSTALL) -d "${DESTDIR}$(prefix)/bin" $(INSTALL) ${STRIP_OPTS} mosquitto_db_dump "${DESTDIR}${prefix}/bin/mosquitto_db_dump" uninstall: ================================================ FILE: apps/db_dump/db_dump.c ================================================ /* Copyright (c) 2010-2021 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 "db_dump.h" #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" #ifdef __ANDROID__ #include #endif struct client_data { UT_hash_handle hh_id; char *id; uint32_t subscriptions; uint32_t subscription_size; int messages; long message_size; }; struct base_msg_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; static int do_json = 0; /* Counts */ static long cfg_count = 0; static long client_count = 0; static long client_msg_count = 0; static long base_msg_count = 0; static long retain_count = 0; static long sub_count = 0; /* ====== */ struct client_data *clients_by_id = NULL; struct base_msg_chunk *msgs_by_id = NULL; static void free__sub(struct P_sub *chunk) { free(chunk->clientid); free(chunk->topic); } static void free__client(struct P_client *chunk) { free(chunk->username); free(chunk->clientid); } static void free__client_msg(struct P_client_msg *chunk) { free(chunk->clientid); } static void free__base_msg(struct P_base_msg *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.\n"); 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 %zu)", chunk.dbid_size, sizeof(dbid_t)); return MOSQ_ERR_INVAL; } 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 = NULL; 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.\n"); return rc; } if(client_stats && chunk.clientid){ cc = calloc(1, sizeof(struct client_data)); if(!cc){ fprintf(stderr, "Error: Out of memory.\n"); free(chunk.clientid); return MOSQ_ERR_NOMEM; } cc->id = strdup(chunk.clientid); HASH_ADD_KEYPTR(hh_id, clients_by_id, cc->id, strlen(cc->id), cc); } if(do_json){ json_add_client(&chunk); } 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 base_msg_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.\n"); return rc; } if(client_stats && chunk.clientid){ HASH_FIND(hh_id, clients_by_id, chunk.clientid, strlen(chunk.clientid), 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_json){ json_add_client_msg(&chunk); } if(do_print){ print__client_msg(&chunk, length); } free__client_msg(&chunk); return 0; } static int dump__base_msg_chunk_process(FILE *db_fptr, uint32_t length) { struct P_base_msg chunk; struct mosquitto__base_msg *stored = NULL; int64_t message_expiry_interval64; uint32_t message_expiry_interval; int rc = 0; struct base_msg_chunk *mcs; base_msg_count++; memset(&chunk, 0, sizeof(struct P_base_msg)); if(db_version == 6 || db_version == 5){ rc = persist__chunk_base_msg_read_v56(db_fptr, &chunk, length); }else{ rc = persist__chunk_base_msg_read_v234(db_fptr, &chunk, db_version); } if(rc){ fprintf(stderr, "Error: Corrupt persistent database.\n"); return rc; } 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__base_msg)); if(stored == NULL){ fprintf(stderr, "Error: Out of memory.\n"); mosquitto_free(chunk.source.id); mosquitto_free(chunk.source.username); mosquitto_free(chunk.topic); mosquitto_free(chunk.payload); return MOSQ_ERR_NOMEM; } stored->data.store_id = chunk.F.store_id; stored->data.source_mid = chunk.F.source_mid; stored->data.topic = chunk.topic; stored->data.qos = chunk.F.qos; stored->data.retain = chunk.F.retain; stored->data.payloadlen = chunk.F.payloadlen; stored->data.payload = chunk.payload; stored->data.properties = chunk.properties; rc = db__message_store(&chunk.source, stored, &message_expiry_interval, mosq_mo_client); if(do_json){ json_add_base_msg(&chunk); } 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; stored->data.store_id = chunk.F.store_id; HASH_ADD(hh, db.msg_store, data.store_id, sizeof(dbid_t), stored); }else{ fprintf(stderr, "Error: Out of memory.\n"); return rc; } if(client_stats){ mcs = calloc(1, sizeof(struct base_msg_chunk)); if(!mcs){ fprintf(stderr, "Error: Out of memory.\n"); return MOSQ_ERR_NOMEM; } 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__base_msg(&chunk, length); } free__base_msg(&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){ fprintf(stderr, "Error: Corrupt persistent database.\n"); return rc; } if(do_json){ json_add_retained_msg(&chunk); } 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.\n"); return rc; } if(client_stats && chunk.clientid){ HASH_FIND(hh_id, clients_by_id, chunk.clientid, strlen(chunk.clientid), cc); if(cc){ cc->subscriptions++; cc->subscription_size += length; } } if(do_json){ json_add_subscription(&chunk); } if(do_print){ print__sub(&chunk, length); } free__sub(&chunk); return 0; } static void report_client_stats(void) { if(client_stats){ struct client_data *cc, *cc_tmp; 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); } } } static void cleanup_client_stats() { struct base_msg_chunk *msg, *msg_tmp; struct client_data *cc, *cc_tmp; HASH_ITER(hh, msgs_by_id, msg, msg_tmp){ HASH_DELETE(hh, msgs_by_id, msg); free(msg); } HASH_ITER(hh_id, clients_by_id, cc, cc_tmp){ HASH_DELETE(hh_id, clients_by_id, cc); free(cc->id); free(cc); } } static void cleanup_msg_store() { struct mosquitto__base_msg *msg, *msg_tmp; HASH_ITER(hh, db.msg_store, msg, msg_tmp){ HASH_DELETE(hh, db.msg_store, msg); free(msg); } } #ifdef WITH_FUZZING int db_dump_fuzz_main(int argc, char *argv[]) #else int main(int argc, char *argv[]) #endif { FILE *fd; char header[15]; int rc = 0; uint32_t crc; uint32_t i32temp; uint32_t length; uint32_t chunk; char *filename; 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 if(argc == 3 && !strcmp(argv[1], "--json")){ do_print = 0; do_json = 1; filename = argv[2]; }else{ fprintf(stderr, "Usage: db_dump [--stats | --client-stats | --json] \n"); return 1; } if(do_json){ json_init(); } 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)){ goto error; } break; case DB_CHUNK_BASE_MSG: if(dump__base_msg_chunk_process(fd, length)){ goto error; } break; case DB_CHUNK_CLIENT_MSG: if(dump__client_msg_chunk_process(fd, length)){ goto error; } break; case DB_CHUNK_RETAIN: if(dump__retain_chunk_process(fd, length)){ goto error; } break; case DB_CHUNK_SUB: if(dump__sub_chunk_process(fd, length)){ goto error; } break; case DB_CHUNK_CLIENT: if(dump__client_chunk_process(fd, length)){ goto error; } break; default: fprintf(stderr, "Warning: Unsupported chunk \"%d\" of length %d in persistent database file at position %ld. Ignoring.\n", chunk, length, ftell(fd)); if(fseek(fd, length, SEEK_CUR)){ fprintf(stderr, "Error: %s\n", strerror(errno)); goto error; } break; } } }else{ fprintf(stderr, "Error: Unrecognised file format.\n"); rc = 1; } fclose(fd); if(do_json){ json_print(); json_cleanup(); } if(stats){ printf("DB_CHUNK_CFG: %ld\n", cfg_count); printf("DB_CHUNK_BASE_MSG: %ld\n", base_msg_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); } report_client_stats(); cleanup_client_stats(); cleanup_msg_store(); return rc; error: cleanup_msg_store(); if(fd){ fclose(fd); } return 1; } ================================================ FILE: apps/db_dump/db_dump.h ================================================ #ifndef DB_DUMP_H #define DB_DUMP_H /* Copyright (c) 2010-2021 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__base_msg(struct P_base_msg *chunk, uint32_t length); void print__sub(struct P_sub *chunk, uint32_t length); void json_init(void); void json_print(void); void json_cleanup(void); void json_add_base_msg(struct P_base_msg *msg); void json_add_client(struct P_client *chunk); void json_add_client_msg(struct P_client_msg *chunk); void json_add_retained_msg(struct P_retain *msg); void json_add_subscription(struct P_sub *chunk); #endif ================================================ FILE: apps/db_dump/json.c ================================================ /* Copyright (c) 2010-2021 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 "json_help.h" #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" cJSON *j_tree = NULL; cJSON *j_base_msgs = NULL; cJSON *j_clients = NULL; cJSON *j_client_msgs = NULL; cJSON *j_retained_msgs = NULL; cJSON *j_subscriptions = NULL; void json_init(void) { j_tree = cJSON_CreateObject(); if(!j_tree){ fprintf(stderr, "Error: Out of memory.\n"); exit(1); } if((j_base_msgs = cJSON_AddArrayToObject(j_tree, "base-messages")) == NULL || (j_clients = cJSON_AddArrayToObject(j_tree, "clients")) == NULL || (j_client_msgs = cJSON_AddArrayToObject(j_tree, "client-messages")) == NULL || (j_retained_msgs = cJSON_AddArrayToObject(j_tree, "retained-messages")) == NULL || (j_subscriptions = cJSON_AddArrayToObject(j_tree, "subscriptions")) == NULL ){ fprintf(stderr, "Error: Out of memory.\n"); exit(1); } } void json_print(void) { char *jstr = cJSON_Print(j_tree); printf("%s\n", jstr); free(jstr); } void json_cleanup(void) { cJSON_Delete(j_tree); } void json_add_base_msg(struct P_base_msg *chunk) { cJSON *j_base_msg = NULL; j_base_msg = cJSON_CreateObject(); cJSON_AddItemToArray(j_base_msgs, j_base_msg); cJSON_AddUIntToObject(j_base_msg, "storeid", chunk->F.store_id); cJSON_AddIntToObject(j_base_msg, "expiry-time", chunk->F.expiry_time); cJSON_AddNumberToObject(j_base_msg, "source-mid", chunk->F.source_mid); cJSON_AddNumberToObject(j_base_msg, "source-port", chunk->F.source_port); cJSON_AddNumberToObject(j_base_msg, "qos", chunk->F.qos); cJSON_AddNumberToObject(j_base_msg, "retain", chunk->F.retain); cJSON_AddStringToObject(j_base_msg, "topic", chunk->topic); if(chunk->source.id){ cJSON_AddStringToObject(j_base_msg, "clientid", chunk->source.id); } if(chunk->source.username){ cJSON_AddStringToObject(j_base_msg, "username", chunk->source.username); } if(chunk->F.payloadlen > 0){ #ifdef WITH_TLS char *payload; if(mosquitto_base64_encode(chunk->payload, chunk->F.payloadlen, &payload) == MOSQ_ERR_SUCCESS){ cJSON_AddStringToObject(j_base_msg, "payload", payload); mosquitto_free(payload); } #else fprintf(stderr, "Warning: payload not output due to missing base64 support.\n"); #endif } if(chunk->properties){ cJSON *j_props = mosquitto_properties_to_json(chunk->properties); if(j_props){ cJSON_AddItemToObject(j_base_msg, "properties", j_props); } } } void json_add_client(struct P_client *chunk) { cJSON *j_client; j_client = cJSON_CreateObject(); cJSON_AddItemToArray(j_clients, j_client); cJSON_AddStringToObject(j_client, "clientid", chunk->clientid); if(chunk->username){ cJSON_AddStringToObject(j_client, "username", chunk->username); } cJSON_AddIntToObject(j_client, "session-expiry-time", chunk->F.session_expiry_time); cJSON_AddNumberToObject(j_client, "session-expiry-interval", chunk->F.session_expiry_interval); cJSON_AddNumberToObject(j_client, "last-mid", chunk->F.last_mid); cJSON_AddNumberToObject(j_client, "listener-port", chunk->F.listener_port); } void json_add_client_msg(struct P_client_msg *chunk) { cJSON *j_client_msg; j_client_msg = cJSON_CreateObject(); cJSON_AddItemToArray(j_client_msgs, j_client_msg); cJSON_AddStringToObject(j_client_msg, "clientid", chunk->clientid); cJSON_AddNumberToObject(j_client_msg, "storeid", chunk->subscription_identifier); cJSON_AddNumberToObject(j_client_msg, "mid", chunk->F.mid); cJSON_AddNumberToObject(j_client_msg, "qos", chunk->F.qos); cJSON_AddNumberToObject(j_client_msg, "state", chunk->F.state); cJSON_AddNumberToObject(j_client_msg, "retain-dup", chunk->F.retain_dup); cJSON_AddNumberToObject(j_client_msg, "direction", chunk->F.direction); cJSON_AddNumberToObject(j_client_msg, "subscription-identifier", chunk->subscription_identifier); } void json_add_subscription(struct P_sub *chunk) { cJSON *j_subscription; j_subscription = cJSON_CreateObject(); cJSON_AddItemToArray(j_subscriptions, j_subscription); cJSON_AddStringToObject(j_subscription, "clientid", chunk->clientid); cJSON_AddStringToObject(j_subscription, "topic", chunk->topic); cJSON_AddNumberToObject(j_subscription, "qos", chunk->F.qos); cJSON_AddNumberToObject(j_subscription, "options", chunk->F.options); cJSON_AddNumberToObject(j_subscription, "identifier", chunk->F.identifier); } void json_add_retained_msg(struct P_retain *chunk) { cJSON *j_retained_msg; j_retained_msg = cJSON_CreateObject(); cJSON_AddItemToArray(j_retained_msgs, j_retained_msg); cJSON_AddUIntToObject(j_retained_msg, "storeid", chunk->F.store_id); } ================================================ FILE: apps/db_dump/print.c ================================================ /* Copyright (c) 2010-2021 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 static void print__properties(mosquitto_property *properties) { int i; if(properties == NULL){ return; } printf("\tProperties:\n"); while(properties){ switch(mosquitto_property_identifier(properties)){ /* Only properties for base messages are valid for saving */ case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: printf("\t\tPayload format indicator: %d\n", mosquitto_property_byte_value(properties)); break; case MQTT_PROP_CONTENT_TYPE: printf("\t\tContent type: %s\n", mosquitto_property_string_value(properties)); break; case MQTT_PROP_RESPONSE_TOPIC: printf("\t\tResponse topic: %s\n", mosquitto_property_string_value(properties)); break; case MQTT_PROP_CORRELATION_DATA: printf("\t\tCorrelation data: "); const uint8_t *bin = mosquitto_property_binary_value(properties); for(i=0; iclientid); 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->clientid); 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); if(chunk->subscription_identifier){ printf("\tSubscription identifier: %d\n", chunk->subscription_identifier); } } void print__base_msg(struct P_base_msg *chunk, uint32_t length) { uint8_t *payload; printf("DB_CHUNK_BASE_MSG:\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->clientid); 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); } ================================================ FILE: apps/db_dump/stubs.c ================================================ #include #include #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(void) { return NULL; } void context__add_to_by_id(struct mosquitto *context) { UNUSED(context); } int db__message_store(const struct mosquitto *source, struct mosquitto__base_msg *base_msg, uint32_t *message_expiry_interval, enum mosquitto_msg_origin origin) { UNUSED(source); UNUSED(base_msg); UNUSED(message_expiry_interval); UNUSED(origin); return 0; } void db__msg_store_ref_inc(struct mosquitto__base_msg *base_msg) { UNUSED(base_msg); } int log__printf(struct mosquitto *mosq, unsigned int level, const char *fmt, ...) { UNUSED(mosq); UNUSED(level); UNUSED(fmt); return 0; } int retain__store(const char *topic, struct mosquitto__base_msg *base_msg, char **split_topics, bool persist) { UNUSED(topic); UNUSED(base_msg); UNUSED(split_topics); UNUSED(persist); return 0; } int sub__add(struct mosquitto *context, const struct mosquitto_subscription *sub) { UNUSED(context); UNUSED(sub); return 0; } void db__msg_add_to_inflight_stats(struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg *msg) { UNUSED(msg_data); UNUSED(msg); } void db__msg_add_to_queued_stats(struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg *msg) { UNUSED(msg_data); UNUSED(msg); } int session_expiry__add_from_persistence(struct mosquitto *context, time_t expiry_time) { UNUSED(context); UNUSED(expiry_time); return 0; } ================================================ FILE: apps/mosquitto_ctrl/CMakeLists.txt ================================================ if(WITH_TLS) set(SRC mosquitto_ctrl.c mosquitto_ctrl.h broker.c client.c dynsec.c dynsec_client.c dynsec_group.c dynsec_role.c ../mosquitto_passwd/get_password.c ../mosquitto_passwd/get_password.h options.c ../../common/json_help.c ../../common/json_help.h ) if(WITH_CTRL_SHELL AND LINEEDITING_FOUND) add_library(ctrl_shell OBJECT ctrl_shell.c ctrl_shell.h ctrl_shell_broker.c ctrl_shell_client.c ctrl_shell_completion_tree.c ctrl_shell_dynsec.c ctrl_shell_post_connect.c ctrl_shell_pre_connect.c ctrl_shell_printf.c ) target_compile_definitions(ctrl_shell PRIVATE WITH_CTRL_SHELL) target_include_directories(ctrl_shell PRIVATE "${mosquitto_SOURCE_DIR}" "${mosquitto_SOURCE_DIR}/common" "${mosquitto_SOURCE_DIR}/include" "${CJSON_INCLUDE_DIRS}" ) target_link_libraries(ctrl_shell PRIVATE LineEditing::LineEditing OpenSSL::SSL ) add_library(ctrl_shell_io OBJECT ctrl_shell_io.c ) target_compile_definitions(ctrl_shell_io PRIVATE WITH_CTRL_SHELL) target_include_directories(ctrl_shell_io PRIVATE "${mosquitto_SOURCE_DIR}" "${mosquitto_SOURCE_DIR}/common" "${mosquitto_SOURCE_DIR}/include" "${CJSON_INCLUDE_DIRS}" ) target_link_libraries(ctrl_shell_io PRIVATE LineEditing::LineEditing OpenSSL::SSL ) endif() add_executable(mosquitto_ctrl ${SRC}) target_include_directories(mosquitto_ctrl PRIVATE "${mosquitto_SOURCE_DIR}/apps/mosquitto_passwd" "${mosquitto_SOURCE_DIR}/common" "${mosquitto_SOURCE_DIR}/plugins/common" "${mosquitto_SOURCE_DIR}/plugins/dynamic-security" "${ARGON2_INCLUDE_DIRS}" "${CJSON_INCLUDE_DIRS}" ) if(WITH_CTRL_SHELL AND LINEEDITING_FOUND) target_compile_definitions(mosquitto_ctrl PRIVATE WITH_CTRL_SHELL) target_link_libraries(mosquitto_ctrl PRIVATE LineEditing::LineEditing ctrl_shell ctrl_shell_io ) endif() if(WITH_STATIC_LIBRARIES) target_link_libraries(mosquitto_ctrl PRIVATE libmosquitto_static) else() target_link_libraries(mosquitto_ctrl PRIVATE libmosquitto) endif() if(UNIX) if(APPLE) target_link_libraries(mosquitto_ctrl PRIVATE dl) elseif(${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD") # elseif(${CMAKE_SYSTEM_NAME} MATCHES "NetBSD") # elseif(QNX) # else() target_link_libraries(mosquitto_ctrl PRIVATE dl) endif() endif() target_link_libraries(mosquitto_ctrl PRIVATE common-options libmosquitto_common OpenSSL::SSL cJSON ) if(WITH_THREADING) if(WIN32) target_link_libraries(mosquitto_ctrl PRIVATE PThreads4W::PThreads4W) else() set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) target_link_libraries(mosquitto_ctrl PRIVATE Threads::Threads) endif() endif() install(TARGETS mosquitto_ctrl RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ) endif() ================================================ FILE: apps/mosquitto_ctrl/Makefile ================================================ R=../.. include ${R}/config.mk .PHONY: all install uninstall clean reallyclean LOCAL_CFLAGS+= LOCAL_CPPFLAGS+=-I${R}/lib -I${R}/apps/mosquitto_passwd -I${R}/plugins/dynamic-security -I${R}/common LOCAL_LDFLAGS+= LOCAL_LDADD+=-lcjson -ldl ${LIBMOSQ} ${LIBMOSQ_COMMON} -lcrypto -lssl # ------------------------------------------ # Compile time options # ------------------------------------------ ifeq ($(WITH_SOCKS),yes) LOCAL_CPPFLAGS+=-DWITH_SOCKS endif ifeq ($(WITH_THREADING),yes) LOCAL_LDFLAGS+=-pthread endif ifeq ($(WITH_EDITLINE),yes) LOCAL_LDADD+=-ledit LOCAL_CPPFLAGS+=-DWITH_CTRL_SHELL -DWITH_EDITLINE endif OBJS= \ mosquitto_ctrl.o \ broker.o \ client.o \ dynsec.o \ dynsec_client.o \ dynsec_group.o \ dynsec_role.o \ options.o ifeq ($(WITH_EDITLINE),yes) OBJS+= \ ctrl_shell.o \ ctrl_shell_broker.o \ ctrl_shell_client.o \ ctrl_shell_completion_tree.o \ ctrl_shell_dynsec.o \ ctrl_shell_io.o \ ctrl_shell_post_connect.o \ ctrl_shell_pre_connect.o \ ctrl_shell_printf.o endif OBJS_EXTERNAL= \ get_password.o \ json_help.o EXAMPLE_OBJS= example.o TARGET:=mosquitto_ctrl mosquitto_ctrl_example.so all : ${TARGET} mosquitto_ctrl : ${OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}${CC} $^ -o $@ $(LOCAL_LDFLAGS) $(LOCAL_LDADD) mosquitto_ctrl_example.so : ${EXAMPLE_OBJS} $(CROSS_COMPILE)$(CC) $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) ${LOCAL_LDFLAGS} -fPIC -shared $< -o $@ ${OBJS} : %.o: %.c mosquitto_ctrl.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ example.o : example.c mosquitto_ctrl.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -fPIC -c $< -o $@ get_password.o : ${R}/apps/mosquitto_passwd/get_password.c ${R}/apps/mosquitto_passwd/get_password.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ json_help.o : ${R}/common/json_help.c ${R}/common/json_help.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ ${R}/lib/libmosquitto.so.${SOVERSION} : $(MAKE) -C ${R}/lib ${R}/lib/libmosquitto.a : $(MAKE) -C ${R}/lib libmosquitto.a install : all ifeq ($(WITH_TLS),yes) $(INSTALL) -d "${DESTDIR}$(prefix)/bin" $(INSTALL) ${STRIP_OPTS} mosquitto_ctrl "${DESTDIR}${prefix}/bin/mosquitto_ctrl" endif uninstall : -rm -f "${DESTDIR}${prefix}/bin/mosquitto_ctrl" clean : -rm -f *.o mosquitto_ctrl *.gcda *.gcno *.so reallyclean : clean -rm -rf *.orig *.db ================================================ FILE: apps/mosquitto_ctrl/broker.c ================================================ /* Copyright (c) 2021 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 #define CJSON_VERSION_FULL (CJSON_VERSION_MAJOR*1000000+CJSON_VERSION_MINOR*1000+CJSON_VERSION_PATCH) #include #include #include #include "json_help.h" #include "mosquitto_ctrl.h" #include "mosquitto.h" void broker__print_usage(void) { printf("\nBroker Control module\n"); printf("=======================\n"); printf("List plugins : listPlugins\n"); printf("List listeners : listListeners\n"); } /* ################################################################ * # * # Payload callback * # * ################################################################ */ static void print_listeners(cJSON *j_response) { cJSON *j_data, *j_listeners, *j_listener, *jtmp; const char *stmp; int i=1; 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_listeners = cJSON_GetObjectItem(j_data, "listeners"); if(j_listeners == NULL || !cJSON_IsArray(j_listeners)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } cJSON_ArrayForEach(j_listener, j_listeners){ printf("Listener %d:\n", i); jtmp = cJSON_GetObjectItem(j_listener, "port"); if(jtmp && cJSON_IsNumber(jtmp)){ printf(" Port: %d\n", jtmp->valueint); } if(json_get_string(j_listener, "protocol", &stmp, false) == MOSQ_ERR_SUCCESS){ printf(" Protocol: %s\n", stmp); } if(json_get_string(j_listener, "socket-path", &stmp, false) == MOSQ_ERR_SUCCESS){ printf(" Socket path: %s\n", stmp); } if(json_get_string(j_listener, "bind-address", &stmp, false) == MOSQ_ERR_SUCCESS){ printf(" Bind address: %s\n", stmp); } jtmp = cJSON_GetObjectItem(j_listener, "tls"); printf(" TLS: %s\n", jtmp && cJSON_IsBool(jtmp) && cJSON_IsTrue(jtmp)?"true":"false"); printf("\n"); i++; } } static void print_plugin_info(cJSON *j_response) { cJSON *j_data, *j_plugins, *j_plugin, *jtmp, *j_eps; const char *stmp; 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_plugins = cJSON_GetObjectItem(j_data, "plugins"); if(j_plugins == NULL || !cJSON_IsArray(j_plugins)){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } cJSON_ArrayForEach(j_plugin, j_plugins){ if(json_get_string(j_plugin, "name", &stmp, false) != MOSQ_ERR_SUCCESS){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } printf("Plugin: %s\n", stmp); if(json_get_string(j_plugin, "version", &stmp, false) == MOSQ_ERR_SUCCESS){ printf("Version: %s\n", stmp); } j_eps = cJSON_GetObjectItem(j_plugin, "control-endpoints"); if(j_eps && cJSON_IsArray(j_eps)){ first = true; cJSON_ArrayForEach(jtmp, j_eps){ if(jtmp && cJSON_IsString(jtmp) && jtmp->valuestring){ if(first){ first = false; printf("Control endpoints: %s\n", jtmp->valuestring); }else{ printf(" %s\n", jtmp->valuestring); } } } } } } static void broker__payload_callback(struct mosq_ctrl *ctrl, long payloadlen, const void *payload) { cJSON *tree, *j_responses, *j_response, *j_command; 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; } const char *error; if(json_get_string(j_response, "error", &error, false) == MOSQ_ERR_SUCCESS){ fprintf(stderr, "%s: Error: %s.\n", j_command->valuestring, error); }else{ if(!strcasecmp(j_command->valuestring, "listPlugins")){ print_plugin_info(j_response); }else if(!strcasecmp(j_command->valuestring, "listListeners")){ print_listeners(j_response); }else{ /* fprintf(stderr, "%s: Success\n", j_command->valuestring); */ } } cJSON_Delete(tree); } static int broker__list_plugins(int argc, char *argv[], cJSON *j_command) { UNUSED(argc); UNUSED(argv); if(cJSON_AddStringToObject(j_command, "command", "listPlugins") == NULL ){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } static int broker__list_listeners(int argc, char *argv[], cJSON *j_command) { UNUSED(argc); UNUSED(argv); if(cJSON_AddStringToObject(j_command, "command", "listListeners") == NULL ){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } /* ################################################################ * # * # Main * # * ################################################################ */ int broker__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")){ broker__print_usage(); return -1; } /* The remaining commands need a network connection and JSON command. */ ctrl->payload_callback = broker__payload_callback; ctrl->request_topic = strdup("$CONTROL/broker/v1"); ctrl->response_topic = strdup("$CONTROL/broker/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], "listPlugins")){ rc = broker__list_plugins(argc-1, &argv[1], j_command); }else if(!strcasecmp(argv[0], "listListeners")){ rc = broker__list_listeners(argc-1, &argv[1], j_command); }else{ fprintf(stderr, "Command '%s' not recognised.\n", argv[0]); cJSON_Delete(j_tree); j_tree = NULL; 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; } ================================================ FILE: apps/mosquitto_ctrl/client.c ================================================ /* Copyright (c) 2020-2021 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 && !ctrl->cfg.tls_use_os_certs && ctrl->cfg.port != 8883 # ifdef FINAL_WITH_TLS_PSK && !ctrl->cfg.psk # endif ){ 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; } ================================================ FILE: apps/mosquitto_ctrl/ctrl_shell.c ================================================ /* Copyright (c) 2023 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 #include #include #ifndef WIN32 # include # include #endif #include "ctrl_shell.h" #include "ctrl_shell_internal.h" #define UNUSED(A) (void)(A) #ifdef WITH_CTRL_SHELL #define FREE(A) do{free(A); A = NULL;}while(0) const char *ANSI_URL = NULL; const char *ANSI_MODULE = NULL; const char *ANSI_INPUT = NULL; const char *ANSI_ERROR = NULL; const char **ANSI_LABEL = NULL; const char *ANSI_RESET = "\001\e[0m\002"; const char *ANSI_TOPIC = NULL; const char *ANSI_POSITIVE = NULL; const char *ANSI_NEGATIVE = NULL; const char *ANSI_LABEL_none[] = {"", ""}; const char ANSI_URL_dark[] = "\001\e[38;5;155m\002"; const char ANSI_MODULE_dark[] = "\001\e[38;5;214m\002"; const char ANSI_INPUT_dark[] = "\001\e[38;5;80m\002"; const char ANSI_ERROR_dark[] = "\001\e[38;5;198m\002"; const char *ANSI_LABEL_dark[] = { "\001\e[38;5;207m\002", "\001\e[38;5;219m\002", }; const char ANSI_TOPIC_dark[] = "\001\e[93m\002"; const char ANSI_POSITIVE_dark[] = "\001\e[92m\002"; const char ANSI_NEGATIVE_dark[] = "\001\e[95m\002"; const char ANSI_URL_light[] = "\001\e[38;5;23m\002"; const char ANSI_MODULE_light[] = "\001\e[38;5;130m\002"; const char ANSI_INPUT_light[] = "\001\e[38;5;27m\002"; const char ANSI_ERROR_light[] = "\001\e[38;5;196m\002"; const char *ANSI_LABEL_light[] = { "\001\e[38;5;165m\002", "\001\e[38;5;171m\002", }; const char ANSI_TOPIC_light[] = "\001\e[33m\002"; const char ANSI_POSITIVE_light[] = "\001\e[32m\002"; const char ANSI_NEGATIVE_light[] = "\001\e[35m\002"; char prompt[200]; struct ctrl_shell data; static int generator_arg = -1; struct completion_tree_cmd *current_cmd_match = NULL; static void signal_winch(int signal) { UNUSED(signal); rl_resize_terminal(); } static void signal_term(int signal) { UNUSED(signal); data.run = 0; } static void term_set_flag(bool set, unsigned int flag) { struct termios ts; tcgetattr(0, &ts); if(set){ ts.c_lflag |= (flag); }else{ ts.c_lflag &= (unsigned int)(~flag); } tcsetattr(0, TCSANOW, &ts); } static void term_set_echo(bool echo) { term_set_flag(echo, ECHO); } static void term_set_canon(bool canon) { term_set_flag(canon, ICANON); } void ctrl_shell_rtrim(char *buf) { size_t slen = strlen(buf); while(slen > 0 && isspace((unsigned char)buf[slen-1])){ buf[slen-1] = '\0'; slen = strlen(buf); } } bool ctrl_shell_get_password(char *buf, size_t len) { ctrl_shell_printf("%spassword:%s", ANSI_INPUT, ANSI_RESET); term_set_echo(false); if(ctrl_shell_fgets(buf, (int)len, stdin) == NULL){ term_set_echo(true); return false; } term_set_echo(true); ctrl_shell_printf("\n"); ctrl_shell_rtrim(buf); return true; } static int response_wait(void) { struct timespec timeout; int rc = 0; data.response_received = false; clock_gettime(CLOCK_REALTIME, &timeout); timeout.tv_sec += 2; while(data.response_received == false){ if(pthread_cond_timedwait(&data.response_cond, &data.response_mutex, &timeout) == ETIMEDOUT){ ctrl_shell_printf("Timed out with no response.\n"); rc = 1; break; } } return rc; } int ctrl_shell_publish_blocking(cJSON *j_command) { int rc = 0; cJSON *j_commands = cJSON_CreateObject(); cJSON *j_array = cJSON_AddArrayToObject(j_commands, "commands"); cJSON_AddItemToArray(j_array, j_command); char *payload = cJSON_PrintUnformatted(j_commands); cJSON_Delete(j_commands); pthread_mutex_lock(&data.response_mutex); mosquitto_publish(data.mosq, NULL, data.request_topic, (int)strlen(payload), payload, 1, false); FREE(payload); /* Check for publish callback */ rc = response_wait(); if(rc){ pthread_mutex_unlock(&data.response_mutex); return rc; } if(data.publish_rc >= 128){ pthread_mutex_unlock(&data.response_mutex); return 1; } /* Check for message callback */ rc = response_wait(); pthread_mutex_unlock(&data.response_mutex); return rc; } void ctrl_shell__connect_blocking(const char *hostname, int port) { pthread_mutex_lock(&data.response_mutex); int rc = mosquitto_connect(data.mosq, hostname, port, 60); rc = mosquitto_loop_start(data.mosq); /* FIXME - do something with the error */ UNUSED(rc); response_wait(); pthread_mutex_unlock(&data.response_mutex); } void ctrl_shell_line_callback_set(void (*callback)(char *line)) { data.line_callback = callback; } int ctrl_shell_command_generic_arg0(const char *command) { cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", command); return ctrl_shell_publish_blocking(j_command); } int ctrl_shell_command_generic_arg1(const char *command, const char *itemlabel, char **saveptr) { const char *item; item = strtok_r(NULL, " ", saveptr); if(!item){ ctrl_shell_printf("%s %s\n", command, itemlabel); return MOSQ_ERR_INVAL; } cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", command); cJSON_AddStringToObject(j_command, itemlabel, item); return ctrl_shell_publish_blocking(j_command); } int ctrl_shell_command_generic_int_arg1(const char *command, const char *itemlabel, char **saveptr) { const char *item; item = strtok_r(NULL, " ", saveptr); if(!item){ ctrl_shell_printf("%s %s\n", command, itemlabel); return MOSQ_ERR_INVAL; } int intval = atoi(item); cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", command); cJSON_AddNumberToObject(j_command, itemlabel, intval); return ctrl_shell_publish_blocking(j_command); } int ctrl_shell_command_generic_arg2(const char *command, const char *itemlabel1, const char *itemlabel2, char **saveptr) { const char *item1, *item2; item1 = strtok_r(NULL, " ", saveptr); item2 = strtok_r(NULL, " ", saveptr); if(!item1 || !item2){ ctrl_shell_printf("%s %s %s\n", command, itemlabel1, itemlabel2); return MOSQ_ERR_INVAL; } cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", command); cJSON_AddStringToObject(j_command, itemlabel1, item1); cJSON_AddStringToObject(j_command, itemlabel2, item2); return ctrl_shell_publish_blocking(j_command); } static int ctrl_shell__subscribe_blocking(const char *topic, void (*module_on_subscribe)(void)) { int rc = 0; for(int i=0; i= 128){ rc = 1; }else{ if(module_on_subscribe){ module_on_subscribe(); } } return rc; } bool ctrl_shell_callback_final(char *line) { if(!line || !strcasecmp(line, "exit")){ data.run = 0; }else if(!strcasecmp(line, "disconnect")){ if(data.mosq){ ctrl_shell__disconnect(); }else{ return false; } }else if(!strcasecmp(line, "return")){ if(data.mod_cleanup){ data.mod_cleanup(); } ctrl_shell__post_connect_init(); }else{ return false; } return true; } void ctrl_shell_print_help_final(const char *command, const char *modul) { if(!strcasecmp(command, "disconnect")){ ctrl_shell_print_help_command("disconnect"); ctrl_shell_printf("\nDisconnect from the broker\n"); }else if(!strcasecmp(command, "exit")){ ctrl_shell_print_help_command("exit"); ctrl_shell_printf("\nQuit the program\n"); }else if(!strcasecmp(command, "help")){ ctrl_shell_print_help_command("help "); ctrl_shell_printf("\nFind help on a command using 'help '\n"); ctrl_shell_printf("Press tab multiple times to find currently available commands.\n"); }else if(modul && !strcasecmp(command, "return")){ ctrl_shell_print_help_command("return"); ctrl_shell_printf("\nLeave %s mode.\n", modul); }else{ ctrl_shell_printf("Unknown command '%s'\n", command); } } static void calc_generator_arg(int start) { char *text_heap; char *text_arg, *saveptr = NULL; int ga = 0; if(start == 0){ generator_arg = -1; return; } text_heap = strdup(rl_line_buffer); if(!text_heap){ return; } text_heap[start] = '\0'; text_arg = strtok_r(text_heap, " ", &saveptr); while(text_arg){ ga++; text_arg = strtok_r(NULL, " ", &saveptr); } FREE(text_heap); generator_arg = ga-1; } char *completion_generator(const char *text, int state) { static size_t len; static struct completion_tree_cmd *cmd, *cmd_prev; static struct completion_tree_arg *arg; if(!data.commands){ return NULL; } if(!state){ len = strlen(text); if(generator_arg < 0){ cmd = data.commands->commands; }else if(current_cmd_match && generator_arg < current_cmd_match->arg_list_count){ arg = current_cmd_match->arg_lists[generator_arg]->args; }else{ return NULL; } } if(generator_arg < 0){ while(cmd){ char *name = cmd->name; cmd_prev = cmd; cmd = cmd->next; if(strncasecmp(name, text, len) == 0){ current_cmd_match = cmd_prev; return strdup(name); } } }else{ while(arg){ char *name = arg->name; arg = arg->next; if(strncasecmp(name, text, len) == 0){ return strdup(name); } } } return NULL; } void ctrl_shell_completion_commands_set(struct completion_tree_root *new_commands) { data.commands = new_commands; } char **completion_matcher(const char *text, int start, int end) { char **matches; UNUSED(end); rl_attempted_completion_over = 1; calc_generator_arg(start); matches = rl_completion_matches(text, completion_generator); return matches; } int my_get_address(int sock, char *buf, size_t len, uint16_t *remote_port) { struct sockaddr_storage addr; socklen_t addrlen; if(sock < 0){ memset(buf, 0, len); *remote_port = 0; return 1; } 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; } } } return 1; } static void on_connect_reconnect(struct mosquitto *mosq, void *userdata, int rc) { UNUSED(userdata); UNUSED(rc); for(int i=0; ipayload); cJSON *j_endpoint_error = cJSON_GetObjectItem(j_tree, "error"); if(j_endpoint_error && !strcmp(j_endpoint_error->valuestring, "endpoint not available")){ ctrl_shell_printf("%s$CONTROL endpoint for this module not available.%s\n", ANSI_ERROR, ANSI_RESET); }else{ cJSON *j_responses = cJSON_GetObjectItem(j_tree, "responses"); cJSON *j_command_obj = cJSON_GetArrayItem(j_responses, 0); cJSON *j_command = cJSON_GetObjectItem(j_command_obj, "command"); cJSON *j_error = cJSON_GetObjectItem(j_command_obj, "error"); cJSON *j_data = cJSON_GetObjectItem(j_command_obj, "data"); if(j_error){ ctrl_shell_printf("%s%s%s\n", ANSI_ERROR, j_error->valuestring, ANSI_RESET); }else if(j_data && data.response_callback){ data.response_callback(j_command->valuestring, j_data, msg->payload); }else if(j_command){ ctrl_shell_printf("OK\n"); }else{ ctrl_shell_printf("Invalid response from broker.\n"); } } cJSON_Delete(j_tree); data.response_received = true; pthread_mutex_unlock(&data.response_mutex); pthread_cond_signal(&data.response_cond); } void ctrl_shell__on_publish(struct mosquitto *mosq, void *userdata, int mid, int reason_code, const mosquitto_property *props) { UNUSED(mosq); UNUSED(userdata); UNUSED(mid); UNUSED(props); if(reason_code >= 128){ ctrl_shell_printf("Publish failed, check you have permission to access this module.\n"); data.publish_rc = reason_code; } data.response_received = true; pthread_mutex_unlock(&data.response_mutex); pthread_cond_signal(&data.response_cond); } void ctrl_shell__on_subscribe(struct mosquitto *mosq, void *userdata, int mid, int qos_count, const int *granted_qos) { UNUSED(mosq); UNUSED(userdata); UNUSED(mid); if(qos_count == 1 && granted_qos[0] >= 128){ ctrl_shell_printf("Subscribe failed, check you have permission to access this module.\n"); data.subscribe_rc = granted_qos[0]; } data.response_received = true; pthread_mutex_unlock(&data.response_mutex); pthread_cond_signal(&data.response_cond); } void ctrl_shell__load_module(void (*mod_init)(struct ctrl_shell__module *mod)) { struct ctrl_shell__module mod; memset(&mod, 0, sizeof(mod)); mod_init(&mod); data.request_topic = mod.request_topic; data.response_callback = mod.response_callback; data.mod_cleanup = mod.cleanup; ctrl_shell_completion_commands_set(mod.completion_commands); ctrl_shell_line_callback_set(mod.line_callback); ctrl_shell__subscribe_blocking(mod.response_topic, mod.on_subscribe); } void set_no_colour(void) { ANSI_URL = ""; ANSI_MODULE = ""; ANSI_INPUT = ""; ANSI_ERROR = ""; ANSI_LABEL = ANSI_LABEL_none; ANSI_RESET = ""; ANSI_TOPIC = ""; ANSI_POSITIVE = ""; ANSI_NEGATIVE = ""; } static void set_bg_light(void) { ANSI_URL = ANSI_URL_light; ANSI_MODULE = ANSI_MODULE_light; ANSI_INPUT = ANSI_INPUT_light; ANSI_ERROR = ANSI_ERROR_light; ANSI_LABEL = ANSI_LABEL_light; ANSI_TOPIC = ANSI_TOPIC_light; ANSI_POSITIVE = ANSI_POSITIVE_light; ANSI_NEGATIVE = ANSI_NEGATIVE_light; } static void set_bg_dark(void) { ANSI_URL = ANSI_URL_dark; ANSI_MODULE = ANSI_MODULE_dark; ANSI_INPUT = ANSI_INPUT_dark; ANSI_ERROR = ANSI_ERROR_dark; ANSI_LABEL = ANSI_LABEL_dark; ANSI_TOPIC = ANSI_TOPIC_dark; ANSI_POSITIVE = ANSI_POSITIVE_dark; ANSI_NEGATIVE = ANSI_NEGATIVE_dark; } static int get_bg(void) { int opt; /* Set non-blocking */ opt = fcntl(STDIN_FILENO, F_GETFL, 0); if(fcntl(STDIN_FILENO, F_SETFL, opt | O_NONBLOCK) < 0){ fprintf(stderr, "Error: Unable to set terminal flags required."); return 1; } set_bg_dark(); term_set_echo(false); term_set_canon(false); ctrl_shell_printf("\e]10;?\a\e]11;?\a"); fflush(stdout); char buf[50] = {0}; ssize_t rl; usleep(100000); do{ rl = read(STDIN_FILENO, buf, sizeof(buf)); }while(rl == 0); if(fcntl(STDIN_FILENO, F_SETFL, opt) < 0){ fprintf(stderr, "Error: Unable to reset terminal flags."); return 1; } term_set_echo(true); term_set_canon(true); for(int i=0; i bg){ set_bg_dark(); }else{ set_bg_light(); } return 0; } void ctrl_shell__cleanup(void) { FREE(data.hostname); for(int i=0; ino_colour){ set_no_colour(); }else{ if(get_bg()){ return; } } if(config){ if(config->host){ data.hostname = strdup(config->host); } if(config->port != PORT_UNDEFINED){ data.port = config->port; } if(config->username){ data.username = strdup(config->username); } if(config->password){ data.password = strdup(config->password); } if(config->id){ data.clientid = strdup(config->id); } if(config->cafile){ data.tls_cafile = strdup(config->cafile); } if(config->capath){ data.tls_capath = strdup(config->capath); } if(config->certfile){ data.tls_certfile = strdup(config->certfile); } if(config->keyfile){ data.tls_keyfile = strdup(config->keyfile); } } pthread_mutex_init(&data.response_mutex, NULL); pthread_cond_init(&data.response_cond, NULL); rl_readline_name = "mosquitto_ctrl"; rl_completion_entry_function = completion_generator; rl_attempted_completion_function = completion_matcher; rl_bind_key('\t', rl_complete); signal(SIGWINCH, signal_winch); signal(SIGTERM, signal_term); signal(SIGINT, signal_term); ctrl_shell_printf("mosquitto_ctrl shell v" VERSION "\n"); if(data.hostname){ if(ctrl_shell__connect()){ ctrl_shell__cleanup(); return; } }else{ ctrl_shell__pre_connect_init(); } while(data.run){ current_cmd_match = NULL; char *line = readline(prompt); if(data.line_callback){ data.line_callback(line); } } clear_history(); ctrl_shell_printf("\n"); ctrl_shell__cleanup(); } static void print_label(unsigned int level, const char *label) { char *str = calloc(1, level*2 + strlen(label) + 30); for(unsigned int 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 CTRL_SHELL_H #define CTRL_SHELL_H #ifdef __cplusplus extern "C" { #endif #include #include #include #include extern const char *ANSI_URL; extern const char *ANSI_MODULE; extern const char *ANSI_INPUT; extern const char *ANSI_ERROR; extern const char **ANSI_LABEL; extern const char *ANSI_RESET; extern const char *ANSI_TOPIC; extern const char *ANSI_POSITIVE; extern const char *ANSI_NEGATIVE; /* This relatively complex structure is used to store the command tree. It * allows for commands to be shared between different parts of the tree, and * for commands to have multiple arguments. The completion_tree_arg_list * members exist to have a fixed memory location that never changes, so that * we can reallocate the list for where we have dynamically updated arguments, * for e.g. dynsec clients, where we want many commands to use the same list. */ struct completion_tree_arg { struct completion_tree_arg *next; char name[]; }; struct completion_tree_arg_list { struct completion_tree_arg *args; bool is_shared; }; struct completion_tree_cmd { struct completion_tree_cmd *next; struct completion_tree_arg_list **arg_lists; int arg_list_count; char name[]; }; struct completion_tree_root { struct completion_tree_cmd *commands; }; extern char prompt[200]; /* Helper functions for sending commands to the broker. */ int ctrl_shell_command_generic_arg0(const char *command); int ctrl_shell_command_generic_arg1(const char *command, const char *itemlabel, char **saveptr); int ctrl_shell_command_generic_arg2(const char *command, const char *itemlabel1, const char *itemlabel2, char **saveptr); int ctrl_shell_command_generic_int_arg1(const char *command, const char *itemlabel, char **saveptr); void ctrl_shell_completion_commands_set(struct completion_tree_root *new_commands); void ctrl_shell_line_callback_set(void (*callback)(char *line)); /* Helper functions for building the command tree. */ void completion_tree_arg_list_free(struct completion_tree_arg_list *arg_list); void completion_tree_arg_list_args_free(struct completion_tree_arg_list *arg_list); void completion_tree_cmd_free(struct completion_tree_cmd *cmd); void completion_tree_free(struct completion_tree_root *tree); struct completion_tree_cmd *completion_tree_cmd_add(struct completion_tree_root *root, struct completion_tree_arg_list *help_arg_list, const char *name); struct completion_tree_arg_list *completion_tree_cmd_new_arg_list(void); void completion_tree_cmd_append_arg_list(struct completion_tree_cmd *cmd, struct completion_tree_arg_list *new_list); struct completion_tree_arg_list *completion_tree_cmd_add_arg_list(struct completion_tree_cmd *cmd); void completion_tree_arg_list_add_arg(struct completion_tree_arg_list *arg_list, const char *name); void ctrl_shell_pre_connect_init(void); void ctrl_shell_post_connect_init(void); int ctrl_shell_publish_blocking(cJSON *j_command); bool ctrl_shell_callback_final(char *line); char *ctrl_shell_fgets(char *s, int size, FILE *stream); bool ctrl_shell_get_password(char *buf, size_t len); void ctrl_shell_rtrim(char *buf); void ctrl_shell_printf(const char *fmt, ...); void ctrl_shell_vprintf(const char *fmt, va_list va); void ctrl_shell_print_label(unsigned int level, const char *label); void ctrl_shell_print_label_value(unsigned int level, const char *label, int align, const char *fmt, ...); void ctrl_shell_print_value(unsigned int level, const char *fmt, ...); void ctrl_shell_print_help_command(const char *cmd); void ctrl_shell_print_help_desc(const char *desc); void ctrl_shell_print_help_final(const char *command, const char *modul); #ifdef __cplusplus } #endif #endif ================================================ FILE: apps/mosquitto_ctrl/ctrl_shell_broker.c ================================================ /* Copyright (c) 2023 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 "ctrl_shell_internal.h" #include "json_help.h" #ifdef WITH_CTRL_SHELL #define UNUSED(A) (void)(A) static struct completion_tree_root *commands_broker = NULL; static void command_tree_create(void) { struct completion_tree_cmd *cmd; struct completion_tree_arg_list *help_arg_list; if(commands_broker){ return; } commands_broker = calloc(1, sizeof(struct completion_tree_root)); cmd = completion_tree_cmd_add(commands_broker, NULL, "help"); help_arg_list = completion_tree_cmd_add_arg_list(cmd); completion_tree_cmd_add(commands_broker, help_arg_list, "listPlugins"); completion_tree_cmd_add(commands_broker, help_arg_list, "listListeners"); completion_tree_cmd_add(commands_broker, help_arg_list, "disconnect"); completion_tree_cmd_add(commands_broker, help_arg_list, "return"); completion_tree_cmd_add(commands_broker, help_arg_list, "exit"); } static void print_help(char **saveptr) { char *command = strtok_r(NULL, " ", saveptr); if(command){ if(!strcasecmp(command, "listPlugins")){ ctrl_shell_print_help_command("listPlugins"); ctrl_shell_printf("\nLists currently loaded plugins.\n"); }else if(!strcasecmp(command, "listListeners")){ ctrl_shell_print_help_command("listListeners"); ctrl_shell_printf("\nLists current listeners.\n"); }else{ ctrl_shell_print_help_final(command, "broker"); } }else{ ctrl_shell_printf("This is the mosquitto_ctrl interactive shell, for controlling aspects of a mosquitto broker.\n"); ctrl_shell_printf("You are in broker mode, for controlling some core broker functionality.\n"); ctrl_shell_printf("Use '%sreturn%s' to leave this mode.\n", ANSI_INPUT, ANSI_RESET); ctrl_shell_printf("Find help on a command using '%shelp %s'\n", ANSI_INPUT, ANSI_RESET); ctrl_shell_printf("Press tab multiple times to find currently available commands.\n\n"); } } static void line_callback(char *line) { if(!line){ ctrl_shell_callback_final(NULL); return; } ctrl_shell_rtrim(line); if(strlen(line) > 0){ add_history(line); }else{ free(line); return; } char *saveptr = NULL; char *command = strtok_r(line, " ", &saveptr); if(!command){ free(line); return; } if(!strcasecmp(command, "listPlugins")){ ctrl_shell_command_generic_arg0("listPlugins"); }else if(!strcasecmp(command, "listListeners")){ ctrl_shell_command_generic_arg0("listListeners"); }else if(!strcasecmp(command, "help")){ print_help(&saveptr); }else{ if(!ctrl_shell_callback_final(line)){ ctrl_shell_printf("Unknown command '%s'\n", command); } } free(line); } static void print_plugins(cJSON *j_data) { cJSON *j_plugins, *j_plugin; j_plugins = cJSON_GetObjectItem(j_data, "plugins"); cJSON_ArrayForEach(j_plugin, j_plugins){ const char *name; if(json_get_string(j_plugin, "name", &name, false) != MOSQ_ERR_SUCCESS){ ctrl_shell_printf("Invalid response from broker.\n"); return; } ctrl_shell_print_label(0, "Plugin:"); ctrl_shell_print_value(1, "%s\n", name); cJSON *j_endpoints, *j_endpoint; j_endpoints = cJSON_GetObjectItem(j_plugin, "control-endpoints"); if(j_endpoints){ ctrl_shell_print_label(0, "Control endpoints:"); cJSON_ArrayForEach(j_endpoint, j_endpoints){ ctrl_shell_print_value(1, "%s\n", j_endpoint->valuestring); } } ctrl_shell_print_value(0, "\n"); } } static void print_listeners(cJSON *j_data) { cJSON *j_listeners, *j_listener; j_listeners = cJSON_GetObjectItem(j_data, "listeners"); cJSON_ArrayForEach(j_listener, j_listeners){ int port; const char *protocol; bool tls; if(json_get_int(j_listener, "port", &port, false, -1) != MOSQ_ERR_SUCCESS || json_get_string(j_listener, "protocol", &protocol, false) != MOSQ_ERR_SUCCESS || json_get_bool(j_listener, "tls", &tls, false, false) != MOSQ_ERR_SUCCESS){ ctrl_shell_printf("Invalid response from broker.\n"); return; } ctrl_shell_print_label(0, "Listener:"); ctrl_shell_print_label(1, "Port:"); ctrl_shell_print_value(2, "%d\n", port); ctrl_shell_print_label(1, "Protocol:"); ctrl_shell_print_value(2, "%s\n", protocol); ctrl_shell_print_label(1, "TLS:"); ctrl_shell_print_value(2, "%s\n\n", tls?"true":"false"); } } static void handle_response(const char *command, cJSON *j_data, const char *payload) { if(!strcmp(command, "listPlugins")){ print_plugins(j_data); }else if(!strcmp(command, "listListeners")){ print_listeners(j_data); }else{ ctrl_shell_printf("%s %s\n", command, payload); } } static void on_subscribe(void) { } static void ctrl_shell__broker_cleanup(void) { completion_tree_free(commands_broker); commands_broker = NULL; } void ctrl_shell__broker_init(struct ctrl_shell__module *mod) { command_tree_create(); mod->completion_commands = commands_broker; mod->request_topic = "$CONTROL/broker/v1"; mod->response_topic = "$CONTROL/broker/v1/response"; mod->line_callback = line_callback; mod->response_callback = handle_response; mod->on_subscribe = on_subscribe; mod->cleanup = ctrl_shell__broker_cleanup; } #endif ================================================ FILE: apps/mosquitto_ctrl/ctrl_shell_client.c ================================================ /* Copyright (c) 2023 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 "ctrl_shell_internal.h" #ifdef WITH_CTRL_SHELL #define UNUSED(A) (void)(A) int ctrl_shell__connect(void) { if(data.port == PORT_UNDEFINED){ data.port = 1883; } if(data.mosq){ mosquitto_destroy(data.mosq); } data.mosq = mosquitto_new(data.clientid, true, NULL); if(!strcmp(data.url_scheme, "mqtts") || !strcmp(data.url_scheme, "wss")){ mosquitto_int_option(data.mosq, MOSQ_OPT_TLS_USE_OS_CERTS, 1); } if(data.transport == MOSQ_T_WEBSOCKETS){ mosquitto_int_option(data.mosq, MOSQ_OPT_TRANSPORT, data.transport); } if(data.username && data.password){ mosquitto_username_pw_set(data.mosq, data.username, data.password); } if(data.tls_cafile || data.tls_capath || data.tls_certfile || data.tls_keyfile){ int rc = mosquitto_tls_set(data.mosq, data.tls_cafile, data.tls_capath, data.tls_certfile, data.tls_keyfile, NULL); if(rc){ if(rc == MOSQ_ERR_INVAL){ ctrl_shell_printf("%sError setting TLS options: File not found.%s\n", ANSI_ERROR, ANSI_RESET); }else{ ctrl_shell_printf("%sError setting TLS options: %s.%s\n", ANSI_ERROR, mosquitto_strerror(rc), ANSI_RESET); } } } mosquitto_int_option(data.mosq, MOSQ_OPT_PROTOCOL_VERSION, 5); mosquitto_connect_callback_set(data.mosq, ctrl_shell__on_connect); mosquitto_subscribe_callback_set(data.mosq, ctrl_shell__on_subscribe); mosquitto_publish_v5_callback_set(data.mosq, ctrl_shell__on_publish); mosquitto_message_callback_set(data.mosq, ctrl_shell__on_message); ctrl_shell__connect_blocking(data.hostname, data.port); if(data.connect_rc){ ctrl_shell_printf("%sUnable to connect: %s%s\n", ANSI_ERROR, mosquitto_reason_string(data.connect_rc), ANSI_RESET); return 1; } ctrl_shell__post_connect_init(); return 0; } void ctrl_shell__disconnect(void) { if(!data.mosq){ return; } mosquitto_disconnect(data.mosq); mosquitto_loop_stop(data.mosq, false); mosquitto_destroy(data.mosq); data.mosq = NULL; for(int 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 #include #include #include "ctrl_shell_internal.h" #ifdef WITH_CTRL_SHELL #define UNUSED(A) (void)(A) void completion_tree_arg_list_args_free(struct completion_tree_arg_list *arg_list) { struct completion_tree_arg *arg, *next; if(!arg_list){ return; } arg = arg_list->args; while(arg){ next = arg->next; free(arg); arg = next; } arg_list->args = NULL; } void completion_tree_arg_list_free(struct completion_tree_arg_list *arg_list) { if(!arg_list){ return; } if(arg_list->is_shared){ return; } completion_tree_arg_list_args_free(arg_list); free(arg_list); } void completion_tree_cmd_free(struct completion_tree_cmd *cmd) { if(!cmd){ return; } for(int i=0; iarg_list_count; i++){ completion_tree_arg_list_free(cmd->arg_lists[i]); } free(cmd->arg_lists); free(cmd); } void completion_tree_free(struct completion_tree_root *tree) { struct completion_tree_cmd *cmd, *next; if(!tree){ return; } cmd = tree->commands; while(cmd){ next = cmd->next; completion_tree_cmd_free(cmd); cmd = next; } free(tree); } struct completion_tree_cmd *completion_tree_cmd_add(struct completion_tree_root *root, struct completion_tree_arg_list *help_arg_list, const char *name) { struct completion_tree_cmd *new_node; new_node = calloc(1, sizeof(struct completion_tree_cmd) + strlen(name) + 1); if(!new_node){ return NULL; } strcpy(new_node->name, name); new_node->next = root->commands; root->commands = new_node; completion_tree_arg_list_add_arg(help_arg_list, name); return new_node; } struct completion_tree_arg_list *completion_tree_cmd_new_arg_list(void) { return calloc(1, sizeof(struct completion_tree_arg_list)); } void completion_tree_cmd_append_arg_list(struct completion_tree_cmd *cmd, struct completion_tree_arg_list *new_list) { struct completion_tree_arg_list **arg_list; arg_list = realloc(cmd->arg_lists, (size_t)(cmd->arg_list_count+1)*sizeof(struct completion_tree_arg_list *)); if(!arg_list){ return; } cmd->arg_lists = arg_list; cmd->arg_lists[cmd->arg_list_count] = new_list; cmd->arg_list_count++; } struct completion_tree_arg_list *completion_tree_cmd_add_arg_list(struct completion_tree_cmd *cmd) { if(!cmd){ return NULL; } struct completion_tree_arg_list *new_list; new_list = completion_tree_cmd_new_arg_list(); if(!new_list){ return NULL; } completion_tree_cmd_append_arg_list(cmd, new_list); return new_list; } void completion_tree_arg_list_add_arg(struct completion_tree_arg_list *arg_list, const char *name) { if(!arg_list || !name){ return; } struct completion_tree_arg *new_node; new_node = calloc(1, sizeof(struct completion_tree_arg) + strlen(name) + 1); if(!new_node){ return; } strcpy(new_node->name, name); new_node->next = arg_list->args; arg_list->args = new_node; } #endif ================================================ FILE: apps/mosquitto_ctrl/ctrl_shell_dynsec.c ================================================ /* Copyright (c) 2023 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 "ctrl_shell_internal.h" #include "json_help.h" #ifdef WITH_CTRL_SHELL #define UNUSED(A) (void)(A) static struct completion_tree_root *commands_dynsec = NULL; static struct completion_tree_arg_list *tree_clients = NULL; static struct completion_tree_arg_list *tree_groups = NULL; static struct completion_tree_arg_list *tree_roles = NULL; static bool do_print_list = false; static void command_tree_create(void) { struct completion_tree_cmd *cmd; struct completion_tree_arg_list *arg_list; struct completion_tree_arg_list *help_arg_list; completion_tree_arg_list_args_free(tree_clients); completion_tree_arg_list_args_free(tree_groups); completion_tree_arg_list_args_free(tree_roles); if(commands_dynsec){ return; } commands_dynsec = calloc(1, sizeof(struct completion_tree_root)); if(!tree_clients){ tree_clients = completion_tree_cmd_new_arg_list(); tree_clients->is_shared = true; } if(!tree_groups){ tree_groups = completion_tree_cmd_new_arg_list(); tree_groups->is_shared = true; } if(!tree_roles){ tree_roles = completion_tree_cmd_new_arg_list(); tree_roles->is_shared = true; } cmd = completion_tree_cmd_add(commands_dynsec, NULL, "help"); help_arg_list = completion_tree_cmd_add_arg_list(cmd); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "addClientRole"); completion_tree_cmd_append_arg_list(cmd, tree_clients); completion_tree_cmd_append_arg_list(cmd, tree_roles); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "addGroupClient"); completion_tree_cmd_append_arg_list(cmd, tree_groups); completion_tree_cmd_append_arg_list(cmd, tree_clients); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "addGroupRole"); completion_tree_cmd_append_arg_list(cmd, tree_groups); completion_tree_cmd_append_arg_list(cmd, tree_roles); { cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "addRoleACL"); completion_tree_cmd_append_arg_list(cmd, tree_roles); arg_list = completion_tree_cmd_add_arg_list(cmd); completion_tree_arg_list_add_arg(arg_list, "publishClientReceive"); completion_tree_arg_list_add_arg(arg_list, "publishClientSend"); completion_tree_arg_list_add_arg(arg_list, "subscribeLiteral"); completion_tree_arg_list_add_arg(arg_list, "subscribePattern"); completion_tree_arg_list_add_arg(arg_list, "unsubscribeLiteral"); completion_tree_arg_list_add_arg(arg_list, "unsubscribePattern"); arg_list = completion_tree_cmd_add_arg_list(cmd); completion_tree_arg_list_add_arg(arg_list, "allow"); completion_tree_arg_list_add_arg(arg_list, "deny"); } completion_tree_cmd_add(commands_dynsec, help_arg_list, "createClient"); completion_tree_cmd_add(commands_dynsec, help_arg_list, "createGroup"); completion_tree_cmd_add(commands_dynsec, help_arg_list, "createRole"); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "deleteClient"); completion_tree_cmd_append_arg_list(cmd, tree_clients); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "deleteGroup"); completion_tree_cmd_append_arg_list(cmd, tree_groups); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "deleteRole"); completion_tree_cmd_append_arg_list(cmd, tree_roles); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "disableClient"); completion_tree_cmd_append_arg_list(cmd, tree_clients); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "enableClient"); completion_tree_cmd_append_arg_list(cmd, tree_clients); completion_tree_cmd_add(commands_dynsec, help_arg_list, "getAnonymousGroup"); completion_tree_cmd_add(commands_dynsec, help_arg_list, "getDetails"); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "getClient"); completion_tree_cmd_append_arg_list(cmd, tree_clients); completion_tree_cmd_add(commands_dynsec, help_arg_list, "getDefaultACLAccess"); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "getGroup"); completion_tree_cmd_append_arg_list(cmd, tree_groups); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "getRole"); completion_tree_cmd_append_arg_list(cmd, tree_roles); completion_tree_cmd_add(commands_dynsec, help_arg_list, "listClients"); completion_tree_cmd_add(commands_dynsec, help_arg_list, "listGroups"); completion_tree_cmd_add(commands_dynsec, help_arg_list, "listRoles"); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "removeClientRole"); completion_tree_cmd_append_arg_list(cmd, tree_clients); completion_tree_cmd_append_arg_list(cmd, tree_roles); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "removeGroupClient"); completion_tree_cmd_append_arg_list(cmd, tree_groups); completion_tree_cmd_append_arg_list(cmd, tree_clients); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "removeGroupRole"); completion_tree_cmd_append_arg_list(cmd, tree_groups); completion_tree_cmd_append_arg_list(cmd, tree_roles); { cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "removeRoleACL"); completion_tree_cmd_append_arg_list(cmd, tree_roles); arg_list = completion_tree_cmd_add_arg_list(cmd); completion_tree_arg_list_add_arg(arg_list, "publishClientReceive"); completion_tree_arg_list_add_arg(arg_list, "publishClientSend"); completion_tree_arg_list_add_arg(arg_list, "subscribeLiteral"); completion_tree_arg_list_add_arg(arg_list, "subscribePattern"); completion_tree_arg_list_add_arg(arg_list, "unsubscribeLiteral"); completion_tree_arg_list_add_arg(arg_list, "unsubscribePattern"); } cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "setAnonymousGroup"); completion_tree_cmd_append_arg_list(cmd, tree_groups); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "setClientId"); completion_tree_cmd_append_arg_list(cmd, tree_clients); cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "setClientPassword"); completion_tree_cmd_append_arg_list(cmd, tree_clients); { cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "modifyClient"); completion_tree_cmd_append_arg_list(cmd, tree_clients); arg_list = completion_tree_cmd_add_arg_list(cmd); completion_tree_arg_list_add_arg(arg_list, "textName"); completion_tree_arg_list_add_arg(arg_list, "textDescription"); } { cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "modifyGroup"); completion_tree_cmd_append_arg_list(cmd, tree_groups); arg_list = completion_tree_cmd_add_arg_list(cmd); completion_tree_arg_list_add_arg(arg_list, "textName"); completion_tree_arg_list_add_arg(arg_list, "textDescription"); } { cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "modifyRole"); completion_tree_cmd_append_arg_list(cmd, tree_roles); arg_list = completion_tree_cmd_add_arg_list(cmd); completion_tree_arg_list_add_arg(arg_list, "allowWildcardSubs"); completion_tree_arg_list_add_arg(arg_list, "textName"); completion_tree_arg_list_add_arg(arg_list, "textDescription"); } { cmd = completion_tree_cmd_add(commands_dynsec, help_arg_list, "setDefaultACLAccess"); arg_list = completion_tree_cmd_add_arg_list(cmd); completion_tree_arg_list_add_arg(arg_list, "publishClientReceive"); completion_tree_arg_list_add_arg(arg_list, "publishClientSend"); completion_tree_arg_list_add_arg(arg_list, "subscribe"); completion_tree_arg_list_add_arg(arg_list, "unsubscribe"); arg_list = completion_tree_cmd_add_arg_list(cmd); completion_tree_arg_list_add_arg(arg_list, "allow"); completion_tree_arg_list_add_arg(arg_list, "deny"); } completion_tree_cmd_add(commands_dynsec, help_arg_list, "disconnect"); completion_tree_cmd_add(commands_dynsec, help_arg_list, "return"); completion_tree_cmd_add(commands_dynsec, help_arg_list, "exit"); } static void print_help(char **saveptr) { char *command = strtok_r(NULL, " ", saveptr); if(command){ if(!strcasecmp(command, "addClientRole")){ ctrl_shell_print_help_command("addClientRole "); ctrl_shell_printf("\nAdds a role directly to a client.\n"); }else if(!strcasecmp(command, "addGroupClient")){ ctrl_shell_print_help_command("addGroupClient "); ctrl_shell_printf("\nAdds a client to a group.\n"); }else if(!strcasecmp(command, "addGroupRole")){ ctrl_shell_print_help_command("addGroupRole "); ctrl_shell_printf("\nAdds a role to a group.\n"); }else if(!strcasecmp(command, "addRoleACL")){ ctrl_shell_print_help_command("addRoleACL publishClientReceive allow|deny [priority] "); ctrl_shell_print_help_command("addRoleACL publishClientSend allow|deny [priority] "); ctrl_shell_print_help_command("addRoleACL subscribeLiteral allow|deny [priority] "); ctrl_shell_print_help_command("addRoleACL subscribePattern allow|deny [priority] "); ctrl_shell_print_help_command("addRoleACL unsubscribeLiteral allow|deny [priority] "); ctrl_shell_print_help_command("addRoleACL unsubscribePattern allow|deny [priority] "); ctrl_shell_printf("\nAdds an ACL to a role, with an optional priority.\n"); ctrl_shell_printf("\nACLs of a specific type within a role are processed in order from highest to lowest priority with the first matching ACL applying.\n"); }else if(!strcasecmp(command, "createClient")){ ctrl_shell_print_help_command("createClient [password [clientid]]"); ctrl_shell_printf("\nCreate a client with password and optional client id.\n"); }else if(!strcasecmp(command, "createGroup")){ ctrl_shell_print_help_command("createGroup "); ctrl_shell_printf("\nCreate a new group.\n"); }else if(!strcasecmp(command, "createRole")){ ctrl_shell_print_help_command("createRole "); ctrl_shell_printf("\nCreate a new role.\n"); }else if(!strcasecmp(command, "deleteClient")){ ctrl_shell_print_help_command("deleteClient "); ctrl_shell_printf("\nDelete a client\n"); }else if(!strcasecmp(command, "deleteGroup")){ ctrl_shell_print_help_command("deleteGroup "); ctrl_shell_printf("\nDelete a group\n"); }else if(!strcasecmp(command, "deleteRole")){ ctrl_shell_print_help_command("deleteRole "); ctrl_shell_printf("\nDelete a role\n"); }else if(!strcasecmp(command, "disableClient")){ ctrl_shell_print_help_command("disableClient "); ctrl_shell_printf("\nDisable a client. This client will not be able to log in, and will be kicked if it has an existing session.\n"); }else if(!strcasecmp(command, "enableClient")){ ctrl_shell_print_help_command("enableClient "); ctrl_shell_printf("\nEnable a client. Disabled clients are unable to log in.\n"); }else if(!strcasecmp(command, "getAnonymousGroup")){ ctrl_shell_print_help_command("getAnonymousGroup"); ctrl_shell_printf("\nPrint the group configured as the anonymous group.\n"); }else if(!strcasecmp(command, "getDetails")){ ctrl_shell_print_help_command("getDetails"); ctrl_shell_printf("\nPrint details including the client, group, and role count, and the current change index.\n"); }else if(!strcasecmp(command, "getClient")){ ctrl_shell_print_help_command("getClient "); ctrl_shell_printf("\nPrint details of a client and its groups and direct roles.\n"); }else if(!strcasecmp(command, "getDefaultACLAccess")){ ctrl_shell_print_help_command("getDefaultACLAccess"); ctrl_shell_printf("\nPrint the default allow/deny values for the different classes of ACL.\n"); }else if(!strcasecmp(command, "getGroup")){ ctrl_shell_print_help_command("getGroup "); ctrl_shell_printf("\nPrint details of a group and its roles.\n"); }else if(!strcasecmp(command, "getRole")){ ctrl_shell_print_help_command("getRole "); ctrl_shell_printf("\nPrint details of a role and its ACLs.\n"); }else if(!strcasecmp(command, "listClients")){ ctrl_shell_print_help_command("listClients [count [offset]]"); ctrl_shell_printf("\nPrint a list of clients configured in the dynsec plugin, with an optional total count and list offset.\n"); }else if(!strcasecmp(command, "listGroups")){ ctrl_shell_print_help_command("listGroups [count [offset]]"); ctrl_shell_printf("\nPrint a list of groups configured in the dynsec plugin, with an optional total count and list offset.\n"); }else if(!strcasecmp(command, "listRoles")){ ctrl_shell_print_help_command("listRoles [count [offset]]"); ctrl_shell_printf("\nPrint a list of roles configured in the dynsec plugin, with an optional total count and list offset.\n"); }else if(!strcasecmp(command, "removeClientRole")){ ctrl_shell_print_help_command("removeClientRole "); ctrl_shell_printf("\nRemoves a role from a client, where the role was directly attached to the client.\n"); }else if(!strcasecmp(command, "removeGroupClient")){ ctrl_shell_print_help_command("removeGroupClient "); ctrl_shell_printf("\nRemoves a client from a group.\n"); }else if(!strcasecmp(command, "removeGroupRole")){ ctrl_shell_print_help_command("removeGroupRole "); ctrl_shell_printf("\nRemoves a role from a group.\n"); }else if(!strcasecmp(command, "removeRoleACL")){ ctrl_shell_print_help_command("removeRoleACL publishClientReceive "); ctrl_shell_print_help_command("removeRoleACL publishClientSend "); ctrl_shell_print_help_command("removeRoleACL subscribeLiteral "); ctrl_shell_print_help_command("removeRoleACL subscribePattern "); ctrl_shell_print_help_command("removeRoleACL unsubscribeLiteral "); ctrl_shell_print_help_command("removeRoleACL unsubscribePattern "); ctrl_shell_printf("\nRemoves an ACL from a role.\n"); }else if(!strcasecmp(command, "setAnonymousGroup")){ ctrl_shell_print_help_command("setAnonymousGroup "); ctrl_shell_printf("\nSets the anonymous group to a new group.\n"); }else if(!strcasecmp(command, "setClientId")){ ctrl_shell_print_help_command("setClientId "); ctrl_shell_print_help_command("setClientId "); ctrl_shell_printf("\nSets or clears the clientid associated with a client. If a client has a clientid, all three of username, password, and clientid must match for a client to be able to authenticate.\n"); }else if(!strcasecmp(command, "setClientPassword")){ ctrl_shell_print_help_command("setClientPassword [password]"); ctrl_shell_printf("\nSets a new password for a client.\n"); }else if(!strcasecmp(command, "setDefaultACLAccess")){ ctrl_shell_print_help_command("setDefaultACLAccess publishClientReceive allow|deny"); ctrl_shell_print_help_command("setDefaultACLAccess publishClientSend allow|deny"); ctrl_shell_print_help_command("setDefaultACLAccess subscribe allow|deny"); ctrl_shell_print_help_command("setDefaultACLAccess unsubscribe allow|deny"); ctrl_shell_printf("\nSets the default ACL access to use for an ACL type. The default access will be applied if no other ACL rules match.\n"); ctrl_shell_printf("Setting a rule to 'allow' means that if no ACLs match, it will be accepted.\n"); ctrl_shell_printf("Setting a rule to 'deny' means that if no ACLs match, it will be denied.\n"); }else if(!strcasecmp(command, "modifyClient")){ ctrl_shell_print_help_command("modifyClient textName "); ctrl_shell_print_help_command("modifyClient textDescription "); ctrl_shell_printf("\nModify the text name or text description for a client.\n"); ctrl_shell_printf("These are free-text fields for your own use.\n"); }else if(!strcasecmp(command, "modifyGroup")){ ctrl_shell_print_help_command("modifyGroup textName "); ctrl_shell_print_help_command("modifyGroup textDescription "); ctrl_shell_printf("\nModify the text name or text description for a group.\n"); ctrl_shell_printf("These are free-text fields for your own use.\n"); }else if(!strcasecmp(command, "modifyRole")){ ctrl_shell_print_help_command("modifyRole allowWildcardSubs true|false"); ctrl_shell_print_help_command("modifyRole textName "); ctrl_shell_print_help_command("modifyRole textDescription "); ctrl_shell_printf("\nModify the text name or text description for a role.\n"); ctrl_shell_printf("These are free-text fields for your own use.\n"); }else{ ctrl_shell_print_help_final(command, "dynsec"); } }else{ ctrl_shell_printf("This is the mosquitto_ctrl interactive shell, for controlling aspects of a mosquitto broker.\n"); ctrl_shell_printf("You are in dynsec mode, for controlling the dynamic-security clients, groups, and roles used in authentication and authorisation.\n"); ctrl_shell_printf("Use '%sreturn%s' to leave dynsec mode.\n", ANSI_INPUT, ANSI_RESET); ctrl_shell_printf("Find help on a command using '%shelp %s'\n", ANSI_INPUT, ANSI_RESET); ctrl_shell_printf("Press tab multiple times to find currently available commands.\n\n"); } } static int send_set_default_acl_access(char **saveptr) { const char *acltype, *allow_s; acltype = strtok_r(NULL, " ", saveptr); if(!acltype || ( strcasecmp(acltype, "publishClientReceive") && strcasecmp(acltype, "publishClientSend") && strcasecmp(acltype, "subscribe") && strcasecmp(acltype, "unsubscribe") )){ ctrl_shell_printf("setDefaultACLAccess acltype allow|deny\n"); return MOSQ_ERR_INVAL; } allow_s = strtok_r(NULL, " ", saveptr); if(!allow_s || ( strcasecmp(allow_s, "allow") && strcasecmp(allow_s, "deny") )){ ctrl_shell_printf("setDefaultACLAccess acltype allow|deny\n"); return MOSQ_ERR_INVAL; } cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", "setDefaultACLAccess"); cJSON *j_acls = cJSON_AddArrayToObject(j_command, "acls"); cJSON *j_acl = cJSON_CreateObject(); cJSON_AddItemToArray(j_acls, j_acl); cJSON_AddStringToObject(j_acl, "acltype", acltype); cJSON_AddBoolToObject(j_acl, "allow", !strcmp(allow_s, "allow")); return ctrl_shell_publish_blocking(j_command); } static int list_update(const char *command) { cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", command); do_print_list = false; return ctrl_shell_publish_blocking(j_command); } static int list_generic(const char *command, char **saveptr) { const char *count, *offset; count = strtok_r(NULL, " ", saveptr); offset = strtok_r(NULL, " ", saveptr); cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", command); if(count){ cJSON_AddNumberToObject(j_command, "count", atoi(count)); } if(offset){ cJSON_AddNumberToObject(j_command, "offset", atoi(offset)); } return ctrl_shell_publish_blocking(j_command); } static int send_create_client(char **saveptr) { char *username = strtok_r(NULL, " ", saveptr); if(!username){ ctrl_shell_printf("createClient username [password [clientid]]\n"); ctrl_shell_printf("createClient username password [clientid]\n"); return MOSQ_ERR_INVAL; } char *password = strtok_r(NULL, " ", saveptr); char pwbuf1[200]; char pwbuf2[200]; char *clientid = NULL; if(password){ clientid = strtok_r(NULL, " ", saveptr); }else{ if(!ctrl_shell_get_password(pwbuf1, sizeof(pwbuf1)) || !ctrl_shell_get_password(pwbuf2, sizeof(pwbuf2))){ ctrl_shell_printf("No password.\n"); return MOSQ_ERR_INVAL; } if(strcmp(pwbuf1, pwbuf2)){ ctrl_shell_printf("Passwords do not match.\n"); return MOSQ_ERR_INVAL; } password = pwbuf1; } cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", "createClient"); cJSON_AddStringToObject(j_command, "username", username); cJSON_AddStringToObject(j_command, "password", password); if(clientid){ cJSON_AddStringToObject(j_command, "clientid", clientid); } ctrl_shell_publish_blocking(j_command); return MOSQ_ERR_SUCCESS; } static int send_add_role_acl(char **saveptr) { char *rolename = strtok_r(NULL, " ", saveptr); char *acltype = strtok_r(NULL, " ", saveptr); char *allow_s = strtok_r(NULL, " ", saveptr); char *s_priority = strtok_r(NULL, " ", saveptr); char *topic = strtok_r(NULL, " ", saveptr); int priority = -1; if(s_priority){ if(topic){ priority = atoi(s_priority); }else{ topic = s_priority; } } if(!rolename || !acltype || !allow_s || !topic){ ctrl_shell_printf("addRoleACL rolename acltype allow|deny [priority] topic\n"); return MOSQ_ERR_INVAL; } if(strcasecmp(acltype, "publishClientReceive") && strcasecmp(acltype, "publishClientSend") && strcasecmp(acltype, "subscribeLiteral") && strcasecmp(acltype, "subscribePattern") && strcasecmp(acltype, "unsubscribeLiteral") && strcasecmp(acltype, "unsubscribePattern") ){ ctrl_shell_printf("addRoleACL rolename acltype allow|deny [priority] topic\n"); ctrl_shell_printf("Invalid acltype '%s'\n", acltype); return MOSQ_ERR_INVAL; } if(strcasecmp(allow_s, "allow") && strcasecmp(allow_s, "deny")){ ctrl_shell_printf("addRoleACL rolename acltype allow|deny [priority] topic\n"); ctrl_shell_printf("Invalid allow/deny '%s'\n", allow_s); return MOSQ_ERR_INVAL; } cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", "addRoleACL"); cJSON_AddStringToObject(j_command, "rolename", rolename); cJSON_AddStringToObject(j_command, "acltype", acltype); cJSON_AddNumberToObject(j_command, "priority", priority); cJSON_AddStringToObject(j_command, "topic", topic); cJSON_AddBoolToObject(j_command, "allow", !strcasecmp(allow_s, "allow")); return ctrl_shell_publish_blocking(j_command); } static int send_remove_role_acl(char **saveptr) { char *rolename = strtok_r(NULL, " ", saveptr); char *acltype = strtok_r(NULL, " ", saveptr); char *topic = strtok_r(NULL, " ", saveptr); if(!rolename || !acltype || !topic){ ctrl_shell_printf("removeRoleACL rolename acltype topic\n"); return MOSQ_ERR_INVAL; } if(strcasecmp(acltype, "publishClientReceive") && strcasecmp(acltype, "publishClientSend") && strcasecmp(acltype, "subscribeLiteral") && strcasecmp(acltype, "subscribePattern") && strcasecmp(acltype, "unsubscribeLiteral") && strcasecmp(acltype, "unsubscribePattern") ){ ctrl_shell_printf("removeRoleACL rolename acltype topic\n"); ctrl_shell_printf("Invalid acltype '%s'\n", acltype); return MOSQ_ERR_INVAL; } cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", "removeRoleACL"); cJSON_AddStringToObject(j_command, "rolename", rolename); cJSON_AddStringToObject(j_command, "acltype", acltype); cJSON_AddStringToObject(j_command, "topic", topic); return ctrl_shell_publish_blocking(j_command); } static int send_modify(const char *command, const char *objectname, char **saveptr) { char *name = strtok_r(NULL, " ", saveptr); char *itemlabel = strtok_r(NULL, " ", saveptr); char *itemvalue = *saveptr; if(!name || !itemlabel || !itemvalue){ ctrl_shell_printf("%s %s \n", command, objectname); return MOSQ_ERR_INVAL; } if(strcasecmp(itemlabel, "textName") && strcasecmp(itemlabel, "textDescription") && strcasecmp(itemlabel, "allowWildcardSubs")){ ctrl_shell_printf("%s %s \n", command, objectname); ctrl_shell_printf("Unknown property '%s'\n", itemlabel); return MOSQ_ERR_INVAL; } if(!strcasecmp(itemlabel, "allowWildcardSubs")){ if(strcasecmp(itemvalue, "true") && strcasecmp(itemvalue, "false")){ ctrl_shell_printf("%s %s \n", command, objectname); ctrl_shell_printf("Invalid value '%s'\n", itemvalue); return MOSQ_ERR_INVAL; } } cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", command); cJSON_AddStringToObject(j_command, objectname, name); if(!strcasecmp(itemlabel, "allowWildcardSubs")){ cJSON_AddBoolToObject(j_command, itemlabel, !strcasecmp(itemvalue, "true")); }else{ cJSON_AddStringToObject(j_command, itemlabel, itemvalue); } return ctrl_shell_publish_blocking(j_command); } static int send_set_client_password(char **saveptr) { char *username, *password; char pwbuf1[200], pwbuf2[200]; username = strtok_r(NULL, " ", saveptr); if(!username){ ctrl_shell_printf("setClientPassword [password]\n"); return MOSQ_ERR_INVAL; } password = strtok_r(NULL, " ", saveptr); if(!password){ if(!ctrl_shell_get_password(pwbuf1, sizeof(pwbuf1)) || !ctrl_shell_get_password(pwbuf2, sizeof(pwbuf2))){ ctrl_shell_printf("No password.\n"); return MOSQ_ERR_INVAL; } if(strcmp(pwbuf1, pwbuf2)){ ctrl_shell_printf("Passwords do not match.\n"); return MOSQ_ERR_INVAL; } password = pwbuf1; } cJSON *j_command = cJSON_CreateObject(); cJSON_AddStringToObject(j_command, "command", "setClientPassword"); cJSON_AddStringToObject(j_command, "username", username); cJSON_AddStringToObject(j_command, "password", password); return ctrl_shell_publish_blocking(j_command); } static void line_callback(char *line) { if(!line){ ctrl_shell_callback_final(NULL); return; } ctrl_shell_rtrim(line); if(strlen(line) > 0){ add_history(line); }else{ free(line); return; } char *saveptr = NULL; char *command = strtok_r(line, " ", &saveptr); if(!command){ free(line); return; } if(!strcasecmp(command, "addClientRole")){ ctrl_shell_command_generic_arg2("addClientRole", "username", "rolename", &saveptr); }else if(!strcasecmp(command, "addGroupClient")){ ctrl_shell_command_generic_arg2("addGroupClient", "groupname", "username", &saveptr); }else if(!strcasecmp(command, "addGroupRole")){ ctrl_shell_command_generic_arg2("addGroupRole", "groupname", "rolename", &saveptr); }else if(!strcasecmp(command, "addRoleACL")){ send_add_role_acl(&saveptr); }else if(!strcasecmp(command, "createClient")){ if(send_create_client(&saveptr) == MOSQ_ERR_SUCCESS){ list_update("listClients"); } }else if(!strcasecmp(command, "createGroup")){ if(ctrl_shell_command_generic_arg1("createGroup", "groupname", &saveptr) == MOSQ_ERR_SUCCESS){ list_update("listGroups"); } }else if(!strcasecmp(command, "createRole")){ if(ctrl_shell_command_generic_arg1("createRole", "rolename", &saveptr) == MOSQ_ERR_SUCCESS){ list_update("listRoles"); } }else if(!strcasecmp(command, "deleteClient")){ if(ctrl_shell_command_generic_arg1("deleteClient", "username", &saveptr) == MOSQ_ERR_SUCCESS){ list_update("listClients"); } }else if(!strcasecmp(command, "deleteGroup")){ if(ctrl_shell_command_generic_arg1("deleteGroup", "groupname", &saveptr) == MOSQ_ERR_SUCCESS){ list_update("listGroups"); } }else if(!strcasecmp(command, "deleteRole")){ if(ctrl_shell_command_generic_arg1("deleteRole", "rolename", &saveptr) == MOSQ_ERR_SUCCESS){ list_update("listRoles"); } }else if(!strcasecmp(command, "disableClient")){ ctrl_shell_command_generic_arg1("disableClient", "username", &saveptr); }else if(!strcasecmp(command, "enableClient")){ ctrl_shell_command_generic_arg1("enableClient", "username", &saveptr); }else if(!strcasecmp(command, "getAnonymousGroup")){ ctrl_shell_command_generic_arg0("getAnonymousGroup"); }else if(!strcasecmp(command, "getDetails")){ ctrl_shell_command_generic_arg0("getDetails"); }else if(!strcasecmp(command, "getClient")){ ctrl_shell_command_generic_arg1("getClient", "username", &saveptr); }else if(!strcasecmp(command, "getDefaultACLAccess")){ ctrl_shell_command_generic_arg0("getDefaultACLAccess"); }else if(!strcasecmp(command, "getGroup")){ ctrl_shell_command_generic_arg1("getGroup", "groupname", &saveptr); }else if(!strcasecmp(command, "getRole")){ ctrl_shell_command_generic_arg1("getRole", "rolename", &saveptr); }else if(!strcasecmp(command, "listClients")){ do_print_list = true; list_generic("listClients", &saveptr); }else if(!strcasecmp(command, "listGroups")){ do_print_list = true; list_generic("listGroups", &saveptr); }else if(!strcasecmp(command, "listRoles")){ do_print_list = true; list_generic("listRoles", &saveptr); }else if(!strcasecmp(command, "removeClientRole")){ ctrl_shell_command_generic_arg2("removeClientRole", "username", "rolename", &saveptr); }else if(!strcasecmp(command, "removeGroupClient")){ ctrl_shell_command_generic_arg2("removeGroupClient", "groupname", "username", &saveptr); }else if(!strcasecmp(command, "removeGroupRole")){ ctrl_shell_command_generic_arg2("removeGroupRole", "groupname", "rolename", &saveptr); }else if(!strcasecmp(command, "removeRoleACL")){ send_remove_role_acl(&saveptr); }else if(!strcasecmp(command, "setAnonymousGroup")){ ctrl_shell_command_generic_arg1("setAnonymousGroup", "groupname", &saveptr); }else if(!strcasecmp(command, "setClientId")){ ctrl_shell_command_generic_arg2("setClientId", "username", "clientid", &saveptr); }else if(!strcasecmp(command, "setClientPassword")){ send_set_client_password(&saveptr); }else if(!strcasecmp(command, "modifyClient")){ send_modify("modifyClient", "username", &saveptr); }else if(!strcasecmp(command, "modifyGroup")){ send_modify("modifyGroup", "groupname", &saveptr); }else if(!strcasecmp(command, "modifyRole")){ send_modify("modifyRole", "rolename", &saveptr); }else if(!strcasecmp(command, "setDefaultACLAccess")){ send_set_default_acl_access(&saveptr); }else if(!strcasecmp(command, "help")){ print_help(&saveptr); }else{ if(!ctrl_shell_callback_final(line)){ ctrl_shell_printf("Unknown command '%s'\n", command); } } free(line); } static void print_json_value(cJSON *value, const char *null_value) { if(value){ if(cJSON_IsString(value)){ if(value->valuestring){ ctrl_shell_print_value(0, "%s", value->valuestring); } }else{ char buffer[1024]; cJSON_PrintPreallocated(value, buffer, sizeof(buffer), 0); ctrl_shell_print_value(0, "%s", buffer); } }else if(null_value){ ctrl_shell_print_value(0, "%s", null_value); } } static void print_json_array(cJSON *j_list, const char *label, const char *element_name, const char *optional_element_name, const char *optional_element_null_value) { cJSON *j_elem; if(j_list && cJSON_IsArray(j_list) && cJSON_GetArraySize(j_list) > 0){ ctrl_shell_print_label(0, label); cJSON_ArrayForEach(j_elem, j_list){ if(cJSON_IsObject(j_elem)){ const char *stmp; if(json_get_string(j_elem, element_name, &stmp, false) != MOSQ_ERR_SUCCESS){ continue; } ctrl_shell_print_value(1, "%s", stmp); if(optional_element_name){ ctrl_shell_print_value(0, " (%s: ", optional_element_name); print_json_value(cJSON_GetObjectItem(j_elem, optional_element_name), optional_element_null_value); ctrl_shell_print_value(0, ")"); } }else if(cJSON_IsString(j_elem) && j_elem->valuestring){ ctrl_shell_print_value(1, "%s", j_elem->valuestring); } ctrl_shell_print_value(0, "\n"); } } } static void print_details(cJSON *j_data) { int64_t clientcount; int64_t groupcount; int64_t rolecount; int64_t changeindex; int align = (int)strlen("Change index: "); json_get_int64(j_data, "clientCount", &clientcount, true, 0); json_get_int64(j_data, "groupCount", &groupcount, true, 0); json_get_int64(j_data, "roleCount", &rolecount, true, 0); json_get_int64(j_data, "changeIndex", &changeindex, true, 0); ctrl_shell_print_label_value(0, "Client count:", align, "%ld\n", clientcount); ctrl_shell_print_label_value(0, "Group count:", align, "%ld\n", groupcount); ctrl_shell_print_label_value(0, "Role count:", align, "%ld\n", rolecount); ctrl_shell_print_label_value(0, "Change index:", align, "%ld\n", changeindex); } static void print_client(cJSON *j_data) { cJSON *j_client, *jtmp; j_client = cJSON_GetObjectItem(j_data, "client"); if(j_client == NULL){ ctrl_shell_printf("Invalid response from broker.\n"); return; } const char *username; if(json_get_string(j_client, "username", &username, false) != MOSQ_ERR_SUCCESS){ ctrl_shell_printf("Invalid response from broker.\n"); return; } ctrl_shell_print_label(0, "Username:"); ctrl_shell_print_value(1, "%s\n", username); const char *clientid; if(json_get_string(j_client, "clientid", &clientid, false) == MOSQ_ERR_SUCCESS){ ctrl_shell_print_label(0, "Clientid:"); ctrl_shell_print_value(1, "%s\n", clientid); } jtmp = cJSON_GetObjectItem(j_client, "disabled"); if(jtmp && cJSON_IsBool(jtmp) && cJSON_IsTrue(jtmp)){ ctrl_shell_print_label(0, "Disabled:"); ctrl_shell_print_value(1, "true\n"); } const char *textname; if(json_get_string(j_client, "textname", &textname, false) == MOSQ_ERR_SUCCESS){ ctrl_shell_print_label(0, "Text name:"); ctrl_shell_print_value(1, "%s\n", textname); } const char *textdescription; if(json_get_string(j_client, "textdescription", &textdescription, false) == MOSQ_ERR_SUCCESS){ ctrl_shell_print_label(0, "Text description:"); ctrl_shell_print_value(1, "%s\n", textdescription); } print_json_array(cJSON_GetObjectItem(j_client, "roles"), "Roles:", "rolename", "priority", "-1"); print_json_array(cJSON_GetObjectItem(j_client, "groups"), "Groups:", "groupname", "priority", "-1"); } static void print_group(cJSON *j_data) { cJSON *j_group; j_group = cJSON_GetObjectItem(j_data, "group"); if(j_group == NULL){ ctrl_shell_printf("Invalid response from broker.\n"); return; } const char *groupname; if(json_get_string(j_group, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ ctrl_shell_printf("Invalid response from broker.\n"); return; } ctrl_shell_print_label(0, "Group name:"); ctrl_shell_print_value(1, "%s\n", groupname); const char *textname; if(json_get_string(j_group, "textname", &textname, false) == MOSQ_ERR_SUCCESS){ ctrl_shell_print_label(0, "Text name:"); ctrl_shell_print_value(1, "%s\n", textname); } const char *textdescription; if(json_get_string(j_group, "textdescription", &textdescription, false) == MOSQ_ERR_SUCCESS){ ctrl_shell_print_label(0, "Text description:"); ctrl_shell_print_value(1, "%s\n", textdescription); } print_json_array(cJSON_GetObjectItem(j_group, "roles"), "Roles:", "rolename", "priority", "-1"); print_json_array(cJSON_GetObjectItem(j_group, "clients"), "Clients:", "username", NULL, NULL); } static void print_role(cJSON *j_data) { cJSON *j_role; j_role = cJSON_GetObjectItem(j_data, "role"); if(j_role == NULL){ ctrl_shell_printf("Invalid response from broker.\n"); return; } const char *rolename; if(json_get_string(j_role, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ ctrl_shell_printf("Invalid response from broker.\n"); return; } ctrl_shell_print_label(0, "Role name:"); ctrl_shell_print_value(1, "%s\n", rolename); const char *textname; if(json_get_string(j_role, "textname", &textname, false) == MOSQ_ERR_SUCCESS){ ctrl_shell_print_label(0, "Text name:"); ctrl_shell_print_value(1, "%s\n", textname); } const char *textdescription; if(json_get_string(j_role, "textdescription", &textdescription, false) == MOSQ_ERR_SUCCESS){ ctrl_shell_print_label(0, "Text description:"); ctrl_shell_print_value(1, "%s\n", textdescription); } bool allowwildcardsubs; if(json_get_bool(j_role, "allowwildcardsubs", &allowwildcardsubs, false, false) == MOSQ_ERR_SUCCESS){ ctrl_shell_print_label(0, "Allow wildcard subscriptions:"); ctrl_shell_print_value(1, "%s\n", allowwildcardsubs?"true":"false"); } cJSON *j_acls = cJSON_GetObjectItem(j_role, "acls"); if(j_acls && cJSON_GetArraySize(j_acls) > 0){ ctrl_shell_print_label(0, "ACLs:"); cJSON *j_acl; cJSON_ArrayForEach(j_acl, j_acls){ const char *acltype; const char *topic; int priority; bool allow; if(json_get_string(j_acl, "acltype", &acltype, false) == MOSQ_ERR_SUCCESS && json_get_string(j_acl, "topic", &topic, false) == MOSQ_ERR_SUCCESS && json_get_int(j_acl, "priority", &priority, true, -1) == MOSQ_ERR_SUCCESS && json_get_bool(j_acl, "allow", &allow, false, false) == MOSQ_ERR_SUCCESS ){ const char *ANSI_ALLOW = allow?ANSI_POSITIVE:ANSI_NEGATIVE; ctrl_shell_print_value(1, "%-*s %s%s%s %s%s%s (priority %d)\n", (int)strlen("publishClientReceive"), acltype, ANSI_ALLOW, allow?"allow":"deny", ANSI_RESET, ANSI_TOPIC, topic, ANSI_RESET, priority); } } } } static void print_default_acls(cJSON *j_data) { cJSON *j_acls = cJSON_GetObjectItem(j_data, "acls"); if(j_acls && cJSON_GetArraySize(j_acls) > 0){ cJSON *j_acl; cJSON_ArrayForEach(j_acl, j_acls){ const char *acltype; bool allow; if(json_get_string(j_acl, "acltype", &acltype, false) == MOSQ_ERR_SUCCESS && json_get_bool(j_acl, "allow", &allow, false, false) == MOSQ_ERR_SUCCESS ){ ctrl_shell_print_value(0, "%-*s %s\n", (int)strlen("publishClientReceive"), acltype, allow?"allow":"deny"); } } } } static void response_callback(const char *command, cJSON *j_data, const char *payload) { UNUSED(payload); if(!strcmp(command, "listClients")){ completion_tree_arg_list_args_free(tree_clients); cJSON *clients, *client; clients = cJSON_GetObjectItem(j_data, "clients"); cJSON_ArrayForEach(client, clients){ if(do_print_list){ ctrl_shell_print_value(0, "%s\n", client->valuestring); } completion_tree_arg_list_add_arg(tree_clients, client->valuestring); } do_print_list = false; }else if(!strcmp(command, "listGroups")){ completion_tree_arg_list_args_free(tree_groups); cJSON *groups, *group; groups = cJSON_GetObjectItem(j_data, "groups"); cJSON_ArrayForEach(group, groups){ if(do_print_list){ ctrl_shell_print_value(0, "%s\n", group->valuestring); } completion_tree_arg_list_add_arg(tree_groups, group->valuestring); } do_print_list = false; }else if(!strcmp(command, "listRoles")){ completion_tree_arg_list_args_free(tree_roles); cJSON *roles, *role; roles = cJSON_GetObjectItem(j_data, "roles"); cJSON_ArrayForEach(role, roles){ if(do_print_list){ ctrl_shell_print_value(0, "%s\n", role->valuestring); } completion_tree_arg_list_add_arg(tree_roles, role->valuestring); } do_print_list = false; }else if(!strcasecmp(command, "getAnonymousGroup")){ cJSON *group, *groupname; group = cJSON_GetObjectItem(j_data, "group"); groupname = cJSON_GetObjectItem(group, "groupname"); ctrl_shell_print_value(0, "%s\n", groupname->valuestring); }else if(!strcasecmp(command, "getDetails")){ print_details(j_data); }else if(!strcasecmp(command, "getClient")){ print_client(j_data); }else if(!strcasecmp(command, "getGroup")){ print_group(j_data); }else if(!strcasecmp(command, "getRole")){ print_role(j_data); }else if(!strcasecmp(command, "getDefaultACLAccess")){ print_default_acls(j_data); }else{ //ctrl_shell_printf("%s %s\n", command, payload); } } static void on_subscribe(void) { int rc; rc = list_update("listClients"); if(rc){ ctrl_shell_printf("Check the dynsec module is configured on the broker.\n"); return; } list_update("listGroups"); list_update("listRoles"); } static void ctrl_shell__dynsec_cleanup(void) { completion_tree_free(commands_dynsec); commands_dynsec = NULL; completion_tree_arg_list_args_free(tree_clients); completion_tree_arg_list_args_free(tree_groups); completion_tree_arg_list_args_free(tree_roles); free(tree_clients); free(tree_groups); free(tree_roles); tree_clients = NULL; tree_groups = NULL; tree_roles = NULL; } void ctrl_shell__dynsec_init(struct ctrl_shell__module *mod) { command_tree_create(); mod->completion_commands = commands_dynsec; mod->request_topic = "$CONTROL/dynamic-security/v1"; mod->response_topic = "$CONTROL/dynamic-security/v1/response"; mod->line_callback = line_callback; mod->response_callback = response_callback; mod->on_subscribe = on_subscribe; mod->cleanup = ctrl_shell__dynsec_cleanup; } #endif ================================================ FILE: apps/mosquitto_ctrl/ctrl_shell_internal.h ================================================ /* Copyright (c) 2023 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 CTRL_SHELL_INTERNAL_H #define CTRL_SHELL_INTERNAL_H #ifdef WITH_CTRL_SHELL #ifdef __cplusplus extern "C" { #endif #include #include #ifdef WITH_EDITLINE #include #elif defined(WITH_READLINE) #include #include #endif #include #include "ctrl_shell.h" #include "mosquitto_ctrl.h" struct ctrl_shell { char **subscription_list; int subscription_list_count; int run; struct mosquitto *mosq; rl_vcpfunc_t *line_callback; pthread_cond_t response_cond; pthread_mutex_t response_mutex; bool response_received; const char *request_topic; struct completion_tree_root *commands; void (*response_callback)(const char *command, cJSON *data, const char *payload); void (*mod_cleanup)(void); const char *url_scheme; char *username; char *password; char *clientid; char *tls_cafile; char *tls_capath; char *tls_certfile; char *tls_keyfile; char *hostname; int port; int connect_rc; int subscribe_rc; int publish_rc; int transport; }; struct ctrl_shell__module { struct completion_tree_root *completion_commands; const char *request_topic; const char *response_topic; void (*response_callback)(const char *command, cJSON *data, const char *payload); void (*line_callback)(char *line); void (*on_subscribe)(void); void (*cleanup)(void); }; extern struct ctrl_shell data; extern char prompt[200]; void term__set_echo(bool echo); int do_connect(void); void ctrl_shell__pre_connect_init(void); void ctrl_shell__pre_connect_cleanup(void); void ctrl_shell__post_connect_init(void); void ctrl_shell__post_connect_cleanup(void); void ctrl_shell__load_module(void (*mod_init)(struct ctrl_shell__module *mod)); void ctrl_shell__connect_blocking(const char *hostname, int port); void ctrl_shell__on_connect(struct mosquitto *mosq, void *userdata, int rc); void ctrl_shell__on_subscribe(struct mosquitto *mosq, void *userdata, int mid, int qos_count, const int *granted_qos); void ctrl_shell__on_publish(struct mosquitto *mosq, void *userdata, int mid, int reason_code, const mosquitto_property *props); void ctrl_shell__on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *msg); void ctrl_shell__broker_init(struct ctrl_shell__module *mod); void ctrl_shell__dynsec_init(struct ctrl_shell__module *mod); void ctrl_shell__main(struct mosq_config *config); int ctrl_shell__connect(void); void ctrl_shell__disconnect(void); void ctrl_shell__output(const char *buf); #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: apps/mosquitto_ctrl/ctrl_shell_io.c ================================================ /* Copyright (c) 2025 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 "ctrl_shell.h" void ctrl_shell__output(const char *buf) { printf("%s", buf); } char *ctrl_shell_fgets(char *s, int size, FILE *stream) { return fgets(s, size, stream); } ================================================ FILE: apps/mosquitto_ctrl/ctrl_shell_post_connect.c ================================================ /* Copyright (c) 2023 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 "ctrl_shell_internal.h" #ifdef WITH_CTRL_SHELL #define UNUSED(A) (void)(A) static struct completion_tree_root *commands_post_connect = NULL; static void command_tree_create(void) { struct completion_tree_cmd *cmd; struct completion_tree_arg_list *help_arg_list; if(commands_post_connect){ return; } commands_post_connect = calloc(1, sizeof(struct completion_tree_root)); cmd = completion_tree_cmd_add(commands_post_connect, NULL, "help"); help_arg_list = completion_tree_cmd_add_arg_list(cmd); completion_tree_cmd_add(commands_post_connect, help_arg_list, "broker"); completion_tree_cmd_add(commands_post_connect, help_arg_list, "disconnect"); completion_tree_cmd_add(commands_post_connect, help_arg_list, "dynsec"); completion_tree_cmd_add(commands_post_connect, help_arg_list, "exit"); } static void print_help(char **saveptr) { char *command = strtok_r(NULL, " ", saveptr); if(command){ if(!strcasecmp(command, "dynsec")){ ctrl_shell_print_help_command("dynsec"); ctrl_shell_printf("\nStart the dynamic-security control mode.\n"); }else if(!strcasecmp(command, "broker")){ ctrl_shell_print_help_command("broker"); ctrl_shell_printf("\nStart the broker control mode.\n"); }else{ ctrl_shell_print_help_final(command, NULL); } }else{ ctrl_shell_printf("This is the mosquitto_ctrl interactive shell, for controlling aspects of a mosquitto broker.\n"); ctrl_shell_printf("Find help on a command using '%shelp %s'\n", ANSI_INPUT, ANSI_RESET); ctrl_shell_printf("Press tab multiple times to find currently available commands.\n\n"); ctrl_shell_printf("Example workflow:\n\n"); ctrl_shell_printf("> auth\n"); ctrl_shell_printf("username: admin\n"); ctrl_shell_printf("password:\n"); ctrl_shell_printf("> connect mqtt://localhost\n"); ctrl_shell_printf("mqtt://localhost:1883> dynsec\n"); ctrl_shell_printf("mqtt://localhost:1883|dynsec> createGroup newgroup\n"); ctrl_shell_printf("OK\n\n"); } } struct module_data { const char *name; void (*mod_init)(struct ctrl_shell__module *mod); }; const struct module_data mod_data[] = { { "broker", ctrl_shell__broker_init }, { "dynsec", ctrl_shell__dynsec_init }, }; static void line_callback(char *line) { if(!line){ ctrl_shell_callback_final(NULL); return; } ctrl_shell_rtrim(line); if(strlen(line) > 0){ add_history(line); }else{ free(line); return; } char *saveptr = NULL; bool found = false; char *command = strtok_r(line, " ", &saveptr); if(!command){ free(line); return; } for(size_t i=0; i%s ", ANSI_URL, data.url_scheme, data.hostname, data.port, ANSI_RESET, ANSI_MODULE, mod_data[i].name, ANSI_INPUT, ANSI_RESET); ctrl_shell__load_module(mod_data[i].mod_init); found = true; break; } } if(!strcasecmp(command, "help")){ found = true; print_help(&saveptr); } if(found == false){ if(!ctrl_shell_callback_final(line)){ ctrl_shell_printf("Unknown command '%s'\n", command); } } free(line); } void ctrl_shell__post_connect_cleanup(void) { completion_tree_free(commands_post_connect); commands_post_connect = NULL; } void ctrl_shell__post_connect_init(void) { command_tree_create(); ctrl_shell_completion_commands_set(commands_post_connect); ctrl_shell_line_callback_set(line_callback); snprintf(prompt, sizeof(prompt), "%s%s://%s:%d%s>%s ", ANSI_URL, data.url_scheme, data.hostname, data.port, ANSI_INPUT, ANSI_RESET); } #endif ================================================ FILE: apps/mosquitto_ctrl/ctrl_shell_pre_connect.c ================================================ /* Copyright (c) 2023 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 "ctrl_shell_internal.h" #ifdef WITH_CTRL_SHELL #define UNUSED(A) (void)(A) static struct completion_tree_root *commands_pre_connect = NULL; static void command_tree_create(void) { struct completion_tree_cmd *cmd; struct completion_tree_arg_list *help_arg_list; if(commands_pre_connect){ return; } commands_pre_connect = calloc(1, sizeof(struct completion_tree_root)); cmd = completion_tree_cmd_add(commands_pre_connect, NULL, "help"); help_arg_list = completion_tree_cmd_add_arg_list(cmd); completion_tree_cmd_add(commands_pre_connect, help_arg_list, "auth"); completion_tree_cmd_add(commands_pre_connect, help_arg_list, "connect"); completion_tree_cmd_add(commands_pre_connect, help_arg_list, "exit"); } void print_help(char **saveptr) { char *command = strtok_r(NULL, " ", saveptr); if(command){ if(!strcasecmp(command, "auth")){ ctrl_shell_print_help_command("auth [username]"); ctrl_shell_printf("\nSet a username and password prior to connecting to a broker.\n"); }else if(!strcasecmp(command, "connect")){ ctrl_shell_print_help_command("connect"); ctrl_shell_print_help_command("connect mqtt://hostname[:port]"); ctrl_shell_print_help_command("connect mqtts://hostname[:port]"); ctrl_shell_print_help_command("connect ws://hostname[:port]"); ctrl_shell_print_help_command("connect wss://hostname[:port]"); ctrl_shell_printf("\nConnect to a broker using the provided transport and port.\n"); ctrl_shell_printf("If no URL is provided, connects to mqtt://localhost:1883\n"); }else if(!strcasecmp(command, "exit")){ ctrl_shell_print_help_command("exit"); ctrl_shell_printf("\nQuit the program\n"); }else if(!strcasecmp(command, "help")){ ctrl_shell_print_help_command("help "); ctrl_shell_printf("\nFind help on a command using '%shelp %s'\n", ANSI_INPUT, ANSI_RESET); ctrl_shell_printf("Press tab multiple times to find currently available commands.\n"); }else{ ctrl_shell_printf("Unknown command '%s'\n", command); } }else{ ctrl_shell_printf("This is the mosquitto_ctrl interactive shell, for controlling aspects of a mosquitto broker.\n"); ctrl_shell_printf("Find help on a command using '%shelp %s'\n", ANSI_INPUT, ANSI_RESET); ctrl_shell_printf("Press tab multiple times to find currently available commands.\n\n"); ctrl_shell_printf("Example workflow:\n\n"); ctrl_shell_printf("> auth\n"); ctrl_shell_printf("username: admin\n"); ctrl_shell_printf("password:\n"); ctrl_shell_printf("> connect mqtt://localhost\n"); ctrl_shell_printf("mqtt://localhost:1883> dynsec\n"); ctrl_shell_printf("mqtt://localhost:1883|dynsec> createGroup newgroup\n"); ctrl_shell_printf("OK\n\n"); } } static void line_callback(char *line) { char *saveptr = NULL; char *command; if(!line){ ctrl_shell_callback_final(NULL); return; } ctrl_shell_rtrim(line); if(strlen(line) > 0){ add_history(line); }else{ free(line); return; } command = strtok_r(line, " ", &saveptr); if(!command){ free(line); return; } if(!strcasecmp(command, "auth")){ free(data.username); char *username_i = strtok_r(NULL, " ", &saveptr); if(username_i){ data.username = strdup(username_i); }else{ char promptbuf[50]; snprintf(promptbuf, sizeof(promptbuf), "%susername:%s ", ANSI_INPUT, ANSI_RESET); data.username = readline(promptbuf); } char pwbuf[200]; if(!ctrl_shell_get_password(pwbuf, sizeof(pwbuf))){ ctrl_shell_printf("No password.\n"); free(line); return; } free(data.password); data.password = strdup(pwbuf); }else if(!strcasecmp(command, "connect")){ char *url = strtok_r(NULL, " ", &saveptr); if(url){ if(!strncasecmp(url, "mqtt://", 7)){ url += 7; data.port = 1883; data.url_scheme = "mqtt"; }else if(!strncasecmp(url, "mqtts://", 8)){ #ifdef WITH_TLS url += 8; data.port = 8883; data.url_scheme = "mqtts"; #else ctrl_shell_printf("TLS support not available.\n"); free(line); return; #endif }else if(!strncasecmp(url, "ws://", 5)){ url += 5; data.port = 1883; data.transport = MOSQ_T_WEBSOCKETS; data.url_scheme = "ws"; }else if(!strncasecmp(url, "wss://", 6)){ #ifdef WITH_TLS url += 6; data.port = 8883; data.transport = MOSQ_T_WEBSOCKETS; data.url_scheme = "wss"; #else ctrl_shell_printf("TLS support not available.\n"); free(line); return; #endif } char *hostname_i = strtok_r(url, ":", &saveptr); char *port_i = strtok_r(NULL, ":", &saveptr); if(!hostname_i){ ctrl_shell_printf("connect mqtt[s]://:port\n"); free(line); return; } free(data.hostname); data.hostname = strdup(hostname_i); if(port_i){ data.port = atoi(port_i); } }else{ if(data.hostname == NULL){ data.hostname = strdup("localhost"); } if(data.port == PORT_UNDEFINED){ data.port = 1883; } } ctrl_shell__connect(); }else if(!strcasecmp(command, "help")){ print_help(&saveptr); }else if(!strcasecmp(command, "exit")){ data.run = 0; }else{ ctrl_shell_printf("Unknown command '%s'\n", command); } free(line); } void ctrl_shell__pre_connect_cleanup(void) { completion_tree_free(commands_pre_connect); commands_pre_connect = NULL; } void ctrl_shell__pre_connect_init(void) { command_tree_create(); ctrl_shell_completion_commands_set(commands_pre_connect); ctrl_shell_line_callback_set(line_callback); snprintf(prompt, sizeof(prompt), "%s>%s ", ANSI_INPUT, ANSI_RESET); } #endif ================================================ FILE: apps/mosquitto_ctrl/ctrl_shell_printf.c ================================================ /* Copyright (c) 2025 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 "ctrl_shell_internal.h" void ctrl_shell_vprintf(const char *fmt, va_list va) { char buf[2000]; vsnprintf(buf, sizeof(buf), fmt, va); ctrl_shell__output(buf); } void ctrl_shell_printf(const char *fmt, ...) { va_list va; va_start(va, fmt); ctrl_shell_vprintf(fmt, va); va_end(va); } ================================================ FILE: apps/mosquitto_ctrl/dynsec.c ================================================ /* Copyright (c) 2020-2021 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 #define CJSON_VERSION_FULL (CJSON_VERSION_MAJOR*1000000+CJSON_VERSION_MINOR*1000+CJSON_VERSION_PATCH) #include #include #include #ifndef WIN32 # include # include # include #endif #include "mosquitto_ctrl.h" #include "mosquitto.h" #include "json_help.h" #include "get_password.h" #define MAX_STRING_LEN 4096 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 [-i clientid] [-p password]\n"); printf("Delete a client: deleteClient \n"); printf("Set a client password: setClientPassword [password]\n"); printf("Set a client password on an existing file:\n"); printf(" mosquitto_ctrl -f dynsec setClientPassword \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"); } /* ################################################################ * # * # Payload callback * # * ################################################################ */ static void print_list(cJSON *j_response, const char *arrayname, const char *keyname) { cJSON *j_data, *j_array, *j_elem; 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)){ const char *stmp; if(json_get_string(j_elem, keyname, &stmp, false) == MOSQ_ERR_SUCCESS){ printf("%s\n", stmp); } }else if(cJSON_IsString(j_elem) && j_elem->valuestring){ printf("%s\n", j_elem->valuestring); } } } static void print_json_value(cJSON *value, const char *null_value) { if(value){ if(cJSON_IsString(value)){ if(value->valuestring){ printf("%s", value->valuestring); } }else{ char buffer[MAX_STRING_LEN]; cJSON_PrintPreallocated(value, buffer, sizeof(buffer), 0); printf("%s", buffer); } }else if(null_value){ printf("%s", null_value); } } static void print_json_array(cJSON *j_list, int slen, const char *label, const char *element_name, const char *optional_element_name, const char *optional_element_null_value) { cJSON *j_elem; if(j_list && cJSON_IsArray(j_list)){ cJSON_ArrayForEach(j_elem, j_list){ if(cJSON_IsObject(j_elem)){ const char *stmp; if(json_get_string(j_elem, element_name, &stmp, false) != MOSQ_ERR_SUCCESS){ continue; } printf("%-*s %s", (int)slen, label, stmp); if(optional_element_name){ printf(" (%s: ", optional_element_name); print_json_value(cJSON_GetObjectItem(j_elem, optional_element_name), optional_element_null_value); printf(")"); } }else if(cJSON_IsString(j_elem) && j_elem->valuestring){ printf("%-*s %s", (int)slen, label, j_elem->valuestring); } label = ""; printf("\n"); } }else{ printf("%s\n", label); } } static void print_client(cJSON *j_response) { cJSON *j_data, *j_client, *jtmp; const int label_width = (int)strlen("Connections:"); 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; } const char *username; if(json_get_string(j_client, "username", &username, false) != MOSQ_ERR_SUCCESS){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } printf("%-*s %s\n", label_width, "Username:", username); const char *clientid; if(json_get_string(j_client, "clientid", &clientid, false) == MOSQ_ERR_SUCCESS){ printf("%-*s %s\n", label_width, "Clientid:", clientid); }else{ printf("Clientid:\n"); } jtmp = cJSON_GetObjectItem(j_client, "disabled"); if(jtmp && cJSON_IsBool(jtmp)){ printf("%-*s %s\n", label_width, "Disabled:", cJSON_IsTrue(jtmp)?"true":"false"); } print_json_array(cJSON_GetObjectItem(j_client, "roles"), label_width, "Roles:", "rolename", "priority", "-1"); print_json_array(cJSON_GetObjectItem(j_client, "groups"), label_width, "Groups:", "groupname", "priority", "-1"); print_json_array(cJSON_GetObjectItem(j_client, "connections"), label_width, "Connections:", "address", NULL, NULL); } static void print_group(cJSON *j_response) { cJSON *j_data, *j_group; int label_width = (int)strlen("Groupname:"); const char *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; } if(json_get_string(j_group, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } printf("Groupname: %s\n", groupname); print_json_array(cJSON_GetObjectItem(j_group, "roles"), label_width, "Roles:", "rolename", "priority", "-1"); print_json_array(cJSON_GetObjectItem(j_group, "clients"), label_width, "Clients:", "username", NULL, NULL); } 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; } const char *rolename; if(json_get_string(j_role, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } printf("Rolename: %s\n", rolename); j_array = cJSON_GetObjectItem(j_role, "acls"); if(j_array && cJSON_IsArray(j_array)){ first = true; cJSON_ArrayForEach(j_elem, j_array){ const char *acltype; if(json_get_string(j_elem, "acltype", &acltype, false) == MOSQ_ERR_SUCCESS){ if(first){ first = false; printf("ACLs: %-20s", acltype); }else{ printf(" %-20s", acltype); } jtmp = cJSON_GetObjectItem(j_elem, "allow"); if(jtmp && cJSON_IsBool(jtmp)){ printf(" : %s", cJSON_IsTrue(jtmp)?"allow":"deny "); } const char *topic; if(json_get_string(j_elem, "topic", &topic, false) == MOSQ_ERR_SUCCESS){ printf(" : %s", topic); } 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; const char *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; } if(json_get_string(j_group, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } printf("%s\n", groupname); } static void print_default_acl_access(cJSON *j_response) { cJSON *j_data, *j_acls, *j_acl; 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){ const char *acltype; bool allow; if(json_get_string(j_acl, "acltype", &acltype, false) != MOSQ_ERR_SUCCESS || json_get_bool(j_acl, "allow", &allow, false, false) != MOSQ_ERR_SUCCESS){ fprintf(stderr, "Error: Invalid response from server.\n"); return; } printf("%-20s : %s\n", acltype, allow?"allow":"deny"); } } static void dynsec__payload_callback(struct mosq_ctrl *ctrl, long payloadlen, const void *payload) { cJSON *tree, *j_responses, *j_response; const char *command, *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; } if(json_get_string(j_response, "command", &command, false) != MOSQ_ERR_SUCCESS){ fprintf(stderr, "Error: Payload missing data.\n"); cJSON_Delete(tree); return; } if(json_get_string(j_response, "error", &error, false) == MOSQ_ERR_SUCCESS){ fprintf(stderr, "%s: Error: %s.\n", command, error); }else{ if(!strcasecmp(command, "listClients")){ print_list(j_response, "clients", "username"); }else if(!strcasecmp(command, "listGroups")){ print_list(j_response, "groups", "groupname"); }else if(!strcasecmp(command, "listRoles")){ print_list(j_response, "roles", "rolename"); }else if(!strcasecmp(command, "getClient")){ print_client(j_response); }else if(!strcasecmp(command, "getGroup")){ print_group(j_response); }else if(!strcasecmp(command, "getRole")){ print_role(j_response); }else if(!strcasecmp(command, "getDefaultACLAccess")){ print_default_acl_access(j_response); }else if(!strcasecmp(command, "getAnonymousGroup")){ print_anonymous_group(j_response); }else{ /* fprintf(stderr, "%s: Success\n", command); */ } } cJSON_Delete(tree); } /* ################################################################ * # * # Default ACL access * # * ################################################################ */ static int dynsec__set_default_acl_access(int argc, char *argv[], cJSON *j_command) { char *acltype, *access; bool b_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")){ b_access = true; }else if(!strcasecmp(access, "deny")){ b_access = false; }else{ 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_AddBoolToObject(j_acl, "allow", b_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; if(mosquitto_pw_new(&pw, MOSQ_PW_DEFAULT) || mosquitto_pw_hash_encoded(pw, password)){ mosquitto_pw_cleanup(pw); return NULL; } j_client = cJSON_CreateObject(); if(j_client == NULL){ mosquitto_pw_cleanup(pw); return NULL; } if(cJSON_AddStringToObject(j_client, "username", username) == NULL || cJSON_AddStringToObject(j_client, "textName", "Dynsec admin user") == NULL ){ cJSON_Delete(j_client); mosquitto_pw_cleanup(pw); return NULL; } if(cJSON_AddStringToObject(j_client, "encoded_password", mosquitto_pw_get_encoded(pw)) == NULL){ cJSON_Delete(j_client); mosquitto_pw_cleanup(pw); return NULL; } mosquitto_pw_cleanup(pw); 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; } 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_PrintUnformatted(tree); cJSON_Delete(tree); #ifdef WIN32 fptr = mosquitto_fopen(filename, "wb", true); #else int fd = open(filename, O_CREAT | O_EXCL | O_WRONLY, 0640); if(fd < 0){ free(json_str); fprintf(stderr, "dynsec init: Unable to open '%s' for writing (%s).\n", filename, strerror(errno)); return -1; } fptr = fdopen(fd, "wb"); #endif 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]); }else if(ctrl->cfg.data_file && !strcasecmp(argv[0], "setClientPassword")){ return dynsec_client__file_set_password(argc-1, &argv[1], ctrl->cfg.data_file); } /* 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]); cJSON_Delete(j_tree); j_tree = NULL; 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; } }else{ cJSON_Delete(j_tree); } return rc; } ================================================ FILE: apps/mosquitto_ctrl/dynsec_client.c ================================================ /* Copyright (c) 2020-2021 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 "json_help.h" #include "dynamic_security.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= 2){ username = argv[0]; password = argv[1]; }else{ return MOSQ_ERR_INVAL; } for(i=2; 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; } } ================================================ FILE: apps/mosquitto_ctrl/dynsec_group.c ================================================ /* Copyright (c) 2020-2021 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 "json_help.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; } } ================================================ FILE: apps/mosquitto_ctrl/dynsec_role.c ================================================ /* Copyright (c) 2020-2021 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 #endif #include "mosquitto.h" #include "mosquitto_ctrl.h" #include "json_help.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; } } ================================================ FILE: apps/mosquitto_ctrl/example.c ================================================ /* Copyright (c) 2020-2021 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 #endif #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; } } ================================================ FILE: apps/mosquitto_ctrl/mosquitto_ctrl.c ================================================ /* Copyright (c) 2020-2021 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 #endif #include "lib_load.h" #include "mosquitto.h" #include "mosquitto_ctrl.h" #include "ctrl_shell_internal.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: broker 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){ #ifdef WITH_CTRL_SHELL ctrl_shell__main(NULL); #else print_usage(); #endif return 0; } memset(&ctrl, 0, sizeof(ctrl)); init_config(&ctrl.cfg); /* Shift program name out of args */ argc--; argv++; rc = ctrl_config_parse(&ctrl.cfg, &argc, &argv); if(rc){ client_config_cleanup(&ctrl.cfg); print_usage(); return rc; } #ifdef WITH_CTRL_SHELL if(argc == 0){ ctrl_shell__main(&ctrl.cfg); return 0; }else #endif { if(argc < 2){ print_usage(); client_config_cleanup(&ctrl.cfg); return 1; } } /* In built modules */ if(!strcasecmp(argv[0], "broker")){ l_ctrl_main = broker__main; }else 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){ if(ctrl.cfg.data_file == NULL){ rc = client_request_response(&ctrl); } }else if(rc == MOSQ_ERR_UNKNOWN){ /* Message printed already */ }else{ fprintf(stderr, "Error: %s.\n", mosquitto_strerror(rc)); } } free(ctrl.payload); free(ctrl.request_topic); free(ctrl.response_topic); client_config_cleanup(&ctrl.cfg); return rc; } ================================================ FILE: apps/mosquitto_ctrl/mosquitto_ctrl.h ================================================ /* Copyright (c) 2020-2021 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 #ifndef __cplusplus #include #endif #include "mosquitto.h" #define PORT_UNDEFINED -1 #define PORT_UNIX 0 #ifdef __cplusplus extern "C" { #endif 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; 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; bool tls_use_os_certs; char *keyform; char *psk; char *psk_identity; bool verbose; /* sub */ unsigned int timeout; /* sub */ char *socks5_host; int socks5_port; char *socks5_username; char *socks5_password; char *data_file; bool no_colour; }; 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); void broker__print_usage(void); int broker__main(int argc, char *argv[], struct mosq_ctrl *ctrl); 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__file_set_password(int argc, char *argv[], const char *file); 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); #ifdef __cplusplus } #endif #endif ================================================ FILE: apps/mosquitto_ctrl/options.c ================================================ /* Copyright (c) 2014-2021 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 "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 free(cfg->data_file); } int ctrl_config_parse(struct mosq_config *cfg, int *argc, char **argv[]) { int rc; init_config(cfg); /* Deal with real argc/argv */ rc = client_config_line_proc(cfg, argc, argv); if(rc){ return rc; } /* Load options from config file - this must be after `-o` has been processed */ rc = client_config_load(cfg); 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], "-f")){ if((*argc) == 1){ fprintf(stderr, "Error: -f argument given but no data file specified.\n\n"); return 1; }else{ cfg->data_file = strdup(argv[1]); } argv++; (*argc)--; }else if(!strcmp(argv[0], "--help")){ return 1; }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; cfg->tls_use_os_certs = true; }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); } if(strlen(url) == 0){ fprintf(stderr, "Error: Empty username in URL.\n"); return 1; } cfg->username = strdup(url); url = tmp; } cfg->host = url; tmp = strchr(url, ':'); if(tmp){ *tmp++ = 0; if(strlen(tmp) == 0){ cfg->host = NULL; /* Prevent free of non-heap memory later */ fprintf(stderr, "Error: Empty port in URL.\n"); return 1; } 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-use-os-certs")){ cfg->tls_use_os_certs = true; }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 1; }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, sizeof(line), fptr)){ if(line[0] == '#'){ /* Comments */ continue; } 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"); return 1; } cfg->password = strdup(password); if(cfg->password == NULL){ fprintf(stderr, "Error: Out of memory.\n"); 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"); return 1; } #ifdef WITH_TLS 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"); return 1; } 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)); } return 1; } # ifdef FINAL_WITH_TLS_PSK }else if(cfg->psk){ if(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 }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); } mosquitto_tls_insecure_set(mosq, cfg->insecure); 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); 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"); 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"); return 1; } 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"); 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){ 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)); } 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){ 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)){ fprintf(stderr, "Error: Invalid URL encoding in username.\n"); goto cleanup; } if(mosquitto__urldecode(password)){ fprintf(stderr, "Error: Invalid URL encoding in password.\n"); 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 ================================================ FILE: apps/mosquitto_ctrl/test/Makefile ================================================ R=../../.. include ${R}/config.mk .PHONY: all check test-compile test test-broker test-lib clean coverage LOCAL_CPPFLAGS+= \ -DWITH_THREADING \ -DWITH_TLS \ -I../ \ -I${R}/include \ -I${R} \ -I${R}/lib \ -I${R}/lib/mock \ -I${R}/test/mock LOCAL_CXXFLAGS+=-std=c++20 -Wall -ggdb -D TEST_SOURCE_DIR='"$(realpath .)"' LOCAL_LDFLAGS+= LOCAL_LIBADD+=-lcjson -lgmock -lgtest_main -lgtest ${R}/libcommon/libmosquitto_common.a OBJS = \ ../ctrl_shell_broker.o \ ../ctrl_shell.o \ ../ctrl_shell_client.o \ ../ctrl_shell_completion_tree.o \ ../ctrl_shell_dynsec.o \ ../ctrl_shell_ha.o \ ../ctrl_shell_inspect.o \ ../ctrl_shell_license.o \ ../ctrl_shell_post_connect.o \ ../ctrl_shell_pre_connect.o \ ../ctrl_shell_printf.o \ ../ctrl_shell_topictree.o LIBMOSQ_MOCKS = \ ${R}/lib/mock/libmosquitto_mock.o \ ${R}/lib/mock/actions_publish_mock.o \ ${R}/lib/mock/actions_subscribe_mock.o \ ${R}/lib/mock/callbacks_mock.o \ ${R}/lib/mock/connect_mock.o \ ${R}/lib/mock/loop_mock.o \ ${R}/lib/mock/options_mock.o \ ${R}/lib/mock/thread_mosq_mock.o LIB_OBJS = \ ${OBJS} \ json_help.o \ ctrl_shell_mock.o \ ${R}/test/mock/editline_mock.o \ ${R}/test/mock/pthread_mock.o \ ${LIBMOSQ_MOCKS} TEST_OBJS = \ ctrl_shell_broker_test.o \ ctrl_shell_dynsec_test.o \ ctrl_shell_help_test.o \ ctrl_shell_pre_connect_test.o ALL_TESTS = \ ctrl_shell_broker_test \ ctrl_shell_dynsec_test \ ctrl_shell_help_test \ ctrl_shell_pre_connect_test all : test-compile check : test # DEPS ${LIBMOSQ_MOCKS}: $(MAKE) -C ${R}/lib ${OBJS} : $(MAKE) -C ../ json_help.o : ${R}/common/json_help.c ${R}/common/json_help.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ # MOCKS ctrl_shell_mock.o : ctrl_shell_mock.cpp ctrl_shell_mock.hpp $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_CXXFLAGS) -c $< -o $@ ${R}/test/mock/editline_mock.o : ${R}/test/mock/editline_mock.cpp ${R}/test/mock/editline_mock.hpp $(MAKE) -C ${R}/test/mock test-compile ${R}/test/mock/pthread_mock.o : ${R}/test/mock/pthread_mock.cpp ${R}/test/mock/pthread_mock.hpp $(MAKE) -C ${R}/test/mock test-compile # TESTS ${TEST_OBJS} : %.o: %.cpp $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_CXXFLAGS) -c $< -o $@ ctrl_shell_broker_test : ctrl_shell_broker_test.o ${LIB_OBJS} $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) ctrl_shell_dynsec_test : ctrl_shell_dynsec_test.o ${LIB_OBJS} $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) ctrl_shell_help_test : ctrl_shell_help_test.o ${LIB_OBJS} $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) ctrl_shell_pre_connect_test : ctrl_shell_pre_connect_test.o ${LIB_OBJS} $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) test-compile : $(ALL_TESTS) test : test-compile ./ctrl_shell_help_test ./ctrl_shell_dynsec_test clean : -rm -rf $(ALL_TESTS) -rm -rf *.o *.gcda *.gcno coverage.info out/ coverage : lcov --capture --directory . --output-file coverage.info genhtml coverage.info --output-directory out install: uninstall: ================================================ FILE: apps/mosquitto_passwd/CMakeLists.txt ================================================ if(WITH_TLS) add_executable(mosquitto_passwd mosquitto_passwd.c get_password.c get_password.h ) target_include_directories(mosquitto_passwd PRIVATE "${mosquitto_SOURCE_DIR}" "${mosquitto_SOURCE_DIR}/common" "${mosquitto_SOURCE_DIR}/include" "${mosquitto_SOURCE_DIR}/lib" "${mosquitto_SOURCE_DIR}/src" ) target_link_libraries(mosquitto_passwd PRIVATE common-options libmosquitto_common OpenSSL::SSL ) install(TARGETS mosquitto_passwd RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ) endif() ================================================ FILE: apps/mosquitto_passwd/Makefile ================================================ R=../.. include ${R}/config.mk LOCAL_CFLAGS+= LOCAL_CPPFLAGS+=-I${R}/lib LOCAL_LDFLAGS+= LOCAL_LDADD+=-lcrypto ${LIBMOSQ_COMMON} .PHONY: all install uninstall clean reallyclean OBJS= \ mosquitto_passwd.o \ get_password.o \ OBJS_EXTERNAL= ifeq ($(WITH_TLS),yes) ifeq ($(WITH_FUZZING),yes) all : mosquitto_passwd.a else all : mosquitto_passwd endif else all: endif mosquitto_passwd : ${OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}${CC} ${LOCAL_LDFLAGS} $^ -o $@ $(LOCAL_LDADD) mosquitto_passwd.a : ${OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}$(AR) cr $@ $^ ${OBJS} : %.o: %.c ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ install : all ifeq ($(WITH_TLS),yes) $(INSTALL) -d "${DESTDIR}$(prefix)/bin" $(INSTALL) ${STRIP_OPTS} mosquitto_passwd "${DESTDIR}${prefix}/bin/mosquitto_passwd" endif uninstall : -rm -f "${DESTDIR}${prefix}/bin/mosquitto_passwd" clean : -rm -f *.o *.a mosquitto_passwd *.gcda *.gcno reallyclean : clean -rm -rf *.orig *.db ================================================ FILE: apps/mosquitto_passwd/get_password.c ================================================ /* Copyright (c) 2012-2021 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 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; char *rs; memset(s, 0, (size_t)len); tcgetattr(0, &ts_quiet); ts_quiet.c_lflag &= (unsigned int)(~(ECHO | ICANON)); tcsetattr(0, TCSANOW, &ts_quiet); rs = fgets(s, len, stdin); get_password__reset_term(); if(!rs){ return 1; }else{ while(strlen(s) > 0 && (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; } ================================================ FILE: apps/mosquitto_passwd/get_password.h ================================================ #ifndef GET_PASSWORD_H #define GET_PASSWORD_H /* Copyright (c) 2012-2021 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 ================================================ FILE: apps/mosquitto_passwd/mosquitto_passwd.c ================================================ /* Copyright (c) 2012-2021 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 "mosquitto.h" #include "get_password.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 struct cb_helper { const char *line; const char *username; const char *password; int iterations; bool found; }; static enum mosquitto_pwhash_type hashtype = MOSQ_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); i 0){ mosquitto_pw_set_param(pw, MOSQ_PW_PARAM_ITERATIONS, iterations); } rc = mosquitto_pw_hash_encoded(pw, password); if(rc){ mosquitto_pw_cleanup(pw); fprintf(stderr, "Error: Unable to hash password.\n"); return rc; } fprintf(fptr, "%s:%s\n", username, mosquitto_pw_get_encoded(pw)); mosquitto_pw_cleanup(pw); return rc; } static int pwfile_iterate(FILE *fptr, FILE *ftmp, int (*cb)(FILE *, FILE *, const char *, const char *, const char *, struct cb_helper *), struct cb_helper *helper) { char *buf; int buflen = 1024; char *lbuf; int lbuflen; int rc = 1; int line = 0; char *username, *password; buf = malloc((size_t)buflen); if(buf == NULL){ fprintf(stderr, "Error: Out of memory.\n"); return 1; } lbuflen = buflen; lbuf = malloc((size_t)lbuflen); if(lbuf == NULL){ fprintf(stderr, "Error: Out of memory.\n"); free(buf); return 1; } while(!feof(fptr) && mosquitto_fgets(&buf, &buflen, fptr)){ if(lbuflen != buflen){ free(lbuf); lbuflen = buflen; lbuf = malloc((size_t)lbuflen); if(lbuf == NULL){ fprintf(stderr, "Error: Out of memory.\n"); free(buf); return 1; } } memcpy(lbuf, buf, (size_t)buflen); line++; username = strtok(buf, ":"); password = strtok(NULL, ":"); if(username && password){ username = mosquitto_trimblanks(username); password = mosquitto_trimblanks(password); } if(username == NULL || strlen(username) == 0 || password == NULL || strlen(password) == 0){ fprintf(stderr, "Error: Corrupt password file at line %d.\n", line); free(lbuf); free(buf); return 1; } rc = cb(fptr, ftmp, username, password, lbuf, helper); if(rc){ break; } } free(lbuf); free(buf); return rc; } /* ====================================================================== * Delete a user from the password file * ====================================================================== */ static int delete_pwuser_cb(FILE *fptr, FILE *ftmp, const char *username, const char *password, const char *line, struct cb_helper *helper) { UNUSED(fptr); UNUSED(password); UNUSED(line); if(strcmp(username, helper->username)){ /* If this isn't the username to delete, write it to the new file */ fprintf(ftmp, "%s", line); }else{ /* Don't write the matching username to the file. */ helper->found = true; } return 0; } 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, -1); } } 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(helper->found || 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){ printf("Updating password for user %s\n", username); return rc; }else{ printf("Adding password for user %s\n", username); 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(char *backup_file, FILE *fptr) { FILE *fbackup; #ifdef WIN32 fbackup = mosquitto_fopen(backup_file, "wt", true); #else int fd; umask(077); fd = mkstemp(backup_file); if(fd < 0){ fprintf(stderr, "Error creating backup password file \"%s\", not continuing.\n", backup_file); return 1; } fbackup = fdopen(fd, "wt"); #endif 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); #ifndef WITH_FUZZING exit(0); #endif } 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{ if(!strcmp(argv[idx], "-")){ use_stdout = true; }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{ if(!strcmp(argv[idx], "-")){ use_stdout = true; }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; } if(!use_stdout){ #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; } if(use_stdout){ fptr = stdout; }else{ fptr = mosquitto_fopen(password_file, "wt", true); 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); } if(!use_stdout){ printf("Adding password for user %s\n", username); } rc = output_new_password(fptr, username, password_cmd, iterations); fclose(fptr); return rc; }else{ fptr = mosquitto_fopen(password_file, "r+t", true); if(!fptr){ fprintf(stderr, "Error: Unable to open password file %s. %s.\n", password_file, strerror(errno)); free(password_file); return 1; } size_t len = strlen(password_file) + strlen(".backup.XXXXXX") + 1; backup_file = malloc(len); if(!backup_file){ fprintf(stderr, "Error: Out of memory.\n"); free(password_file); return 1; } snprintf(backup_file, len, "%s.backup.XXXXXX", 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 == 0){ /* 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)){ fprintf(stderr, "Error occurred updating password file.\n"); fprintf(stderr, "Password file may be corrupt, check the backup file: %s.\n", backup_file); rc = 1; } fclose(fptr); fclose(ftmp); if(rc == 0){ /* 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; } ================================================ FILE: apps/mosquitto_signal/CMakeLists.txt ================================================ set(SRC mosquitto_signal.c ) if(WIN32) set(SRC ${SRC} signal_windows.c) else() set(SRC ${SRC} signal_unix.c) endif() add_executable(mosquitto_signal ${SRC}) target_include_directories(mosquitto_signal PRIVATE "${mosquitto_SOURCE_DIR}" "${mosquitto_SOURCE_DIR}/include" "${mosquitto_SOURCE_DIR}/lib" "${mosquitto_SOURCE_DIR}/src" ) install(TARGETS mosquitto_signal RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ) ================================================ FILE: apps/mosquitto_signal/Makefile ================================================ R=../.. include ${R}/config.mk LOCAL_CFLAGS+= LOCAL_CPPFLAGS+=-I${R}/lib LOCAL_LDFLAGS+= LOCAL_LDADD+= .PHONY: all install uninstall clean reallyclean OBJS= \ mosquitto_signal.o \ signal_unix.o \ all : mosquitto_signal mosquitto_signal : ${OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}${CC} ${LOCAL_LDFLAGS} $^ -o $@ $(LOCAL_LDADD) ${OBJS} : %.o: %.c ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ install : all ifeq ($(WITH_TLS),yes) $(INSTALL) -d "${DESTDIR}$(prefix)/bin" $(INSTALL) ${STRIP_OPTS} mosquitto_signal "${DESTDIR}${prefix}/bin/mosquitto_signal" endif uninstall : -rm -f "${DESTDIR}${prefix}/bin/mosquitto_signal" clean : -rm -f *.o *.a mosquitto_signal *.gcda *.gcno reallyclean : clean -rm -rf *.orig *.db ================================================ FILE: apps/mosquitto_signal/mosquitto_signal.c ================================================ /* Copyright (c) 2024 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 "mosquitto_signal.h" static void print_usage(void) { printf("mosquitto_signal is a tool for sending control signals to mosquitto.\n"); printf(" it is primarily useful on Windows.\n"); printf(" on other systems the `kill` tool can be used.\n\n"); printf("Usage: mosquitto_signal {-a | -p } \n"); printf(" mosquitto_signal --help\n\n"); #ifdef WIN32 printf(" -a : signal all processes that match the name 'mosquitto.exe'.\n"); #else printf(" -a : signal all processes that match the name 'mosquitto'.\n"); #endif printf(" -p : specify a process ID to signal\n\n"); printf(" may be one of:\n"); printf(" config-reload - reload the configuration file, if in use.\n"); printf(" log-rotate - if using `file` logging ask the broker to close and reopen the\n"); printf(" log file.\n"); printf(" shutdown - quit the broker.\n"); printf(" tree-print - (debug) print out subscription and retain tree information to\n"); printf(" stdout.\n"); printf(" xtreport - (debug) write internal data to xtmosquitto.kcg..\n"); printf("\nSee https://mosquitto.org/ for more information.\n\n"); } int main(int argc, char *argv[]) { int idx; int pid = -2; enum mosq_signal msig = 0; if(argc == 1){ print_usage(); return 1; } idx = 1; for(idx = 1; idx < argc; idx++){ if(!strcmp(argv[idx], "--help")){ print_usage(); return 1; }else if(!strcmp(argv[idx], "-a")){ pid = -1; }else if(!strcmp(argv[idx], "-p")){ if(idx+1 == argc){ fprintf(stderr, "Error: -p argument given but process ID missing.\n"); return 1; } pid = atoi(argv[idx+1]); if(pid < 1){ fprintf(stderr, "Error: Process ID must be >0.\n"); return 1; } idx++; }else{ break; } } if(pid == -2){ fprintf(stderr, "Error: One of -a or -p must be used.\n"); return 1; } if(idx == argc){ fprintf(stderr, "Error: No signal given.\n"); return 1; } if(!strcmp(argv[idx], "config-reload")){ msig = MSIG_CONFIG_RELOAD; }else if(!strcmp(argv[idx], "log-rotate")){ msig = MSIG_LOG_ROTATE; }else if(!strcmp(argv[idx], "shutdown")){ msig = MSIG_SHUTDOWN; }else if(!strcmp(argv[idx], "tree-print")){ msig = MSIG_TREE_PRINT; }else if(!strcmp(argv[idx], "xtreport")){ msig = MSIG_XTREPORT; }else{ fprintf(stderr, "Error: Unknown signal '%s'.\n", argv[idx]); return 1; } send_signal(pid, msig); return 0; } ================================================ FILE: apps/mosquitto_signal/mosquitto_signal.h ================================================ #ifndef MOSQUITTO_SIGNAL_H #define MOSQUITTO_SIGNAL_H enum mosq_signal { MSIG_CONFIG_RELOAD, MSIG_LOG_ROTATE, MSIG_SHUTDOWN, MSIG_TREE_PRINT, MSIG_XTREPORT, }; void signal_all(int sig); void send_signal(int pid, enum mosq_signal msig); #endif ================================================ FILE: apps/mosquitto_signal/signal_unix.c ================================================ /* Copyright (c) 2024 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 "mosquitto_signal.h" #ifndef PATH_MAX # define PATH_MAX 4096 #endif void signal_all(int sig) { DIR *dir; struct dirent *d; char pathbuf[PATH_MAX+1]; char cmdline[256]; const char *cmd; FILE *fptr; pid_t pid; dir = opendir("/proc"); if(dir == NULL){ fprintf(stderr, "Error reading /proc: %s.\n", strerror(errno)); return; } while((d = readdir(dir))){ #ifdef DT_DIR if(d->d_type == DT_DIR) #endif { pid = atoi(d->d_name); if(pid > 0){ snprintf(pathbuf, sizeof(pathbuf), "/proc/%s/cmdline", d->d_name); fptr = fopen(pathbuf, "r"); if(fptr){ if(fgets(cmdline, sizeof(cmdline), fptr)){ cmd = strrchr(cmdline, '/'); if(cmd){ cmd += 1; }else{ cmd = cmdline; } if(!strcmp(cmd, "mosquitto")){ if(kill(pid, sig) < 0){ fprintf(stderr, "Unable to signal process %d: %s\n", pid, strerror(errno)); } } } fclose(fptr); } } } } closedir(dir); } void send_signal(int pid, enum mosq_signal msig) { int sig; switch(msig){ case MSIG_CONFIG_RELOAD: sig = SIGHUP; break; case MSIG_LOG_ROTATE: sig = SIGHUP; break; case MSIG_SHUTDOWN: sig = SIGINT; break; case MSIG_TREE_PRINT: sig = SIGUSR2; break; #ifdef SIGRTMIN case MSIG_XTREPORT: sig = SIGRTMIN; break; #endif default: return; } if(pid > 0){ if(kill(pid, sig) != 0){ fprintf(stderr, "Error sending signal to process %d: %s\n", pid, strerror(errno)); } }else{ signal_all(sig); } } ================================================ FILE: apps/mosquitto_signal/signal_windows.c ================================================ /* Copyright (c) 2024 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 WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN #endif #include #include #include #include #include #include #include #include #include "mosquitto_signal.h" #undef WITH_TLS #include "config.h" static const char *msig_to_string(enum mosq_sig msig) { switch(msig){ case MSIG_CONFIG_RELOAD: return "reload"; case MSIG_LOG_ROTATE: return "log_rotate"; case MSIG_SHUTDOWN: return "shutdown"; case MSIG_TREE_PRINT: return "tree_print"; case MSIG_XTREPORT: return "xtreport"; default: return ""; } } void signal_all(enum mosq_signal msig) { DWORD processes[2048], cbneeded, count; int pid; if(!EnumProcesses(processes, sizeof(processes), &cbneeded)){ fprintf(stderr, "Error enumerating processes.\n"); return; } count = cbneeded / sizeof(DWORD); for(DWORD 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 #include #ifndef WIN32 #include #include #else #include #include #define snprintf sprintf_s #define strncasecmp _strnicmp #endif #include "mosquitto.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 %s given in --property argument.\n\n", cmdname); return MOSQ_ERR_INVAL; } propname = argv[(*idx)+1]; if(mosquitto_string_to_property_info(propname, &identifier, &type)){ fprintf(stderr, "Error: Invalid property name %s given in --property argument.\n\n", propname); 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: 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; } ================================================ FILE: client/client_shared.c ================================================ /* Copyright (c) 2014-2021 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 # include #else # include # include # define snprintf sprintf_s # define strncasecmp _strnicmp #endif #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[]); #ifdef WITH_TLS static void tls_keylog_callback(const SSL *ssl, const char *line); static int tls_ex_index_cfg = -1; #endif const char hexseplist[32] = { '!', '"', '#', '$', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~', ' ', }; 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; } } } /* Hex field separator character */ for(size_t j=0; jport = 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. */ cfg->transport = MOSQ_T_TCP; } void client_config_cleanup(struct mosq_config *cfg) { int i; free(cfg->id); free(cfg->id_prefix); free(cfg->host); free(cfg->file_input); mosquitto_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); free(cfg->options_file); } /* Find if there is "-o" in the options */ static int client_config_options_file(struct mosq_config *cfg, int argc, char *argv[]) { int i; for(i=1; ioptions_file){ fprintf(stderr, "Error: Duplicate -o argument given.\n\n"); return 1; } if(i==argc-1){ fprintf(stderr, "Error: -o argument given but no options file specified.\n\n"); return 1; }else{ cfg->options_file = strdup(argv[i+1]); } } } return 0; } 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); if(client_config_options_file(cfg, argc, argv)){ return 1; } if(cfg->options_file == NULL){ /* 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(cfg->options_file){ fptr = fopen(cfg->options_file, "rt"); }else if(loc){ fptr = fopen(loc, "rt"); free(loc); loc = NULL; }else{ fptr = NULL; } if(fptr){ while(fgets(line, 1024, fptr)){ if(line[0] == '#'){ /* Comments */ continue; } 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); } /* 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 && cfg->unsub_topic_count == 0){ fprintf(stderr, "Error: You must specify a topic to subscribe to (-t) or unsubscribe from (-U).\n"); return 1; } } if(!cfg->host){ cfg->host = strdup("localhost"); if(!cfg->host){ err_printf(cfg, "Error: Out of memory.\n"); 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 if(!strncasecmp(url, "ws://", 5)){ url += 5; cfg->port = 1883; cfg->transport = MOSQ_T_WEBSOCKETS; }else if(!strncasecmp(url, "wss://", 6)){ #ifdef WITH_TLS url += 6; cfg->port = 8883; cfg->tls_use_os_certs = true; cfg->transport = MOSQ_T_WEBSOCKETS; #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], "--latency")){ if(pub_or_sub != CLIENT_RR){ goto unknown_option; } cfg->measure_latency = true; cfg->tcp_nodelay = true; /* Remove influence of nagle */ }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 = mosquitto_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], "--message-rate")){ if(pub_or_sub != CLIENT_SUB){ goto unknown_option; } cfg->message_rate = true; }else if(!strcmp(argv[i], "--nodelay")){ cfg->tcp_nodelay = true; }else if(!strcmp(argv[i], "--no-tls")){ cfg->no_tls = 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], "-o")){ /* Already handled */ i++; }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], "--retain-handling")){ if(pub_or_sub == CLIENT_PUB){ goto unknown_option; } if(i==argc-1){ fprintf(stderr, "Error: --retain-handling argument given but no option specified.\n\n"); return 1; }else{ if(!strcmp(argv[i+1], "always")){ MQTT_SUB_OPT_SET_RETAIN_HANDLING(cfg->sub_opts, MQTT_SUB_OPT_SEND_RETAIN_ALWAYS); }else if(!strcmp(argv[i+1], "new")){ MQTT_SUB_OPT_SET_RETAIN_HANDLING(cfg->sub_opts, MQTT_SUB_OPT_SEND_RETAIN_NEW); }else if(!strcmp(argv[i+1], "never")){ MQTT_SUB_OPT_SET_RETAIN_HANDLING(cfg->sub_opts, MQTT_SUB_OPT_SEND_RETAIN_NEVER); }else{ fprintf(stderr, "Error: Unknown value '%s' for --retain-handling.\n\n", argv[i+1]); return 1; } } i++; }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++; }else if(!strcmp(argv[i], "--tls-keylog")){ if(i==argc-1){ fprintf(stderr, "Error: --tls-keylog argument given but no file specified.\n\n"); return 1; }else{ cfg->tls_keylog = 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], "-w") || !strcmp(argv[i], "--watch")){ if(pub_or_sub != CLIENT_SUB){ goto unknown_option; } #ifdef WIN32 fprintf(stderr, "Error: --watch not supported on Windows.\n\n"); return 1; #else cfg->watch = true; #endif }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], "--ws")){ cfg->transport = MOSQ_T_WEBSOCKETS; }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; } } cfg->protocol_version = MQTT_PROTOCOL_V5; } i++; }else{ goto unknown_option; } } return MOSQ_ERR_SUCCESS; unknown_option: fprintf(stderr, "Error: Unknown option '%s'.\n", argv[i]); return 1; } #ifdef WITH_TLS static int client_tls_opts_set(struct mosquitto *mosq, struct mosq_config *cfg) { int rc; if(cfg->no_tls){ return MOSQ_ERR_SUCCESS; } if(cfg->tls_keylog){ if(tls_ex_index_cfg == -1){ tls_ex_index_cfg = SSL_CTX_get_ex_new_index(0, "client config", NULL, NULL, NULL); } cfg->ssl_ctx = SSL_CTX_new(TLS_client_method()); if(!cfg->ssl_ctx){ err_printf(cfg, "Error: Unable to create SSL_CTX.\n"); return 1; } if(!SSL_CTX_set_ex_data(cfg->ssl_ctx, tls_ex_index_cfg, cfg)){ err_printf(cfg, "Error: Unable to set SSL_CTX ex data.\n"); return 1; } mosquitto_void_option(mosq, MOSQ_OPT_SSL_CTX, cfg->ssl_ctx); mosquitto_int_option(mosq, MOSQ_OPT_SSL_CTX_WITH_DEFAULTS, 1); SSL_CTX_set_keylog_callback(cfg->ssl_ctx, tls_keylog_callback); } 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)); } 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"); 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"); 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); 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"); 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"); 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"); return 1; } if((cfg->tls_version || cfg->ciphers) && mosquitto_tls_opts_set(mosq, !cfg->insecure, cfg->tls_version, cfg->ciphers)){ err_printf(cfg, "Error: Problem setting TLS options, check the options are valid.\n"); return 1; } return MOSQ_ERR_SUCCESS; } #endif int client_opts_set(struct mosquitto *mosq, struct mosq_config *cfg) { #if defined(WITH_SOCKS) int rc; #endif mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, cfg->protocol_version); mosquitto_int_option(mosq, MOSQ_OPT_TRANSPORT, cfg->transport); 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"); 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"); return 1; } #ifdef WITH_TLS if(client_tls_opts_set(mosq, cfg)){ 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){ 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 clientid_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"); 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; #ifndef WIN32 signal(SIGPIPE, SIG_IGN); #endif 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{ 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); 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); } #ifdef WITH_TLS static void tls_keylog_callback(const SSL *ssl, const char *line) { struct mosq_config *cfg; FILE *fptr; UNUSED(ssl); cfg = SSL_CTX_get_ex_data(SSL_get_SSL_CTX(ssl), tls_ex_index_cfg); if(cfg && cfg->tls_keylog){ fptr = fopen(cfg->tls_keylog, "at"); if(fptr){ fprintf(fptr, "%s\n", line); fclose(fptr); } } } #endif ================================================ FILE: client/client_shared.h ================================================ /* Copyright (c) 2014-2021 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_SHARED_H #define CLIENT_SHARED_H #include #ifdef WIN32 # include #else # include #endif #ifdef WITH_TLS # 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; char *tls_keylog; SSL_CTX *ssl_ctx; # 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 */ int transport; #ifndef WIN32 bool watch; /* sub */ #endif #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; char *response_topic; /* rr */ char *options_file; bool have_topic_alias; /* pub */ bool tcp_nodelay; bool no_tls; bool message_rate; /* sub */ bool measure_latency; /* rr */ }; extern const char hexseplist[32]; 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 clientid_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 ================================================ FILE: client/pub_client.c ================================================ /* Copyright (c) 2009-2021 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 "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){ first_publish = true; 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; rc = mosquitto_loop_start(mosq); if(rc != MOSQ_ERR_SUCCESS){ return rc; } 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 && disconnect_sent == false); 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] [--ws] -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(" [--no-tls]\n"); 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(" [-o options-file]\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(" ws(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(" -o : provide options in a file rather than on the command line.\n"); printf(" See the Options section of https://mosquitto.org/man/mosquitto_pub-1.html\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"); printf(" --ws : connect using WebSockets.\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 or tlsv1.2.\n"); printf(" Defaults to tlsv1.2 if available.\n"); printf(" --insecure : do not verify the the server certificate. Using this option means that\n"); printf(" you cannot be sure that the remote host is the server you wish to connect\n"); printf(" 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(clientid_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_destroy(mosq); mosquitto_lib_cleanup(); client_config_cleanup(&cfg); pub_shared_cleanup(); return 1; } ================================================ FILE: client/pub_shared.c ================================================ /* Copyright (c) 2009-2021 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 "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 = mosquitto_realloc(cfg.message, pos+rlen); if(!aux_message){ err_printf(&cfg, "Error: Out of memory.\n"); mosquitto_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); mosquitto_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 buflen; char *buf; cfg.pub_mode = MSGMODE_FILE; int rc = mosquitto_read_file(filename, false, &buf, &buflen); if(rc){ err_printf(&cfg, "Error: Unable to read file \"%s\": %s.\n", filename, mosquitto_strerror(rc)); return 1; } if(buflen > MQTT_MAX_PAYLOAD){ err_printf(&cfg, "Error: File must be less than %u bytes.\n\n", MQTT_MAX_PAYLOAD); mosquitto_FREE(buf); return 1; }else if(buflen == 0){ cfg.message = NULL; cfg.msglen = 0; return 0; } cfg.msglen = (int )buflen; cfg.message = buf; return 0; } ================================================ FILE: client/pub_shared.h ================================================ /* Copyright (c) 2009-2021 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 ================================================ FILE: client/pub_test_properties ================================================ LD_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 ================================================ FILE: client/rr_client.c ================================================ /* Copyright (c) 2009-2021 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 "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; static struct timespec publish_send_time; static struct timespec publish_recv_time; #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) { mosquitto_time_ns(&publish_send_time.tv_sec, &publish_send_time.tv_nsec); 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); if(process_messages == false){ return; } if(message->retain && cfg.no_retain){ return; } mosquitto_time_ns(&publish_recv_time.tv_sec, &publish_recv_time.tv_nsec); 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; } } 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, cfg.sub_opts, cfg.subscribe_props); }else{ client_state = rr_s_disconnect; if(result){ 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); } } 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(" {-f file | -l | -n | -m message}\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(" [--no-tls]\n"); 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(" [-o options-file]\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(" ws(s)://[username[:password]@]host[:port]/topic\n"); printf(" -N : do not add an end of line character when printing the payload.\n"); printf(" -o : provide options in a file rather than on the command line.\n"); printf(" See the Options section of https://mosquitto.org/man/mosquitto_pub-1.html\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"); printf(" --ws : connect using WebSockets.\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 or tlsv1.2.\n"); printf(" Defaults to tlsv1.2 if available.\n"); printf(" --insecure : do not verify the the server certificate. Using this option means that\n"); printf(" you cannot be sure that the remote host is the server you wish to connect\n"); printf(" 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"); } static void report_latency(void) { if(cfg.measure_latency){ time_t s = publish_recv_time.tv_sec - publish_send_time.tv_sec; long ns = publish_recv_time.tv_nsec - publish_send_time.tv_nsec; if(ns < 0){ s--; ns += 1000000000; } if(s > 0){ printf("Latency: %ld.%09ld\n", s, ns); }else{ if(ns < 1000){ printf("Latency: %ldns\n", ns); }else if(ns < 1000000){ printf("Latency: %fµs\n", ((double)ns)/1000.0); }else{ printf("Latency: %fms\n", ((double)ns)/1000000.0); } } } } 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.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 || !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; } output_init(&cfg); if(clientid_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); report_latency(); 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; } ================================================ FILE: client/sub_client.c ================================================ /* Copyright (c) 2009-2021 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 "client_shared.h" #include "sub_client_output.h" struct mosq_config cfg; static bool run = true; bool process_messages = true; int msg_count = 0; int message_rate_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; #ifdef WIN32 static HANDLE timeout_h = NULL; #endif #ifdef WIN32 void CALLBACK timeout_cb(PVOID lpParameter, BOOLEAN TimerOrWaitFired) { UNUSED(lpParameter); UNUSED(TimerOrWaitFired); if(connack_received){ process_messages = false; mosquitto_disconnect_v5(g_mosq, MQTT_RC_DISCONNECT_WITH_WILL_MSG, cfg.disconnect_props); }else{ exit(-1); } timed_out = true; (void)DeleteTimerQueueTimer(NULL, timeout_h, NULL); timeout_h = NULL; } #else 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); } run = false; } 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); message_rate_msg_count++; 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; } ================================================ FILE: client/sub_client_output.c ================================================ /* Copyright (c) 2009-2021 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 # include # include #endif #include #include #include #include #include #include #include #ifndef WIN32 #include #else #include #include #define snprintf sprintf_s #endif #undef uthash_malloc #undef uthash_free #include #ifdef __APPLE__ # include #endif #include #include "client_shared.h" #include "sub_client_output.h" extern struct mosq_config cfg; struct fieldoptions { int field_width; int precision; char hexsepchar; char align; char pad; }; struct watch_topic { UT_hash_handle hh; char *topic; int line; }; static int watch_max = 2; static struct watch_topic *watch_items = NULL; 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 const signed char nibble_to_hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; static void hexsep(int xpos, int precision, char sepchar) { if(precision > 0 && xpos%precision == (precision-1)){ putchar(sepchar); } } static void write_payload(const unsigned char *payload, int payloadlen, int hex, struct fieldoptions *fopts) { int i; int padlen; if(fopts->field_width > 0){ if(payloadlen > fopts->field_width){ payloadlen = fopts->field_width; } if(hex > 0){ padlen = fopts->field_width - payloadlen*2; }else{ padlen = fopts->field_width - payloadlen; } }else{ padlen = fopts->field_width - payloadlen; } int xpos = 0; if(fopts->align != '-'){ for(i=0; ipad); if(hex > 0){ hexsep(xpos, fopts->precision, fopts->hexsepchar); } xpos++; } } if(hex == 0){ (void)fwrite(payload, 1, (size_t )payloadlen, stdout); }else{ signed char casemod = (hex == 1?0x20:0x00); for(i=0; i> 4)] | casemod); hexsep(xpos, fopts->precision, fopts->hexsepchar); xpos += 1; putchar(nibble_to_hex[(payload[i] & 0x0F)] | casemod); if(i < payloadlen-1){ hexsep(xpos, fopts->precision, fopts->hexsepchar); xpos += 1; } } } if(fopts->align == '-'){ printf("%*s", padlen, ""); } } 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_props = NULL, *user_json; 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_TOPIC_ALIAS, &i16value, false); tmp = cJSON_CreateNumber(i16value); break; case MQTT_PROP_USER_PROPERTY: if(user_props == NULL){ user_props = cJSON_CreateArray(); if(user_props == NULL){ return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(prop_json, "user-properties", user_props); } user_json = cJSON_CreateObject(); if(user_json == NULL){ return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(user_props, user_json); mosquitto_property_read_string_pair(prop, MQTT_PROP_USER_PROPERTY, &strname, &strvalue, false); if(strname == NULL || strvalue == NULL){ free(strname); free(strvalue); 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; } static void format_time_8601(const struct tm *ti, int ns, char *buf, size_t len) { char c; strftime(buf, len, "%Y-%m-%dT%H:%M:%S.000000%z", ti); c = buf[strlen("2020-05-06T21:48:00.000000")]; snprintf(&buf[strlen("2020-05-06T21:48:00.")], 9, "%06d", ns/1000); buf[strlen("2020-05-06T21:48:00.000000")] = c; } 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]; cJSON *root; cJSON *tmp; char *json_str; const char *return_parse_end; root = cJSON_CreateObject(); if(root == NULL){ return MOSQ_ERR_NOMEM; } format_time_8601(ti, ns, buf, sizeof(buf)); if(cJSON_AddStringToObject(root, "tst", buf) == NULL || cJSON_AddStringToObject(root, "topic", message->topic) == NULL || cJSON_AddNumberToObject(root, "qos", message->qos) == NULL || cJSON_AddBoolToObject(root, "retain", message->retain) == NULL || cJSON_AddNumberToObject(root, "payloadlen", message->payloadlen) == NULL || (message->qos > 0 && cJSON_AddNumberToObject(root, "mid", message->mid) == NULL) || (properties && json_print_properties(root, properties)) ){ cJSON_Delete(root); return MOSQ_ERR_NOMEM; } /* Payload */ if(escaped){ if(message->payload){ tmp = cJSON_AddStringToObject(root, "payload", message->payload); }else{ tmp = cJSON_AddNullToObject(root, "payload"); } if(tmp == NULL){ cJSON_Delete(root); return MOSQ_ERR_NOMEM; } }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; } static void formatted_print_blank(struct fieldoptions *fopts) { int i; for(i=0; ifield_width; i++){ putchar(fopts->pad); } } #ifdef __STDC_IEC_559__ static int formatted_print_float(const unsigned char *payload, int payloadlen, char format, struct fieldoptions *fopts) { float float_value; double value = 0.0; if(format == 'f'){ if(sizeof(float_value) != payloadlen){ return -1; } memcpy(&float_value, payload, sizeof(float_value)); value = float_value; }else if(format == 'd'){ if(sizeof(value) != payloadlen){ return -1; } memcpy(&value, payload, sizeof(value)); } if(fopts->field_width == 0){ printf("%.*f", fopts->precision, value); }else{ if(fopts->align == '-'){ printf("%-*.*f", fopts->field_width, fopts->precision, value); }else{ if(fopts->pad == '0'){ printf("%0*.*f", fopts->field_width, fopts->precision, value); }else{ printf("%*.*f", fopts->field_width, fopts->precision, value); } } } return 0; } #endif static void formatted_print_int(int value, struct fieldoptions *fopts) { if(fopts->field_width == 0){ printf("%d", value); }else{ if(fopts->align == '-'){ printf("%-*d", fopts->field_width, value); }else{ if(fopts->pad == '0'){ printf("%0*d", fopts->field_width, value); }else{ printf("%*d", fopts->field_width, value); } } } } static void formatted_print_str(const char *value, struct fieldoptions *fopts) { if(fopts->field_width == 0 && fopts->precision == -1){ fputs(value, stdout); }else{ if(fopts->precision == -1){ if(fopts->align == '-'){ printf("%-*s", fopts->field_width, value); }else{ printf("%*s", fopts->field_width, value); } }else if(fopts->field_width == 0){ if(fopts->align == '-'){ printf("%-.*s", fopts->precision, value); }else{ printf("%.*s", fopts->precision, value); } }else{ if(fopts->align == '-'){ printf("%-*.*s", fopts->field_width, fopts->precision, value); }else{ printf("%*.*s", fopts->field_width, fopts->precision, value); } } } } static void formatted_print_percent(const struct mosq_config *lcfg, const struct mosquitto_message *message, const mosquitto_property *properties, char format, struct fieldoptions *fopts) { struct tm *ti = NULL; long ns = 0; char buf[100]; int rc; uint8_t i8value; uint16_t i16value; uint32_t i32value; char *binvalue = NULL, *strname, *strvalue; const mosquitto_property *prop; switch(format){ case '%': fputc('%', stdout); break; case 'A': if(mosquitto_property_read_int16(properties, MQTT_PROP_TOPIC_ALIAS, &i16value, false)){ formatted_print_int(i16value, fopts); }else{ formatted_print_blank(fopts); } break; case 'C': if(mosquitto_property_read_string(properties, MQTT_PROP_CONTENT_TYPE, &strvalue, false)){ formatted_print_str(strvalue, fopts); free(strvalue); }else{ formatted_print_blank(fopts); } break; case 'D': if(mosquitto_property_read_binary(properties, MQTT_PROP_CORRELATION_DATA, (void **)&binvalue, &i16value, false)){ fwrite(binvalue, 1, i16value, stdout); free(binvalue); } break; case 'E': if(mosquitto_property_read_int32(properties, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, &i32value, false)){ formatted_print_int((int)i32value, fopts); }else{ formatted_print_blank(fopts); } break; case 'F': if(mosquitto_property_read_byte(properties, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, &i8value, false)){ formatted_print_int(i8value, fopts); }else{ formatted_print_blank(fopts); } break; case 'I': if(!ti){ if(get_time(&ti, &ns)){ err_printf(lcfg, "Error obtaining system time.\n"); return; } } if(strftime(buf, 100, "%FT%T%z", ti) != 0){ formatted_print_str(buf, fopts); }else{ formatted_print_blank(fopts); } break; case 'j': if(!ti){ if(get_time(&ti, &ns)){ err_printf(lcfg, "Error obtaining system time.\n"); return; } } if(json_print(message, properties, ti, (int)ns, true, lcfg->pretty) != 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, fopts); break; case 'm': formatted_print_int(message->mid, fopts); 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, fopts); 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, fopts); 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, fopts); }else{ formatted_print_blank(fopts); } break; case 't': formatted_print_str(message->topic, fopts); 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, fopts); break; case 'X': write_payload(message->payload, message->payloadlen, 2, fopts); break; #ifdef __STDC_IEC_559__ case 'f': if(formatted_print_float(message->payload, message->payloadlen, 'f', fopts)){ err_printf(lcfg, "requested float printing, but non-float data received"); } break; case 'd': if(formatted_print_float(message->payload, message->payloadlen, 'd', fopts)){ err_printf(lcfg, "requested double printing, but non-double data received"); } break; #endif } } static void formatted_print(const struct mosq_config *lcfg, const struct mosquitto_message *message, const mosquitto_property *properties) { size_t len; struct tm *ti = NULL; long ns = 0; len = strlen(lcfg->format); for(size_t i=0; iformat[i] == '%'){ struct fieldoptions fopts = {0, -1, ' ', '\0', ' '}; if(i < len-1){ i++; /* Optional alignment */ if(lcfg->format[i] == '-'){ fopts.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'){ fopts.pad = '0'; if(i < len-1){ i++; } } /* Optional field width */ while(i < len-1 && lcfg->format[i] >= '0' && lcfg->format[i] <= '9'){ fopts.field_width *= 10; fopts.field_width += lcfg->format[i]-'0'; i++; } /* Optional precision */ if(lcfg->format[i] == '.'){ if(i < len-1){ i++; fopts.precision = 0; while(i < len-1 && lcfg->format[i] >= '0' && lcfg->format[i] <= '9'){ fopts.precision *= 10; fopts.precision += lcfg->format[i]-'0'; i++; } } } /* Optional hex field separator character */ for(size_t j=0; jformat[i] == hexseplist[j]){ fopts.hexsepchar = hexseplist[j]; i++; break; } } if(i < len){ formatted_print_percent(lcfg, message, properties, lcfg->format[i], &fopts); //align, pad, field_width, precision, hexsepchar); } } }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; } } char strf[3] = {0, 0, 0}; strf[0] = '%'; strf[1] = lcfg->format[i]; strf[2] = 0; if(lcfg->format[i] == 'N'){ printf("%09ld", ns); }else{ char buf[100]; if(strftime(buf, sizeof(buf), 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); } static void rand_init(void) { #ifndef WIN32 struct tm *ti = NULL; long ns; if(!get_time(&ti, &ns)){ srandom((unsigned int)ns); } #endif } #ifndef WIN32 static void watch_print(const struct mosquitto_message *message) { struct watch_topic *item = NULL; HASH_FIND(hh, watch_items, message->topic, strlen(message->topic), item); if(item == NULL){ item = calloc(1, sizeof(struct watch_topic)); if(item == NULL){ return; } item->line = watch_max++; item->topic = strdup(message->topic); if(item->topic == NULL){ free(item); return; } HASH_ADD_KEYPTR(hh, watch_items, item->topic, strlen(item->topic), item); } printf("\e[%d;1H", item->line); } #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 struct fieldoptions fopts = {0, 0, ' ', '\0', ' '}; #ifndef WIN32 if(lcfg->watch){ watch_print(message); } #endif if(lcfg->random_filter < 10000){ #ifdef WIN32 rand_s(&r); #else /* coverity[dont_call] - we don't care about random() not being cryptographically secure here */ 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, &fopts); 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, &fopts); if(lcfg->eol){ printf("\n"); } fflush(stdout); } } #ifndef WIN32 if(lcfg->watch){ printf("\e[%d;1H\n", watch_max-1); } #endif } void output_init(struct mosq_config *lcfg) { rand_init(); #ifndef WIN32 if(lcfg->watch){ printf("\e[2J\e[1;1H"); printf("Broker: %s\n", lcfg->host); } #endif #ifdef WIN32 /* Disable text translation so binary payloads aren't modified */ (void)_setmode(_fileno(stdout), _O_BINARY); #endif } ================================================ FILE: client/sub_client_output.h ================================================ /* Copyright (c) 2019-2021 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 output_init(struct mosq_config *cfg); void print_message(struct mosq_config *cfg, const struct mosquitto_message *message, const mosquitto_property *properties); #endif ================================================ FILE: client/sub_test_fixed_width ================================================ LD_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 ================================================ FILE: client/sub_test_properties ================================================ LD_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 ================================================ FILE: cmake/FindCUnit.cmake ================================================ find_package(PkgConfig) pkg_check_modules(PC_CUnit QUIET cunit) find_path(CUnit_INCLUDE_DIR NAMES CUnit/CUnit.h PATHS ${PC_CUnit_INCLUDE_DIRS} ) find_library(CUnit_LIBRARY NAMES cunit PATHS ${PC_CUnit_LIBRARY_DIRS} ) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(CUnit FOUND_VAR CUnit_FOUND REQUIRED_VARS CUnit_LIBRARY CUnit_INCLUDE_DIR VERSION_VAR CUnit_VERSION ) if(CUnit_FOUND) set(CUnit_LIBRARIES ${CUnit_LIBRARY}) set(CUnit_INCLUDE_DIRS ${CUnit_INCLUDE_DIR}) set(CUnit_DEFINITIONS ${PC_CUnit_CFLAGS_OTHER}) endif() if(CUnit_FOUND AND NOT TARGET CUnit::CUnit) add_library(CUnit::CUnit UNKNOWN IMPORTED) set_target_properties(CUnit::CUnit PROPERTIES IMPORTED_LOCATION "${CUnit_LIBRARY}" INTERFACE_COMPILE_OPTIONS "${PC_CUnit_CFLAGS_OTHER}" INTERFACE_INCLUDE_DIRECTORIES "${CUnit_INCLUDE_DIR}" ) endif() ================================================ FILE: cmake/FindLineEditing.cmake ================================================ include(FindPackageHandleStandardArgs) set(FIND_PATH_OPTS "") if(APPLE) list(APPEND FIND_PATH_OPTS NO_CMAKE_SYSTEM_PATH NO_SYSTEM_ENVIRONMENT_PATH ) endif() # Checks an environment variable; note that the first check # does not require the usual CMake $-sign. if(DEFINED env{EDITLINE_DIR}) set(EDITLINE_DIR "$ENV{EDITLINE_DIR}") endif() find_path( EDITLINE_INCLUDE_DIR editline/readline.h HINTS EDITLINE_DIR ${FIND_PATH_OPTS} ) find_library(EDITLINE_LIBRARY NAMES edit HINTS ${EDITLINE_DIR} ) if(EDITLINE_INCLUDE_DIR AND EDITLINE_LIBRARY) set(EDITLINE_FOUND TRUE) set(LINEEDITING_FOUND TRUE) set(LINEEDITING_INCLUDE_DIRS ${EDITLINE_INCLUDE_DIR}) set(LINEEDITING_LIBRARIES ${EDITLINE_LIBRARY}) if(NOT TARGET LineEditing::LineEditing) add_library(LineEditing::LineEditing UNKNOWN IMPORTED) set_target_properties(LineEditing::LineEditing PROPERTIES IMPORTED_LOCATION "${EDITLINE_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${EDITLINE_INCLUDE_DIR}" INTERFACE_COMPILE_DEFINITIONS "WITH_EDITLINE" ) endif() else() find_path( READLINE_INCLUDE_DIR readline/readline.h HINTS READLINE_DIR ${FIND_PATH_OPTS} ) find_library(READLINE_LIBRARY NAMES readline HINTS ${READLINE_DIR} ) if(READLINE_INCLUDE_DIR AND READLINE_LIBRARY) set(LINEEDITING_FOUND TRUE) set(LINEEDITING_INCLUDE_DIRS ${READLINE_INCLUDE_DIR}) set(LINEEDITING_LIBRARIES ${READLINE_LIBRARY}) if(NOT TARGET LineEditing::LineEditing) add_library(LineEditing::LineEditing UNKNOWN IMPORTED) set_target_properties(LineEditing::LineEditing PROPERTIES IMPORTED_LOCATION "${READLINE_LIBRARY}" INTERFACE_INCLUDE_DIRECTORIES "${READLINE_INCLUDE_DIR}" INTERFACE_COMPILE_DEFINITIONS "WITH_READLINE" ) endif() endif() endif() find_package_handle_standard_args(LineEditing REQUIRED_VARS LINEEDITING_LIBRARIES LINEEDITING_INCLUDE_DIRS FAIL_MESSAGE "Could not find libedit or readline library" ) ================================================ FILE: cmake/Findargon2.cmake ================================================ INCLUDE( FindPackageHandleStandardArgs ) # Checks an environment variable; note that the first check # does not require the usual CMake $-sign. IF( DEFINED ENV{ARGON2_DIR} ) SET( ARGON2_DIR "$ENV{ARGON2_DIR}" ) ENDIF() FIND_PATH( ARGON2_INCLUDE_DIR argon2.h HINTS ARGON2_DIR ) FIND_LIBRARY( ARGON2_LIBRARY NAMES argon2 HINTS ${ARGON2_DIR} ) FIND_PACKAGE_HANDLE_STANDARD_ARGS( argon2 DEFAULT_MSG ARGON2_INCLUDE_DIR ARGON2_LIBRARY ) IF( ARGON2_FOUND ) SET( ARGON2_INCLUDE_DIRS ${ARGON2_INCLUDE_DIR} ) SET( ARGON2_LIBRARIES ${ARGON2_LIBRARY} ) MARK_AS_ADVANCED( ARGON2_LIBRARY ARGON2_INCLUDE_DIR ARGON2_DIR ) add_library(argon2 SHARED IMPORTED) set_target_properties(argon2 PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${ARGON2_INCLUDE_DIRS}" ) set_target_properties(argon2 PROPERTIES IMPORTED_LOCATION "${ARGON2_LIBRARY}" IMPORTED_IMPLIB "${ARGON2_LIBRARY}" ) ELSE() SET( ARGON2_DIR "" CACHE STRING "An optional hint to a directory for finding `argon2`" ) ENDIF() ================================================ FILE: cmake/FindcJSON.cmake ================================================ INCLUDE( 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 ) add_library(cJSON SHARED IMPORTED) set_target_properties(cJSON PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${CJSON_INCLUDE_DIRS}" ) set_target_properties(cJSON PROPERTIES IMPORTED_LOCATION "${CJSON_LIBRARY}" IMPORTED_IMPLIB "${CJSON_LIBRARY}" ) ELSE() SET( CJSON_DIR "" CACHE STRING "An optional hint to a directory for finding `cJSON`" ) ENDIF() ================================================ FILE: codecov.yml ================================================ codecov: max_report_age: off ignore: - "deps/picohttpparser" - "deps/*.h" - "plugins/examples" - "test" - "^.*/test/.*" parsers: gcov: branch_detection: conditional: no loop: no ================================================ FILE: common/json_help.c ================================================ /* Copyright (c) 2020-2021 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_int64(cJSON *json, const char *name, int64_t *value, bool optional, int64_t 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 = (int64_t)jtmp->valuedouble; }else{ if(optional == false){ return MOSQ_ERR_INVAL; } } return MOSQ_ERR_SUCCESS; } int json_get_string(cJSON *json, const char *name, const char **value, bool optional) { cJSON *jtmp; *value = NULL; jtmp = cJSON_GetObjectItem(json, name); if(jtmp){ if(cJSON_IsString(jtmp) == false){ return MOSQ_ERR_INVAL; } if(jtmp->valuestring){ *value = jtmp->valuestring; }else{ *value = ""; } }else{ if(optional == false){ return MOSQ_ERR_INVAL; } } return MOSQ_ERR_SUCCESS; } cJSON *cJSON_AddIntToObject(cJSON * const object, const char * const name, long long number) { char buf[30]; snprintf(buf, sizeof(buf), "%lld", number); return cJSON_AddRawToObject(object, name, buf); } cJSON *cJSON_AddUIntToObject(cJSON * const object, const char * const name, unsigned long long number) { char buf[30]; snprintf(buf, sizeof(buf), "%llu", number); return cJSON_AddRawToObject(object, name, buf); } ================================================ FILE: common/json_help.h ================================================ #ifndef JSON_HELP_H #define JSON_HELP_H /* Copyright (c) 2020-2021 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 #ifdef __cplusplus extern "C" { #endif /* "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_int64(cJSON *json, const char *name, int64_t *value, bool optional, int64_t default_value); int json_get_string(cJSON *json, const char *name, const char **value, bool optional); cJSON *cJSON_AddIntToObject(cJSON * const object, const char * const name, long long number); cJSON *cJSON_AddUIntToObject(cJSON * const object, const char * const name, unsigned long long number); cJSON *cJSON_CreateInt(int num); #ifdef __cplusplus } #endif #endif ================================================ FILE: common/lib_load.h ================================================ /* Copyright (c) 2012-2021 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_LOCAL) # 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 ================================================ FILE: config.h ================================================ #ifndef CONFIG_H #define CONFIG_H /* ============================================================ * Platform options * ============================================================ */ #ifdef __APPLE__ # define __DARWIN_C_SOURCE #elif defined(__FreeBSD__) || defined(__NetBSD__) # define HAVE_NETINET_IN_H #elif defined(__QNX__) # define _XOPEN_SOURCE 600 # define __BSD_VISIBLE 1 # define HAVE_NETINET_IN_H #elif defined(_AIX) # define HAVE_NETINET_IN_H #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 # define strcasecmp _stricmp # define strncasecmp _strnicmp # define strtok_r strtok_s # define strerror_r(e, b, l) strerror_s(b, l, e) # ifdef _MSC_VER # include typedef SSIZE_T ssize_t; # endif #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 */ #if !defined(ANDROID) && !defined(WIN32) # define HAVE_PTHREAD_CANCEL #endif #define WS_IS_LWS 1 #define WS_IS_BUILTIN 2 #ifdef WITH_BROKER # ifdef __GNUC__ # define BROKER_EXPORT __attribute__((__used__)) # else # define BROKER_EXPORT # endif #else # define BROKER_EXPORT #endif #define TOPIC_HIERARCHY_LIMIT 200 #ifdef WITH_ADNS # define _GNU_SOURCE #endif #endif ================================================ FILE: config.mk ================================================ # ============================================================================= # 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 overridden 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 # Uncomment to activate a consistency check on the usage of the memory tracking # alloc/free function use. Any memory allocated without a tracking function, # but freed with the tracking function will trigger an invalid memory read in # memory trackers like valgrind memcheck or ASAN. #ALLOC_MISMATCH_INVALID_READ:=yes # Uncomment to activate consistency check on the usage of the memory tracking # alloc/free function use. Any memory allocated without a tracking function, # but freed with the tracking function will trigger an abort. #ALLOC_MISMATCH_ABORT:=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. # Set to yes to build with new websockets support # Set to lws to build with old libwebsockets code # Set to no to disable WITH_WEBSOCKETS:=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 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 # Use the old O(n) keepalive check routine, instead of the new O(1) keepalive # check routine. See src/keepalive.c for notes on this. WITH_OLD_KEEPALIVE=no # Use link time optimisation - note that enabling this currently prevents # broker plugins from working. #WITH_LTO=yes # Build with sqlite3 support - this enables the sqlite persistence plugin. WITH_SQLITE=yes # Use gmock for testing WITH_GMOCK:=yes # Build broker for fuzzing only - does not work as a normal broker. This is # currently only suitable for use with oss-fuzz. WITH_FUZZING=no # Build using clang and with address sanitiser enabled WITH_ASAN=no # Build with editline support to allow the mosquitto_ctrl shell WITH_EDITLINE=yes # Build with basic HTTP API support WITH_HTTP_API=yes # ============================================================================= # End of user configuration # ============================================================================= # Also bump lib/mosquitto.h, CMakeLists.txt, # installer/mosquitto.nsi, installer/mosquitto64.nsi VERSION=2.1.2 # 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 MAKE_ALL:=mosquitto UNAME:=$(shell uname -s) ARCH:=$(shell uname -p) INSTALL?=install prefix?=/usr/local incdir?=${prefix}/include libdir?=${prefix}/lib${LIB_SUFFIX} localedir?=${prefix}/share/locale mandir?=${prefix}/share/man STRIP?=strip ifeq ($(UNAME),SunOS) ifeq ($(CC),cc) CFLAGS?=-O else CFLAGS?=-Wall -ggdb -O2 endif else CFLAGS?=-Wall -ggdb -O3 -Wconversion -Wextra -std=gnu99 -Werror=switch CXXFLAGS?=-Wall -ggdb -O3 -Wconversion -Wextra endif LOCAL_CPPFLAGS=$(CPPFLAGS) LOCAL_CFLAGS=$(CFLAGS) LOCAL_CXXFLAGS=$(CXXFLAGS) LOCAL_LDFLAGS=$(LDFLAGS) LOCAL_LIBADD=$(LIBADD) LOCAL_CPPFLAGS+=-DVERSION=\""${VERSION}\"" -I${R} -I. -I${R}/include -I${R}/common ifneq ($(or $(findstring $(UNAME),FreeBSD), $(findstring $(UNAME),OpenBSD), $(findstring $(UNAME),NetBSD)),) SEDINPLACE:=-i "" else ifeq ($(UNAME),SunOS) SEDINPLACE:= else SEDINPLACE:=-i endif endif ifeq ($(UNAME),QNX) LOCAL_LDADD+=-lsocket endif ifeq ($(UNAME),SunOS) LOCAL_LDADD+=-lsocket -lnsl LOCAL_LIBADD+=-lsocket -lnsl endif ifeq ($(WITH_FUZZING),yes) WITH_GMOCK:=no WITH_SHARED_LIBRARIES:=no WITH_STATIC_LIBRARIES:=yes endif ifeq ($(WITH_SHARED_LIBRARIES),yes) LIBMOSQ:=${R}/lib/libmosquitto.so.${SOVERSION} else LIBMOSQ:=${R}/lib/libmosquitto.a endif LIBMOSQ_COMMON:=-Wl,--whole-archive ${R}/libcommon/libmosquitto_common.a -Wl,--no-whole-archive -lcjson ifeq ($(WITH_TLS),yes) LOCAL_CPPFLAGS+=-DWITH_TLS ifeq ($(WITH_TLS_PSK),yes) LOCAL_CPPFLAGS+=-DWITH_TLS_PSK endif endif ifeq ($(WITH_ASAN),yes) CC:=clang CXX:=clang++ LOCAL_CFLAGS+=-fsanitize=address -fno-omit-frame-pointer LOCAL_CXXFLAGS+=-fsanitize=address -fno-omit-frame-pointer LOCAL_LDFLAGS+=-fsanitize=address -fno-omit-frame-pointer -static-libsan endif ifeq ($(WITH_LTO),yes) LOCAL_CFLAGS+=-flto LOCAL_LDFLAGS+=-flto endif ifeq ($(WITH_DOCS),yes) MAKE_ALL+=docs endif ifeq ($(WITH_JEMALLOC),yes) LOCAL_LDADD+=-ljemalloc endif ifeq ($(WITH_UNIX_SOCKETS),yes) LOCAL_CPPFLAGS+=-DWITH_UNIX_SOCKETS endif ifeq ($(WITH_WEBSOCKETS),yes) ifeq ($(WITH_TLS),yes) LOCAL_CPPFLAGS+=-DWITH_WEBSOCKETS=WS_IS_BUILTIN -I${R}/deps/picohttpparser endif endif ifeq ($(WITH_WEBSOCKETS),lws) LOCAL_CPPFLAGS+=-DWITH_WEBSOCKETS=WS_IS_LWS LOCAL_LDADD+=-lwebsockets endif ifeq ($(WITH_STRIP),yes) STRIP_OPTS?=-s --strip-program=${CROSS_COMPILE}${STRIP} endif ifeq ($(WITH_BUNDLED_DEPS),yes) LOCAL_CPPFLAGS+=-I${R}/deps endif ifeq ($(WITH_COVERAGE),yes) LOCAL_CFLAGS+=-coverage LOCAL_CXXFLAGS+=-coverage LOCAL_LDFLAGS+=-coverage endif ifeq ($(WITH_FUZZING),yes) MAKE_ALL+=fuzzing LOCAL_CPPFLAGS+=-DWITH_FUZZING LOCAL_CFLAGS+=-fPIC LOCAL_LDFLAGS+=-shared $(LOCAL_CFLAGS) endif ifeq ($(WITH_ARGON2),yes) LOCAL_CPPFLAGS+=-DWITH_ARGON2 LIB_ARGON2=-largon2 LIBMOSQ_COMMON+=${LIB_ARGON2} endif ================================================ FILE: dashboard/README.md ================================================ ### Simple web-based graphical user interface for Mosquitto To develop UI locally. 1) Install tailwind: ```sh npm -g install tailwindcss@3 ``` 2) Go into `src` and run tailwind to generate a CSS file based on tailwind classes used in `index.html`: ```sh tailwindcss -i ./css/styles.css -o ./tailwind/styles.css ``` 3) Run mosquitto http api mock 4) Change mosquitto api endponits in `src/consts.js` 5) Go into `src` and run a simple http server, e.g. `python3 -m http.server 3000` Dependencies (in `src/lib` directory): * chartjs 4.3.0 (https://cdnjs.com/libraries/Chart.js/4.3.0) * chartjs-plugin-zoom 2.2.0 (https://cdnjs.com/libraries/chartjs-plugin-zoom) * hammer.js 2.0.8 (https://cdnjs.com/libraries/hammer.js) ================================================ FILE: dashboard/src/app/consts.js ================================================ const MAX_POINTS_IN_CHART = 5_000; const KEEP_DATAPOINTS_FOR_INTERVAL = 1000 * // 1 sec 60 * // 1 minute 60 * // 1 hour 2; // 2 hours const CHART_UPDATE_INTERVAL_IN_MILLISECONDS = 1000 * // 1 sec 60 * // 1 minute 1; const SMOOTHED_CHART_UPDATE_INTERVAL_IN_MILLISECONDS = 1000 * // 1 sec 60 * // 1 minute 5; // 5 minutes const INTERVAL_5SECS_IN_MILLISECONDS = 1000 * 5; const CHARTJS_ANIMATION_DURATION_MS = 400; const SYSTOPIC_ENDPOINT = "/api/v1/systree"; const LISTENERS_ENDPOINT = "/api/v1/listeners"; const CHART_DISPLAY_WINDOW = 16; ================================================ FILE: dashboard/src/app/dashboard.js ================================================ const MAIN_CHART_COLOR = "#fd602e"; const SUPPLEMENTARY_CHART_COLOR = "#6366f1"; class MosquittoDashboard { constructor(headless = false) { this.abort = new AbortController(); registerAbortController(this.abort, this); this.headlessMode = !!headless; !this.headlessMode && window.Chart.register(window.ChartZoom); // chartjs comes from lib/ this.previousDataFetchFailed = false; this.brokerOnline = true; this.version = ""; this.dashboardDataObject = { lastSysTopics: [] }; const dashboardDataObject = this.composeDashboardObject(); const [entitiesToUpdate] = this.getElementsToUpdate( dashboardDataObject.lastSysTopics, ); // if metrics were present in the session store, update them immediately if (!this.headlessMode && entitiesToUpdate) { Object.entries(entitiesToUpdate).forEach(([id, value]) => { this.updateHtmlElementById(id, value); }); } this.dashboardDataObject = dashboardDataObject; this.charts = {}; this.timeoutHandler = null; !this.headlessMode && this.initializeCharts(); !this.headlessMode && this.addToggle(); this.startDataUpdates(); } getChartDataFromStore(chartId) { const chartDataString = sessionStorage.getItem(chartId); let chartDataObject = null; try { if (chartDataString) { chartDataObject = JSON.parse(chartDataString); } return chartDataObject; } catch (error) { const errorMsg = `Error while creating dashboards: ${error?.message}. Chart data string: "${chartDataString}"`; console.error(errorMsg, error); alert(errorMsg); throw new Error(errorMsg); } } createOptions() { return { chartDataType: "raw", }; } createChartDataObject() { // we are already updating dashboardDataObject directly in updateChartInner return { data: { rawData: [], smoothedData: [], }, labels: { rawLabels: [], smoothedLabels: [], }, options: { mustUpdate: false, }, }; } composeDashboardObject() { const dashboardDataObject = { charts: { "chart-messages-dropped": this.getChartDataFromStore("chart-messages-dropped") || this.createChartDataObject(), "chart-messages-sent": this.getChartDataFromStore("chart-messages-sent") || this.createChartDataObject(), "chart-messages-received": this.getChartDataFromStore("chart-messages-received") || this.createChartDataObject(), "chart-messages-sent-rate": this.getChartDataFromStore("chart-messages-sent-rate") || this.createChartDataObject(), "chart-messages-received-rate": this.getChartDataFromStore("chart-messages-received-rate") || this.createChartDataObject(), "chart-clients-connected": this.getChartDataFromStore("chart-clients-connected") || this.createChartDataObject(), "chart-clients-disconnected": this.getChartDataFromStore("chart-clients-disconnected") || this.createChartDataObject(), }, lastSysTopics: this.getChartDataFromStore("sysTopics") || {}, lastUpdateDueToIntervalTimestamp: this.getChartDataFromStore("updateDueToIntervalTimestamp") || 0, // used to make sure we also always update graphs at certain intervals options: this.getChartDataFromStore("options") || this.createOptions(), }; return dashboardDataObject; } setBrokerVersion() { if (this.headlessMode) { return; } this.updateHtmlElementById("broker-version", this.version); } setBrokerStatus() { if (this.headlessMode) { return; } this.removeHtmlElementClass( "broker-status", this.brokerOnline ? "broker-inactive" : "broker-active", ); this.addHtmlElementClass( "broker-status", this.brokerOnline ? "broker-active" : "broker-inactive", ); this.updateHtmlElementById( "broker-status-text", this.brokerOnline ? "Online" : "Offline", ); } createLineChart( canvasId, label, color = SUPPLEMENTARY_CHART_COLOR, chartDataType, ) { const labelsType = chartDataType === "raw" ? "rawLabels" : "smoothedLabels"; const dataType = chartDataType === "raw" ? "rawData" : "smoothedData"; const ctx = document.getElementById(canvasId).getContext("2d"); const totalLen = this.dashboardDataObject.charts[canvasId].labels[labelsType].length; const windowSize = CHART_DISPLAY_WINDOW; const startIndex = Math.max(0, totalLen - windowSize); const chart = new window.Chart(ctx, { type: "line", data: { labels: this.dashboardDataObject.charts[canvasId].labels[labelsType], datasets: [ { label: label, data: this.dashboardDataObject.charts[canvasId].data[dataType], borderColor: color, backgroundColor: color + "20", borderWidth: 2, fill: true, tension: 0.4, pointRadius: 3, pointHoverRadius: 5, }, ], }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false, }, zoom: { zoom: { wheel: { enabled: true, }, pinch: { enabled: true, }, mode: "xy", }, pan: { enabled: true, mode: "xy", rangeMin: startIndex, rangeMax: totalLen - 1, }, }, }, scales: { x: { display: true, grid: { color: "#f3f4f6", }, ticks: { font: { size: 10, }, maxRotation: 45, }, min: startIndex, max: totalLen - 1, }, y: { display: true, beginAtZero: true, grid: { color: "#f3f4f6", }, ticks: { font: { size: 10, }, }, }, }, interaction: { intersect: false, mode: "index", }, }, }); return chart; } createSentVsReceivedChart(chartDataType) { const labelsType = chartDataType === "raw" ? "rawLabels" : "smoothedLabels"; const dataType = chartDataType === "raw" ? "rawData" : "smoothedData"; const ctx = document .getElementById("chart-message-overview") .getContext("2d"); const totalLen = this.dashboardDataObject.charts["chart-messages-sent"].labels[labelsType] .length; const windowSize = CHART_DISPLAY_WINDOW; const startIndex = Math.max(0, totalLen - windowSize); const chart = new window.Chart(ctx, { type: "line", data: { labels: this.dashboardDataObject.charts["chart-messages-sent"].labels[ labelsType ], datasets: [ { label: "Messages Sent", data: this.dashboardDataObject.charts["chart-messages-sent"].data[ dataType ], borderColor: SUPPLEMENTARY_CHART_COLOR, backgroundColor: SUPPLEMENTARY_CHART_COLOR + "20", borderWidth: 2, fill: false, tension: 0.4, }, { label: "Messages Received", data: this.dashboardDataObject.charts["chart-messages-received"] .data[dataType], borderColor: MAIN_CHART_COLOR, backgroundColor: MAIN_CHART_COLOR + "20", borderWidth: 2, fill: false, tension: 0.4, }, ], }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: true, position: "top", }, zoom: { zoom: { wheel: { enabled: true, }, pinch: { enabled: true, }, mode: "xy", }, pan: { enabled: true, mode: "xy", rangeMin: startIndex, rangeMax: totalLen - 1, }, }, }, scales: { x: { display: true, grid: { color: "#f3f4f6", }, min: startIndex, max: totalLen - 1, }, y: { display: true, beginAtZero: true, grid: { color: "#f3f4f6", }, }, }, interaction: { intersect: false, mode: "index", }, }, }); return chart; } createRateSentVsReceivedChart(chartDataType) { const labelsType = chartDataType === "raw" ? "rawLabels" : "smoothedLabels"; const dataType = chartDataType === "raw" ? "rawData" : "smoothedData"; const ctx = document .getElementById("chart-message-rate-overview") .getContext("2d"); const totalLen = this.dashboardDataObject.charts["chart-messages-sent-rate"].labels[ labelsType ].length; const windowSize = CHART_DISPLAY_WINDOW; const startIndex = Math.max(0, totalLen - windowSize); const chart = new window.Chart(ctx, { type: "line", data: { labels: this.dashboardDataObject.charts["chart-messages-sent-rate"].labels[ labelsType ], datasets: [ { label: "Messages Sent per Minute", data: this.dashboardDataObject.charts["chart-messages-sent-rate"] .data[dataType], borderColor: SUPPLEMENTARY_CHART_COLOR, backgroundColor: SUPPLEMENTARY_CHART_COLOR + "20", borderWidth: 2, fill: false, tension: 0.4, }, { label: "Messages Received per Minute", data: this.dashboardDataObject.charts[ "chart-messages-received-rate" ].data[dataType], borderColor: MAIN_CHART_COLOR, backgroundColor: MAIN_CHART_COLOR + "20", borderWidth: 2, fill: false, tension: 0.4, }, ], }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: true, position: "top", }, zoom: { zoom: { wheel: { enabled: true, }, pinch: { enabled: true, }, mode: "xy", }, pan: { enabled: true, mode: "xy", rangeMin: startIndex, rangeMax: totalLen - 1, }, }, }, scales: { x: { display: true, grid: { color: "#f3f4f6", }, min: startIndex, max: totalLen - 1, }, y: { display: true, beginAtZero: true, grid: { color: "#f3f4f6", }, }, }, interaction: { intersect: false, mode: "index", }, }, }); return chart; } handleChartAction(chartId, action) { const chart = this.charts[chartId]; if (!chart) { const errorMsg = "Couldn't find the chart: " + chartId; console.error(errorMsg + ". Charts:", Object.keys(this.charts)); alert(errorMsg); } switch (action) { case "zoom-in": chart.zoom(1.2); break; case "zoom-out": chart.zoom(0.8); break; case "pan-left": chart.pan({ x: 100 }); break; case "pan-right": chart.pan({ x: -100 }); break; case "reset": const newTotalLen = chart.data.labels.length; const newStart = Math.max(0, newTotalLen - CHART_DISPLAY_WINDOW); chart.options.scales.x.min = newStart; chart.options.scales.x.max = newTotalLen - 1; chart.update(); //chart.update("none"); //Object.values(chart.options.scales).forEach((axisOptions) => { // delete axisOptions.min; // delete axisOptions.max; //}); chart.resetZoom(); break; default: const errorMsg = `Unrecognized action "${action}"`; console.error(errorMsg); alert(errorMsg); } } addToggle() { const toggleChartDataTypeButton = document.getElementById( "chart-data-type-global-toggle", ); const toggleChartDataTypeText = document.getElementById( "chart-data-type-text", ); // set to an opposite state and toggle once to refresh the button captions etc if (this.dashboardDataObject.options.chartDataType === "raw") { this.dashboardDataObject.options.chartDataType = "smooth"; } else { this.dashboardDataObject.options.chartDataType = "raw"; } const handleChartDataTypeToggle = () => { if (this.dashboardDataObject.options.chartDataType === "raw") { this.dashboardDataObject.options.chartDataType = "smooth"; this.destroyCharts(); toggleChartDataTypeText.textContent = "Show Raw Data"; this.addHtmlElementClass("smooth-state-svg", "hidden"); this.removeHtmlElementClass("raw-state-svg", "hidden"); } else { this.dashboardDataObject.options.chartDataType = "raw"; this.destroyCharts(); toggleChartDataTypeText.textContent = "Show Smoothed Data"; this.addHtmlElementClass("raw-state-svg", "hidden"); this.removeHtmlElementClass("smooth-state-svg", "hidden"); } this.initializeCharts(); sessionStorage.setItem( "options", JSON.stringify(this.dashboardDataObject.options), ); }; toggleChartDataTypeButton.addEventListener("click", () => { queue.enqueue(toAsyncAndWaitAfter(handleChartDataTypeToggle)); }); queue.enqueue(toAsyncAndWaitAfter(handleChartDataTypeToggle)); } initializeCharts() { let id = ""; id = "chart-messages-dropped"; this.charts[id] = this.createLineChart( id, "Dropped Messages", MAIN_CHART_COLOR, this.dashboardDataObject.options.chartDataType, ); id = "chart-messages-sent"; this.charts[id] = this.createLineChart( id, "Messages Sent", MAIN_CHART_COLOR, this.dashboardDataObject.options.chartDataType, ); id = "chart-messages-received"; this.charts[id] = this.createLineChart( id, "Messages Received", MAIN_CHART_COLOR, this.dashboardDataObject.options.chartDataType, ); id = "chart-messages-sent-rate"; this.charts[id] = this.createLineChart( id, "Sent Rate", MAIN_CHART_COLOR, this.dashboardDataObject.options.chartDataType, ); id = "chart-messages-received-rate"; this.charts[id] = this.createLineChart( id, "Received Rate", MAIN_CHART_COLOR, this.dashboardDataObject.options.chartDataType, ); id = "chart-clients-connected"; this.charts[id] = this.createLineChart( id, "Connected Clients", MAIN_CHART_COLOR, this.dashboardDataObject.options.chartDataType, ); id = "chart-clients-disconnected"; this.charts[id] = this.createLineChart( id, "Disconnected Persistent Clients", MAIN_CHART_COLOR, this.dashboardDataObject.options.chartDataType, ); id = "chart-message-overview"; this.charts[id] = this.createSentVsReceivedChart( this.dashboardDataObject.options.chartDataType, ); id = "chart-message-rate-overview"; this.charts[id] = this.createRateSentVsReceivedChart( this.dashboardDataObject.options.chartDataType, ); document.addEventListener("click", (e) => { if (e.target.dataset.action) { const chartId = e.target.dataset.chart; if (chartId) { const action = e.target.dataset.action; queue.enqueue( toAsyncAndWaitAfter(() => this.handleChartAction(chartId, action)), ); } } }); } getChartDatasets(chartId) { let labels, dataset, dataset2; let id1, id2; if (chartId === "chart-message-overview") { id1 = "chart-messages-sent"; id2 = "chart-messages-received"; labels = this.dashboardDataObject.charts[id1].labels; dataset = this.dashboardDataObject.charts[id1].data; dataset2 = this.dashboardDataObject.charts[id2].data; assertExistence(labels, `Labels not found for "${id1}"`); assertExistence(labels, `Dataset not found for "${id1}"`); assertExistence(labels, `Dataset not found for "${id2}"`); } else if (chartId === "chart-message-rate-overview") { id1 = "chart-messages-sent-rate"; id2 = "chart-messages-received-rate"; labels = this.dashboardDataObject.charts[id1].labels; dataset = this.dashboardDataObject.charts[id1].data; dataset2 = this.dashboardDataObject.charts[id2].data; assertExistence(labels, `Labels not found for "${id1}"`); assertExistence(labels, `Dataset not found for "${id1}"`); assertExistence(labels, `Dataset not found for "${id2}"`); } else { labels = this.dashboardDataObject.charts[chartId].labels; dataset = this.dashboardDataObject.charts[chartId].data; assertExistence(labels, `Labels not found for chartId "${chartId}"`); assertExistence(labels, `Dataset not found for chartId "${chartId}"`); } return [labels, dataset, dataset2]; } getChartPositionalData(chart) { const lastX = chart.data.labels.length - 1; const secondToLastX = chart.data.labels.length - 2; const currentViewFieldEnd = chart.scales.x.max; const zoomLevel = chart.getZoomLevel(); return [zoomLevel, currentViewFieldEnd, lastX, secondToLastX]; } isEndElementVisibleAndDefaultZoom(lastX, currentEnd, zoomLevel) { if (currentEnd === lastX && zoomLevel === 1) { return true; } return false; } slideChart(chart) { const newTotalLen = chart.data.labels.length; const newStart = Math.max(0, newTotalLen - CHART_DISPLAY_WINDOW); chart.options.scales.x.min = newStart; chart.options.scales.x.max = newTotalLen - 1; } destroyCharts() { for (const [chartId, _] of Object.entries(this.charts)) { let data; let data2; let labels; [labels, data, data2] = this.getChartDatasets(chartId); this.charts[chartId].destroy(); } } updateLastSysTopics(id, value) { this.dashboardDataObject.lastSysTopics[id] = value; } updateMatchingChart(chartId, sysTopics, chartIdsToUpdate) { const createErrorMsg = (matchingChartId, matchingChartSysTopic) => `datapoint doesn't exist in current sysTopic data for the chart "${matchingChartId}" matching the chart "${chartId}". Matching chart sys topic: ${matchingChartSysTopic}. Available sys topics: ${JSON.stringify( sysTopics, )}`; if (chartId === "chart-messages-sent") { const matchingChartId = "chart-messages-received"; const matchingChartSysTopic = "$SYS/broker/messages/received"; const datapoint = sysTopics[matchingChartSysTopic]; assertExistence( datapoint, createErrorMsg(matchingChartId, matchingChartSysTopic), ); chartIdsToUpdate[matchingChartId] = datapoint; } if (chartId === "chart-messages-received") { const matchingChartId = "chart-messages-sent"; const matchingChartSysTopic = "$SYS/broker/messages/sent"; const datapoint = sysTopics[matchingChartSysTopic]; assertExistence( datapoint, createErrorMsg(matchingChartId, matchingChartSysTopic), ); chartIdsToUpdate[matchingChartId] = datapoint; } if (chartId === "chart-messages-sent-rate") { const matchingChartId = "chart-messages-received-rate"; const matchingChartSysTopic = "$SYS/broker/load/messages/received/1min"; const datapoint = sysTopics[matchingChartSysTopic]; assertExistence( datapoint, createErrorMsg(matchingChartId, matchingChartSysTopic), ); chartIdsToUpdate[matchingChartId] = datapoint; } if (chartId === "chart-messages-received-rate") { const matchingChartId = "chart-messages-sent-rate"; const matchingChartSysTopic = "$SYS/broker/load/messages/sent/1min"; const datapoint = sysTopics[matchingChartSysTopic]; assertExistence( datapoint, createErrorMsg(matchingChartId, matchingChartSysTopic), ); chartIdsToUpdate[matchingChartId] = datapoint; } } getElementsToUpdate(sysTopics) { // we only update what has actually changed let htmlIdsToUpdate = {}; let chartIdsToUpdate = {}; let topic = ""; // sys topics object looks as follows: //{ // "$SYS/broker/uptime": 99999, // "$SYS/broker/clients/total": 0, // "$SYS/broker/clients/maximum": 1, // "$SYS/broker/clients/disconnected": 0, // "$SYS/broker/clients/connected": 0, // "$SYS/broker/clients/expired": 0, // "$SYS/broker/messages/stored": 2, // "$SYS/broker/store/messages/bytes": 32, // "$SYS/broker/subscriptions/count": 0, // "$SYS/broker/shared_subscriptions/count": 0, // "$SYS/broker/retained messages/count": 2, // "$SYS/broker/heap/current": 796624, // "$SYS/broker/heap/maximum": 796704, // "$SYS/broker/messages/received": 0, // "$SYS/broker/messages/sent": 0, // "$SYS/broker/bytes/received": 0, // "$SYS/broker/bytes/sent": 0, // "$SYS/broker/publish/bytes/received": 0, // "$SYS/broker/publish/bytes/sent": 0, // "$SYS/broker/packet/out/count": 0, // "$SYS/broker/packet/out/bytes": 0, // "$SYS/broker/connections/socket/count": 0, // "$SYS/broker/publish/messages/dropped": 0, // "$SYS/broker/publish/messages/received": 0, // "$SYS/broker/publish/messages/sent": 0 //} topic = "$SYS/broker/uptime"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["broker-uptime"] = secondsToIntervalString( sysTopics[topic], ); } topic = "$SYS/broker/clients/total"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["clients-total"] = prettifyNumber(sysTopics[topic]); htmlIdsToUpdate["systopic-clients-total"] = sysTopics[topic]; } topic = "$SYS/broker/clients/disconnected"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["clients-disconnected"] = prettifyNumber( sysTopics[topic], ); htmlIdsToUpdate["systopic-clients-disconnected"] = sysTopics[topic]; chartIdsToUpdate["chart-clients-disconnected"] = sysTopics[topic]; } topic = "$SYS/broker/clients/connected"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["clients-connected"] = prettifyNumber(sysTopics[topic]); htmlIdsToUpdate["systopic-clients-connected"] = sysTopics[topic]; chartIdsToUpdate["chart-clients-connected"] = sysTopics[topic]; } topic = "$SYS/broker/clients/maximum"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics["clients-maximum"] !== sysTopics[topic] ) { this.updateLastSysTopics("clients-disconnected", sysTopics[topic]); htmlIdsToUpdate["clients-maximum"] = sysTopics[topic]; htmlIdsToUpdate["systopic-clients-max"] = sysTopics[topic]; } topic = "$SYS/broker/clients/expired"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["clients-expired"] = prettifyNumber(sysTopics[topic]); htmlIdsToUpdate["systopic-clients-expired"] = sysTopics[topic]; } topic = "$SYS/broker/subscriptions/count"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["total-subscriptions"] = prettifyNumber(sysTopics[topic]); htmlIdsToUpdate["systopic-total-subscriptions"] = sysTopics[topic]; } topic = "$SYS/broker/shared_subscriptions/count"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-total-shared-subscriptions"] = sysTopics[topic]; } topic = "$SYS/broker/heap/current"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-heap-current"] = sysTopics[topic]; } topic = "$SYS/broker/heap/maximum"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-heap-max"] = sysTopics[topic]; } topic = "$SYS/broker/connections/socket/count"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["connection-sockets"] = sysTopics[topic]; htmlIdsToUpdate["systopic-connection-sockets"] = sysTopics[topic]; } topic = "$SYS/broker/load/messages/received/1min"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); const chartId = "chart-messages-received-rate"; chartIdsToUpdate[chartId] = sysTopics[topic]; this.updateMatchingChart(chartId, sysTopics, chartIdsToUpdate); htmlIdsToUpdate["systopic-messages-received-1min"] = sysTopics[topic]; } topic = "$SYS/broker/load/messages/received/10min"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-messages-received-10min"] = sysTopics[topic]; } topic = "$SYS/broker/load/messages/received/15min"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-messages-received-15min"] = sysTopics[topic]; } topic = "$SYS/broker/load/messages/sent/1min"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); const chartId = "chart-messages-sent-rate"; chartIdsToUpdate[chartId] = sysTopics[topic]; this.updateMatchingChart(chartId, sysTopics, chartIdsToUpdate); htmlIdsToUpdate["systopic-messages-sent-1min"] = sysTopics[topic]; } topic = "$SYS/broker/load/messages/sent/10min"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-messages-sent-10min"] = sysTopics[topic]; } topic = "$SYS/broker/load/messages/sent/15min"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-messages-sent-15min"] = sysTopics[topic]; } topic = "$SYS/broker/messages/stored"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["messages-stored"] = sysTopics[topic]; htmlIdsToUpdate["systopic-messages-stored"] = sysTopics[topic]; } topic = "$SYS/broker/retained messages/count"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["messages-retained"] = sysTopics[topic]; htmlIdsToUpdate["systopic-messages-retained"] = sysTopics[topic]; } topic = "$SYS/broker/messages/received"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-messages-received"] = sysTopics[topic]; const chartId = "chart-messages-received"; chartIdsToUpdate[chartId] = sysTopics[topic]; this.updateMatchingChart(chartId, sysTopics, chartIdsToUpdate); } topic = "$SYS/broker/messages/sent"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-messages-sent"] = sysTopics[topic]; const chartId = "chart-messages-sent"; chartIdsToUpdate[chartId] = sysTopics[topic]; this.updateMatchingChart(chartId, sysTopics, chartIdsToUpdate); } topic = "$SYS/broker/store/messages/bytes"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-messages-stored-bytes"] = sysTopics[topic]; } topic = "$SYS/broker/bytes/received"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-received-bytes"] = sysTopics[topic]; } topic = "$SYS/broker/bytes/sent"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-sent-bytes"] = sysTopics[topic]; } topic = "$SYS/broker/publish/bytes/received"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-publish-received-bytes"] = sysTopics[topic]; } topic = "$SYS/broker/publish/bytes/sent"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-publish-sent-bytes"] = sysTopics[topic]; } topic = "$SYS/broker/publish/messages/dropped"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["messages-dropped"] = sysTopics[topic]; htmlIdsToUpdate["systopic-messages-dropped"] = sysTopics[topic]; chartIdsToUpdate["chart-messages-dropped"] = sysTopics[topic]; } topic = "$SYS/broker/publish/messages/received"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["messages-published-to-broker"] = sysTopics[topic]; htmlIdsToUpdate["systopic-messages-published-to-broker"] = sysTopics[topic]; } topic = "$SYS/broker/publish/messages/sent"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["messages-published-by-broker"] = sysTopics[topic]; htmlIdsToUpdate["systopic-messages-published-by-broker"] = sysTopics[topic]; } topic = "$SYS/broker/packet/out/count"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-out-packets"] = sysTopics[topic]; } topic = "$SYS/broker/packet/out/bytes"; if ( sysTopics[topic] !== undefined && this.dashboardDataObject.lastSysTopics[topic] !== sysTopics[topic] ) { this.updateLastSysTopics(topic, sysTopics[topic]); htmlIdsToUpdate["systopic-out-bytes"] = sysTopics[topic]; } if (!Object.keys(htmlIdsToUpdate).length) { htmlIdsToUpdate = null; } if (!Object.keys(chartIdsToUpdate).length) { chartIdsToUpdate = null; } return [htmlIdsToUpdate, chartIdsToUpdate]; } trimChartDataWindow(labels, dataset, timestampNow) { let earliestTimestamp = 0; while ( timestampNow - earliestTimestamp >= KEEP_DATAPOINTS_FOR_INTERVAL && labels.length && dataset.length ) { earliestTimestamp = timeStringToTimestamp(labels[0]); labels.shift(); dataset.shift(); } } processChartOverflow(labels, dataset, timestamp) { if (!labels.length || !dataset.length) { return; } if ( labels.length > MAX_POINTS_IN_CHART && dataset.length > MAX_POINTS_IN_CHART ) { labels.shift(); dataset.shift(); } if ( timestamp - timeStringToTimestamp(labels[0]) >= KEEP_DATAPOINTS_FOR_INTERVAL ) { this.trimChartDataWindow(labels, dataset, timestamp); } } datapointsAreSufficientlyDifferent(datapoint1, datapoint2) { if (Math.abs(datapoint1 - datapoint2) / datapoint1 > 0.2) { return true; } return false; } labelsAreFarApart(earlierTimeString, laterTimeString) { const earlierTimestamp = timeStringToTimestamp(earlierTimeString); const laterTimestamp = timeStringToTimestamp(laterTimeString); if ( laterTimestamp - earlierTimestamp > SMOOTHED_CHART_UPDATE_INTERVAL_IN_MILLISECONDS ) { // also works at the bound between two days because laterTimestamp - earlierTimestamp will in this case be negative, so we return false for the check happening when one timestamp (earlierTimestamp) is coming from the previous day and the current timestamp (laterTimestamp) is for the new day, just after midnight return true; } return false; } setMustUpdateForMatchingGraph(chartId) { const createAssertErrorMsg = (id) => `mustUpdate option not found for chart "${id}". Available options: ${JSON.stringify( this.dashboardDataObject.charts[id]?.options, )}. Available charts: ${Object.keys(this.dashboardDataObject.charts)}`; let oppositeChartId; if (chartId === "chart-messages-sent") { oppositeChartId = "chart-messages-received"; assertExistence( this.dashboardDataObject.charts[oppositeChartId]?.options?.mustUpdate, createAssertErrorMsg(oppositeChartId), ); this.dashboardDataObject.charts[oppositeChartId].options.mustUpdate = true; } else if (chartId === "chart-messages-received") { oppositeChartId = "chart-messages-sent"; assertExistence( this.dashboardDataObject.charts[oppositeChartId]?.options?.mustUpdate, createAssertErrorMsg(oppositeChartId), ); this.dashboardDataObject.charts[oppositeChartId].options.mustUpdate = true; } else if (chartId === "chart-messages-sent-rate") { oppositeChartId = "chart-messages-received-rate"; assertExistence( this.dashboardDataObject.charts[oppositeChartId]?.options?.mustUpdate, createAssertErrorMsg(oppositeChartId), ); this.dashboardDataObject.charts[oppositeChartId].options.mustUpdate = true; } else if (chartId === "chart-messages-received-rate") { oppositeChartId = "chart-messages-sent-rate"; assertExistence( this.dashboardDataObject.charts[oppositeChartId]?.options?.mustUpdate, createAssertErrorMsg(oppositeChartId), ); this.dashboardDataObject.charts[oppositeChartId].options.mustUpdate = true; } } addSmoothedDataPoint( chartData, chartLabels, chartOptions, datapoint, timeString, chartId, ) { const lastElement = chartData.smoothedData.pop(); const lastLabel = chartLabels.smoothedLabels.pop(); const smoothedDataLen = chartData.smoothedData.length; const smoothedLabelsLen = chartLabels.smoothedLabels.length; if (smoothedDataLen != smoothedLabelsLen) { const errorMessage = `Smoothed data and label set size deviated: ${smoothedDataLen} vs ${smoothedLabelsLen}. Broken state`; throw new Error(errorMessage); } if ( lastElement && lastLabel && (chartOptions.mustUpdate || // Compare popped datapoint and the one that is left in the array before it. We check that the differences between datapoints' values reaches a certain threshold or these datapoints have large time interval between insertions (smoothedDataLen == 0 && smoothedLabelsLen == 0) || this.datapointsAreSufficientlyDifferent( chartData.smoothedData[smoothedDataLen - 1], lastElement, ) || this.labelsAreFarApart( chartLabels.smoothedLabels[smoothedLabelsLen - 1], lastLabel, )) ) { !chartOptions.mustUpdate && this.setMustUpdateForMatchingGraph(chartId); // check is needed to avoud a circular update chartOptions.mustUpdate = false; chartData.smoothedData.push(lastElement); chartLabels.smoothedLabels.push(lastLabel); } // always append the latest datapoint regardless if its value is sufficiently different or not. this is to keep the graph up to date with the latest change and not make it appear stale or simply empty chartData.smoothedData.push(datapoint); chartLabels.smoothedLabels.push(timeString); } updateChartInner(id, datapoint, timestamp, dashboardDataObject) { const chart = this.charts[id]; // note: in headless mode chart will be undefined as no chart objects are initialized const chartData = dashboardDataObject.charts[id].data; const chartLabels = dashboardDataObject.charts[id].labels; const chartOptions = dashboardDataObject.charts[id].options; !this.headlessMode && assertExistence( chart, `Chart "${id}" not found. Available charts: ${Object.keys(this.charts)}`, ); assertExistence( chartData, `Data for the chart "${id}" not found. Available charts: ${Object.keys( this.dashboardDataObject.charts, )}`, ); assertExistence( chartLabels, `Labels for the chart "${id}" not found. Available charts: ${Object.keys( this.dashboardDataObject.charts, )}`, ); assertExistence( chartOptions, `Options for the chart "${id}" not found. Available charts: ${Object.keys( this.dashboardDataObject.charts, )}`, ); this.processChartOverflow( chartLabels.rawLabels, chartData.rawData, timestamp, ); let zoomLevel, currentEnd, lastX; if (!this.headlessMode) { [zoomLevel, currentEnd, lastX] = this.getChartPositionalData(chart); } const timeString = toTimeString(new Date(timestamp)); chartData.rawData.push(datapoint); chartLabels.rawLabels.push(timeString); this.addSmoothedDataPoint( chartData, chartLabels, chartOptions, datapoint, timeString, id, ); if ( !this.headlessMode && this.isEndElementVisibleAndDefaultZoom(lastX, currentEnd, zoomLevel) ) { this.slideChart(chart); } !this.headlessMode && chart.update(); // put 'none' for no animation on updates } getOverviewChartSubchartIds(id) { if (id == "chart-message-overview") { return ["chart-messages-sent", "chart-messages-received"]; } else if (id == "chart-message-rate-overview") { return ["chart-messages-sent-rate", "chart-messages-received-rate"]; } else { throw new Error(`No such overview chart id: ${id}`); } } updateOverviewChartInner(id, firstSubChartId, secondSubChartId) { if (this.headlessMode) { // this function only update the chart chart view itself, no data manipulations are done as it simply consumes other line charts. So we have nothing to do in headless mode return; } const chart = this.charts[id]; const firstChartData = this.dashboardDataObject.charts[firstSubChartId].data; const firstChartLabels = this.dashboardDataObject.charts[firstSubChartId].labels; const secondChartData = this.dashboardDataObject.charts[secondSubChartId].data; const secondChartLabels = this.dashboardDataObject.charts[secondSubChartId].labels; assertExistence( chart, `Chart "${id}" not found. Available charts: ${Object.keys(this.charts)}`, ); assertExistence( firstChartData, `Data for the first sub chart with id "${firstSubChartId}" not found. Available charts: ${Object.keys( this.dashboardDataObject.charts, )}`, ); assertExistence( firstChartLabels, `Labels for the first sub chart with id "${firstSubChartId}" not found. Available charts: ${Object.keys( this.dashboardDataObject.charts, )}`, ); assertExistence( secondChartData, `Data for the second sub chart with "${secondSubChartId}" not found. Available charts: ${Object.keys( this.dashboardDataObject.charts, )}`, ); assertExistence( secondChartLabels, `Labels for the second sub chart with id "${secondSubChartId}" not found. Available charts: ${Object.keys( this.dashboardDataObject.charts, )}`, ); const [zoomLevel, currentEnd, lastX, secondToLastX] = this.getChartPositionalData(chart); // compare to both last and second to last x because x may have already moved forward one step since it comes from a separate graph that gets rendered before overview graphs if ( this.isEndElementVisibleAndDefaultZoom(lastX, currentEnd, zoomLevel) || this.isEndElementVisibleAndDefaultZoom( secondToLastX, currentEnd, zoomLevel, ) ) { this.slideChart(chart); } chart.update(); } updateHtmlElementById(elementId, value) { const element = document.getElementById(elementId); if (element) { element.textContent = value; } } removeHtmlElementClass(elementId, className) { const element = document.getElementById(elementId); if (element) { element.classList.remove(className); } } addHtmlElementClass(elementId, className) { const element = document.getElementById(elementId); if (element) { element.classList.add(className); } } updateChart( id, datapoint, timestampMilliseconds, dashboardDataObject, lastDataPoint, isUpdatingAllCharts, ) { if (datapoint !== undefined || isUpdatingAllCharts) { this.updateChartInner( id, datapoint !== undefined ? datapoint : lastDataPoint, timestampMilliseconds, dashboardDataObject, ); } } updateOverviewChart( id, firstChartDatapoint, secondChartDatapoint, isUpdatingAllCharts, firstSubChartId, secondSubChartId, ) { if ( firstChartDatapoint !== undefined || secondChartDatapoint !== undefined || isUpdatingAllCharts ) { this.updateOverviewChartInner(id, firstSubChartId, secondSubChartId); } } getLastChartsDataPoints(dashboardDataObject) { const lastChartsDataPoints = { "chart-messages-dropped": dashboardDataObject.lastSysTopics[ "$SYS/broker/publish/messages/dropped" ], "chart-messages-sent": dashboardDataObject.lastSysTopics["$SYS/broker/messages/sent"], "chart-messages-received": dashboardDataObject.lastSysTopics["$SYS/broker/messages/received"], "chart-messages-sent-rate": dashboardDataObject.lastSysTopics[ "$SYS/broker/load/messages/sent/1min" ], "chart-messages-received-rate": dashboardDataObject.lastSysTopics[ "$SYS/broker/load/messages/received/1min" ], "chart-clients-connected": dashboardDataObject.lastSysTopics["$SYS/broker/clients/connected"], "chart-clients-disconnected": dashboardDataObject.lastSysTopics["$SYS/broker/clients/disconnected"], }; return lastChartsDataPoints; } updateCharts( chartData, dashboardDataObject, timestampMilliseconds, isUpdatingAllCharts, ) { const lastDataPoints = this.getLastChartsDataPoints(dashboardDataObject); let id = ""; id = "chart-messages-dropped"; this.updateChart( id, chartData[id], timestampMilliseconds, dashboardDataObject, lastDataPoints[id], isUpdatingAllCharts, ); id = "chart-messages-sent"; this.updateChart( id, chartData[id], timestampMilliseconds, dashboardDataObject, lastDataPoints[id], isUpdatingAllCharts, ); id = "chart-messages-received"; this.updateChart( id, chartData[id], timestampMilliseconds, dashboardDataObject, lastDataPoints[id], isUpdatingAllCharts, ); id = "chart-messages-sent-rate"; this.updateChart( id, chartData[id], timestampMilliseconds, dashboardDataObject, lastDataPoints[id], isUpdatingAllCharts, ); id = "chart-messages-received-rate"; this.updateChart( id, chartData[id], timestampMilliseconds, dashboardDataObject, lastDataPoints[id], isUpdatingAllCharts, ); id = "chart-clients-connected"; this.updateChart( id, chartData[id], timestampMilliseconds, dashboardDataObject, lastDataPoints[id], isUpdatingAllCharts, ); id = "chart-clients-disconnected"; this.updateChart( id, chartData[id], timestampMilliseconds, dashboardDataObject, lastDataPoints[id], isUpdatingAllCharts, ); id = "chart-messages-sent"; let id2 = "chart-messages-received"; this.updateOverviewChart( "chart-message-overview", chartData[id], chartData[id2], isUpdatingAllCharts, id, id2, ); id = "chart-messages-sent-rate"; id2 = "chart-messages-received-rate"; this.updateOverviewChart( "chart-message-rate-overview", chartData[id], chartData[id2], isUpdatingAllCharts, id, id2, ); } mustInsertDatapointDueToInterval( lastUpdateDueToIntervalTimestamp, nowTimestampMilliseconds, ) { if ( lastUpdateDueToIntervalTimestamp === 0 || nowTimestampMilliseconds - lastUpdateDueToIntervalTimestamp >= CHART_UPDATE_INTERVAL_IN_MILLISECONDS ) { return true; } return false; } async checkForDataUpdates() { const nowTimestampMilliseconds = new Date().getTime(); let sysTopics = null; try { sysTopics = await fetchData(SYSTOPIC_ENDPOINT, { signal: this.abort.signal, cache: "no-store", }); this.version = sysTopics?.["$SYS/broker/version"]; this.previousDataFetchFailed = false; this.brokerOnline = true; this.setBrokerVersion(); this.setBrokerStatus(); } catch (error) { const errorMsg = `Error fetching sys topics: ${error?.message}`; if (this.abort.signal.aborted || error?.name === "AbortError") { console.log("Fetching systopics aborted"); } else { console.error(errorMsg); if (!this.previousDataFetchFailed) { alert(errorMsg); } } this.brokerOnline = false; this.setBrokerStatus(); this.previousDataFetchFailed = true; } if (!sysTopics) { return; } const [metricsToUpdate, chartsToUpdate] = this.getElementsToUpdate(sysTopics); this.dashboardDataObject.lastSysTopics = sysTopics; if (!this.headlessMode && metricsToUpdate) { Object.entries(metricsToUpdate).forEach(([id, value]) => { this.updateHtmlElementById(id, value); }); } let updateAllCharts = false; if ( this.mustInsertDatapointDueToInterval( this.dashboardDataObject.lastUpdateDueToIntervalTimestamp, nowTimestampMilliseconds, ) ) { updateAllCharts = true; this.dashboardDataObject.lastUpdateDueToIntervalTimestamp = nowTimestampMilliseconds; } if (chartsToUpdate || updateAllCharts) { this.updateCharts( chartsToUpdate || {}, this.dashboardDataObject, nowTimestampMilliseconds, updateAllCharts, ); let chartsIds; if (updateAllCharts) { const lastDataPointsOfAllCharts = this.getLastChartsDataPoints( this.dashboardDataObject, ); // importantly this gives us ids of all charts chartsIds = Object.keys(lastDataPointsOfAllCharts); } else if (chartsToUpdate) { chartsIds = Object.keys(chartsToUpdate); } else { chartsIds = []; // nothing to update } this.updateStore(this.dashboardDataObject, chartsIds); } } updateStore(dashboardDataObject, idsOfChartsToUpdate) { try { sessionStorage.setItem( "options", JSON.stringify(dashboardDataObject.options), ); sessionStorage.setItem( "sysTopics", JSON.stringify(dashboardDataObject.lastSysTopics), ); sessionStorage.setItem( "updateDueToIntervalTimestamp", JSON.stringify(dashboardDataObject.lastUpdateDueToIntervalTimestamp), ); for (const key of idsOfChartsToUpdate) { const chartData = dashboardDataObject.charts[key]; if (!chartData) { throw new Error( `dashboardDataObject.charts does not contain key ${key}`, ); } sessionStorage.setItem(key, JSON.stringify(chartData)); } } catch (error) { const errorMsg = `Error while updating sessionStorage`; console.error(errorMsg); throw new Error(errorMsg + ": " + error?.message); } } async startDataUpdates() { const checkForDataUpdatesWrapper = async () => { try { await this.checkForDataUpdates(); } catch (error) { const errorMsg = `Error while checking for dashboard data updates ${error?.message}. Reopen the page to try again.`; console.error(errorMsg); alert(errorMsg); throw error; } }; try { await checkForDataUpdatesWrapper(); } catch (error) { return; } // we assume that we want to perform data updates every 5 seconds const timestampNow = new Date().getTime(); const nextTimestampDivisibleBy5Seconds = INTERVAL_5SECS_IN_MILLISECONDS * Math.floor(timestampNow / INTERVAL_5SECS_IN_MILLISECONDS) + INTERVAL_5SECS_IN_MILLISECONDS; // integer division and then reconstruct the actual number const interval = nextTimestampDivisibleBy5Seconds - timestampNow; const doDataUpdate = async () => { clearTimeout(this.timeoutHandler); let startTs, endTs; try { startTs = Date.now(); await checkForDataUpdatesWrapper(); endTs = Date.now(); } catch (error) { return; } const executionTimeMs = endTs - startTs; this.timeoutHandler = setTimeout( // don't want anything to get into a contending state while animation is running, so wait a bit after doDataUpdate returns () => queue.enqueue( toAsyncAndWaitAfter( doDataUpdate, CHARTJS_ANIMATION_DURATION_MS + 50, ), ), INTERVAL_5SECS_IN_MILLISECONDS - executionTimeMs > 0 ? INTERVAL_5SECS_IN_MILLISECONDS - executionTimeMs : 0, ); }; this.timeoutHandler = setTimeout( () => queue.enqueue(doDataUpdate), interval, ); } } ================================================ FILE: dashboard/src/app/index.js ================================================ document.addEventListener("DOMContentLoaded", () => { new Sidebar(); new MosquittoDashboard(); }); function checkNormalBannerImage(bannerImage, bannerCard) { const imageSrc = "https://mosquitto.org/banner/image"; // no extension on the file - it can svg or png const probe = new Image(); probe.onload = () => { bannerImage.src = imageSrc; }; probe.onerror = () => { console.warn("Banner-image didn't loaded"); }; probe.src = imageSrc; } function checkSvgBannerImage(bannerImage, bannerCard, bannerLink, bannerInner) { // if a full fledged svg found, display it and remove the default link const svgSrc = "https://mosquitto.org/banner/image.svg"; const svgProbe = new Image(); svgProbe.onload = () => { bannerImage.src = svgSrc; // Only if the svg exists (was loaded successfully) make a call to fetch it and then inline it. Requires CORS to be set on svgSrc fetch(svgSrc) .then((r) => r.text()) .then((svg) => { bannerInner.innerHTML = svg; bannerLink.removeAttribute("href"); }) .catch((error) => console.warn("SVG banner-image couldn't be fetched:", error), ); }; svgProbe.onerror = () => { console.warn("SVG Banner-image didn't loaded"); }; svgProbe.src = svgSrc; } document.addEventListener("DOMContentLoaded", function () { const toggleButton = document.getElementById("layout-toggle"); const chartsGrid = document.getElementById("charts-grid"); const layoutText = document.getElementById("layout-text"); const bannerImage = document.getElementById("banner-img"); const bannerCard = document.getElementById("banner-card"); const bannerInner = document.getElementById("banner-inner"); const bannerLink = document.getElementById("banner-link"); checkNormalBannerImage(bannerImage, bannerCard); checkSvgBannerImage(bannerImage, bannerCard, bannerLink, bannerInner); let isGridView = true; let storedSetting = sessionStorage.getItem("isGridView"); const toggleView = () => { if (isGridView) { // switch to single column chartsGrid.className = "grid grid-cols-1 gap-4"; layoutText.textContent = "Grid View"; isGridView = false; } else { // switch back to grid chartsGrid.className = "grid grid-cols-1 lg:grid-cols-2 gap-4"; layoutText.textContent = "Single Column"; isGridView = true; } sessionStorage.setItem("isGridView", JSON.stringify(isGridView)); }; if (storedSetting) { storedSetting = JSON.parse(storedSetting); if (storedSetting === false) { // set isGridView from the default value of true to match the "false" coming from the session store by calling the toggle function queue.enqueue(toAsyncAndWaitAfter(toggleView)); } } toggleButton.addEventListener("click", toggleView); }); ================================================ FILE: dashboard/src/app/listeners.js ================================================ class Listeners { constructor() { this.abort = new AbortController(); registerAbortController(this.abort, this); this.init(); } async init() { try { const listeners = await fetchData(LISTENERS_ENDPOINT, { signal: this.abort.signal, cache: "no-store", }); this.displayListeners(listeners); } catch (error) { if ( this.pageHiding || this.abort.signal.aborted || error?.name === "AbortError" ) { console.log("Fetching listeners aborted"); } else { console.error("Error fetching listeners:", error); alert(`Error loading listeners: ${error}`); } } } displayListeners(data) { const listenersContainer = document.getElementById("listeners-container"); const brokerAnonymListenerCnt = document.getElementById( "broker-anonym-listener-cnt", ); const brokerAllListenerCnt = document.getElementById( "broker-all-listener-cnt", ); brokerAnonymListenerCnt.innerHTML = ""; brokerAllListenerCnt.innerHTML = ""; listenersContainer.innerHTML = ""; if (!data || !data.listeners) { listenersContainer.innerHTML = '

No listeners available

'; return; } const listeners = data.listeners; brokerAllListenerCnt.textContent = listeners.length; const anonymousCount = listeners.filter((l) => l.allow_anonymous).length; if (anonymousCount > 0) { const warningText = document.createElement("span"); warningText.textContent = anonymousCount; const warningBadge = document.createElement("span"); warningBadge.className = "ml-2 px-2 py-1 text-xs font-medium rounded-full"; warningBadge.style.backgroundColor = "#fee2e2"; // red-100 warningBadge.style.color = "#dc2626"; // red-600 warningBadge.textContent = "UNSAFE"; brokerAnonymListenerCnt.appendChild(warningText); brokerAnonymListenerCnt.appendChild(warningBadge); } else { brokerAnonymListenerCnt.textContent = "none"; } listeners.forEach((listener, index) => { const listenerCard = this.createListenerCard(listener, index); listenersContainer.appendChild(listenerCard); }); } createCommandSection(listener, type, addMargin = true) { const commandSection = document.createElement("div"); if (addMargin) { commandSection.className = "mt-4"; } const commandHeader = document.createElement("div"); commandHeader.style.display = "flex"; commandHeader.style.alignItems = "center"; commandHeader.style.justifyContent = "space-between"; commandHeader.style.marginBottom = "0.5rem"; const commandContainer = document.createElement("div"); commandContainer.style.display = "flex"; const copyButton = document.createElement("button"); copyButton.className = "p-2 hover:bg-c-orange transition-colors"; copyButton.style.cursor = "pointer"; copyButton.style.border = "0.1px solid #d3d3d3"; copyButton.title = "Copy"; // create an svg copy icon const copyIcon = document.createElementNS( "http://www.w3.org/2000/svg", "svg", ); copyIcon.setAttribute("width", "16"); copyIcon.setAttribute("height", "16"); copyIcon.setAttribute("viewBox", "0 0 24 24"); copyIcon.setAttribute("fill", "none"); copyIcon.setAttribute("stroke", "currentColor"); copyIcon.setAttribute("stroke-width", "2"); copyIcon.style.color = "#6b7280"; // gray-500 copyButton.addEventListener("mouseenter", () => { copyIcon.style.stroke = "white"; checkIcon.style.stroke = "white"; }); copyButton.addEventListener("mouseleave", () => { copyIcon.style.stroke = "#6b7280"; // back to gray for copy icon and green for the checkmark checkIcon.style.stroke = "#10b981"; }); const copyPath = document.createElementNS( "http://www.w3.org/2000/svg", "path", ); copyPath.setAttribute( "d", "M8 4H6a2 2 0 00-2 2v12a2 2 0 002 2h8a2 2 0 002-2V6a2 2 0 00-2-2h-2m-4-1v1m0 0V2a1 1 0 011-1h2a1 1 0 011 1v1m-4 0h4", ); copyPath.setAttribute("stroke-linecap", "round"); copyPath.setAttribute("stroke-linejoin", "round"); copyIcon.appendChild(copyPath); copyButton.appendChild(copyIcon); // create an svg checkmark icon for the success state after copying const checkIcon = document.createElementNS( "http://www.w3.org/2000/svg", "svg", ); checkIcon.setAttribute("width", "16"); checkIcon.setAttribute("height", "16"); checkIcon.setAttribute("viewBox", "0 0 24 24"); checkIcon.setAttribute("fill", "none"); checkIcon.setAttribute("stroke", "currentColor"); checkIcon.setAttribute("stroke-width", "2"); checkIcon.style.color = "#10b981"; // green-500 checkIcon.style.display = "none"; const checkPath = document.createElementNS( "http://www.w3.org/2000/svg", "path", ); checkPath.setAttribute("d", "M5 13l4 4L19 7"); checkPath.setAttribute("stroke-linecap", "round"); checkPath.setAttribute("stroke-linejoin", "round"); checkIcon.appendChild(checkPath); copyButton.appendChild(checkIcon); copyButton.addEventListener("click", async () => { try { const command = this.generateConnectionCommand(listener, type); copyToClipboard(command); copyIcon.style.display = "none"; checkIcon.style.display = "block"; copyButton.title = "Copied!"; setTimeout(() => { copyIcon.style.display = "block"; checkIcon.style.display = "none"; copyButton.title = "Copy command"; }, 2000); } catch (err) { console.error("Error when copying to clipboard:", err); } }); const commandText = document.createElement("pre"); commandText.className = "bg-gray-100 p-2 text-sm font-mono"; commandText.style.overflowX = "auto"; commandText.style.whiteSpace = "pre-wrap"; commandText.style.width = "100%"; commandText.style.wordBreak = "break-all"; commandText.textContent = this.generateConnectionCommand(listener, type); commandContainer.appendChild(commandText); commandContainer.appendChild(copyButton); commandSection.appendChild(commandContainer); return commandSection; } createListenerCard(listener, index) { const card = document.createElement("div"); card.className = "card p-4 border border-gray-200"; const title = document.createElement("h3"); title.className = "font-semibold mb-4"; title.textContent = `Listener ${index + 1}`; const details = document.createElement("div"); details.className = "grid gap-2 text-sm mb-4"; if (listener.port) { details.appendChild(this.createDetailRow("Port", listener.port)); } if (listener.path) { details.appendChild(this.createDetailRow("Unix Socket", listener.path)); } if (listener.protocol) { details.appendChild(this.createDetailRow("Protocol", listener.protocol)); } details.appendChild( this.createDetailRow("TLS", listener.tls ? "Yes" : "No"), ); details.appendChild( this.createDetailRow("mTLS", listener.mtls ? "Yes" : "No"), ); details.appendChild( this.createDetailRow( "Allow Anonymous", listener.allow_anonymous ? "Yes" : "No", ), ); let commandSectionPub; if (listener.protocol !== "httpapi") { commandSectionPub = this.createCommandSection(listener, "mosquitto_pub"); } card.appendChild(title); card.appendChild(details); commandSectionPub && card.appendChild(commandSectionPub); return card; } createDetailRow(label, value) { const row = document.createElement("div"); row.className = "flex items-center"; const labelSpan = document.createElement("span"); labelSpan.className = "text-gray-500 mr-2"; labelSpan.style.width = "120px"; labelSpan.style.display = "inline-block"; labelSpan.textContent = label + ":"; const valueSpan = document.createElement("span"); valueSpan.className = "px-3 py-1 text-xs font-medium rounded-full text-center"; valueSpan.style.display = "inline-block"; valueSpan.style.border = "0.1px solid #d3d3d3"; valueSpan.textContent = value; row.appendChild(labelSpan); row.appendChild(valueSpan); return row; } generateConnectionCommand(listener, commandType = "mosquitto_pub") { if (listener.protocol === "httpapi") { return "HTTP API Listener - use REST calls instead of mosquitto_pub/sub"; } let command = commandType; if (listener.path) { command += ` --unix ${listener.path}`; } else { command += ` -h -p ${listener.port}`; } if (listener.mtls) { command += " --cert --key "; } if (listener.tls) { command += " --cafile "; } if (listener.protocol === "websockets") { command += " --ws"; } if (!listener.allow_anonymous) { command += " -u -P "; } command += " -t "; if (commandType === "mosquitto_pub") { command += " -m "; } return command; } } document.addEventListener("DOMContentLoaded", () => { new Sidebar(); new Listeners(); new MosquittoDashboard(true); }); ================================================ FILE: dashboard/src/app/sidebar.js ================================================ class Sidebar { constructor() { this.menuToggle = document.getElementById("menu-toggle"); this.menuClose = document.getElementById("menu-close"); this.slidingMenu = document.getElementById("sliding-menu"); this.menuOverlay = document.getElementById("menu-overlay"); this.mainContent = document.getElementById("main-content"); this.root = document.documentElement; this.isOpen = sessionStorage.getItem("isSidebarOpen") === "true"; // !isMobile() becase we don't want the sidebar to be preloaded as open on mobile - there is no space anyway if (!isMobile() && this.isOpen) { this.openMenu(); // the initial open of the sidebar is hanlded by the inlined preload script but calling openMenu will properly set hamburger icon to be an arrow icon } this.bindEvents(); } bindEvents() { this.menuToggle.addEventListener("click", () => this.toggleMenu()); this.menuClose.addEventListener("click", () => this.closeMenu()); this.menuOverlay.addEventListener("click", () => this.closeMenu()); document.addEventListener("keydown", (e) => { if (e.key === "Escape" && this.isOpen) { this.closeMenu(); } }); window.addEventListener("resize", () => { this.syncUi(); }); } toggleMenu() { if (this.isOpen) { this.closeMenu(); } else { this.openMenu(); } } syncUi() { document .getElementById("hamburger-icon") .classList.toggle("hidden", this.isOpen); document .getElementById("arrow-icon") .classList.toggle("hidden", !this.isOpen); const showOverlay = this.isOpen && isMobile(); document.body.classList.toggle("sidebar-lock-scroll", showOverlay); } openMenu() { this.isOpen = true; sessionStorage.setItem("isSidebarOpen", "true"); this.root.classList.add("sidebar-open"); this.syncUi(); } closeMenu() { this.isOpen = false; sessionStorage.setItem("isSidebarOpen", "false"); this.root.classList.remove("sidebar-open"); this.syncUi(); } } ================================================ FILE: dashboard/src/css/styles.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; .bg-c-orange { background-color: #fd602e; } .hover\:bg-c-orange:hover { background-color: #fd602e; } #menu-overlay { transition: opacity 300ms; opacity: 0; pointer-events: none; background: rgba(0,0,0,0.45); } @media (min-width: 1024px) { #menu-overlay { display: none; } #sliding-menu { box-shadow: none; } #menu-close { visibility: hidden; } #broker-info-icon { display: block; } } #sliding-menu { transform: translateX(-100%); transition: transform 300ms; } .sidebar-open #sliding-menu { transform: translateX(0); } @media (max-width: 1023px) { .sidebar-open #menu-overlay { opacity: 1; pointer-events: auto; } } @media (min-width: 1024px) { .sidebar-open #main-content { margin-left: 320px; } } /* lock scroll on mobile when sidebar open */ .sidebar-lock-scroll { overflow: hidden; } .sidebar-preload #sliding-menu { transition: none; } @media (max-width: 1024px) { #layout-toggle { display: none; } } @media (max-width: 375px) { #logo-icon { display: block; } #logo-text { display: none } } .broker-active { background-color: rgb(34 197 94); /* green-500 */ } .broker-inactive { background-color: rgb(239 68 68); /* red-500 */ } @layer components { .card { @apply bg-white rounded-lg border border-gray-200 shadow-sm; } .card-header { @apply px-6 py-4 border-b border-gray-200; } .card-content { @apply px-6 py-4; } .metric-value { @apply text-3xl font-bold text-gray-900; } .metric-label { @apply text-sm font-medium text-gray-500 mb-2; } .status-dot { @apply w-3 h-3 rounded-full; } .chart-container { position: relative; height: 200px; width: 100%; } .nav-btn { @apply inline-flex items-center justify-center w-8 h-8 text-gray-500 bg-white border border-gray-300 rounded hover:bg-gray-50 hover:text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 transition-colors duration-150 disabled:opacity-50 disabled:cursor-not-allowed; } .nav-btn:hover:not(:disabled) { @apply shadow-sm; } .nav-btn.active { @apply bg-blue-50 border-blue-300 text-blue-600; } .nav-separator { @apply w-px h-6 bg-gray-300 mx-2; } .nav-btn svg { pointer-events: none; } } ================================================ FILE: dashboard/src/index.html ================================================ Mosquitto Broker Dashboard

Broker Information

version:
uptime: ?
status:
clients online
?
clients total
?
clients expired
?
clients offline
?
max simultaneous clients
?
connection sockets
?
total subscriptions
?
messages published to the broker
?
messages published by the broker
?
publishes dropped
?
messages retained
?
messages stored
?
messages dropped
online clients
offline clients
messages sent
messages received
messages sent per minute
messages received per minute

Published vs Received Messages Total

Publish vs Received Messages Rates

System Metrics

$SYS/broker/clients/total ?
$SYS/broker/clients/disconnected ?
$SYS/broker/clients/connected ?
$SYS/broker/clients/maximum ?
$SYS/broker/clients/expired ?
$SYS/broker/subscriptions/count ?
$SYS/broker/shared_subscriptions/count ?
$SYS/broker/heap/current ?
$SYS/broker/heap/maximum ?
$SYS/broker/connections/socket/count ?

Traffic Metrics

$SYS/broker/load/messages/received/1min ?
$SYS/broker/load/messages/received/10min ?
$SYS/broker/load/messages/received/15min ?
$SYS/broker/load/messages/sent/1min ?
$SYS/broker/load/messages/sent/10min ?
$SYS/broker/load/messages/sent/15min ?
$SYS/broker/messages/stored ?
$SYS/broker/retained messages/count ?
$SYS/broker/messages/received ?
$SYS/broker/messages/sent ?
$SYS/broker/store/messages/bytes ?
$SYS/broker/bytes/received ?
$SYS/broker/bytes/sent ?
$SYS/broker/publish/bytes/received ?
$SYS/broker/publish/bytes/sent ?
$SYS/broker/publish/messages/dropped ?
$SYS/broker/publish/messages/received ?
$SYS/broker/publish/messages/sent ?
$SYS/broker/packet/out/count ?
$SYS/broker/packet/out/bytes ?
================================================ FILE: dashboard/src/lib/chart.umd.js ================================================ /*! * Chart.js v4.3.0 * https://www.chartjs.org * (c) 2023 Chart.js Contributors * Released under the MIT License */ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Ko},get Decimation(){return Jo},get Filler(){return pa},get Legend(){return _a},get SubTitle(){return wa},get Title(){return va},get Tooltip(){return Va}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;at,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)t-e)).pop(),e}function W(t){return!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;sl&&h=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return nt[s][e]et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;ss&&t[n-1]>i;)n--;return s>0||n{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...e){const n=s.apply(this,e);return t._chartjs.listeners.forEach((t=>{"function"==typeof t[i]&&t[i](...e)})),n}})})))}function rt(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(ot.forEach((e=>{delete t[e]})),delete t._chartjs)}function lt(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const ht="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function ct(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,ht.call(window,(()=>{s=!1,t.apply(e,i)})))}}function dt(t,e){let i;return function(...s){return e?(clearTimeout(i),i=setTimeout(t,e,s)):t.apply(this,s),e}}const ut=t=>"start"===t?"left":"end"===t?"right":"center",ft=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2,gt=(t,e,i,s)=>t===(s?"left":"right")?i:"center"===t?(e+i)/2:e;function pt(t,e,i){const s=e.length;let n=0,o=s;if(t._sorted){const{iScale:a,_parsed:r}=t,l=a.axis,{min:h,max:c,minDefined:d,maxDefined:u}=a.getUserBounds();d&&(n=J(Math.min(it(r,a.axis,h).lo,i?s:it(e,l,a.getPixelForValue(h)).lo),0,s-1)),o=u?J(Math.max(it(r,a.axis,c,!0).hi+1,i?0:it(e,l,a.getPixelForValue(c),!0).hi+1),n,s)-n:s-n}return{start:n,count:o}}function mt(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=n,!0;const o=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,n),o}class bt{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,s){const n=e.listeners[s],o=e.duration;n.forEach((s=>s({chart:t,initial:e.initial,numSteps:o,currentStep:Math.min(i-e.start,o)})))}_refresh(){this._request||(this._running=!0,this._request=ht.call(window,(()=>{this._update(),this._request=null,this._running&&this._refresh()})))}_update(t=Date.now()){let e=0;this._charts.forEach(((i,s)=>{if(!i.running||!i.items.length)return;const n=i.items;let o,a=n.length-1,r=!1;for(;a>=0;--a)o=n[a],o._active?(o._total>i.duration&&(i.duration=o._total),o.tick(t),r=!0):(n[a]=n[n.length-1],n.pop());r&&(s.draw(),this._notify(s,i,t,"progress")),n.length||(i.running=!1,this._notify(s,i,t,"complete"),i.initial=!1),e+=n.length})),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce(((t,e)=>Math.max(t,e._duration)),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const i=e.items;let s=i.length-1;for(;s>=0;--s)i[s].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}var xt=new bt; /*! * @kurkle/color v0.3.2 * https://github.com/kurkle/color#readme * (c) 2023 Jukka Kurkela * Released under the MIT License */function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=Ft(s),t.r=s[0],t.g=s[1],t.b=s[2]}}function qt(t,e){return t?Object.assign(e||{},t):t}function Kt(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Mt(t[3]))):(e=qt(t,{r:0,g:0,b:0,a:1})).a=Mt(e.a),e}function Gt(t){return"r"===t.charAt(0)?function(t){const e=$t.exec(t);let i,s,n,o=255;if(e){if(e[7]!==i){const t=+e[7];o=e[8]?vt(t):yt(255*t,0,255)}return i=+e[1],s=+e[3],n=+e[5],i=255&(e[2]?vt(i):yt(i,0,255)),s=255&(e[4]?vt(s):yt(s,0,255)),n=255&(e[6]?vt(n):yt(n,0,255)),{r:i,g:s,b:n,a:o}}}(t):Bt(t)}class Zt{constructor(t){if(t instanceof Zt)return t;const e=typeof t;let i;var s,n,o;"object"===e?i=Kt(t):"string"===e&&(o=(s=t).length,"#"===s[0]&&(4===o||5===o?n={r:255&17*St[s[1]],g:255&17*St[s[2]],b:255&17*St[s[3]],a:5===o?17*St[s[4]]:255}:7!==o&&9!==o||(n={r:St[s[1]]<<4|St[s[2]],g:St[s[3]]<<4|St[s[4]],b:St[s[5]]<<4|St[s[6]],a:9===o?St[s[7]]<<4|St[s[8]]:255})),i=n||jt(t)||Gt(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=qt(this._rgb);return t&&(t.a=wt(t.a)),t}set rgb(t){this._rgb=Kt(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${wt(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?At(this._rgb):void 0}hslString(){return this._valid?function(t){if(!t)return;const e=It(t),i=e[0],s=kt(e[1]),n=kt(e[2]);return t.a<255?`hsla(${i}, ${s}%, ${n}%, ${wt(t.a)})`:`hsl(${i}, ${s}%, ${n}%)`}(this._rgb):void 0}mix(t,e){if(t){const i=this.rgb,s=t.rgb;let n;const o=e===n?.5:e,a=2*o-1,r=i.a-s.a,l=((a*r==-1?a:(a+r)/(1+a*r))+1)/2;n=1-l,i.r=255&l*i.r+n*s.r+.5,i.g=255&l*i.g+n*s.g+.5,i.b=255&l*i.b+n*s.b+.5,i.a=o*i.a+(1-o)*s.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=function(t,e,i){const s=Ut(wt(t.r)),n=Ut(wt(t.g)),o=Ut(wt(t.b));return{r:Mt(Yt(s+i*(Ut(wt(e.r))-s))),g:Mt(Yt(n+i*(Ut(wt(e.g))-n))),b:Mt(Yt(o+i*(Ut(wt(e.b))-o))),a:t.a+i*(e.a-t.a)}}(this._rgb,t._rgb,e)),this}clone(){return new Zt(this.rgb)}alpha(t){return this._rgb.a=Mt(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=_t(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Xt(this._rgb,2,t),this}darken(t){return Xt(this._rgb,2,-t),this}saturate(t){return Xt(this._rgb,1,t),this}desaturate(t){return Xt(this._rgb,1,-t),this}rotate(t){return function(t,e){var i=It(t);i[0]=Vt(i[0]+e),i=Ft(i),t.r=i[0],t.g=i[1],t.b=i[2]}(this._rgb,t),this}}function Jt(t){if(t&&"object"==typeof t){const e=t.toString();return"[object CanvasPattern]"===e||"[object CanvasGradient]"===e}return!1}function Qt(t){return Jt(t)?t:new Zt(t)}function te(t){return Jt(t)?t:new Zt(t).saturate(.5).darken(.1).hexString()}const ee=["x","y","borderWidth","radius","tension"],ie=["color","borderColor","backgroundColor"];const se=new Map;function ne(t,e,i){return function(t,e){e=e||{};const i=t+JSON.stringify(e);let s=se.get(i);return s||(s=new Intl.NumberFormat(t,e),se.set(i,s)),s}(e,i).format(t)}const oe={values:t=>n(t)?t:""+t,numeric(t,e,i){if(0===t)return"0";const s=this.chart.options.locale;let n,o=t;if(i.length>1){const e=Math.max(Math.abs(i[0].value),Math.abs(i[i.length-1].value));(e<1e-4||e>1e15)&&(n="scientific"),o=function(t,e){let i=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;Math.abs(i)>=1&&t!==Math.floor(t)&&(i=t-Math.floor(t));return i}(t,i)}const a=z(Math.abs(o)),r=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),l={notation:n,minimumFractionDigits:r,maximumFractionDigits:r};return Object.assign(l,this.options.ticks.format),ne(t,s,l)},logarithmic(t,e,i){if(0===t)return"0";const s=i[e].significand||t/Math.pow(10,Math.floor(z(t)));return[1,2,3,5,10,15].includes(s)||e>.8*i.length?oe.numeric.call(this,t,e,i):""}};var ae={formatters:oe};const re=Object.create(null),le=Object.create(null);function he(t,e){if(!e)return t;const i=e.split(".");for(let e=0,s=i.length;et.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>te(e.backgroundColor),this.hoverBorderColor=(t,e)=>te(e.borderColor),this.hoverColor=(t,e)=>te(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return ce(this,t,e)}get(t){return he(this,t)}describe(t,e){return ce(le,t,e)}override(t,e){return ce(re,t,e)}route(t,e,i,s){const n=he(this,t),a=he(this,i),r="_"+e;Object.defineProperties(n,{[r]:{value:n[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[r],e=a[s];return o(t)?Object.assign({},e,t):l(t,e)},set(t){this[r]=t}}})}apply(t){t.forEach((t=>t(this)))}}var ue=new de({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),t.set("animations",{colors:{type:"color",properties:ie},numbers:{type:"number",properties:ee}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}})},function(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:ae.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t&&"dash"!==t}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t})}]);function fe(){return"undefined"!=typeof window&&"undefined"!=typeof document}function ge(t){let e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e}function pe(t,e,i){let s;return"string"==typeof t?(s=parseInt(t,10),-1!==t.indexOf("%")&&(s=s/100*e.parentNode[i])):s=t,s}const me=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function be(t,e){return me(t).getPropertyValue(e)}const xe=["top","right","bottom","left"];function _e(t,e,i){const s={};i=i?"-"+i:"";for(let n=0;n<4;n++){const o=xe[n];s[o]=parseFloat(t[e+"-"+o+i])||0}return s.width=s.left+s.right,s.height=s.top+s.bottom,s}const ye=(t,e,i)=>(t>0||e>0)&&(!i||!i.shadowRoot);function ve(t,e){if("native"in t)return t;const{canvas:i,currentDevicePixelRatio:s}=e,n=me(i),o="border-box"===n.boxSizing,a=_e(n,"padding"),r=_e(n,"border","width"),{x:l,y:h,box:c}=function(t,e){const i=t.touches,s=i&&i.length?i[0]:t,{offsetX:n,offsetY:o}=s;let a,r,l=!1;if(ye(n,o,t.target))a=n,r=o;else{const t=e.getBoundingClientRect();a=s.clientX-t.left,r=s.clientY-t.top,l=!0}return{x:a,y:r,box:l}}(t,i),d=a.left+(c&&r.left),u=a.top+(c&&r.top);let{width:f,height:g}=e;return o&&(f-=a.width+r.width,g-=a.height+r.height),{x:Math.round((l-d)/f*i.width/s),y:Math.round((h-u)/g*i.height/s)}}const Me=t=>Math.round(10*t)/10;function we(t,e,i,s){const n=me(t),o=_e(n,"margin"),a=pe(n.maxWidth,t,"clientWidth")||T,r=pe(n.maxHeight,t,"clientHeight")||T,l=function(t,e,i){let s,n;if(void 0===e||void 0===i){const o=ge(t);if(o){const t=o.getBoundingClientRect(),a=me(o),r=_e(a,"border","width"),l=_e(a,"padding");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=pe(a.maxWidth,o,"clientWidth"),n=pe(a.maxHeight,o,"clientHeight")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||T,maxHeight:n||T}}(t,e,i);let{width:h,height:c}=l;if("content-box"===n.boxSizing){const t=_e(n,"border","width"),e=_e(n,"padding");h-=e.width+t.width,c-=e.height+t.height}h=Math.max(0,h-o.width),c=Math.max(0,s?h/s:c-o.height),h=Me(Math.min(h,a,l.maxWidth)),c=Me(Math.min(c,r,l.maxHeight)),h&&!c&&(c=Me(h/2));return(void 0!==e||void 0!==i)&&s&&l.height&&c>l.height&&(c=l.height,h=Me(Math.floor(c*s))),{width:h,height:c}}function ke(t,e,i){const s=e||1,n=Math.floor(t.height*s),o=Math.floor(t.width*s);t.height=Math.floor(t.height),t.width=Math.floor(t.width);const a=t.canvas;return a.style&&(i||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`),(t.currentDevicePixelRatio!==s||a.height!==n||a.width!==o)&&(t.currentDevicePixelRatio=s,a.height=n,a.width=o,t.ctx.setTransform(s,0,0,s,0,0),!0)}const Se=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};window.addEventListener("test",null,e),window.removeEventListener("test",null,e)}catch(t){}return t}();function Pe(t,e){const i=be(t,e),s=i&&i.match(/^(\d+)(\.\d+)?px$/);return s?+s[1]:void 0}function De(t){return!t||s(t.size)||s(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Ce(t,e,i,s,n){let o=e[n];return o||(o=e[n]=t.measureText(n).width,i.push(n)),o>s&&(s=o),s}function Oe(t,e,i,s){let o=(s=s||{}).data=s.data||{},a=s.garbageCollect=s.garbageCollect||[];s.font!==e&&(o=s.data={},a=s.garbageCollect=[],s.font=e),t.save(),t.font=e;let r=0;const l=i.length;let h,c,d,u,f;for(h=0;hi.length){for(h=0;h0&&t.stroke()}}function Re(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.xe.top-i&&t.y0&&""!==r.strokeColor;let c,d;for(t.save(),t.font=a.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),s(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,r),c=0;ct[0])){const o=i||t;void 0===s&&(s=ti("_fallback",t));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:s,_getTarget:n,override:i=>je([i,...t],e,o,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete e._keys,delete t[0][i],!0),get:(i,s)=>qe(i,s,(()=>function(t,e,i,s){let n;for(const o of e)if(n=ti(Ue(o,t),i),void 0!==n)return Xe(t,n)?Je(i,s,t,n):n}(s,e,t,i))),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>ei(t).includes(e),ownKeys:t=>ei(t),set(t,e,i){const s=t._storage||(t._storage=n());return t[e]=s[e]=i,delete t._keys,!0}})}function $e(t,e,i,s){const a={_cacheable:!1,_proxy:t,_context:e,_subProxy:i,_stack:new Set,_descriptors:Ye(t,s),setContext:e=>$e(t,e,i,s),override:n=>$e(t.override(n),e,i,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete t[i],!0),get:(t,e,i)=>qe(t,e,(()=>function(t,e,i){const{_proxy:s,_context:a,_subProxy:r,_descriptors:l}=t;let h=s[e];S(h)&&l.isScriptable(e)&&(h=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_stack:r}=i;if(r.has(t))throw new Error("Recursion detected: "+Array.from(r).join("->")+"->"+t);r.add(t);let l=e(o,a||s);r.delete(t),Xe(t,l)&&(l=Je(n._scopes,n,t,l));return l}(e,h,t,i));n(h)&&h.length&&(h=function(t,e,i,s){const{_proxy:n,_context:a,_subProxy:r,_descriptors:l}=i;if(void 0!==a.index&&s(t))return e[a.index%e.length];if(o(e[0])){const i=e,s=n._scopes.filter((t=>t!==i));e=[];for(const o of i){const i=Je(s,n,t,o);e.push($e(i,a,r&&r[t],l))}}return e}(e,h,t,l.isIndexable));Xe(e,h)&&(h=$e(h,a,r&&r[e],l));return h}(t,e,i))),getOwnPropertyDescriptor:(e,i)=>e._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,i)=>Reflect.has(t,i),ownKeys:()=>Reflect.ownKeys(t),set:(e,i,s)=>(t[i]=s,delete e[i],!0)})}function Ye(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:n=e.allKeys}=t;return{allKeys:n,scriptable:i,indexable:s,isScriptable:S(i)?i:()=>i,isIndexable:S(s)?s:()=>s}}const Ue=(t,e)=>t?t+w(e):e,Xe=(t,e)=>o(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function qe(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const s=i();return t[e]=s,s}function Ke(t,e,i){return S(t)?t(e,i):t}const Ge=(t,e)=>!0===t?e:"string"==typeof t?M(e,t):void 0;function Ze(t,e,i,s,n){for(const o of e){const e=Ge(i,o);if(e){t.add(e);const o=Ke(e._fallback,i,n);if(void 0!==o&&o!==i&&o!==s)return o}else if(!1===e&&void 0!==s&&i!==s)return null}return!1}function Je(t,e,i,s){const a=e._rootScopes,r=Ke(e._fallback,i,s),l=[...t,...a],h=new Set;h.add(s);let c=Qe(h,l,i,r||i,s);return null!==c&&((void 0===r||r===i||(c=Qe(h,l,r,c,s),null!==c))&&je(Array.from(h),[""],a,r,(()=>function(t,e,i){const s=t._getTarget();e in s||(s[e]={});const a=s[e];if(n(a)&&o(i))return i;return a||{}}(e,i,s))))}function Qe(t,e,i,s,n){for(;i;)i=Ze(t,e,i,s,n);return i}function ti(t,e){for(const i of e){if(!i)continue;const e=i[t];if(void 0!==e)return e}}function ei(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter((t=>!t.startsWith("_"))))e.add(t);return Array.from(e)}(t._scopes)),e}function ii(t,e,i,s){const{iScale:n}=t,{key:o="r"}=this._parsing,a=new Array(s);let r,l,h,c;for(r=0,l=s;re"x"===t?"y":"x";function ai(t,e,i,s){const n=t.skip?e:t,o=e,a=i.skip?e:i,r=q(o,n),l=q(a,o);let h=r/(r+l),c=l/(r+l);h=isNaN(h)?0:h,c=isNaN(c)?0:c;const d=s*h,u=s*c;return{previous:{x:o.x-d*(a.x-n.x),y:o.y-d*(a.y-n.y)},next:{x:o.x+u*(a.x-n.x),y:o.y+u*(a.y-n.y)}}}function ri(t,e="x"){const i=oi(e),s=t.length,n=Array(s).fill(0),o=Array(s);let a,r,l,h=ni(t,0);for(a=0;a!t.skip))),"monotone"===e.cubicInterpolationMode)ri(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o0===t||1===t,di=(t,e,i)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*O/i),ui=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*O/i)+1,fi={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*E),easeOutSine:t=>Math.sin(t*E),easeInOutSine:t=>-.5*(Math.cos(C*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>ci(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ci(t)?t:di(t,.075,.3),easeOutElastic:t=>ci(t)?t:ui(t,.075,.3),easeInOutElastic(t){const e=.1125;return ci(t)?t:t<.5?.5*di(2*t,e,.45):.5+.5*ui(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-fi.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*fi.easeInBounce(2*t):.5*fi.easeOutBounce(2*t-1)+.5};function gi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function pi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:"middle"===s?i<.5?t.y:e.y:"after"===s?i<1?t.y:e.y:i>0?e.y:t.y}}function mi(t,e,i,s){const n={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},a=gi(t,n,i),r=gi(n,o,i),l=gi(o,e,i),h=gi(a,r,i),c=gi(r,l,i);return gi(h,c,i)}const bi=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,xi=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function _i(t,e){const i=(""+t).match(bi);if(!i||"normal"===i[1])return 1.2*e;switch(t=+i[2],i[3]){case"px":return t;case"%":t/=100}return e*t}const yi=t=>+t||0;function vi(t,e){const i={},s=o(e),n=s?Object.keys(e):e,a=o(t)?s?i=>l(t[i],t[e[i]]):e=>t[e]:()=>t;for(const t of n)i[t]=yi(a(t));return i}function Mi(t){return vi(t,{top:"y",right:"x",bottom:"y",left:"x"})}function wi(t){return vi(t,["topLeft","topRight","bottomLeft","bottomRight"])}function ki(t){const e=Mi(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Si(t,e){t=t||{},e=e||ue.font;let i=l(t.size,e.size);"string"==typeof i&&(i=parseInt(i,10));let s=l(t.style,e.style);s&&!(""+s).match(xi)&&(console.warn('Invalid font style specified: "'+s+'"'),s=void 0);const n={family:l(t.family,e.family),lineHeight:_i(l(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:l(t.weight,e.weight),string:""};return n.string=De(n),n}function Pi(t,e,i,s){let o,a,r,l=!0;for(o=0,a=t.length;oi&&0===t?0:t+e;return{min:a(s,-Math.abs(o)),max:a(n,o)}}function Ci(t,e){return Object.assign(Object.create(t),e)}function Oi(t,e,i){return t?function(t,e){return{x:i=>t+t+e-i,setWidth(t){e=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,i):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Ai(t,e){let i,s;"ltr"!==e&&"rtl"!==e||(i=t.canvas.style,s=[i.getPropertyValue("direction"),i.getPropertyPriority("direction")],i.setProperty("direction",e,"important"),t.prevTextDirection=s)}function Ti(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Li(t){return"angle"===t?{between:Z,compare:K,normalize:G}:{between:tt,compare:(t,e)=>t-e,normalize:t=>t}}function Ei({start:t,end:e,count:i,loop:s,style:n}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:n}}function Ri(t,e,i){if(!i)return[t];const{property:s,start:n,end:o}=i,a=e.length,{compare:r,between:l,normalize:h}=Li(s),{start:c,end:d,loop:u,style:f}=function(t,e,i){const{property:s,start:n,end:o}=i,{between:a,normalize:r}=Li(s),l=e.length;let h,c,{start:d,end:u,loop:f}=t;if(f){for(d+=l,u+=l,h=0,c=l;hx||l(n,b,p)&&0!==r(n,b),v=()=>!x||0===r(o,p)||l(o,b,p);for(let t=c,i=c;t<=d;++t)m=e[t%a],m.skip||(p=h(m[s]),p!==b&&(x=l(p,n,o),null===_&&y()&&(_=0===r(p,n)?t:i),null!==_&&v()&&(g.push(Ei({start:_,end:t,loop:u,count:a,style:f})),_=null),i=t,b=p));return null!==_&&g.push(Ei({start:_,end:d,loop:u,count:a,style:f})),g}function Ii(t,e){const i=[],s=t.segments;for(let n=0;nn&&t[o%e].skip;)o--;return o%=e,{start:n,end:o}}(i,n,o,s);if(!0===s)return Fi(t,[{start:a,end:r,loop:o}],i,e);return Fi(t,function(t,e,i,s){const n=t.length,o=[];let a,r=e,l=t[e];for(a=e+1;a<=i;++a){const i=t[a%n];i.skip||i.stop?l.skip||(s=!1,o.push({start:e%n,end:(a-1)%n,loop:s}),e=r=i.stop?a:null):(r=a,l.skip&&(e=a)),l=i}return null!==r&&o.push({start:e%n,end:r%n,loop:s}),o}(i,a,r{t[a](e[i],n)&&(o.push({element:t,datasetIndex:s,index:l}),r=r||t.inRange(e.x,e.y,n))})),s&&!r?[]:o}var Xi={evaluateInteractionItems:Hi,modes:{index(t,e,i,s){const n=ve(e,t),o=i.axis||"x",a=i.includeInvisible||!1,r=i.intersect?ji(t,n,o,s,a):Yi(t,n,o,!1,s,a),l=[];return r.length?(t.getSortedVisibleDatasetMetas().forEach((t=>{const e=r[0].index,i=t.data[e];i&&!i.skip&&l.push({element:i,datasetIndex:t.index,index:e})})),l):[]},dataset(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;let r=i.intersect?ji(t,n,o,s,a):Yi(t,n,o,!1,s,a);if(r.length>0){const e=r[0].datasetIndex,i=t.getDatasetMeta(e).data;r=[];for(let t=0;tji(t,ve(e,t),i.axis||"xy",s,i.includeInvisible||!1),nearest(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;return Yi(t,n,o,i.intersect,s,a)},x:(t,e,i,s)=>Ui(t,ve(e,t),"x",i.intersect,s),y:(t,e,i,s)=>Ui(t,ve(e,t),"y",i.intersect,s)}};const qi=["left","top","right","bottom"];function Ki(t,e){return t.filter((t=>t.pos===e))}function Gi(t,e){return t.filter((t=>-1===qi.indexOf(t.pos)&&t.box.axis===e))}function Zi(t,e){return t.sort(((t,i)=>{const s=e?i:t,n=e?t:i;return s.weight===n.weight?s.index-n.index:s.weight-n.weight}))}function Ji(t,e){const i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:n}=i;if(!t||!qi.includes(s))continue;const o=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=n}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:n}=e;let o,a,r;for(o=0,a=t.length;o{s[t]=Math.max(e[t],i[t])})),s}return s(t?["left","right"]:["top","bottom"])}function ss(t,e,i,s){const n=[];let o,a,r,l,h,c;for(o=0,a=t.length,h=0;ot.box.fullSize)),!0),s=Zi(Ki(e,"left"),!0),n=Zi(Ki(e,"right")),o=Zi(Ki(e,"top"),!0),a=Zi(Ki(e,"bottom")),r=Gi(e,"x"),l=Gi(e,"y");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Ki(e,"chartArea"),vertical:s.concat(n).concat(l),horizontal:o.concat(a).concat(r)}}(t.boxes),l=r.vertical,h=r.horizontal;u(t.boxes,(t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()}));const c=l.reduce(((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1),0)||1,d=Object.freeze({outerWidth:e,outerHeight:i,padding:n,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/c,hBoxMaxHeight:a/2}),f=Object.assign({},n);ts(f,ki(s));const g=Object.assign({maxPadding:f,w:o,h:a,x:n.left,y:n.top},n),p=Ji(l.concat(h),d);ss(r.fullSize,g,d,p),ss(l,g,d,p),ss(h,g,d,p)&&ss(l,g,d,p),function(t){const e=t.maxPadding;function i(i){const s=Math.max(e[i]-t[i],0);return t[i]+=s,s}t.y+=i("top"),t.x+=i("left"),i("right"),i("bottom")}(g),os(r.leftAndTop,g,d,p),g.x+=g.w,g.y+=g.h,os(r.rightAndBottom,g,d,p),t.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},u(r.chartArea,(e=>{const i=e.box;Object.assign(i,t.chartArea),i.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})}))}};class rs{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,s){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,s?Math.floor(e/s):i)}}isAttached(t){return!0}updateConfig(t){}}class ls extends rs{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const hs="$chartjs",cs={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},ds=t=>null===t||""===t;const us=!!Se&&{passive:!0};function fs(t,e,i){t.canvas.removeEventListener(e,i,us)}function gs(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function ps(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||gs(i.addedNodes,s),e=e&&!gs(i.removedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}function ms(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||gs(i.removedNodes,s),e=e&&!gs(i.addedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}const bs=new Map;let xs=0;function _s(){const t=window.devicePixelRatio;t!==xs&&(xs=t,bs.forEach(((e,i)=>{i.currentDevicePixelRatio!==t&&e()})))}function ys(t,e,i){const s=t.canvas,n=s&&ge(s);if(!n)return;const o=ct(((t,e)=>{const s=n.clientWidth;i(t,e),s{const e=t[0],i=e.contentRect.width,s=e.contentRect.height;0===i&&0===s||o(i,s)}));return a.observe(n),function(t,e){bs.size||window.addEventListener("resize",_s),bs.set(t,e)}(t,o),a}function vs(t,e,i){i&&i.disconnect(),"resize"===e&&function(t){bs.delete(t),bs.size||window.removeEventListener("resize",_s)}(t)}function Ms(t,e,i){const s=t.canvas,n=ct((e=>{null!==t.ctx&&i(function(t,e){const i=cs[t.type]||t.type,{x:s,y:n}=ve(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==n?n:null}}(e,t))}),t);return function(t,e,i){t.addEventListener(e,i,us)}(s,e,n),n}class ws extends rs{acquireContext(t,e){const i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(function(t,e){const i=t.style,s=t.getAttribute("height"),n=t.getAttribute("width");if(t[hs]={initial:{height:s,width:n,style:{display:i.display,height:i.height,width:i.width}}},i.display=i.display||"block",i.boxSizing=i.boxSizing||"border-box",ds(n)){const e=Pe(t,"width");void 0!==e&&(t.width=e)}if(ds(s))if(""===t.style.height)t.height=t.width/(e||2);else{const e=Pe(t,"height");void 0!==e&&(t.height=e)}}(t,e),i):null}releaseContext(t){const e=t.canvas;if(!e[hs])return!1;const i=e[hs].initial;["height","width"].forEach((t=>{const n=i[t];s(n)?e.removeAttribute(t):e.setAttribute(t,n)}));const n=i.style||{};return Object.keys(n).forEach((t=>{e.style[t]=n[t]})),e.width=e.width,delete e[hs],!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),n={attach:ps,detach:ms,resize:ys}[e]||Ms;s[e]=n(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];if(!s)return;({attach:vs,detach:vs,resize:vs}[e]||fs)(t,e,s),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return we(t,e,i,s)}isAttached(t){const e=ge(t);return!(!e||!e.isConnected)}}function ks(t){return!fe()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?ls:ws}var Ss=Object.freeze({__proto__:null,BasePlatform:rs,BasicPlatform:ls,DomPlatform:ws,_detectPlatform:ks});const Ps="transparent",Ds={boolean:(t,e,i)=>i>.5?e:t,color(t,e,i){const s=Qt(t||Ps),n=s.valid&&Qt(e||Ps);return n&&n.valid?n.mix(s,i).hexString():e},number:(t,e,i)=>t+(e-t)*i};class Cs{constructor(t,e,i,s){const n=e[i];s=Pi([t.to,s,n,t.from]);const o=Pi([t.from,n,s]);this._active=!0,this._fn=t.fn||Ds[t.type||typeof o],this._easing=fi[t.easing]||fi.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=o,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);const s=this._target[this._prop],n=i-this._start,o=this._duration-n;this._start=i,this._duration=Math.floor(Math.max(o,t.duration)),this._total+=n,this._loop=!!t.loop,this._to=Pi([t.to,e,s,t.from]),this._from=Pi([t.from,s,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,i=this._duration,s=this._prop,n=this._from,o=this._loop,a=this._to;let r;if(this._active=n!==a&&(o||e1?2-r:r,r=this._easing(Math.min(1,Math.max(0,r))),this._target[s]=this._fn(n,a,r))}wait(){const t=this._promises||(this._promises=[]);return new Promise(((e,i)=>{t.push({res:e,rej:i})}))}_notify(t){const e=t?"res":"rej",i=this._promises||[];for(let t=0;t{const a=t[s];if(!o(a))return;const r={};for(const t of e)r[t]=a[t];(n(a.properties)&&a.properties||[s]).forEach((t=>{t!==s&&i.has(t)||i.set(t,r)}))}))}_animateOptions(t,e){const i=e.options,s=function(t,e){if(!e)return;let i=t.options;if(!i)return void(t.options=e);i.$shared&&(t.options=i=Object.assign({},i,{$shared:!1,$animations:{}}));return i}(t,i);if(!s)return[];const n=this._createAnimations(s,i);return i.$shared&&function(t,e){const i=[],s=Object.keys(e);for(let e=0;e{t.options=i}),(()=>{})),n}_createAnimations(t,e){const i=this._properties,s=[],n=t.$animations||(t.$animations={}),o=Object.keys(e),a=Date.now();let r;for(r=o.length-1;r>=0;--r){const l=o[r];if("$"===l.charAt(0))continue;if("options"===l){s.push(...this._animateOptions(t,e));continue}const h=e[l];let c=n[l];const d=i.get(l);if(c){if(d&&c.active()){c.update(d,h,a);continue}c.cancel()}d&&d.duration?(n[l]=c=new Cs(d,t,l,h),s.push(c)):t[l]=h}return s}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const i=this._createAnimations(t,e);return i.length?(xt.add(this._chart,i),!0):void 0}}function As(t,e){const i=t&&t.options||{},s=i.reverse,n=void 0===i.min?e:0,o=void 0===i.max?e:0;return{start:s?o:n,end:s?n:o}}function Ts(t,e){const i=[],s=t._getSortedDatasetMetas(e);let n,o;for(n=0,o=s.length;n0||!i&&e<0)return n.index}return null}function zs(t,e){const{chart:i,_cachedMeta:s}=t,n=i._stacks||(i._stacks={}),{iScale:o,vScale:a,index:r}=s,l=o.axis,h=a.axis,c=function(t,e,i){return`${t.id}.${e.id}.${i.stack||i.type}`}(o,a,s),d=e.length;let u;for(let t=0;ti[t].axis===e)).shift()}function Vs(t,e){const i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[s]||void 0===e[s][i])return;delete e[s][i],void 0!==e[s]._visualValues&&void 0!==e[s]._visualValues[i]&&delete e[s]._visualValues[i]}}}const Bs=t=>"reset"===t||"none"===t,Ns=(t,e)=>e?t:Object.assign({},t);class Ws{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=Es(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Vs(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>"x"===t?e:"r"===t?s:i,n=e.xAxisID=l(i.xAxisID,Fs(t,"x")),o=e.yAxisID=l(i.yAxisID,Fs(t,"y")),a=e.rAxisID=l(i.rAxisID,Fs(t,"r")),r=e.indexAxis,h=e.iAxisID=s(r,n,o,a),c=e.vAxisID=s(r,o,n,a);e.xScale=this.getScaleForId(n),e.yScale=this.getScaleForId(o),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(h),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&rt(this._data,this),t._stacked&&Vs(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(o(e))this._data=function(t){const e=Object.keys(t),i=new Array(e.length);let s,n,o;for(s=0,n=e.length;s0&&i._parsed[t-1];if(!1===this._parsing)i._parsed=s,i._sorted=!0,d=s;else{d=n(s[t])?this.parseArrayData(i,s,t,e):o(s[t])?this.parseObjectData(i,s,t,e):this.parsePrimitiveData(i,s,t,e);const a=()=>null===c[l]||f&&c[l]t&&!e.hidden&&e._stacked&&{keys:Ts(i,!0),values:null})(e,i,this.chart),h={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:c,max:d}=function(t){const{min:e,max:i,minDefined:s,maxDefined:n}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:n?i:Number.POSITIVE_INFINITY}}(r);let u,f;function g(){f=s[u];const e=f[r.axis];return!a(f[t.axis])||c>e||d=0;--u)if(!g()){this.updateRangeFromParsed(h,t,f,l);break}return h}getAllParsedValues(t){const e=this._cachedMeta._parsed,i=[];let s,n,o;for(s=0,n=e.length;s=0&&tthis.getContext(i,s,e)),c);return f.$shared&&(f.$shared=r,n[o]=Object.freeze(Ns(f,r))),f}_resolveAnimations(t,e,i){const s=this.chart,n=this._cachedDataOpts,o=`animation-${e}`,a=n[o];if(a)return a;let r;if(!1!==s.options.animation){const s=this.chart.config,n=s.datasetAnimationScopeKeys(this._type,e),o=s.getOptionScopes(this.getDataset(),n);r=s.createResolver(o,this.getContext(t,i,e))}const l=new Os(s,r&&r.animations);return r&&r._cacheable&&(n[o]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Bs(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){const i=this.resolveDataElementOptions(t,e),s=this._sharedOptions,n=this.getSharedOptions(i),o=this.includeOptions(e,n)||n!==s;return this.updateSharedOptions(n,e,i),{sharedOptions:n,includeOptions:o}}updateElement(t,e,i,s){Bs(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!Bs(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;const n=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(n)||n})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];const s=i.length,n=e.length,o=Math.min(n,s);o&&this.parse(0,o),n>s?this._insertElements(s,n-s,t):n{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]})),s}}function js(t,e){const i=t.options.ticks,n=function(t){const e=t.options.offset,i=t._tickSize(),s=t._length/i+(e?0:1),n=t._maxLength/i;return Math.floor(Math.min(s,n))}(t),o=Math.min(i.maxTicksLimit||n,n),a=i.major.enabled?function(t){const e=[];let i,s;for(i=0,s=t.length;io)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;nn)return e}return Math.max(n,1)}(a,e,o);if(r>0){let t,i;const n=r>1?Math.round((h-l)/(r-1)):null;for($s(e,c,d,s(n)?0:l-n,l),t=0,i=r-1;t"top"===e||"left"===e?t[e]+i:t[e]-i,Us=(t,e)=>Math.min(e||t,t);function Xs(t,e){const i=[],s=t.length/e,n=t.length;let o=0;for(;oa+r)))return h}function Ks(t){return t.drawTicks?t.tickLength:0}function Gs(t,e){if(!t.display)return 0;const i=Si(t.font,e),s=ki(t.padding);return(n(t.text)?t.text.length:1)*i.lineHeight+s.height}function Zs(t,e,i){let s=ut(t);return(i&&"right"!==e||!i&&"right"===e)&&(s=(t=>"left"===t?"right":"right"===t?"left":t)(s)),s}class Js extends Hs{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:s}=this;return t=r(t,Number.POSITIVE_INFINITY),e=r(e,Number.NEGATIVE_INFINITY),i=r(i,Number.POSITIVE_INFINITY),s=r(s,Number.NEGATIVE_INFINITY),{min:r(t,i),max:r(e,s),minDefined:a(t),maxDefined:a(e)}}getMinMax(t){let e,{min:i,max:s,minDefined:n,maxDefined:o}=this.getUserBounds();if(n&&o)return{min:i,max:s};const a=this.getMatchingVisibleMetas();for(let r=0,l=a.length;rs?s:i,s=n&&i>s?i:s,{min:r(i,r(s,i)),max:r(s,r(i,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){d(this.options.beforeUpdate,[this])}update(t,e,i){const{beginAtZero:s,grace:n,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Di(this,n,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const r=a=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=J(this.chart.width-c,0,this.maxWidth);o=t.offset?this.maxWidth/i:u/(i-1),c+6>o&&(o=u/(i-(t.offset?.5:1)),a=this.maxHeight-Ks(t.grid)-e.padding-Gs(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=Y(Math.min(Math.asin(J((h.highest.height+6)/o,-1,1)),Math.asin(J(a/r,-1,1))-Math.asin(J(d/r,-1,1)))),l=Math.max(s,Math.min(n,l))),this.labelRotation=l}afterCalculateLabelRotation(){d(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){d(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:i,title:s,grid:n}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const o=Gs(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Ks(n)+o):(t.height=this.maxHeight,t.width=Ks(n)+o),i.display&&this.ticks.length){const{first:e,last:s,widest:n,highest:o}=this._getLabelSizes(),r=2*i.padding,l=$(this.labelRotation),h=Math.cos(l),c=Math.sin(l);if(a){const e=i.mirror?0:c*n.width+h*o.height;t.height=Math.min(this.maxHeight,t.height+e+r)}else{const e=i.mirror?0:h*n.width+c*o.height;t.width=Math.min(this.maxWidth,t.width+e+r)}this._calculatePadding(e,s,c,h)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,s){const{ticks:{align:n,padding:o},position:a}=this.options,r=0!==this.labelRotation,l="top"!==a&&"x"===this.axis;if(this.isHorizontal()){const a=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1);let c=0,d=0;r?l?(c=s*t.width,d=i*e.height):(c=i*t.height,d=s*e.width):"start"===n?d=e.width:"end"===n?c=t.width:"inner"!==n&&(c=t.width/2,d=e.width/2),this.paddingLeft=Math.max((c-a+o)*this.width/(this.width-a),0),this.paddingRight=Math.max((d-h+o)*this.width/(this.width-h),0)}else{let i=e.height/2,s=t.height/2;"start"===n?(i=0,s=t.height):"end"===n&&(i=e.height,s=0),this.paddingTop=i+o,this.paddingBottom=s+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){d(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return"top"===e||"bottom"===e||"x"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,i;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,i=t.length;e{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n({width:r[t]||0,height:l[t]||0});return{first:P(0),last:P(e-1),widest:P(k),highest:P(S),widths:r,heights:l}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return Q(this._alignToPixels?Ae(this.chart,e,0):e)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&ta*s?a/i:r/s:r*s0}_computeGridLineItems(t){const e=this.axis,i=this.chart,s=this.options,{grid:n,position:a,border:r}=s,h=n.offset,c=this.isHorizontal(),d=this.ticks.length+(h?1:0),u=Ks(n),f=[],g=r.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,b=function(t){return Ae(i,t,p)};let x,_,y,v,M,w,k,S,P,D,C,O;if("top"===a)x=b(this.bottom),w=this.bottom-u,S=x-m,D=b(t.top)+m,O=t.bottom;else if("bottom"===a)x=b(this.top),D=t.top,O=b(t.bottom)-m,w=x+m,S=this.top+u;else if("left"===a)x=b(this.right),M=this.right-u,k=x-m,P=b(t.left)+m,C=t.right;else if("right"===a)x=b(this.left),P=t.left,C=b(t.right)-m,M=x+m,k=this.left+u;else if("x"===e){if("center"===a)x=b((t.top+t.bottom)/2+.5);else if(o(a)){const t=Object.keys(a)[0],e=a[t];x=b(this.chart.scales[t].getPixelForValue(e))}D=t.top,O=t.bottom,w=x+m,S=w+u}else if("y"===e){if("center"===a)x=b((t.left+t.right)/2);else if(o(a)){const t=Object.keys(a)[0],e=a[t];x=b(this.chart.scales[t].getPixelForValue(e))}M=x-m,k=M-u,P=t.left,C=t.right}const A=l(s.ticks.maxTicksLimit,d),T=Math.max(1,Math.ceil(d/A));for(_=0;_e.value===t));if(i>=0){return e.setContext(this.getContext(i)).lineWidth}return 0}drawGrid(t){const e=this.options.grid,i=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let n,o;const a=(t,e,s)=>{s.width&&s.color&&(i.save(),i.lineWidth=s.width,i.strokeStyle=s.color,i.setLineDash(s.borderDash||[]),i.lineDashOffset=s.borderDashOffset,i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(e.x,e.y),i.stroke(),i.restore())};if(e.display)for(n=0,o=s.length;n{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",s=[];let n,o;for(n=0,o=e.length;n{const s=i.split("."),n=s.pop(),o=[t].concat(s).join("."),a=e[i].split("."),r=a.pop(),l=a.join(".");ue.route(o,n,l,r)}))}(e,t.defaultRoutes);t.descriptors&&ue.describe(e,t.descriptors)}(t,o,i),this.override&&ue.override(t.id,t.overrides)),o}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in ue[s]&&(delete ue[s][i],this.override&&delete re[i])}}class tn{constructor(){this.controllers=new Qs(Ws,"datasets",!0),this.elements=new Qs(Hs,"elements"),this.plugins=new Qs(Object,"plugins"),this.scales=new Qs(Js,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,e,i){[...e].forEach((e=>{const s=i||this._getRegistryForType(e);i||s.isForType(e)||s===this.plugins&&e.id?this._exec(t,s,e):u(e,(e=>{const s=i||this._getRegistryForType(e);this._exec(t,s,e)}))}))}_exec(t,e,i){const s=w(t);d(i["before"+s],[],i),e[t](i),d(i["after"+s],[],i)}_getRegistryForType(t){for(let e=0;et.filter((t=>!e.some((e=>t.plugin.id===e.plugin.id))));this._notify(s(e,i),t,"stop"),this._notify(s(i,e),t,"start")}}function nn(t,e){return e||!1!==t?!0===t?{}:t:null}function on(t,{plugin:e,local:i},s,n){const o=t.pluginScopeKeys(e),a=t.getOptionScopes(s,o);return i&&e.defaults&&a.push(e.defaults),t.createResolver(a,n,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function an(t,e){const i=ue.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||"x"}function rn(t){if("x"===t||"y"===t||"r"===t)return t}function ln(t,...e){if(rn(t))return t;for(const s of e){const e=s.axis||("top"===(i=s.position)||"bottom"===i?"x":"left"===i||"right"===i?"y":void 0)||t.length>1&&rn(t[0].toLowerCase());if(e)return e}var i;throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function hn(t,e,i){if(i[e+"AxisID"]===t)return{axis:e}}function cn(t,e){const i=re[t.type]||{scales:{}},s=e.scales||{},n=an(t.type,e),a=Object.create(null);return Object.keys(s).forEach((e=>{const r=s[e];if(!o(r))return console.error(`Invalid scale configuration for scale: ${e}`);if(r._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${e}`);const l=ln(e,r,function(t,e){if(e.data&&e.data.datasets){const i=e.data.datasets.filter((e=>e.xAxisID===t||e.yAxisID===t));if(i.length)return hn(t,"x",i[0])||hn(t,"y",i[0])}return{}}(e,t),ue.scales[r.type]),h=function(t,e){return t===e?"_index_":"_value_"}(l,n),c=i.scales||{};a[e]=x(Object.create(null),[{axis:l},r,c[l],c[h]])})),t.data.datasets.forEach((i=>{const n=i.type||t.type,o=i.indexAxis||an(n,e),r=(re[n]||{}).scales||{};Object.keys(r).forEach((t=>{const e=function(t,e){let i=t;return"_index_"===t?i=e:"_value_"===t&&(i="x"===e?"y":"x"),i}(t,o),n=i[e+"AxisID"]||e;a[n]=a[n]||Object.create(null),x(a[n],[{axis:e},s[n],r[t]])}))})),Object.keys(a).forEach((t=>{const e=a[t];x(e,[ue.scales[e.type],ue.scale])})),a}function dn(t){const e=t.options||(t.options={});e.plugins=l(e.plugins,{}),e.scales=cn(t,e)}function un(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const fn=new Map,gn=new Set;function pn(t,e){let i=fn.get(t);return i||(i=e(),fn.set(t,i),gn.add(i)),i}const mn=(t,e,i)=>{const s=M(e,i);void 0!==s&&t.add(s)};class bn{constructor(t){this._config=function(t){return(t=t||{}).data=un(t.data),dn(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=un(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),dn(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return pn(t,(()=>[[`datasets.${t}`,""]]))}datasetAnimationScopeKeys(t,e){return pn(`${t}.transition.${e}`,(()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]]))}datasetElementScopeKeys(t,e){return pn(`${t}-${e}`,(()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]]))}pluginScopeKeys(t){const e=t.id;return pn(`${this.type}-plugin-${e}`,(()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]]))}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(t,e,i){const{options:s,type:n}=this,o=this._cachedScopes(t,i),a=o.get(e);if(a)return a;const r=new Set;e.forEach((e=>{t&&(r.add(t),e.forEach((e=>mn(r,t,e)))),e.forEach((t=>mn(r,s,t))),e.forEach((t=>mn(r,re[n]||{},t))),e.forEach((t=>mn(r,ue,t))),e.forEach((t=>mn(r,le,t)))}));const l=Array.from(r);return 0===l.length&&l.push(Object.create(null)),gn.has(e)&&o.set(e,l),l}chartOptionScopes(){const{options:t,type:e}=this;return[t,re[e]||{},ue.datasets[e]||{},{type:e},ue,le]}resolveNamedOptions(t,e,i,s=[""]){const o={$shared:!0},{resolver:a,subPrefixes:r}=xn(this._resolverCache,t,s);let l=a;if(function(t,e){const{isScriptable:i,isIndexable:s}=Ye(t);for(const o of e){const e=i(o),a=s(o),r=(a||e)&&t[o];if(e&&(S(r)||_n(r))||a&&n(r))return!0}return!1}(a,e)){o.$shared=!1;l=$e(a,i=S(i)?i():i,this.createResolver(t,i,r))}for(const t of e)o[t]=l[t];return o}createResolver(t,e,i=[""],s){const{resolver:n}=xn(this._resolverCache,t,i);return o(e)?$e(n,e,void 0,s):n}}function xn(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));const n=i.join();let o=s.get(n);if(!o){o={resolver:je(e,i),subPrefixes:i.filter((t=>!t.toLowerCase().includes("hover")))},s.set(n,o)}return o}const _n=t=>o(t)&&Object.getOwnPropertyNames(t).reduce(((e,i)=>e||S(t[i])),!1);const yn=["top","bottom","left","right","chartArea"];function vn(t,e){return"top"===t||"bottom"===t||-1===yn.indexOf(t)&&"x"===e}function Mn(t,e){return function(i,s){return i[t]===s[t]?i[e]-s[e]:i[t]-s[t]}}function wn(t){const e=t.chart,i=e.options.animation;e.notifyPlugins("afterRender"),d(i&&i.onComplete,[t],e)}function kn(t){const e=t.chart,i=e.options.animation;d(i&&i.onProgress,[t],e)}function Sn(t){return fe()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const Pn={},Dn=t=>{const e=Sn(t);return Object.values(Pn).filter((t=>t.canvas===e)).pop()};function Cn(t,e,i){const s=Object.keys(t);for(const n of s){const s=+n;if(s>=e){const o=t[n];delete t[n],(i>0||s>e)&&(t[s+i]=o)}}}class On{static defaults=ue;static instances=Pn;static overrides=re;static registry=en;static version="4.3.0";static getChart=Dn;static register(...t){en.add(...t),An()}static unregister(...t){en.remove(...t),An()}constructor(t,e){const s=this.config=new bn(e),n=Sn(t),o=Dn(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const a=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||ks(n)),this.platform.updateConfig(s);const r=this.platform.acquireContext(n,a.aspectRatio),l=r&&r.canvas,h=l&&l.height,c=l&&l.width;this.id=i(),this.ctx=r,this.canvas=l,this.width=c,this.height=h,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new sn,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=dt((t=>this.update(t)),a.resizeDelay||0),this._dataChanges=[],Pn[this.id]=this,r&&l?(xt.listen(this,"complete",wn),xt.listen(this,"progress",kn),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return s(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return en}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():ke(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Te(this.canvas,this.ctx),this}stop(){return xt.stop(this),this}resize(t,e){xt.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const i=this.options,s=this.canvas,n=i.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(s,t,e,n),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),r=this.width?"resize":"attach";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,ke(this,a,!0)&&(this.notifyPlugins("resize",{size:o}),d(i.onResize,[this,o],this),this.attached&&this._doResize(r)&&this.render())}ensureScalesHaveIDs(){u(this.options.scales||{},((t,e)=>{t.id=e}))}buildOrUpdateScales(){const t=this.options,e=t.scales,i=this.scales,s=Object.keys(i).reduce(((t,e)=>(t[e]=!1,t)),{});let n=[];e&&(n=n.concat(Object.keys(e).map((t=>{const i=e[t],s=ln(t,i),n="r"===s,o="x"===s;return{options:i,dposition:n?"chartArea":o?"bottom":"left",dtype:n?"radialLinear":o?"category":"linear"}})))),u(n,(e=>{const n=e.options,o=n.id,a=ln(o,n),r=l(n.type,e.dtype);void 0!==n.position&&vn(n.position,a)===vn(e.dposition)||(n.position=e.dposition),s[o]=!0;let h=null;if(o in i&&i[o].type===r)h=i[o];else{h=new(en.getScale(r))({id:o,type:r,ctx:this.ctx,chart:this}),i[h.id]=h}h.init(n,t)})),u(s,((t,e)=>{t||delete i[e]})),u(i,(t=>{as.configure(this,t,t.options),as.addBox(this,t)}))}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort(((t,e)=>t.index-e.index)),i>e){for(let t=e;te.length&&delete this._stacks,t.forEach(((t,i)=>{0===e.filter((e=>e===t._dataset)).length&&this._destroyDatasetMeta(i)}))}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let i,s;for(this._removeUnreferencedMetasets(),i=0,s=e.length;i{this.getDatasetMeta(e).controller.reset()}),this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const e=this.config;e.update();const i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0}))return;const n=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let o=0;for(let t=0,e=this.data.datasets.length;t{t.reset()})),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(Mn("z","_idx"));const{_active:a,_lastEvent:r}=this;r?this._eventHandler(r,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){u(this.scales,(t=>{as.removeBox(this,t)})),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);P(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:i,start:s,count:n}of e){Cn(t,s,"_removeElements"===i?-n:n)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,i=e=>new Set(t.filter((t=>t[0]===e)).map(((t,e)=>e+","+t.splice(1).join(",")))),s=i(0);for(let t=1;tt.split(","))).map((t=>({method:t[1],start:+t[2],count:+t[3]})))}_updateLayout(t){if(!1===this.notifyPlugins("beforeLayout",{cancelable:!0}))return;as.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],u(this.boxes,(t=>{i&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))}),this),this._layers.forEach(((t,e)=>{t._idx=e})),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const e=this.ctx,i=t._clip,s=!i.disabled,n=function(t){const{xScale:e,yScale:i}=t;if(e&&i)return{left:e.left,right:e.right,top:i.top,bottom:i.bottom}}(t)||this.chartArea,o={meta:t,index:t.index,cancelable:!0};!1!==this.notifyPlugins("beforeDatasetDraw",o)&&(s&&Ie(e,{left:!1===i.left?0:n.left-i.left,right:!1===i.right?this.width:n.right+i.right,top:!1===i.top?0:n.top-i.top,bottom:!1===i.bottom?this.height:n.bottom+i.bottom}),t.controller.draw(),s&&ze(e),o.cancelable=!1,this.notifyPlugins("afterDatasetDraw",o))}isPointInArea(t){return Re(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,s){const n=Xi.modes[e];return"function"==typeof n?n(this,t,i,s):[]}getDatasetMeta(t){const e=this.data.datasets[t],i=this._metasets;let s=i.filter((t=>t&&t._dataset===e)).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Ci(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const i=this.getDatasetMeta(t);return"boolean"==typeof i.hidden?!i.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){const s=i?"show":"hide",n=this.getDatasetMeta(t),o=n.controller._resolveAnimations(void 0,s);k(e)?(n.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),o.update(n,{visible:i}),this.update((e=>e.datasetIndex===t?s:void 0)))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),xt.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,i,s),t[i]=s},s=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};u(this.options.events,(t=>i(t,s)))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(i,s)=>{t[i]&&(e.removeEventListener(this,i,s),delete t[i])},n=(t,e)=>{this.canvas&&this.resize(t,e)};let o;const a=()=>{s("attach",a),this.attached=!0,this.resize(),i("resize",n),i("detach",o)};o=()=>{this.attached=!1,s("resize",n),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():o()}unbindEvents(){u(this._listeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._listeners={},u(this._responsiveListeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){const s=i?"set":"remove";let n,o,a,r;for("dataset"===e&&(n=this.getDatasetMeta(t[0].datasetIndex),n.controller["_"+s+"DatasetHoverStyle"]()),a=0,r=t.length;a{const i=this.getDatasetMeta(t);if(!i)throw new Error("No dataset found at index "+t);return{datasetIndex:t,element:i.data[e],index:e}}));!f(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return 1===this._plugins._cache.filter((e=>e.plugin.id===t)).length}_updateHoverStyles(t,e,i){const s=this.options.hover,n=(t,e)=>t.filter((t=>!e.some((e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)))),o=n(e,t),a=i?t:n(t,e);o.length&&this.updateHoverStyle(o,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,e){const i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},s=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins("beforeEvent",i,s))return;const n=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,s),(n||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:n}=this,o=e,a=this._getActiveElements(t,s,i,o),r=D(t),l=function(t,e,i,s){return i&&"mouseout"!==t.type?s?e:t:null}(t,this._lastEvent,i,r);i&&(this._lastEvent=null,d(n.onHover,[t,a,this],this),r&&d(n.onClick,[t,a,this],this));const h=!f(a,s);return(h||e)&&(this._active=a,this._updateHoverStyles(a,s,e)),this._lastEvent=l,h}_getActiveElements(t,e,i,s){if("mouseout"===t.type)return[];if(!i)return e;const n=this.options.hover;return this.getElementsAtEventForMode(t,n.mode,n,s)}}function An(){return u(On.instances,(t=>t._plugins.invalidate()))}function Tn(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class Ln{static override(t){Object.assign(Ln.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return Tn()}parse(){return Tn()}format(){return Tn()}add(){return Tn()}diff(){return Tn()}startOf(){return Tn()}endOf(){return Tn()}}var En={_date:Ln};function Rn(t){const e=t.iScale,i=function(t,e){if(!t._cache.$bar){const i=t.getMatchingVisibleMetas(e);let s=[];for(let e=0,n=i.length;et-e)))}return t._cache.$bar}(e,t.type);let s,n,o,a,r=e._length;const l=()=>{32767!==o&&-32768!==o&&(k(a)&&(r=Math.min(r,Math.abs(o-a)||r)),a=o)};for(s=0,n=i.length;sMath.abs(r)&&(l=r,h=a),e[i.axis]=h,e._custom={barStart:l,barEnd:h,start:n,end:o,min:a,max:r}}(t,e,i,s):e[i.axis]=i.parse(t,s),e}function zn(t,e,i,s){const n=t.iScale,o=t.vScale,a=n.getLabels(),r=n===o,l=[];let h,c,d,u;for(h=i,c=i+s;ht.x,i="left",s="right"):(e=t.base"spacing"!==t,_indexable:t=>"spacing"!==t&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const i=this.getDataset().data,s=this._cachedMeta;if(!1===this._parsing)s._parsed=i;else{let n,a,r=t=>+i[t];if(o(i[t])){const{key:t="value"}=this._parsing;r=e=>+M(i[e],t)}for(n=t,a=t+e;nZ(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>Z(t,r,l,!0)?-1:Math.min(e,e*i,s,s*i),p=f(0,h,d),m=f(E,c,u),b=g(C,h,d),x=g(C+E,c,u);s=(p-b)/2,n=(m-x)/2,o=-(p+b)/2,a=-(m+x)/2}return{ratioX:s,ratioY:n,offsetX:o,offsetY:a}}(u,d,r),b=(i.width-o)/f,x=(i.height-o)/g,_=Math.max(Math.min(b,x)/2,0),y=c(this.options.radius,_),v=(y-Math.max(y*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=p*y,this.offsetY=m*y,s.total=this.calculateTotal(),this.outerRadius=y-v*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-v*l,0),this.updateElements(n,0,n.length,t)}_circumference(t,e){const i=this.options,s=this._cachedMeta,n=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*n/O)}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.chartArea,r=o.options.animation,l=(a.left+a.right)/2,h=(a.top+a.bottom)/2,c=n&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,{sharedOptions:f,includeOptions:g}=this._getSharedOptions(e,s);let p,m=this._getRotation();for(p=0;p0&&!isNaN(t)?O*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t],i.options.locale);return{label:s[t]||"",value:n}}getMaxBorderWidth(t){let e=0;const i=this.chart;let s,n,o,a,r;if(!t)for(s=0,n=i.data.datasets.length;s{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t].r,i.options.locale);return{label:s[t]||"",value:n}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach(((t,i)=>{const s=this.getParsed(i).r;!isNaN(s)&&this.chart.getDataVisibility(i)&&(se.max&&(e.max=s))})),e}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),n=Math.max(s/2,0),o=(n-Math.max(i.cutoutPercentage?n/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=n-o*this.index,this.innerRadius=this.outerRadius-o}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.options.animation,r=this._cachedMeta.rScale,l=r.xCenter,h=r.yCenter,c=r.getIndexAngle(0)-.5*C;let d,u=c;const f=360/this.countVisibleElements();for(d=0;d{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++})),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?$(this.resolveDataElementOptions(t,e).angle||i):0}}var $n=Object.freeze({__proto__:null,BarController:class extends Ws{static id="bar";static defaults={datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}};static overrides={scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}};parsePrimitiveData(t,e,i,s){return zn(t,e,i,s)}parseArrayData(t,e,i,s){return zn(t,e,i,s)}parseObjectData(t,e,i,s){const{iScale:n,vScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l="x"===n.axis?a:r,h="x"===o.axis?a:r,c=[];let d,u,f,g;for(d=i,u=i+s;dt.controller.options.grouped)),o=i.options.stacked,a=[],r=t=>{const i=t.controller.getParsed(e),n=i&&i[t.vScale.axis];if(s(n)||isNaN(n))return!0};for(const i of n)if((void 0===e||!r(i))&&((!1===o||-1===a.indexOf(i.stack)||void 0===o&&void 0===i.stack)&&a.push(i.stack),i.index===t))break;return a.length||a.push(void 0),a}_getStackCount(t){return this._getStacks(void 0,t).length}_getStackIndex(t,e,i){const s=this._getStacks(t,i),n=void 0!==e?s.indexOf(e):-1;return-1===n?s.length-1:n}_getRuler(){const t=this.options,e=this._cachedMeta,i=e.iScale,s=[];let n,o;for(n=0,o=e.data.length;n=i?1:-1)}(u,e,r)*a,f===r&&(b-=u/2);const t=e.getPixelForDecimal(0),s=e.getPixelForDecimal(1),o=Math.min(t,s),h=Math.max(t,s);b=Math.max(Math.min(b,h),o),d=b+u,i&&!c&&(l._stacks[e.axis]._visualValues[n]=e.getValueForPixel(d)-e.getValueForPixel(b))}if(b===e.getPixelForValue(r)){const t=F(u)*e.getLineWidthForValue(r)/2;b+=t,u-=t}return{size:u,base:b,head:d,center:d+u/2}}_calculateBarIndexPixels(t,e){const i=e.scale,n=this.options,o=n.skipNull,a=l(n.maxBarThickness,1/0);let r,h;if(e.grouped){const i=o?this._getStackCount(t):e.stackCount,l="flex"===n.barThickness?function(t,e,i,s){const n=e.pixels,o=n[t];let a=t>0?n[t-1]:null,r=t=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y),l=o._custom;return{label:i[t]||"",value:"("+a+", "+r+(l?", "+l:"")+")"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,s){const n="reset"===s,{iScale:o,vScale:a}=this._cachedMeta,{sharedOptions:r,includeOptions:l}=this._getSharedOptions(e,s),h=o.axis,c=a.axis;for(let d=e;d0&&this.getParsed(e-1);for(let i=0;i<_;++i){const g=t[i],_=b?g:{};if(i=x){_.skip=!0;continue}const v=this.getParsed(i),M=s(v[f]),w=_[u]=a.getPixelForValue(v[u],i),k=_[f]=o||M?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,v,l):v[f],i);_.skip=isNaN(w)||isNaN(k)||M,_.stop=i>0&&Math.abs(v[u]-y[u])>m,p&&(_.parsed=v,_.raw=h.data[i]),d&&(_.options=c||this.resolveDataElementOptions(i,g.active?"active":n)),b||this.updateElement(g,i,_,n),y=v}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;const n=s[0].size(this.resolveDataElementOptions(0)),o=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,n,o)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends Hn{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}},PolarAreaController:jn,RadarController:class extends Ws{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],n=e.iScale.getLabels();if(i.points=s,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const o={_loop:!0,_fullLoop:n.length===s.length,options:e};this.updateElement(i,void 0,o,t)}this.updateElements(s,0,s.length,t)}updateElements(t,e,i,s){const n=this._cachedMeta.rScale,o="reset"===s;for(let a=e;a0&&this.getParsed(e-1);for(let c=e;c0&&Math.abs(i[f]-_[f])>b,m&&(p.parsed=i,p.raw=h.data[c]),u&&(p.options=d||this.resolveDataElementOptions(c,e.active?"active":n)),x||this.updateElement(e,c,p,n),_=i}this.updateSharedOptions(d,n,c)}getMaxOverflow(){const t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let t=0;for(let i=e.length-1;i>=0;--i)t=Math.max(t,e[i].size(this.resolveDataElementOptions(i))/2);return t>0&&t}const i=t.dataset,s=i.options&&i.options.borderWidth||0;if(!e.length)return s;const n=e[0].size(this.resolveDataElementOptions(0)),o=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(s,n,o)/2}}});function Yn(t,e,i,s){const n=vi(t.options.borderRadius,["outerStart","outerEnd","innerStart","innerEnd"]);const o=(i-e)/2,a=Math.min(o,s*e/2),r=t=>{const e=(i-Math.min(o,t))*s/2;return J(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:J(n.innerStart,0,a),innerEnd:J(n.innerEnd,0,a)}}function Un(t,e,i,s){return{x:i+t*Math.cos(e),y:s+t*Math.sin(e)}}function Xn(t,e,i,s,n,o){const{x:a,y:r,startAngle:l,pixelMargin:h,innerRadius:c}=e,d=Math.max(e.outerRadius+s+i-h,0),u=c>0?c+s+i+h:0;let f=0;const g=n-l;if(s){const t=((c>0?c-s:0)+(d>0?d-s:0))/2;f=(g-(0!==t?g*t/(t+s):g))/2}const p=(g-Math.max(.001,g*d-i/C)/d)/2,m=l+p+f,b=n-p-f,{outerStart:x,outerEnd:_,innerStart:y,innerEnd:v}=Yn(e,u,d,b-m),M=d-x,w=d-_,k=m+x/M,S=b-_/w,P=u+y,D=u+v,O=m+y/P,A=b-v/D;if(t.beginPath(),o){const e=(k+S)/2;if(t.arc(a,r,d,k,e),t.arc(a,r,d,e,S),_>0){const e=Un(w,S,a,r);t.arc(e.x,e.y,_,S,b+E)}const i=Un(D,b,a,r);if(t.lineTo(i.x,i.y),v>0){const e=Un(D,A,a,r);t.arc(e.x,e.y,v,b+E,A+Math.PI)}const s=(b-v/u+(m+y/u))/2;if(t.arc(a,r,u,b-v/u,s,!0),t.arc(a,r,u,s,m+y/u,!0),y>0){const e=Un(P,O,a,r);t.arc(e.x,e.y,y,O+Math.PI,m-E)}const n=Un(M,m,a,r);if(t.lineTo(n.x,n.y),x>0){const e=Un(M,k,a,r);t.arc(e.x,e.y,x,m-E,k)}}else{t.moveTo(a,r);const e=Math.cos(k)*d+a,i=Math.sin(k)*d+r;t.lineTo(e,i);const s=Math.cos(S)*d+a,n=Math.sin(S)*d+r;t.lineTo(s,n)}t.closePath()}function qn(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r,options:l}=e,{borderWidth:h,borderJoinStyle:c,borderDash:d,borderDashOffset:u}=l,f="inner"===l.borderAlign;if(!h)return;t.setLineDash(d||[]),t.lineDashOffset=u,f?(t.lineWidth=2*h,t.lineJoin=c||"round"):(t.lineWidth=h,t.lineJoin=c||"bevel");let g=e.endAngle;if(o){Xn(t,e,i,s,g,n);for(let e=0;en?(h=n/l,t.arc(o,a,l,i+h,s-h,!0)):t.arc(o,a,n,i+E,s-E),t.closePath(),t.clip()}(t,e,g),o||(Xn(t,e,i,s,g,n),t.stroke())}function Kn(t,e,i=e){t.lineCap=l(i.borderCapStyle,e.borderCapStyle),t.setLineDash(l(i.borderDash,e.borderDash)),t.lineDashOffset=l(i.borderDashOffset,e.borderDashOffset),t.lineJoin=l(i.borderJoinStyle,e.borderJoinStyle),t.lineWidth=l(i.borderWidth,e.borderWidth),t.strokeStyle=l(i.borderColor,e.borderColor)}function Gn(t,e,i){t.lineTo(i.x,i.y)}function Zn(t,e,i={}){const s=t.length,{start:n=0,end:o=s-1}=i,{start:a,end:r}=e,l=Math.max(n,a),h=Math.min(o,r),c=nr&&o>r;return{count:s,start:l,loop:e.loop,ilen:h(a+(h?r-t:t))%o,_=()=>{f!==g&&(t.lineTo(m,g),t.lineTo(m,f),t.lineTo(m,p))};for(l&&(d=n[x(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c){if(d=n[x(c)],d.skip)continue;const e=d.x,i=d.y,s=0|e;s===u?(ig&&(g=i),m=(b*m+e)/++b):(_(),t.lineTo(e,i),u=s,b=0,f=g=i),p=i}_()}function to(t){const e=t.options,i=e.borderDash&&e.borderDash.length;return!(t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||i)?Qn:Jn}const eo="function"==typeof Path2D;function io(t,e,i,s){eo&&!e.options.segment?function(t,e,i,s){let n=e._path;n||(n=e._path=new Path2D,e.path(n,i,s)&&n.closePath()),Kn(t,e.options),t.stroke(n)}(t,e,i,s):function(t,e,i,s){const{segments:n,options:o}=e,a=to(e);for(const r of n)Kn(t,o,r.style),t.beginPath(),a(t,e,r,{start:i,end:i+s-1})&&t.closePath(),t.stroke()}(t,e,i,s)}class so extends Hs{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t&&"fill"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const i=this.options;if((i.tension||"monotone"===i.cubicInterpolationMode)&&!i.stepped&&!this._pointsUpdated){const s=i.spanGaps?this._loop:this._fullLoop;hi(this._points,i,t,s,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=zi(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){const i=this.options,s=t[e],n=this.points,o=Ii(this,{property:e,start:s,end:s});if(!o.length)return;const a=[],r=function(t){return t.stepped?pi:t.tension||"monotone"===t.cubicInterpolationMode?mi:gi}(i);let l,h;for(l=0,h=o.length;l"borderDash"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.getProps(["x","y"],i),{angle:n,distance:o}=X(s,{x:t,y:e}),{startAngle:a,endAngle:r,innerRadius:h,outerRadius:c,circumference:d}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),u=(this.options.spacing+this.options.borderWidth)/2,f=l(d,r-a)>=O||Z(n,a,r),g=tt(o,h+u,c+u);return f&&g}getCenterPoint(t){const{x:e,y:i,startAngle:s,endAngle:n,innerRadius:o,outerRadius:a}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],t),{offset:r,spacing:l}=this.options,h=(s+n)/2,c=(o+a+l+r)/2;return{x:e+Math.cos(h)*c,y:i+Math.sin(h)*c}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:i}=this,s=(e.offset||0)/4,n=(e.spacing||0)/2,o=e.circular;if(this.pixelMargin="inner"===e.borderAlign?.33:0,this.fullCircles=i>O?Math.floor(i/O):0,0===i||this.innerRadius<0||this.outerRadius<0)return;t.save();const a=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(a)*s,Math.sin(a)*s);const r=s*(1-Math.sin(Math.min(C,i||0)));t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor,function(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r}=e;let l=e.endAngle;if(o){Xn(t,e,i,s,l,n);for(let e=0;e("string"==typeof e?(i=t.push(e)-1,s.unshift({index:i,label:e})):isNaN(e)&&(i=null),i))(t,e,i,s);return n!==t.lastIndexOf(e)?i:n}function go(t){const e=this.getLabels();return t>=0&&ts=e?s:t,a=t=>n=i?n:t;if(t){const t=F(s),e=F(n);t<0&&e<0?a(0):t>0&&e>0&&o(0)}if(s===n){let e=0===n?1:Math.abs(.05*n);a(n+e),t||o(s-e)}this.min=s,this.max=n}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:i,stepSize:s}=t;return s?(e=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),i=i||11),i&&(e=Math.min(i,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let i=this.getTickLimit();i=Math.max(2,i);const n=function(t,e){const i=[],{bounds:n,step:o,min:a,max:r,precision:l,count:h,maxTicks:c,maxDigits:d,includeBounds:u}=t,f=o||1,g=c-1,{min:p,max:m}=e,b=!s(a),x=!s(r),_=!s(h),y=(m-p)/(d+1);let v,M,w,k,S=B((m-p)/g/f)*f;if(S<1e-14&&!b&&!x)return[{value:p},{value:m}];k=Math.ceil(m/S)-Math.floor(p/S),k>g&&(S=B(k*S/g/f)*f),s(l)||(v=Math.pow(10,l),S=Math.ceil(S*v)/v),"ticks"===n?(M=Math.floor(p/S)*S,w=Math.ceil(m/S)*S):(M=p,w=m),b&&x&&o&&H((r-a)/o,S/1e3)?(k=Math.round(Math.min((r-a)/S,c)),S=(r-a)/k,M=a,w=r):_?(M=b?a:M,w=x?r:w,k=h-1,S=(w-M)/k):(k=(w-M)/S,k=V(k,Math.round(k),S/1e3)?Math.round(k):Math.ceil(k));const P=Math.max(U(S),U(M));v=Math.pow(10,s(l)?P:l),M=Math.round(M*v)/v,w=Math.round(w*v)/v;let D=0;for(b&&(u&&M!==a?(i.push({value:a}),Mr)break;i.push({value:t})}return x&&u&&w!==r?i.length&&V(i[i.length-1].value,r,po(r,y,t))?i[i.length-1].value=r:i.push({value:r}):x&&w!==r||i.push({value:w}),i}({maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return"ticks"===t.bounds&&j(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}configure(){const t=this.ticks;let e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){const s=(i-e)/Math.max(t.length-1,1)/2;e-=s,i+=s}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ne(t,this.chart.options.locale,this.options.ticks.format)}}class bo extends mo{static id="linear";static defaults={ticks:{callback:ae.formatters.numeric}};determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?t:0,this.max=a(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),e=t?this.width:this.height,i=$(this.options.ticks.minRotation),s=(t?Math.sin(i):Math.cos(i))||.001,n=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,n.lineHeight/s))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const xo=t=>Math.floor(z(t)),_o=(t,e)=>Math.pow(10,xo(t)+e);function yo(t){return 1===t/Math.pow(10,xo(t))}function vo(t,e,i){const s=Math.pow(10,i),n=Math.floor(t/s);return Math.ceil(e/s)-n}function Mo(t,{min:e,max:i}){e=r(t.min,e);const s=[],n=xo(e);let o=function(t,e){let i=xo(e-t);for(;vo(t,e,i)>10;)i++;for(;vo(t,e,i)<10;)i--;return Math.min(i,xo(t))}(e,i),a=o<0?Math.pow(10,Math.abs(o)):1;const l=Math.pow(10,o),h=n>o?Math.pow(10,n):0,c=Math.round((e-h)*a)/a,d=Math.floor((e-h)/l/10)*l*10;let u=Math.floor((c-d)/Math.pow(10,o)),f=r(t.min,Math.round((h+d+u*Math.pow(10,o))*a)/a);for(;f=10?u=u<15?15:20:u++,u>=20&&(o++,u=2,a=o>=0?1:a),f=Math.round((h+d+u*Math.pow(10,o))*a)/a;const g=r(t.max,f);return s.push({value:g,major:yo(g),significand:u}),s}class wo extends Js{static id="logarithmic";static defaults={ticks:{callback:ae.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){const i=mo.prototype.parse.apply(this,[t,e]);if(0!==i)return a(i)&&i>0?i:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?Math.max(0,t):null,this.max=a(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!a(this._userMin)&&(this.min=t===_o(this.min,0)?_o(this.min,-1):_o(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let i=this.min,s=this.max;const n=e=>i=t?i:e,o=t=>s=e?s:t;i===s&&(i<=0?(n(1),o(10)):(n(_o(i,-1)),o(_o(s,1)))),i<=0&&n(_o(s,-1)),s<=0&&o(_o(i,1)),this.min=i,this.max=s}buildTicks(){const t=this.options,e=Mo({min:this._userMin,max:this._userMax},this);return"ticks"===t.bounds&&j(e,this,"value"),t.reverse?(e.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),e}getLabelForValue(t){return void 0===t?"0":ne(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=z(t),this._valueRange=z(this.max)-z(t)}getPixelForValue(t){return void 0!==t&&0!==t||(t=this.min),null===t||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(z(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}}function ko(t){const e=t.ticks;if(e.display&&t.display){const t=ki(e.backdropPadding);return l(e.font&&e.font.size,ue.font.size)+t.height}return 0}function So(t,e,i,s,n){return t===s||t===n?{start:e-i/2,end:e+i/2}:tn?{start:e-i,end:e}:{start:e,end:e+i}}function Po(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},i=Object.assign({},e),s=[],o=[],a=t._pointLabels.length,r=t.options.pointLabels,l=r.centerPointLabels?C/a:0;for(let u=0;ue.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.starte.b&&(l=(n.end-e.b)/a,t.b=Math.max(t.b,e.b+l))}function Co(t,e,i){const s=t.drawingArea,{extra:n,additionalAngle:o,padding:a,size:r}=i,l=t.getPointPosition(e,s+n+a,o),h=Math.round(Y(G(l.angle+E))),c=function(t,e,i){90===i||270===i?t-=e/2:(i>270||i<90)&&(t-=e);return t}(l.y,r.h,h),d=function(t){if(0===t||180===t)return"center";if(t<180)return"left";return"right"}(h),u=function(t,e,i){"right"===i?t-=e:"center"===i&&(t-=e/2);return t}(l.x,r.w,d);return{visible:!0,x:l.x,y:c,textAlign:d,left:u,top:c,right:u+r.w,bottom:c+r.h}}function Oo(t,e){if(!e)return!0;const{left:i,top:s,right:n,bottom:o}=t;return!(Re({x:i,y:s},e)||Re({x:i,y:o},e)||Re({x:n,y:s},e)||Re({x:n,y:o},e))}function Ao(t,e,i){const{left:n,top:o,right:a,bottom:r}=i,{backdropColor:l}=e;if(!s(l)){const i=wi(e.borderRadius),s=ki(e.backdropPadding);t.fillStyle=l;const h=n-s.left,c=o-s.top,d=a-n+s.width,u=r-o+s.height;Object.values(i).some((t=>0!==t))?(t.beginPath(),He(t,{x:h,y:c,w:d,h:u,radius:i}),t.fill()):t.fillRect(h,c,d,u)}}function To(t,e,i,s){const{ctx:n}=t;if(i)n.arc(t.xCenter,t.yCenter,e,0,O);else{let i=t.getPointPosition(0,e);n.moveTo(i.x,i.y);for(let o=1;ot,padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"};static descriptors={angleLines:{_fallback:"grid"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=ki(ko(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!1);this.min=a(t)&&!isNaN(t)?t:0,this.max=a(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/ko(this.options))}generateTickLabels(t){mo.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map(((t,e)=>{const i=d(this.options.pointLabels.callback,[t,e],this);return i||0===i?i:""})).filter(((t,e)=>this.chart.getDataVisibility(e)))}fit(){const t=this.options;t.display&&t.pointLabels.display?Po(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return G(t*(O/(this._pointLabels.length||1))+$(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(s(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(s(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t=0;n--){const e=t._pointLabelItems[n];if(!e.visible)continue;const o=s.setContext(t.getPointLabelContext(n));Ao(i,o,e);const a=Si(o.font),{x:r,y:l,textAlign:h}=e;We(i,t._pointLabels[n],r,l+a.lineHeight/2,a,{color:o.color,textAlign:h,textBaseline:"middle"})}}(this,o),s.display&&this.ticks.forEach(((t,e)=>{if(0!==e){r=this.getDistanceFromCenterForValue(t.value);const i=this.getContext(e),a=s.setContext(i),l=n.setContext(i);!function(t,e,i,s,n){const o=t.ctx,a=e.circular,{color:r,lineWidth:l}=e;!a&&!s||!r||!l||i<0||(o.save(),o.strokeStyle=r,o.lineWidth=l,o.setLineDash(n.dash),o.lineDashOffset=n.dashOffset,o.beginPath(),To(t,i,a,s),o.closePath(),o.stroke(),o.restore())}(this,a,r,o,l)}})),i.display){for(t.save(),a=o-1;a>=0;a--){const s=i.setContext(this.getPointLabelContext(a)),{color:n,lineWidth:o}=s;o&&n&&(t.lineWidth=o,t.strokeStyle=n,t.setLineDash(s.borderDash),t.lineDashOffset=s.borderDashOffset,r=this.getDistanceFromCenterForValue(e.ticks.reverse?this.min:this.max),l=this.getPointPosition(a,r),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;const s=this.getIndexAngle(0);let n,o;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach(((s,a)=>{if(0===a&&!e.reverse)return;const r=i.setContext(this.getContext(a)),l=Si(r.font);if(n=this.getDistanceFromCenterForValue(this.ticks[a].value),r.showLabelBackdrop){t.font=l.string,o=t.measureText(s.label).width,t.fillStyle=r.backdropColor;const e=ki(r.backdropPadding);t.fillRect(-o/2-e.left,-n-l.size/2-e.top,o+e.width,l.size+e.height)}We(t,s.label,0,-n,l,{color:r.color})})),t.restore()}drawTitle(){}}const Eo={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},Ro=Object.keys(Eo);function Io(t,e){return t-e}function zo(t,e){if(s(e))return null;const i=t._adapter,{parser:n,round:o,isoWeekday:r}=t._parseOpts;let l=e;return"function"==typeof n&&(l=n(l)),a(l)||(l="string"==typeof n?i.parse(l,n):i.parse(l)),null===l?null:(o&&(l="week"!==o||!W(r)&&!0!==r?i.startOf(l,o):i.startOf(l,"isoWeek",r)),+l)}function Fo(t,e,i,s){const n=Ro.length;for(let o=Ro.indexOf(t);o=e?i[s]:i[n]]=!0}}else t[e]=!0}function Bo(t,e,i){const s=[],n={},o=e.length;let a,r;for(a=0;a=0&&(e[l].major=!0);return e}(t,s,n,i):s}class No extends Js{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){const i=t.time||(t.time={}),s=this._adapter=new En._date(t.adapters.date);s.init(e),x(i.displayFormats,s.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:zo(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,i=t.time.unit||"day";let{min:s,max:n,minDefined:o,maxDefined:r}=this.getUserBounds();function l(t){o||isNaN(t.min)||(s=Math.min(s,t.min)),r||isNaN(t.max)||(n=Math.max(n,t.max))}o&&r||(l(this._getLabelBounds()),"ticks"===t.bounds&&"labels"===t.ticks.source||l(this.getMinMax(!1))),s=a(s)&&!isNaN(s)?s:+e.startOf(Date.now(),i),n=a(n)&&!isNaN(n)?n:+e.endOf(Date.now(),i)+1,this.min=Math.min(s,n-1),this.max=Math.max(s+1,n)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){const t=this.options,e=t.time,i=t.ticks,s="labels"===i.source?this.getLabelTimestamps():this._generate();"ticks"===t.bounds&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const n=this.min,o=nt(s,n,this.max);return this._unit=e.unit||(i.autoSkip?Fo(e.minUnit,this.min,this.max,this._getLabelCapacity(n)):function(t,e,i,s,n){for(let o=Ro.length-1;o>=Ro.indexOf(i);o--){const i=Ro[o];if(Eo[i].common&&t._adapter.diff(n,s,i)>=e-1)return i}return Ro[i?Ro.indexOf(i):0]}(this,o.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&"year"!==this._unit?function(t){for(let e=Ro.indexOf(t)+1,i=Ro.length;e+t.value)))}initOffsets(t=[]){let e,i,s=0,n=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),s=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,i=this.getDecimalForValue(t[t.length-1]),n=1===t.length?i:(i-this.getDecimalForValue(t[t.length-2]))/2);const o=t.length<3?.5:.25;s=J(s,0,o),n=J(n,0,o),this._offsets={start:s,end:n,factor:1/(s+1+n)}}_generate(){const t=this._adapter,e=this.min,i=this.max,s=this.options,n=s.time,o=n.unit||Fo(n.minUnit,e,i,this._getLabelCapacity(e)),a=l(s.ticks.stepSize,1),r="week"===o&&n.isoWeekday,h=W(r)||!0===r,c={};let d,u,f=e;if(h&&(f=+t.startOf(f,"isoWeek",r)),f=+t.startOf(f,h?"day":o),t.diff(i,e,o)>1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+o);const g="data"===s.ticks.source&&this.getDataTimestamps();for(d=f,u=0;dt-e)).map((t=>+t))}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){const i=this.options.time.displayFormats,s=this._unit,n=e||i[s];return this._adapter.format(t,n)}_tickFormatFunction(t,e,i,s){const n=this.options,o=n.ticks.callback;if(o)return d(o,[t,e,i],this);const a=n.time.displayFormats,r=this._unit,l=this._majorUnit,h=r&&a[r],c=l&&a[l],u=i[e],f=l&&c&&u&&u.major;return this._adapter.format(t,s||(f?c:h))}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e0?a:1}getDataTimestamps(){let t,e,i=this._cache.data||[];if(i.length)return i;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(t=0,e=s.length;t=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=it(t,"pos",e)),({pos:s,time:o}=t[r]),({pos:n,time:a}=t[l])):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=it(t,"time",e)),({time:s,pos:o}=t[r]),({time:n,pos:a}=t[l]));const h=n-s;return h?o+(a-o)*(e-s)/h:o}var Ho=Object.freeze({__proto__:null,CategoryScale:class extends Js{static id="category";static defaults={ticks:{callback:go}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(s(t))return null;const i=this.getLabels();return((t,e)=>null===t?null:J(Math.round(t),0,e))(e=isFinite(e)&&i[e]===t?e:fo(i,t,l(e,t),this._addedLabels),i.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const t=this.min,e=this.max,i=this.options.offset,s=[];let n=this.getLabels();n=0===t&&e===n.length-1?n:n.slice(t,e+1),this._valueRange=Math.max(n.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let i=t;i<=e;i++)s.push({value:i});return s}getLabelForValue(t){return go.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return"number"!=typeof t&&(t=this.parse(t)),null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:bo,LogarithmicScale:wo,RadialLinearScale:Lo,TimeScale:No,TimeSeriesScale:class extends No{static id="timeseries";static defaults=No.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=Wo(e,this.min),this._tableRange=Wo(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],n=[];let o,a,r,l,h;for(o=0,a=t.length;o=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(o=0,a=s.length;ot.replace("rgb(","rgba(").replace(")",", 0.5)")));function Yo(t){return jo[t%jo.length]}function Uo(t){return $o[t%$o.length]}function Xo(t){let e=0;return(i,s)=>{const n=t.getDatasetMeta(s).controller;n instanceof Hn?e=function(t,e){return t.backgroundColor=t.data.map((()=>Yo(e++))),e}(i,e):n instanceof jn?e=function(t,e){return t.backgroundColor=t.data.map((()=>Uo(e++))),e}(i,e):n&&(e=function(t,e){return t.borderColor=Yo(e),t.backgroundColor=Uo(e),++e}(i,e))}}function qo(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}var Ko={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,i){if(!i.enabled)return;const{data:{datasets:s},options:n}=t.config,{elements:o}=n;if(!i.forceOverride&&(qo(s)||(a=n)&&(a.borderColor||a.backgroundColor)||o&&qo(o)))return;var a;const r=Xo(t);s.forEach(r)}};function Go(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function Zo(t){t.data.datasets.forEach((t=>{Go(t)}))}var Jo={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,i)=>{if(!i.enabled)return void Zo(t);const n=t.width;t.data.datasets.forEach(((e,o)=>{const{_data:a,indexAxis:r}=e,l=t.getDatasetMeta(o),h=a||e.data;if("y"===Pi([r,t.options.indexAxis]))return;if(!l.controller.supportsDecimation)return;const c=t.scales[l.xAxisID];if("linear"!==c.type&&"time"!==c.type)return;if(t.options.parsing)return;let{start:d,count:u}=function(t,e){const i=e.length;let s,n=0;const{iScale:o}=t,{min:a,max:r,minDefined:l,maxDefined:h}=o.getUserBounds();return l&&(n=J(it(e,o.axis,a).lo,0,i-1)),s=h?J(it(e,o.axis,r).hi+1,n,i)-n:i-n,{start:n,count:s}}(l,h);if(u<=(i.threshold||4*n))return void Go(e);let f;switch(s(a)&&(e._data=h,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),i.algorithm){case"lttb":f=function(t,e,i,s,n){const o=n.samples||s;if(o>=i)return t.slice(e,e+i);const a=[],r=(i-2)/(o-2);let l=0;const h=e+i-1;let c,d,u,f,g,p=e;for(a[l++]=t[p],c=0;cu&&(u=f,d=t[s],g=s);a[l++]=d,p=g}return a[l++]=t[h],a}(h,d,u,n,i);break;case"min-max":f=function(t,e,i,n){let o,a,r,l,h,c,d,u,f,g,p=0,m=0;const b=[],x=e+i-1,_=t[e].x,y=t[x].x-_;for(o=e;og&&(g=l,d=o),p=(m*p+a.x)/++m;else{const i=o-1;if(!s(c)&&!s(d)){const e=Math.min(c,d),s=Math.max(c,d);e!==u&&e!==i&&b.push({...t[e],x:p}),s!==u&&s!==i&&b.push({...t[s],x:p})}o>0&&i!==u&&b.push(t[i]),b.push(a),h=e,m=0,f=g=l,c=d=u=o}}return b}(h,d,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${i.algorithm}'`)}e._decimated=f}))},destroy(t){Zo(t)}};function Qo(t,e,i,s){if(s)return;let n=e[t],o=i[t];return"angle"===t&&(n=G(n),o=G(o)),{property:t,start:n,end:o}}function ta(t,e,i){for(;e>t;e--){const t=i[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function ea(t,e,i,s){return t&&e?s(t[i],e[i]):t?t[i]:e?e[i]:0}function ia(t,e){let i=[],s=!1;return n(t)?(s=!0,i=t):i=function(t,e){const{x:i=null,y:s=null}=t||{},n=e.points,o=[];return e.segments.forEach((({start:t,end:e})=>{e=ta(t,e,n);const a=n[t],r=n[e];null!==s?(o.push({x:a.x,y:s}),o.push({x:r.x,y:s})):null!==i&&(o.push({x:i,y:a.y}),o.push({x:i,y:r.y}))})),o}(t,e),i.length?new so({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function sa(t){return t&&!1!==t.fill}function na(t,e,i){let s=t[e].fill;const n=[e];let o;if(!i)return s;for(;!1!==s&&-1===n.indexOf(s);){if(!a(s))return s;if(o=t[s],!o)return!1;if(o.visible)return s;n.push(s),s=o.fill}return!1}function oa(t,e,i){const s=function(t){const e=t.options,i=e.fill;let s=l(i&&i.target,i);void 0===s&&(s=!!e.backgroundColor);if(!1===s||null===s)return!1;if(!0===s)return"origin";return s}(t);if(o(s))return!isNaN(s.value)&&s;let n=parseFloat(s);return a(n)&&Math.floor(n)===n?function(t,e,i,s){"-"!==t&&"+"!==t||(i=e+i);if(i===e||i<0||i>=s)return!1;return i}(s[0],e,n,i):["origin","start","end","stack","shape"].indexOf(s)>=0&&s}function aa(t,e,i){const s=[];for(let n=0;n=0;--e){const i=n[e].$filler;i&&(i.line.updateControlPoints(o,i.axis),s&&i.fill&&ca(t.ctx,i,o))}},beforeDatasetsDraw(t,e,i){if("beforeDatasetsDraw"!==i.drawTime)return;const s=t.getSortedVisibleDatasetMetas();for(let e=s.length-1;e>=0;--e){const i=s[e].$filler;sa(i)&&ca(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,i){const s=e.meta.$filler;sa(s)&&"beforeDatasetDraw"===i.drawTime&&ca(t.ctx,s,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const ma=(t,e)=>{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class ba extends Hs{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=d(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter((e=>t.filter(e,this.chart.data)))),t.sort&&(e=e.sort(((e,i)=>t.sort(e,i,this.chart.data)))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const i=t.labels,s=Si(i.font),n=s.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:r}=ma(i,n);let l,h;e.font=s.string,this.isHorizontal()?(l=this.maxWidth,h=this._fitRows(o,n,a,r)+10):(h=this.maxHeight,l=this._fitCols(o,s,a,r)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(h,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,s){const{ctx:n,maxWidth:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.lineWidths=[0],h=s+a;let c=t;n.textAlign="left",n.textBaseline="middle";let d=-1,u=-h;return this.legendItems.forEach(((t,f)=>{const g=i+e/2+n.measureText(t.text).width;(0===f||l[l.length-1]+g+2*a>o)&&(c+=h,l[l.length-(f>0?0:1)]=0,u+=h,d++),r[f]={left:0,top:u,row:d,width:g,height:s},l[l.length-1]+=g+a})),c}_fitCols(t,e,i,s){const{ctx:n,maxHeight:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.columnSizes=[],h=o-t;let c=a,d=0,u=0,f=0,g=0;return this.legendItems.forEach(((t,o)=>{const{itemWidth:p,itemHeight:m}=function(t,e,i,s,n){const o=function(t,e,i,s){let n=t.text;n&&"string"!=typeof n&&(n=n.reduce(((t,e)=>t.length>e.length?t:e)));return e+i.size/2+s.measureText(n).width}(s,t,e,i),a=function(t,e,i){let s=t;"string"!=typeof e.text&&(s=xa(e,i));return s}(n,s,e.lineHeight);return{itemWidth:o,itemHeight:a}}(i,e,n,t,s);o>0&&u+m+2*a>h&&(c+=d+a,l.push({width:d,height:u}),f+=d+a,g++,d=u=0),r[o]={left:f,top:u,col:g,width:p,height:m},d=Math.max(d,p),u+=m+a})),c+=d,l.push({width:d,height:u}),c}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:s},rtl:n}}=this,o=Oi(n,this.left,this.width);if(this.isHorizontal()){let n=0,a=ft(i,this.left+s,this.right-this.lineWidths[n]);for(const r of e)n!==r.row&&(n=r.row,a=ft(i,this.left+s,this.right-this.lineWidths[n])),r.top+=this.top+t+s,r.left=o.leftForLtr(o.x(a),r.width),a+=r.width+s}else{let n=0,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height);for(const r of e)r.col!==n&&(n=r.col,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height)),r.top=a,r.left+=this.left+s,r.left=o.leftForLtr(o.x(r.left),r.width),a+=r.height+s}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){if(this.options.display){const t=this.ctx;Ie(t,this),this._draw(),ze(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:i,ctx:s}=this,{align:n,labels:o}=t,a=ue.color,r=Oi(t.rtl,this.left,this.width),h=Si(o.font),{padding:c}=o,d=h.size,u=d/2;let f;this.drawTitle(),s.textAlign=r.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=h.string;const{boxWidth:g,boxHeight:p,itemHeight:m}=ma(o,d),b=this.isHorizontal(),x=this._computeTitleHeight();f=b?{x:ft(n,this.left+c,this.right-i[0]),y:this.top+c+x,line:0}:{x:this.left+c,y:ft(n,this.top+x+c,this.bottom-e[0].height),line:0},Ai(this.ctx,t.textDirection);const _=m+c;this.legendItems.forEach(((y,v)=>{s.strokeStyle=y.fontColor,s.fillStyle=y.fontColor;const M=s.measureText(y.text).width,w=r.textAlign(y.textAlign||(y.textAlign=o.textAlign)),k=g+u+M;let S=f.x,P=f.y;r.setWidth(this.width),b?v>0&&S+k+c>this.right&&(P=f.y+=_,f.line++,S=f.x=ft(n,this.left+c,this.right-i[f.line])):v>0&&P+_>this.bottom&&(S=f.x=S+e[f.line].width+c,f.line++,P=f.y=ft(n,this.top+x+c,this.bottom-e[f.line].height));if(function(t,e,i){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;s.save();const n=l(i.lineWidth,1);if(s.fillStyle=l(i.fillStyle,a),s.lineCap=l(i.lineCap,"butt"),s.lineDashOffset=l(i.lineDashOffset,0),s.lineJoin=l(i.lineJoin,"miter"),s.lineWidth=n,s.strokeStyle=l(i.strokeStyle,a),s.setLineDash(l(i.lineDash,[])),o.usePointStyle){const a={radius:p*Math.SQRT2/2,pointStyle:i.pointStyle,rotation:i.rotation,borderWidth:n},l=r.xPlus(t,g/2);Ee(s,a,l,e+u,o.pointStyleWidth&&g)}else{const o=e+Math.max((d-p)/2,0),a=r.leftForLtr(t,g),l=wi(i.borderRadius);s.beginPath(),Object.values(l).some((t=>0!==t))?He(s,{x:a,y:o,w:g,h:p,radius:l}):s.rect(a,o,g,p),s.fill(),0!==n&&s.stroke()}s.restore()}(r.x(S),P,y),S=gt(w,S+g+u,b?S+k:this.right,t.rtl),function(t,e,i){We(s,i.text,t,e+m/2,h,{strikethrough:i.hidden,textAlign:r.textAlign(i.textAlign)})}(r.x(S),P,y),b)f.x+=k+c;else if("string"!=typeof y.text){const t=h.lineHeight;f.y+=xa(y,t)}else f.y+=_})),Ti(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,i=Si(e.font),s=ki(e.padding);if(!e.display)return;const n=Oi(t.rtl,this.left,this.width),o=this.ctx,a=e.position,r=i.size/2,l=s.top+r;let h,c=this.left,d=this.width;if(this.isHorizontal())d=Math.max(...this.lineWidths),h=this.top+l,c=ft(t.align,c,this.right-d);else{const e=this.columnSizes.reduce(((t,e)=>Math.max(t,e.height)),0);h=l+ft(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const u=ft(a,c,c+d);o.textAlign=n.textAlign(ut(a)),o.textBaseline="middle",o.strokeStyle=e.color,o.fillStyle=e.color,o.font=i.string,We(o,e.text,u,h,i)}_computeTitleHeight(){const t=this.options.title,e=Si(t.font),i=ki(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,n;if(tt(t,this.left,this.right)&&tt(e,this.top,this.bottom))for(n=this.legendHitBoxes,i=0;it.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:i,pointStyle:s,textAlign:n,color:o,useBorderRadius:a,borderRadius:r}}=t.legend.options;return t._getSortedDatasetMetas().map((t=>{const l=t.controller.getStyle(i?0:void 0),h=ki(l.borderWidth);return{text:e[t.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!t.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(h.width+h.height)/4,strokeStyle:l.borderColor,pointStyle:s||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:a&&(r||l.borderRadius),datasetIndex:t.index}}),this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class ya extends Hs{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const i=this.options;if(this.left=0,this.top=0,!i.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const s=n(i.text)?i.text.length:1;this._padding=ki(i.padding);const o=s*Si(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){const{top:e,left:i,bottom:s,right:n,options:o}=this,a=o.align;let r,l,h,c=0;return this.isHorizontal()?(l=ft(a,i,n),h=e+t,r=n-i):("left"===o.position?(l=i+t,h=ft(a,s,e),c=-.5*C):(l=n-t,h=ft(a,e,s),c=.5*C),r=s-e),{titleX:l,titleY:h,maxWidth:r,rotation:c}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const i=Si(e.font),s=i.lineHeight/2+this._padding.top,{titleX:n,titleY:o,maxWidth:a,rotation:r}=this._drawArgs(s);We(t,e.text,0,0,i,{color:e.color,maxWidth:a,rotation:r,textAlign:ut(e.align),textBaseline:"middle",translation:[n,o]})}}var va={id:"title",_element:ya,start(t,e,i){!function(t,e){const i=new ya({ctx:t.ctx,options:e,chart:t});as.configure(t,i,e),as.addBox(t,i),t.titleBlock=i}(t,i)},stop(t){const e=t.titleBlock;as.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;as.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Ma=new WeakMap;var wa={id:"subtitle",start(t,e,i){const s=new ya({ctx:t.ctx,options:i,chart:t});as.configure(t,s,i),as.addBox(t,s),Ma.set(t,s)},stop(t){as.removeBox(t,Ma.get(t)),Ma.delete(t)},beforeUpdate(t,e,i){const s=Ma.get(t);as.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const ka={average(t){if(!t.length)return!1;let e,i,s=0,n=0,o=0;for(e=0,i=t.length;e-1?t.split("\n"):t}function Da(t,e){const{element:i,datasetIndex:s,index:n}=e,o=t.getDatasetMeta(s).controller,{label:a,value:r}=o.getLabelAndValue(n);return{chart:t,label:a,parsed:o.getParsed(n),raw:t.data.datasets[s].data[n],formattedValue:r,dataset:o.getDataset(),dataIndex:n,datasetIndex:s,element:i}}function Ca(t,e){const i=t.chart.ctx,{body:s,footer:n,title:o}=t,{boxWidth:a,boxHeight:r}=e,l=Si(e.bodyFont),h=Si(e.titleFont),c=Si(e.footerFont),d=o.length,f=n.length,g=s.length,p=ki(e.padding);let m=p.height,b=0,x=s.reduce(((t,e)=>t+e.before.length+e.lines.length+e.after.length),0);if(x+=t.beforeBody.length+t.afterBody.length,d&&(m+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),x){m+=g*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(x-g)*l.lineHeight+(x-1)*e.bodySpacing}f&&(m+=e.footerMarginTop+f*c.lineHeight+(f-1)*e.footerSpacing);let _=0;const y=function(t){b=Math.max(b,i.measureText(t).width+_)};return i.save(),i.font=h.string,u(t.title,y),i.font=l.string,u(t.beforeBody.concat(t.afterBody),y),_=e.displayColors?a+2+e.boxPadding:0,u(s,(t=>{u(t.before,y),u(t.lines,y),u(t.after,y)})),_=0,i.font=c.string,u(t.footer,y),i.restore(),b+=p.width,{width:b,height:m}}function Oa(t,e,i,s){const{x:n,width:o}=i,{width:a,chartArea:{left:r,right:l}}=t;let h="center";return"center"===s?h=n<=(r+l)/2?"left":"right":n<=o/2?h="left":n>=a-o/2&&(h="right"),function(t,e,i,s){const{x:n,width:o}=s,a=i.caretSize+i.caretPadding;return"left"===t&&n+o+a>e.width||"right"===t&&n-o-a<0||void 0}(h,t,e,i)&&(h="center"),h}function Aa(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return it.height-s/2?"bottom":"center"}(t,i);return{xAlign:i.xAlign||e.xAlign||Oa(t,e,i,s),yAlign:s}}function Ta(t,e,i,s){const{caretSize:n,caretPadding:o,cornerRadius:a}=t,{xAlign:r,yAlign:l}=i,h=n+o,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(a);let g=function(t,e){let{x:i,width:s}=t;return"right"===e?i-=s:"center"===e&&(i-=s/2),i}(e,r);const p=function(t,e,i){let{y:s,height:n}=t;return"top"===e?s+=i:s-="bottom"===e?n+i:n/2,s}(e,l,h);return"center"===l?"left"===r?g+=h:"right"===r&&(g-=h):"left"===r?g-=Math.max(c,u)+n:"right"===r&&(g+=Math.max(d,f)+n),{x:J(g,0,s.width-e.width),y:J(p,0,s.height-e.height)}}function La(t,e,i){const s=ki(i.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-s.right:t.x+s.left}function Ea(t){return Sa([],Pa(t))}function Ra(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}const Ia={beforeTitle:e,title(t){if(t.length>0){const e=t[0],i=e.chart.data.labels,s=i?i.length:0;if(this&&this.options&&"dataset"===this.options.mode)return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex{const e={before:[],lines:[],after:[]},n=Ra(i,t);Sa(e.before,Pa(za(n,"beforeLabel",this,t))),Sa(e.lines,za(n,"label",this,t)),Sa(e.after,Pa(za(n,"afterLabel",this,t))),s.push(e)})),s}getAfterBody(t,e){return Ea(za(e.callbacks,"afterBody",this,t))}getFooter(t,e){const{callbacks:i}=e,s=za(i,"beforeFooter",this,t),n=za(i,"footer",this,t),o=za(i,"afterFooter",this,t);let a=[];return a=Sa(a,Pa(s)),a=Sa(a,Pa(n)),a=Sa(a,Pa(o)),a}_createItems(t){const e=this._active,i=this.chart.data,s=[],n=[],o=[];let a,r,l=[];for(a=0,r=e.length;at.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),u(l,(e=>{const i=Ra(t.callbacks,e);s.push(za(i,"labelColor",this,e)),n.push(za(i,"labelPointStyle",this,e)),o.push(za(i,"labelTextColor",this,e))})),this.labelColors=s,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l,l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let n,o=[];if(s.length){const t=ka[i.position].call(this,s,this._eventPosition);o=this._createItems(i),this.title=this.getTitle(o,i),this.beforeBody=this.getBeforeBody(o,i),this.body=this.getBody(o,i),this.afterBody=this.getAfterBody(o,i),this.footer=this.getFooter(o,i);const e=this._size=Ca(this,i),a=Object.assign({},t,e),r=Aa(this.chart,i,a),l=Ta(i,a,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,n={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(n={opacity:0});this._tooltipItems=o,this.$context=void 0,n&&this._resolveAnimations().update(this,n),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){const n=this.getCaretPosition(t,i,s);e.lineTo(n.x1,n.y1),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3)}getCaretPosition(t,e,i){const{xAlign:s,yAlign:n}=this,{caretSize:o,cornerRadius:a}=i,{topLeft:r,topRight:l,bottomLeft:h,bottomRight:c}=wi(a),{x:d,y:u}=t,{width:f,height:g}=e;let p,m,b,x,_,y;return"center"===n?(_=u+g/2,"left"===s?(p=d,m=p-o,x=_+o,y=_-o):(p=d+f,m=p+o,x=_-o,y=_+o),b=p):(m="left"===s?d+Math.max(r,h)+o:"right"===s?d+f-Math.max(l,c)-o:this.caretX,"top"===n?(x=u,_=x-o,p=m-o,b=m+o):(x=u+g,_=x+o,p=m+o,b=m-o),y=x),{x1:p,x2:m,x3:b,y1:x,y2:_,y3:y}}drawTitle(t,e,i){const s=this.title,n=s.length;let o,a,r;if(n){const l=Oi(i.rtl,this.x,this.width);for(t.x=La(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",o=Si(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=o.string,r=0;r0!==t))?(t.beginPath(),t.fillStyle=n.multiKeyBackground,He(t,{x:e,y:g,w:h,h:l,radius:r}),t.fill(),t.stroke(),t.fillStyle=a.backgroundColor,t.beginPath(),He(t,{x:i,y:g+1,w:h-2,h:l-2,radius:r}),t.fill()):(t.fillStyle=n.multiKeyBackground,t.fillRect(e,g,h,l),t.strokeRect(e,g,h,l),t.fillStyle=a.backgroundColor,t.fillRect(i,g+1,h-2,l-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){const{body:s}=this,{bodySpacing:n,bodyAlign:o,displayColors:a,boxHeight:r,boxWidth:l,boxPadding:h}=i,c=Si(i.bodyFont);let d=c.lineHeight,f=0;const g=Oi(i.rtl,this.x,this.width),p=function(i){e.fillText(i,g.x(t.x+f),t.y+d/2),t.y+=d+n},m=g.textAlign(o);let b,x,_,y,v,M,w;for(e.textAlign=o,e.textBaseline="middle",e.font=c.string,t.x=La(this,m,i),e.fillStyle=i.bodyColor,u(this.beforeBody,p),f=a&&"right"!==m?"center"===o?l/2+h:l+2+h:0,y=0,M=s.length;y0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=ka[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Ca(this,t),a=Object.assign({},i,this._size),r=Aa(e,t,a),l=Ta(t,a,r,e);s._to===l.x&&n._to===l.y||(this.xAlign=r.xAlign,this.yAlign=r.yAlign,this.width=o.width,this.height=o.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,l))}}_willRender(){return!!this.opacity}draw(t){const e=this.options.setContext(this.getContext());let i=this.opacity;if(!i)return;this._updateAnimationTarget(e);const s={width:this.width,height:this.height},n={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;const o=ki(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(n,t,s,e),Ai(t,e.textDirection),n.y+=o.top,this.drawTitle(n,t,e),this.drawBody(n,t,e),this.drawFooter(n,t,e),Ti(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const i=this._active,s=t.map((({datasetIndex:t,index:e})=>{const i=this.chart.getDatasetMeta(t);if(!i)throw new Error("Cannot find a dataset at index "+t);return{datasetIndex:t,element:i.data[e],index:e}})),n=!f(i,s),o=this._positionChanged(s,e);(n||o)&&(this._active=s,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,n=this._active||[],o=this._getActiveElements(t,n,e,i),a=this._positionChanged(o,t),r=e||!f(o,n)||a;return r&&(this._active=o,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),r}_getActiveElements(t,e,i,s){const n=this.options;if("mouseout"===t.type)return[];if(!s)return e;const o=this.chart.getElementsAtEventForMode(t,n.mode,n,i);return n.reverse&&o.reverse(),o}_positionChanged(t,e){const{caretX:i,caretY:s,options:n}=this,o=ka[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}var Va={id:"tooltip",_element:Fa,positioners:ka,afterInit(t,e,i){i&&(t.tooltip=new Fa({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const i={tooltip:e};if(!1===t.notifyPlugins("beforeTooltipDraw",{...i,cancelable:!0}))return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",i)}},afterEvent(t,e){if(t.tooltip){const i=e.replay;t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:Ia},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};return On.register($n,Ho,uo,t),On.helpers={...Ni},On._adapters=En,On.Animation=Cs,On.Animations=Os,On.animator=xt,On.controllers=en.controllers.items,On.DatasetController=Ws,On.Element=Hs,On.elements=uo,On.Interaction=Xi,On.layouts=as,On.platforms=Ss,On.Scale=Js,On.Ticks=ae,Object.assign(On,$n,Ho,uo,t,Ss),On.Chart=On,"undefined"!=typeof window&&(window.Chart=On),On})); //# sourceMappingURL=chart.umd.js.map ================================================ FILE: dashboard/src/listeners.html ================================================ Mosquitto Broker Dashboard

Listener Information

Number of listeners: ?
Anonymous listeners: none
================================================ FILE: dashboard/src/tailwind/styles.css ================================================ *, ::before, ::after { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-gradient-from-position: ; --tw-gradient-via-position: ; --tw-gradient-to-position: ; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; --tw-contain-size: ; --tw-contain-layout: ; --tw-contain-paint: ; --tw-contain-style: ; } ::backdrop { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-gradient-from-position: ; --tw-gradient-via-position: ; --tw-gradient-to-position: ; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; --tw-contain-size: ; --tw-contain-layout: ; --tw-contain-paint: ; --tw-contain-style: ; } /* ! tailwindcss v3.4.19 | MIT License | https://tailwindcss.com */ /* 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) 2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) */ *, ::before, ::after { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ border-color: #e5e7eb; /* 2 */ } ::before, ::after { --tw-content: ''; } /* 1. Use a consistent sensible line-height in all browsers. 2. Prevent adjustments of font size after orientation changes in iOS. 3. Use a more readable tab size. 4. Use the user's configured `sans` font-family by default. 5. Use the user's configured `sans` font-feature-settings by default. 6. Use the user's configured `sans` font-variation-settings by default. 7. Disable tap highlights on iOS */ html, :host { line-height: 1.5; /* 1 */ -webkit-text-size-adjust: 100%; /* 2 */ -moz-tab-size: 4; /* 3 */ -o-tab-size: 4; tab-size: 4; /* 3 */ font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; /* 4 */ font-feature-settings: normal; /* 5 */ font-variation-settings: normal; /* 6 */ -webkit-tap-highlight-color: transparent; /* 7 */ } /* 1. Remove the margin in all browsers. 2. Inherit line-height from `html` so users can set them as a class directly on the `html` element. */ body { margin: 0; /* 1 */ line-height: inherit; /* 2 */ } /* 1. Add the correct height in Firefox. 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) 3. Ensure horizontal rules are visible by default. */ hr { height: 0; /* 1 */ color: inherit; /* 2 */ border-top-width: 1px; /* 3 */ } /* Add the correct text decoration in Chrome, Edge, and Safari. */ abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } /* Remove the default font size and weight for headings. */ h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } /* Reset links to optimize for opt-in styling instead of opt-out. */ a { color: inherit; text-decoration: inherit; } /* Add the correct font weight in Edge and Safari. */ b, strong { font-weight: bolder; } /* 1. Use the user's configured `mono` font-family by default. 2. Use the user's configured `mono` font-feature-settings by default. 3. Use the user's configured `mono` font-variation-settings by default. 4. Correct the odd `em` font sizing in all browsers. */ code, kbd, samp, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; /* 1 */ font-feature-settings: normal; /* 2 */ font-variation-settings: normal; /* 3 */ font-size: 1em; /* 4 */ } /* Add the correct font size in all browsers. */ small { font-size: 80%; } /* Prevent `sub` and `sup` elements from affecting the line height in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } /* 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) 3. Remove gaps between table borders by default. */ table { text-indent: 0; /* 1 */ border-color: inherit; /* 2 */ border-collapse: collapse; /* 3 */ } /* 1. Change the font styles in all browsers. 2. Remove the margin in Firefox and Safari. 3. Remove default padding in all browsers. */ button, input, optgroup, select, textarea { font-family: inherit; /* 1 */ font-feature-settings: inherit; /* 1 */ font-variation-settings: inherit; /* 1 */ font-size: 100%; /* 1 */ font-weight: inherit; /* 1 */ line-height: inherit; /* 1 */ letter-spacing: inherit; /* 1 */ color: inherit; /* 1 */ margin: 0; /* 2 */ padding: 0; /* 3 */ } /* Remove the inheritance of text transform in Edge and Firefox. */ button, select { text-transform: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Remove default button styles. */ button, input:where([type='button']), input:where([type='reset']), input:where([type='submit']) { -webkit-appearance: button; /* 1 */ background-color: transparent; /* 2 */ background-image: none; /* 2 */ } /* Use the modern Firefox focus style for all focusable elements. */ :-moz-focusring { outline: auto; } /* Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) */ :-moz-ui-invalid { box-shadow: none; } /* Add the correct vertical alignment in Chrome and Firefox. */ progress { vertical-align: baseline; } /* Correct the cursor style of increment and decrement buttons in Safari. */ ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } /* 1. Correct the odd appearance in Chrome and Safari. 2. Correct the outline style in Safari. */ [type='search'] { -webkit-appearance: textfield; /* 1 */ outline-offset: -2px; /* 2 */ } /* Remove the inner padding in Chrome and Safari on macOS. */ ::-webkit-search-decoration { -webkit-appearance: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Change font properties to `inherit` in Safari. */ ::-webkit-file-upload-button { -webkit-appearance: button; /* 1 */ font: inherit; /* 2 */ } /* Add the correct display in Chrome and Safari. */ summary { display: list-item; } /* Removes the default spacing and border for appropriate elements. */ blockquote, dl, dd, h1, h2, h3, h4, h5, h6, hr, figure, p, pre { margin: 0; } fieldset { margin: 0; padding: 0; } legend { padding: 0; } ol, ul, menu { list-style: none; margin: 0; padding: 0; } /* Reset default styling for dialogs. */ dialog { padding: 0; } /* Prevent resizing textareas horizontally by default. */ textarea { resize: vertical; } /* 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) 2. Set the default placeholder color to the user's configured gray 400 color. */ input::-moz-placeholder, textarea::-moz-placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } input::placeholder, textarea::placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } /* Set the default cursor for buttons. */ button, [role="button"] { cursor: pointer; } /* Make sure disabled buttons don't get the pointer cursor. */ :disabled { cursor: default; } /* 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) This can trigger a poorly considered lint error in some tools but is included by design. */ img, svg, video, canvas, audio, iframe, embed, object { display: block; /* 1 */ vertical-align: middle; /* 2 */ } /* Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) */ img, video { max-width: 100%; height: auto; } /* Make elements with the HTML hidden attribute stay hidden by default */ [hidden]:where(:not([hidden="until-found"])) { display: none; } .card { border-radius: 0.5rem; border-width: 1px; --tw-border-opacity: 1; border-color: rgb(229 231 235 / var(--tw-border-opacity, 1)); --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity, 1)); --tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); --tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .card-header { border-bottom-width: 1px; --tw-border-opacity: 1; border-color: rgb(229 231 235 / var(--tw-border-opacity, 1)); padding-left: 1.5rem; padding-right: 1.5rem; padding-top: 1rem; padding-bottom: 1rem; } .card-content { padding-left: 1.5rem; padding-right: 1.5rem; padding-top: 1rem; padding-bottom: 1rem; } .metric-value { font-size: 1.875rem; line-height: 2.25rem; font-weight: 700; --tw-text-opacity: 1; color: rgb(17 24 39 / var(--tw-text-opacity, 1)); } .metric-label { margin-bottom: 0.5rem; font-size: 0.875rem; line-height: 1.25rem; font-weight: 500; --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity, 1)); } .chart-container { position: relative; height: 200px; width: 100%; } .nav-btn { display: inline-flex; height: 2rem; width: 2rem; align-items: center; justify-content: center; border-radius: 0.25rem; border-width: 1px; --tw-border-opacity: 1; border-color: rgb(209 213 219 / var(--tw-border-opacity, 1)); --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity, 1)); --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity, 1)); transition-property: color, background-color, border-color, text-decoration-color, fill, stroke; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .nav-btn:hover { --tw-bg-opacity: 1; background-color: rgb(249 250 251 / var(--tw-bg-opacity, 1)); --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity, 1)); } .nav-btn:focus { outline: 2px solid transparent; outline-offset: 2px; --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); --tw-ring-opacity: 1; --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1)); --tw-ring-offset-width: 1px; } .nav-btn:disabled { cursor: not-allowed; opacity: 0.5; } .nav-btn:hover:not(:disabled) { --tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); --tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .nav-btn.active { --tw-border-opacity: 1; border-color: rgb(147 197 253 / var(--tw-border-opacity, 1)); --tw-bg-opacity: 1; background-color: rgb(239 246 255 / var(--tw-bg-opacity, 1)); --tw-text-opacity: 1; color: rgb(37 99 235 / var(--tw-text-opacity, 1)); } .nav-separator { margin-left: 0.5rem; margin-right: 0.5rem; height: 1.5rem; width: 1px; --tw-bg-opacity: 1; background-color: rgb(209 213 219 / var(--tw-bg-opacity, 1)); } .nav-btn svg { pointer-events: none; } .fixed { position: fixed; } .absolute { position: absolute; } .relative { position: relative; } .sticky { position: sticky; } .inset-0 { inset: 0px; } .left-0 { left: 0px; } .right-0 { right: 0px; } .right-2 { right: 0.5rem; } .top-0 { top: 0px; } .top-2 { top: 0.5rem; } .z-10 { z-index: 10; } .z-40 { z-index: 40; } .z-50 { z-index: 50; } .mx-auto { margin-left: auto; margin-right: auto; } .mb-1 { margin-bottom: 0.25rem; } .mb-4 { margin-bottom: 1rem; } .mb-8 { margin-bottom: 2rem; } .ml-2 { margin-left: 0.5rem; } .mr-2 { margin-right: 0.5rem; } .mr-\[3\%\] { margin-right: 3%; } .mt-2 { margin-top: 0.5rem; } .mt-4 { margin-top: 1rem; } .mt-\[5\%\] { margin-top: 5%; } .block { display: block; } .inline-block { display: inline-block; } .inline { display: inline; } .flex { display: flex; } .inline-flex { display: inline-flex; } .grid { display: grid; } .hidden { display: none; } .h-2 { height: 0.5rem; } .h-20 { height: 5rem; } .h-24 { height: 6rem; } .h-3 { height: 0.75rem; } .h-4 { height: 1rem; } .h-5 { height: 1.25rem; } .h-8 { height: 2rem; } .h-\[335px\] { height: 335px; } .h-full { height: 100%; } .min-h-screen { min-height: 100vh; } .w-16 { width: 4rem; } .w-2 { width: 0.5rem; } .w-20 { width: 5rem; } .w-24 { width: 6rem; } .w-32 { width: 8rem; } .w-4 { width: 1rem; } .w-5 { width: 1.25rem; } .w-64 { width: 16rem; } .w-8 { width: 2rem; } .w-80 { width: 20rem; } .w-full { width: 100%; } .min-w-max { min-width: -moz-max-content; min-width: max-content; } .max-w-7xl { max-width: 80rem; } .flex-1 { flex: 1 1 0%; } .-translate-x-full { --tw-translate-x: -100%; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .transform { transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } @keyframes pulse { 50% { opacity: .5; } } .animate-pulse { animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; } .cursor-pointer { cursor: pointer; } .grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); } .grid-rows-3 { grid-template-rows: repeat(3, minmax(0, 1fr)); } .flex-col { flex-direction: column; } .items-center { align-items: center; } .justify-start { justify-content: flex-start; } .justify-end { justify-content: flex-end; } .justify-center { justify-content: center; } .justify-between { justify-content: space-between; } .justify-evenly { justify-content: space-evenly; } .gap-1 { gap: 0.25rem; } .gap-2 { gap: 0.5rem; } .gap-3 { gap: 0.75rem; } .gap-4 { gap: 1rem; } .gap-6 { gap: 1.5rem; } .space-y-1 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(0.25rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(0.25rem * var(--tw-space-y-reverse)); } .space-y-4 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(1rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(1rem * var(--tw-space-y-reverse)); } .space-y-6 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(1.5rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(1.5rem * var(--tw-space-y-reverse)); } .overflow-hidden { overflow: hidden; } .overflow-x-auto { overflow-x: auto; } .overflow-y-auto { overflow-y: auto; } .whitespace-nowrap { white-space: nowrap; } .break-words { overflow-wrap: break-word; } .rounded { border-radius: 0.25rem; } .rounded-full { border-radius: 9999px; } .rounded-lg { border-radius: 0.5rem; } .rounded-md { border-radius: 0.375rem; } .rounded-xl { border-radius: 0.75rem; } .border { border-width: 1px; } .border-b { border-bottom-width: 1px; } .border-t { border-top-width: 1px; } .border-gray-200 { --tw-border-opacity: 1; border-color: rgb(229 231 235 / var(--tw-border-opacity, 1)); } .border-gray-300 { --tw-border-opacity: 1; border-color: rgb(209 213 219 / var(--tw-border-opacity, 1)); } .bg-gray-100 { --tw-bg-opacity: 1; background-color: rgb(243 244 246 / var(--tw-bg-opacity, 1)); } .bg-gray-200 { --tw-bg-opacity: 1; background-color: rgb(229 231 235 / var(--tw-bg-opacity, 1)); } .bg-gray-50 { --tw-bg-opacity: 1; background-color: rgb(249 250 251 / var(--tw-bg-opacity, 1)); } .bg-gray-500 { --tw-bg-opacity: 1; background-color: rgb(107 114 128 / var(--tw-bg-opacity, 1)); } .bg-white { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity, 1)); } .bg-white\/80 { background-color: rgb(255 255 255 / 0.8); } .p-1 { padding: 0.25rem; } .p-2 { padding: 0.5rem; } .p-3 { padding: 0.75rem; } .p-4 { padding: 1rem; } .p-6 { padding: 1.5rem; } .px-3 { padding-left: 0.75rem; padding-right: 0.75rem; } .px-4 { padding-left: 1rem; padding-right: 1rem; } .py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; } .pb-2 { padding-bottom: 0.5rem; } .pb-6 { padding-bottom: 1.5rem; } .pr-6 { padding-right: 1.5rem; } .pt-6 { padding-top: 1.5rem; } .text-center { text-align: center; } .font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; } .text-base { font-size: 1rem; line-height: 1.5rem; } .text-lg { font-size: 1.125rem; line-height: 1.75rem; } .text-sm { font-size: 0.875rem; line-height: 1.25rem; } .font-medium { font-weight: 500; } .font-semibold { font-weight: 600; } .text-blue-700 { --tw-text-opacity: 1; color: rgb(29 78 216 / var(--tw-text-opacity, 1)); } .text-gray-500 { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity, 1)); } .text-gray-600 { --tw-text-opacity: 1; color: rgb(75 85 99 / var(--tw-text-opacity, 1)); } .text-gray-700 { --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity, 1)); } .text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity, 1)); } .opacity-0 { opacity: 0; } .shadow-2xl { --tw-shadow: 0 25px 50px -12px rgb(0 0 0 / 0.25); --tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .shadow-lg { --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .transition-all { transition-property: all; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .transition-colors { transition-property: color, background-color, border-color, text-decoration-color, fill, stroke; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .transition-opacity { transition-property: opacity; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .transition-transform { transition-property: transform; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .duration-200 { transition-duration: 200ms; } .duration-300 { transition-duration: 300ms; } .ease-in-out { transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } .bg-c-orange { background-color: #fd602e; } .hover\:bg-c-orange:hover { background-color: #fd602e; } #menu-overlay { transition: opacity 300ms; opacity: 0; pointer-events: none; background: rgba(0,0,0,0.45); } @media (min-width: 1024px) { #menu-overlay { display: none; } #sliding-menu { box-shadow: none; } #menu-close { visibility: hidden; } #broker-info-icon { display: block; } } #sliding-menu { transform: translateX(-100%); transition: transform 300ms; } .sidebar-open #sliding-menu { transform: translateX(0); } @media (max-width: 1023px) { .sidebar-open #menu-overlay { opacity: 1; pointer-events: auto; } } @media (min-width: 1024px) { .sidebar-open #main-content { margin-left: 320px; } } /* lock scroll on mobile when sidebar open */ .sidebar-lock-scroll { overflow: hidden; } .sidebar-preload #sliding-menu { transition: none; } @media (max-width: 1024px) { #layout-toggle { display: none; } } @media (max-width: 375px) { #logo-icon { display: block; } #logo-text { display: none } } .broker-active { background-color: rgb(34 197 94); /* green-500 */ } .broker-inactive { background-color: rgb(239 68 68); /* red-500 */ } .hover\:cursor-pointer:hover { cursor: pointer; } .hover\:bg-gray-100:hover { --tw-bg-opacity: 1; background-color: rgb(243 244 246 / var(--tw-bg-opacity, 1)); } .hover\:bg-gray-50:hover { --tw-bg-opacity: 1; background-color: rgb(249 250 251 / var(--tw-bg-opacity, 1)); } .hover\:bg-orange-700:hover { --tw-bg-opacity: 1; background-color: rgb(194 65 12 / var(--tw-bg-opacity, 1)); } .hover\:bg-white:hover { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity, 1)); } .hover\:text-blue-900:hover { --tw-text-opacity: 1; color: rgb(30 58 138 / var(--tw-text-opacity, 1)); } .hover\:text-white:hover { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity, 1)); } .hover\:underline:hover { text-decoration-line: underline; } .focus\:outline-none:focus { outline: 2px solid transparent; outline-offset: 2px; } .focus\:ring-2:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .focus\:ring-blue-500:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1)); } .group[open] .group-open\:block { display: block; } @media (min-width: 768px) { .md\:grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .md\:grid-cols-5 { grid-template-columns: repeat(5, minmax(0, 1fr)); } .md\:justify-start { justify-content: flex-start; } .md\:justify-end { justify-content: flex-end; } } @media (min-width: 1024px) { .lg\:grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .lg\:grid-cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } } ================================================ FILE: dashboard/src/tailwind.config.js ================================================ /** @type {import('tailwindcss').Config} */ module.exports = { content: ["./*.html", "./*.js"], theme: { extend: {}, }, plugins: [], }; ================================================ FILE: dashboard/src/utils/assert.js ================================================ function assertExistence(value, error) { if (value === undefined) { throw new Error(error); } } // assertValue(value, expected, error) {} ================================================ FILE: dashboard/src/utils/queue.js ================================================ class Queue { constructor() { this.tasks = []; this.active = false; } enqueue(task) { this.tasks.push(task); this.#dequeue(); } async #dequeue() { if (this.active) { return; } this.active = true; while (this.tasks.length) { const task = this.tasks.shift(); try { await task(); } catch (err) { console.error("Error in queue:", err); } } this.active = false; } } const queue = new Queue(); ================================================ FILE: dashboard/src/utils/utils.js ================================================ function toAsyncAndWaitAfter(task, delay = 0) { return () => { const promise = new Promise((resolve, reject) => { let result; try { result = task(); } catch (err) { return reject(err); } if (delay) { setTimeout(() => { resolve(result); }, delay); } else { resolve(result); } }); return promise; }; } async function fetchData(endpoint, opts = {}) { if (!endpoint) { throw new Error("No endpoint provided to fetch data function"); } let data; const res = await fetch(endpoint, { ...opts, headers: { Accept: "application/json" }, }); if (res.ok) { data = await res.json(); } else { throw new Error(`Failed to fetch: ${res.status} ${res.statusText}`); } return data; } function toTimeString(date = new Date()) { const d = new Date(date); const hours = String(d.getHours()).padStart(2, "0"); const minutes = String(d.getMinutes()).padStart(2, "0"); const seconds = String(d.getSeconds()).padStart(2, "0"); return `${hours}:${minutes}:${seconds}`; } function timeStringToTimestamp(timeString) { const regex = /^(\d{2}):(\d{2}):(\d{2})$/; const match = timeString.match(regex); if (!match) { throw new Error(`Invalid format. Expected HH:mm:ss, got: ${timeString}`); } const [, hours, minutes, seconds] = match; const now = new Date(); const [year, month, day] = [now.getFullYear(), now.getMonth(), now.getDate()]; const date = new Date( year, month, day, Number(hours), Number(minutes), Number(seconds), ); return date.getTime(); } function prettifyNumber(number) { if (number > Number.MAX_SAFE_INTEGER) { return ">" + String(Number.MAX_SAFE_INTEGER); } let strNumber = String(number); let prettifiedNumber = ""; if (strNumber.length - 1 > 3) { let i = strNumber.length - 3; for (; i > 0; i -= 3) { prettifiedNumber = "," + strNumber.substring(i, i + 3) + prettifiedNumber; } prettifiedNumber = strNumber.substring(0, i + 3) + prettifiedNumber; } else { prettifiedNumber = strNumber; } return prettifiedNumber; } function secondsToIntervalString(number) { const minuteInSeconds = 60; const hourInSeconds = minuteInSeconds * 60; const dayInSeconds = hourInSeconds * 24; const yearInSeconds = dayInSeconds * 365; if (typeof number !== "number") { throw new Error( `Invalid datatype for converting into interval string. Expected: number. Got: ${typeof number}`, ); } if (number < 0) { throw new Error( `Invalid value for converting into interval string. Received negative number: ${number}`, ); } let intervalString = ""; const years = Math.floor(number / yearInSeconds); number = number % yearInSeconds; if (years) { intervalString += years === 1 ? "1 year " : `${years} years `; } const days = Math.floor(number / dayInSeconds); number = number % dayInSeconds; if (days) { intervalString += days === 1 ? "1 day " : `${days} days `; } const hours = Math.floor(number / hourInSeconds); number = number % hourInSeconds; if (hours) { intervalString += hours === 1 ? "1 hour " : `${hours} hours `; } const minutes = Math.floor(number / minuteInSeconds); number = number % minuteInSeconds; if (minutes) { intervalString += minutes === 1 ? "1 minute " : `${minutes} minutes `; } const seconds = number; if (seconds) { intervalString += seconds === 1 ? "1 second " : `${seconds} seconds `; } if (!intervalString) { return "0 seconds"; // This would be strange if this happened. Maybe better to throw an error } return intervalString; } async function copyToClipboard(textToCopy) { if (navigator.clipboard) { return await navigator.clipboard.writeText(textToCopy); } const dummyTextArea = document.createElement("textarea"); dummyTextArea.value = textToCopy; document.body.appendChild(dummyTextArea); dummyTextArea.focus({ preventScroll: true }); dummyTextArea.select(); try { document.execCommand("copy"); } catch (err) { throw new Error("Copy command failed: " + err?.message); } finally { dummyTextArea.remove(); } } function isMobile() { return window.innerWidth < 1024; } function registerAbortController(abortController) { // in firefox the below doesn't help unfortunately: a general netrowk error is being thrown even before the below callback is executed. A proper implementation would require aborying in-flight requets right before the navigation but it's not worth the effort. Currently you will see an alert for a quick moment when spam-clicking onto the "listern" tab in the sidebar on firefox const abortCallback = () => { abortController.abort(); }; window.addEventListener("pagehide", abortCallback, { once: true }); } ================================================ FILE: deps/picohttpparser/README.md ================================================ PicoHTTPParser ============= Copyright (c) 2009-2014 [Kazuho Oku](https://github.com/kazuho), [Tokuhiro Matsuno](https://github.com/tokuhirom), [Daisuke Murase](https://github.com/typester), [Shigeo Mitsunari](https://github.com/herumi) PicoHTTPParser is a tiny, primitive, fast HTTP request/response parser. Unlike most parsers, it is stateless and does not allocate memory by itself. All it does is accept pointer to buffer and the output structure, and setups the pointers in the latter to point at the necessary portions of the buffer. The code is widely deployed within Perl applications through popular modules that use it, including [Plack](https://metacpan.org/pod/Plack), [Starman](https://metacpan.org/pod/Starman), [Starlet](https://metacpan.org/pod/Starlet), [Furl](https://metacpan.org/pod/Furl). It is also the HTTP/1 parser of [H2O](https://github.com/h2o/h2o). Check out [test.c] to find out how to use the parser. The software is dual-licensed under the Perl License or the MIT License. Usage ----- The library exposes four functions: `phr_parse_request`, `phr_parse_response`, `phr_parse_headers`, `phr_decode_chunked`. ### phr_parse_request The example below reads an HTTP request from socket `sock` using `read(2)`, parses it using `phr_parse_request`, and prints the details. ```c char buf[4096], *method, *path; int pret, minor_version; struct phr_header headers[100]; size_t buflen = 0, prevbuflen = 0, method_len, path_len, num_headers; ssize_t rret; while (1) { /* read the request */ while ((rret = read(sock, buf + buflen, sizeof(buf) - buflen)) == -1 && errno == EINTR) ; if (rret <= 0) return IOError; prevbuflen = buflen; buflen += rret; /* parse the request */ num_headers = sizeof(headers) / sizeof(headers[0]); pret = phr_parse_request(buf, buflen, &method, &method_len, &path, &path_len, &minor_version, headers, &num_headers, prevbuflen); if (pret > 0) break; /* successfully parsed the request */ else if (pret == -1) return ParseError; /* request is incomplete, continue the loop */ assert(pret == -2); if (buflen == sizeof(buf)) return RequestIsTooLongError; } printf("request is %d bytes long\n", pret); printf("method is %.*s\n", (int)method_len, method); printf("path is %.*s\n", (int)path_len, path); printf("HTTP version is 1.%d\n", minor_version); printf("headers:\n"); for (i = 0; i != num_headers; ++i) { printf("%.*s: %.*s\n", (int)headers[i].name_len, headers[i].name, (int)headers[i].value_len, headers[i].value); } ``` ### phr_parse_response, phr_parse_headers `phr_parse_response` and `phr_parse_headers` provide similar interfaces as `phr_parse_request`. `phr_parse_response` parses an HTTP response, and `phr_parse_headers` parses the headers only. ### phr_decode_chunked The example below decodes incoming data in chunked-encoding. The data is decoded in-place. ```c struct phr_chunked_decoder decoder = {}; /* zero-clear */ char *buf = malloc(4096); size_t size = 0, capacity = 4096, rsize; ssize_t rret, pret; /* set consume_trailer to 1 to discard the trailing header, or the application * should call phr_parse_headers to parse the trailing header */ decoder.consume_trailer = 1; do { /* expand the buffer if necessary */ if (size == capacity) { capacity *= 2; buf = realloc(buf, capacity); assert(buf != NULL); } /* read */ while ((rret = read(sock, buf + size, capacity - size)) == -1 && errno == EINTR) ; if (rret <= 0) return IOError; /* decode */ rsize = rret; pret = phr_decode_chunked(&decoder, buf + size, &rsize); if (pret == -1) return ParseError; size += rsize; } while (pret == -2); /* successfully decoded the chunked data */ assert(pret >= 0); printf("decoded data is at %p (%zu bytes)\n", buf, size); ``` Benchmark --------- ![benchmark results](http://i.gyazo.com/a85c18d3162dfb46b485bb41e0ad443a.png) The benchmark code is from [fukamachi/fast-http@6b91103](https://github.com/fukamachi/fast-http/tree/6b9110347c7a3407310c08979aefd65078518478). The internals of picohttpparser has been described to some extent in [my blog entry]( http://blog.kazuhooku.com/2014/11/the-internals-h2o-or-how-to-write-fast.html). ================================================ FILE: deps/picohttpparser/picohttpparser.c ================================================ /* * Copyright (c) 2009-2014 Kazuho Oku, Tokuhiro Matsuno, Daisuke Murase, * Shigeo Mitsunari * * The software is licensed under either the MIT License (below) or the Perl * license. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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. 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. */ #include #include #include #ifdef __SSE4_2__ #ifdef _MSC_VER #include #else #include #endif #endif #include "picohttpparser.h" #if __GNUC__ >= 3 #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else #define likely(x) (x) #define unlikely(x) (x) #endif #ifdef _MSC_VER #define ALIGNED(n) _declspec(align(n)) #else #define ALIGNED(n) __attribute__((aligned(n))) #endif #define IS_PRINTABLE_ASCII(c) ((unsigned char)(c)-040u < 0137u) #define CHECK_EOF() \ if (buf == buf_end) { \ *ret = -2; \ return NULL; \ } #define EXPECT_CHAR_NO_CHECK(ch) \ if (*buf++ != ch) { \ *ret = -1; \ return NULL; \ } #define EXPECT_CHAR(ch) \ CHECK_EOF(); \ EXPECT_CHAR_NO_CHECK(ch); #define ADVANCE_TOKEN(tok, toklen) \ do { \ const char *tok_start = buf; \ static const char ALIGNED(16) ranges2[16] = "\000\040\177\177"; \ int found2; \ buf = findchar_fast(buf, buf_end, ranges2, 4, &found2); \ if (!found2) { \ CHECK_EOF(); \ } \ while (1) { \ if (*buf == ' ') { \ break; \ } else if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { \ if ((unsigned char)*buf < '\040' || *buf == '\177') { \ *ret = -1; \ return NULL; \ } \ } \ ++buf; \ CHECK_EOF(); \ } \ tok = tok_start; \ toklen = (size_t)(buf - tok_start); \ } while (0) static const char *token_char_map = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\1\0\1\1\1\1\1\0\0\1\1\0\1\1\0\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0" "\0\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\1\1" "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\1\0\1\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; static const char *findchar_fast(const char *buf, const char *buf_end, const char *ranges, size_t ranges_size, int *found) { *found = 0; #if __SSE4_2__ if (likely(buf_end - buf >= 16)) { __m128i ranges16 = _mm_loadu_si128((const __m128i *)ranges); size_t left = (buf_end - buf) & ~15; do { __m128i b16 = _mm_loadu_si128((const __m128i *)buf); int r = _mm_cmpestri(ranges16, ranges_size, b16, 16, _SIDD_LEAST_SIGNIFICANT | _SIDD_CMP_RANGES | _SIDD_UBYTE_OPS); if (unlikely(r != 16)) { buf += r; *found = 1; break; } buf += 16; left -= 16; } while (likely(left != 0)); } #else /* suppress unused parameter warning */ (void)buf_end; (void)ranges; (void)ranges_size; #endif return buf; } static const char *get_token_to_eol(const char *buf, const char *buf_end, const char **token, size_t *token_len, int *ret) { const char *token_start = buf; #ifdef __SSE4_2__ static const char ALIGNED(16) ranges1[16] = "\0\010" /* allow HT */ "\012\037" /* allow SP and up to but not including DEL */ "\177\177"; /* allow chars w. MSB set */ int found; buf = findchar_fast(buf, buf_end, ranges1, 6, &found); if (found) goto FOUND_CTL; #else /* find non-printable char within the next 8 bytes, this is the hottest code; manually inlined */ while (likely(buf_end - buf >= 8)) { #define DOIT() \ do { \ if (unlikely(!IS_PRINTABLE_ASCII(*buf))) \ goto NonPrintable; \ ++buf; \ } while (0) DOIT(); DOIT(); DOIT(); DOIT(); DOIT(); DOIT(); DOIT(); DOIT(); #undef DOIT continue; NonPrintable: if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { goto FOUND_CTL; } ++buf; } #endif for (;; ++buf) { CHECK_EOF(); if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) { goto FOUND_CTL; } } } FOUND_CTL: if (likely(*buf == '\015')) { ++buf; EXPECT_CHAR('\012'); *token_len = (size_t)(buf - 2 - token_start); } else if (*buf == '\012') { *token_len = (size_t)(buf - token_start); ++buf; } else { *ret = -1; return NULL; } *token = token_start; return buf; } static const char *is_complete(const char *buf, const char *buf_end, size_t last_len, int *ret) { int ret_cnt = 0; buf = last_len < 3 ? buf : buf + last_len - 3; while (1) { CHECK_EOF(); if (*buf == '\015') { ++buf; CHECK_EOF(); EXPECT_CHAR('\012'); ++ret_cnt; } else if (*buf == '\012') { ++buf; ++ret_cnt; } else { ++buf; ret_cnt = 0; } if (ret_cnt == 2) { return buf; } } } #define PARSE_INT(valp_, mul_) \ if (*buf < '0' || '9' < *buf) { \ buf++; \ *ret = -1; \ return NULL; \ } \ *(valp_) = (mul_) * (*buf++ - '0'); #define PARSE_INT_3(valp_) \ do { \ int res_ = 0; \ PARSE_INT(&res_, 100) \ *valp_ = res_; \ PARSE_INT(&res_, 10) \ *valp_ += res_; \ PARSE_INT(&res_, 1) \ *valp_ += res_; \ } while (0) /* returned pointer is always within [buf, buf_end), or null */ static const char *parse_token(const char *buf, const char *buf_end, const char **token, size_t *token_len, char next_char, int *ret) { /* We use pcmpestri to detect non-token characters. This instruction can take no more than eight character ranges (8*2*8=128 * bits that is the size of a SSE register). Due to this restriction, characters `|` and `~` are handled in the slow loop. */ static const char ALIGNED(16) ranges[] = "\x00 " /* control chars and up to SP */ "\"\"" /* 0x22 */ "()" /* 0x28,0x29 */ ",," /* 0x2c */ "//" /* 0x2f */ ":@" /* 0x3a-0x40 */ "[]" /* 0x5b-0x5d */ "{\xff"; /* 0x7b-0xff */ const char *buf_start = buf; int found; buf = findchar_fast(buf, buf_end, ranges, sizeof(ranges) - 1, &found); if (!found) { CHECK_EOF(); } while (1) { if (*buf == next_char) { break; } else if (!token_char_map[(unsigned char)*buf]) { *ret = -1; return NULL; } ++buf; CHECK_EOF(); } *token = buf_start; *token_len = (size_t)(buf - buf_start); return buf; } /* returned pointer is always within [buf, buf_end), or null */ static const char *parse_http_version(const char *buf, const char *buf_end, int *minor_version, int *ret) { /* we want at least [HTTP/1.] to try to parse */ if (buf_end - buf < 9) { *ret = -2; return NULL; } EXPECT_CHAR_NO_CHECK('H'); EXPECT_CHAR_NO_CHECK('T'); EXPECT_CHAR_NO_CHECK('T'); EXPECT_CHAR_NO_CHECK('P'); EXPECT_CHAR_NO_CHECK('/'); EXPECT_CHAR_NO_CHECK('1'); EXPECT_CHAR_NO_CHECK('.'); PARSE_INT(minor_version, 1); return buf; } static const char *parse_headers(const char *buf, const char *buf_end, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret) { for (;; ++*num_headers) { CHECK_EOF(); if (*buf == '\015') { ++buf; EXPECT_CHAR('\012'); break; } else if (*buf == '\012') { ++buf; break; } if (*num_headers == max_headers) { *ret = -1; return NULL; } if (!(*num_headers != 0 && (*buf == ' ' || *buf == '\t'))) { /* parsing name, but do not discard SP before colon, see * http://www.mozilla.org/security/announce/2006/mfsa2006-33.html */ if ((buf = parse_token(buf, buf_end, &headers[*num_headers].name, &headers[*num_headers].name_len, ':', ret)) == NULL) { return NULL; } if (headers[*num_headers].name_len == 0) { *ret = -1; return NULL; } ++buf; for (;; ++buf) { CHECK_EOF(); if (!(*buf == ' ' || *buf == '\t')) { break; } } } else { headers[*num_headers].name = NULL; headers[*num_headers].name_len = 0; } const char *value; size_t value_len; if ((buf = get_token_to_eol(buf, buf_end, &value, &value_len, ret)) == NULL) { return NULL; } /* remove trailing SPs and HTABs */ const char *value_end = value + value_len; for (; value_end != value; --value_end) { const char c = *(value_end - 1); if (!(c == ' ' || c == '\t')) { break; } } headers[*num_headers].value = value; headers[*num_headers].value_len = (size_t)(value_end - value); } return buf; } static const char *parse_request(const char *buf, const char *buf_end, const char **method, size_t *method_len, const char **path, size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret) { /* skip first empty line (some clients add CRLF after POST content) */ CHECK_EOF(); if (*buf == '\015') { ++buf; EXPECT_CHAR('\012'); } else if (*buf == '\012') { ++buf; } /* parse request line */ if ((buf = parse_token(buf, buf_end, method, method_len, ' ', ret)) == NULL) { return NULL; } do { ++buf; CHECK_EOF(); } while (*buf == ' '); ADVANCE_TOKEN(*path, *path_len); do { ++buf; CHECK_EOF(); } while (*buf == ' '); if (*method_len == 0 || *path_len == 0) { *ret = -1; return NULL; } if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) { return NULL; } if (*buf == '\015') { ++buf; EXPECT_CHAR('\012'); } else if (*buf == '\012') { ++buf; } else { *ret = -1; return NULL; } return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); } int phr_parse_request(const char *buf_start, size_t len, const char **method, size_t *method_len, const char **path, size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len) { const char *buf = buf_start, *buf_end = buf_start + len; size_t max_headers = *num_headers; int r; *method = NULL; *method_len = 0; *path = NULL; *path_len = 0; *minor_version = -1; *num_headers = 0; /* if last_len != 0, check if the request is complete (a fast countermeasure againt slowloris */ if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { return r; } if ((buf = parse_request(buf, buf_end, method, method_len, path, path_len, minor_version, headers, num_headers, max_headers, &r)) == NULL) { return r; } return (int)(buf - buf_start); } static const char *parse_response(const char *buf, const char *buf_end, int *minor_version, int *status, const char **msg, size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret) { /* parse "HTTP/1.x" */ if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) { return NULL; } /* skip space */ if (*buf != ' ') { *ret = -1; return NULL; } do { ++buf; CHECK_EOF(); } while (*buf == ' '); /* parse status code, we want at least [:digit:][:digit:][:digit:] to try to parse */ if (buf_end - buf < 4) { *ret = -2; return NULL; } PARSE_INT_3(status); /* get message including preceding space */ if ((buf = get_token_to_eol(buf, buf_end, msg, msg_len, ret)) == NULL) { return NULL; } if (*msg_len == 0) { /* ok */ } else if (**msg == ' ') { /* Remove preceding space. Successful return from `get_token_to_eol` guarantees that we would hit something other than SP * before running past the end of the given buffer. */ do { ++*msg; --*msg_len; } while (**msg == ' '); } else { /* garbage found after status code */ *ret = -1; return NULL; } return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret); } int phr_parse_response(const char *buf_start, size_t len, int *minor_version, int *status, const char **msg, size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t last_len) { const char *buf = buf_start, *buf_end = buf + len; size_t max_headers = *num_headers; int r; *minor_version = -1; *status = 0; *msg = NULL; *msg_len = 0; *num_headers = 0; /* if last_len != 0, check if the response is complete (a fast countermeasure against slowloris */ if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { return r; } if ((buf = parse_response(buf, buf_end, minor_version, status, msg, msg_len, headers, num_headers, max_headers, &r)) == NULL) { return r; } return (int)(buf - buf_start); } int phr_parse_headers(const char *buf_start, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len) { const char *buf = buf_start, *buf_end = buf + len; size_t max_headers = *num_headers; int r; *num_headers = 0; /* if last_len != 0, check if the response is complete (a fast countermeasure against slowloris */ if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) { return r; } if ((buf = parse_headers(buf, buf_end, headers, num_headers, max_headers, &r)) == NULL) { return r; } return (int)(buf - buf_start); } enum { CHUNKED_IN_CHUNK_SIZE, CHUNKED_IN_CHUNK_EXT, CHUNKED_IN_CHUNK_DATA, CHUNKED_IN_CHUNK_CRLF, CHUNKED_IN_TRAILERS_LINE_HEAD, CHUNKED_IN_TRAILERS_LINE_MIDDLE }; static int decode_hex(int ch) { if ('0' <= ch && ch <= '9') { return ch - '0'; } else if ('A' <= ch && ch <= 'F') { return ch - 'A' + 0xa; } else if ('a' <= ch && ch <= 'f') { return ch - 'a' + 0xa; } else { return -1; } } ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_t *_bufsz) { size_t dst = 0, src = 0, bufsz = *_bufsz; ssize_t ret = -2; /* incomplete */ while (1) { switch (decoder->_state) { case CHUNKED_IN_CHUNK_SIZE: for (;; ++src) { int v; if (src == bufsz) goto Exit; if ((v = decode_hex(buf[src])) == -1) { if (decoder->_hex_count == 0) { ret = -1; goto Exit; } break; } if (decoder->_hex_count == sizeof(size_t) * 2) { ret = -1; goto Exit; } decoder->bytes_left_in_chunk = decoder->bytes_left_in_chunk * 16 + (size_t)v; ++decoder->_hex_count; } decoder->_hex_count = 0; decoder->_state = CHUNKED_IN_CHUNK_EXT; /* fallthru */ case CHUNKED_IN_CHUNK_EXT: /* RFC 7230 A.2 "Line folding in chunk extensions is disallowed" */ for (;; ++src) { if (src == bufsz) goto Exit; if (buf[src] == '\012') break; } ++src; if (decoder->bytes_left_in_chunk == 0) { if (decoder->consume_trailer) { decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD; break; } else { goto Complete; } } decoder->_state = CHUNKED_IN_CHUNK_DATA; /* fallthru */ case CHUNKED_IN_CHUNK_DATA: { size_t avail = bufsz - src; if (avail < decoder->bytes_left_in_chunk) { if (dst != src) memmove(buf + dst, buf + src, avail); src += avail; dst += avail; decoder->bytes_left_in_chunk -= avail; goto Exit; } if (dst != src) memmove(buf + dst, buf + src, decoder->bytes_left_in_chunk); src += decoder->bytes_left_in_chunk; dst += decoder->bytes_left_in_chunk; decoder->bytes_left_in_chunk = 0; decoder->_state = CHUNKED_IN_CHUNK_CRLF; } /* fallthru */ case CHUNKED_IN_CHUNK_CRLF: for (;; ++src) { if (src == bufsz) goto Exit; if (buf[src] != '\015') break; } if (buf[src] != '\012') { ret = -1; goto Exit; } ++src; decoder->_state = CHUNKED_IN_CHUNK_SIZE; break; case CHUNKED_IN_TRAILERS_LINE_HEAD: for (;; ++src) { if (src == bufsz) goto Exit; if (buf[src] != '\015') break; } if (buf[src++] == '\012') goto Complete; decoder->_state = CHUNKED_IN_TRAILERS_LINE_MIDDLE; /* fallthru */ case CHUNKED_IN_TRAILERS_LINE_MIDDLE: for (;; ++src) { if (src == bufsz) goto Exit; if (buf[src] == '\012') break; } ++src; decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD; break; default: assert(0 /*"decoder is corrupt"*/); } } Complete: ret = (ssize_t)(bufsz - src); Exit: if (dst != src) memmove(buf + dst, buf + src, bufsz - src); *_bufsz = dst; return ret; } int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder) { return decoder->_state == CHUNKED_IN_CHUNK_DATA; } #undef CHECK_EOF #undef EXPECT_CHAR #undef ADVANCE_TOKEN ================================================ FILE: deps/picohttpparser/picohttpparser.h ================================================ /* * Copyright (c) 2009-2014 Kazuho Oku, Tokuhiro Matsuno, Daisuke Murase, * Shigeo Mitsunari * * The software is licensed under either the MIT License (below) or the Perl * license. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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. 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. */ #ifndef picohttpparser_h #define picohttpparser_h #include #ifdef _MSC_VER #define ssize_t intptr_t #endif #ifdef __cplusplus extern "C" { #endif /* contains name and value of a header (name == NULL if is a continuing line * of a multiline header */ struct phr_header { const char *name; size_t name_len; const char *value; size_t value_len; }; /* returns number of bytes consumed if successful, -2 if request is partial, * -1 if failed */ int phr_parse_request(const char *buf, size_t len, const char **method, size_t *method_len, const char **path, size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len); /* ditto */ int phr_parse_response(const char *_buf, size_t len, int *minor_version, int *status, const char **msg, size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t last_len); /* ditto */ int phr_parse_headers(const char *buf, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len); /* should be zero-filled before start */ struct phr_chunked_decoder { size_t bytes_left_in_chunk; /* number of bytes left in current chunk */ char consume_trailer; /* if trailing headers should be consumed */ char _hex_count; char _state; }; /* the function rewrites the buffer given as (buf, bufsz) removing the chunked- * encoding headers. When the function returns without an error, bufsz is * updated to the length of the decoded data available. Applications should * repeatedly call the function while it returns -2 (incomplete) every time * supplying newly arrived data. If the end of the chunked-encoded data is * found, the function returns a non-negative number indicating the number of * octets left undecoded, that starts from the offset returned by `*bufsz`. * Returns -1 on error. */ ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_t *bufsz); /* returns if the chunked decoder is in middle of chunked data */ int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder); #ifdef __cplusplus } #endif #endif ================================================ FILE: deps/uthash.h ================================================ /* Copyright (c) 2003-2025, Troy D. Hanson https://troydhanson.github.io/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.3.0 #include /* memcmp, memset, strlen */ #include /* ptrdiff_t */ #include /* exit */ #if defined(HASH_NO_STDINT) && HASH_NO_STDINT /* The user doesn't have , and must figure out their own way to provide definitions for uint8_t and uint32_t. */ #else #include /* uint8_t, uint32_t */ #endif /* 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(__MCST__) /* Elbrus C Compiler */ #define DECLTYPE(x) (__typeof(x)) #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 #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 #ifndef HASH_FUNCTION #define HASH_FUNCTION(keyptr,keylen,hashv) HASH_JEN(keyptr, keylen, hashv) #endif #ifndef HASH_KEYCMP #define HASH_KEYCMP(a,b,n) 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*)(void*)(((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_FUNCTION(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)) { \ 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 { \ (out) = NULL; \ if (head) { \ 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))) != 0) #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 = (const void*) (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 { \ const 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 #include /* fprintf, stderr */ #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 /* 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 * (archive link: https://archive.is/Ivcan ) */ #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 { \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ a -= b; a -= c; a ^= ( c >> 13 ); \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ b -= c; b -= a; b ^= ( a << 8 ); \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ c -= a; c -= b; c ^= ( b >> 13 ); \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ a -= b; a -= c; a ^= ( c >> 12 ); \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ b -= c; b -= a; b ^= ( a << 16 ); \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ c -= a; c -= b; c ^= ( b >> 5 ); \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ a -= b; a -= c; a ^= ( c >> 3 ); \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ b -= c; b -= a; b ^= ( a << 10 ); \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ c -= a; c -= b; c ^= ( b >> 15 ); \ } while (0) #define HASH_JEN(key,keylen,hashv) \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ 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) { \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + ( (unsigned)_hj_key[2] << 16 ) \ + ( (unsigned)_hj_key[3] << 24 ) ); \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ + ( (unsigned)_hj_key[6] << 16 ) \ + ( (unsigned)_hj_key[7] << 24 ) ); \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ + ( (unsigned)_hj_key[10] << 16 ) \ + ( (unsigned)_hj_key[11] << 24 ) ); \ \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ \ _hj_key += 12; \ _hj_k -= 12U; \ } \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ hashv += (unsigned)(keylen); \ switch ( _hj_k ) { \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ case 1: _hj_i += _hj_key[0]; /* FALLTHROUGH */ \ default: ; \ } \ /* coverity[overflow_const] - intentional wrapping in Jenkins hash */ \ 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; \ break; \ default: ; \ } \ \ /* 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) /* 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( \ sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U); \ if (!_he_new_buckets) { \ HASH_RECORD_OOM(oomed); \ } else { \ uthash_bzero(_he_new_buckets, \ sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U); \ (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*)(void*)(((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 */ const 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 */ ================================================ FILE: deps/utlist.h ================================================ /* Copyright (c) 2007-2025, Troy D. Hanson https://troydhanson.github.io/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.3.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(__MCST__) /* Elbrus C Compiler */ #define LDECLTYPE(x) __typeof(x) #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)) { \ assert((del)->next != NULL); \ (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 */ ================================================ FILE: doc/historical/old-regex.txt ================================================ This is the description of the regex used previously for topic/subscription matching. It is reproduced here for posterity. When a message is ready to be published at the broker, we need to check all of the subscriptions to see which ones the message should be sent to. This would be easy without wildcards, but requires a bit more work with them. The regex used to do the matching is of the form below for a topic of a/b/c: ^(?:(?:(a|\+)(?!$))(?:(?:/(?:(b|\+)(?!$)))(?:(?:/(?:c|\+))|/#)?|/#)?|#)$ In general, we're matching (a or +) followed by (the next levels of hierarchy or #). More specifically, all the levels of hierarchy must match, unless the last level is #. ^(?: # Must start at beginning of string (?: # (Level 1 hierarchy) (a|\+)(?!$) # Match a or +, but only if not EOL. ) # AND (?: (?: # (Level 2 hierarchy) / # Match / (?: # AND (b|\+)(?!$) # Match b or +, but only if not EOL. ) ) # AND (?: (?: # (Level 3 hierarchy) / # Match / (?: # AND c|\+ # Match c or +. ) ) | # OR (instead of level 3) /# # Match /# at level 3 )? # Level 3 exist 1/0 times | # OR (instead of level 2) /# # Match /# at level 2 )? # Level 2 exist 1/0 times | # OR (instead of level 1) # # Match # at level 1 )$ # Must end on EOL. ================================================ FILE: doc/historical/topic-match.kds ================================================ S'^(?:(?:(a|\\+)(?!$))(?:(?:/(?:(b|\\+)(?!$)))(?:(?:/(?:c|\\+))|/#)?|/#)?|#)$' p1 .S'a/#\na/b/c\na/b/+\na/b\na/+\n+\n+/b\n+/+/+\n+/b/c\na/c' p2 .I8 .S'' . ================================================ FILE: doc/joss-paper/codemeta.json ================================================ { "@context": "https://raw.githubusercontent.com/codemeta/codemeta/master/codemeta.jsonld", "@type": "Code", "author": [ { "@id": "http://orcid.org/0000-0001-9218-7797", "@type": "Person", "email": "", "name": "Roger A. Light", "affiliation": "" } ], "identifier": "", "codeRepository": "https://github.com/eclipse/mosquitto", "datePublished": "2017-05-17", "dateModified": "2017-05-17", "dateCreated": "2017-05-17", "description": "Broker and client implementation of the MQTT protocol.", "keywords": "IoT, MQTT, messaging, pubsub", "license": "EPL 2.0 / EDL 2.0", "title": "Mosquitto", "version": "v1.4.11" } ================================================ FILE: doc/joss-paper/paper.bib ================================================ @inproceedings{Schulz_2014, title = {Real-time animation of equipment in a remote laboratory}, doi = {10.1109/REV.2014.6784247}, booktitle = {2014 11th {International} {Conference} on {Remote} {Engineering} and {Virtual} {Instrumentation} ({REV})}, author = {Schulz, M. and Chen, F. and Payne, L.}, month = feb, year = {2014}, keywords = {Animation, cameras, client-server systems, computer aided instruction, computer animation, Computer architecture, data path, data streaming, Electron tubes, Engines, equipment animation, Hardware, message server, MIT iLabs shared architecture, MQTT, real-time animation, real-time systems, remote laboratory, servers, software architecture, student experiments, webcam}, pages = {172--176} } @inproceedings{Antonic_2015, title = {Comparison of the {CUPUS} middleware and {MQTT} protocol for smart city services}, doi = {10.1109/ConTEL.2015.7231225}, booktitle = {2015 13th {International} {Conference} on {Telecommunications} ({Con}TEL)}, author = {Antonić, A. and Marjanović, M. and Skočir, P. and Žarko, I. P.}, month = jul, year = {2015}, keywords = {cloud-based publish-subscribe middleware, cloud computing, CUPUS middleware, Engines, FP7 project OpenIoT platform, Internet of Things, IoT services, message passing, message queue telemetry transport protocol, message queuing solutions, middleware, Mobile communication, mobile computing, mobile devices, Mobile handsets, MQTT protocol, open-source cloud platform, Protocols, public domain software, sensors, smart cities, smart city services, telemetry, transport protocols, wearable sensors, wireless sensor networks, WSNs}, pages = {1--8} } @inproceedings{Thangavel_2014, title = {Performance evaluation of {MQTT} and {CoAP} via a common middleware}, doi = {10.1109/ISSNIP.2014.6827678}, booktitle = {2014 {IEEE} {Ninth} {International} {Conference} on {Intelligent} {Sensors}, {Sensor} {Networks} and {Information} {Processing} ({ISSNIP})}, author = {Thangavel, D. and Ma, X. and Valera, A. and Tan, H. X. and Tan, C. K. Y.}, month = apr, year = {2014}, keywords = {bandwidth consumption, CoAP, constrained application protocol, data transmission, delays, end-to-end delay, gateways, internetworking, Logic gates, message queue telemetry transport, middleware, MQTT, Packet loss, Protocols, Quality of service, queueing theory, sensor nodes, servers, wireless sensor networks}, pages = {1--6} } @inproceedings{Kang_2017, title = {Room {Temperature} {Control} and {Fire} {Alarm} \#x002F;{Suppression} {IoT} {Service} {Using} {MQTT} on {AWS}}, doi = {10.1109/PlatCon.2017.7883724}, abstract = {In this paper we build an MQTT(Message Queue Telemetry Transportation) broker on Amazon Web Service(AWS). The MQTT broker has been utilized as a platform to provide the Internet of Things(IoT) services which monitor and control room temperatures, and sense, alarm, and suppress fire. Arduino was used as the IoT end device connecting sensors and actuators to the platform via Wi-Fi channel. We created smart home scenario and designed IoT massages satisfying the scenario requirement. We also implemented the smart some system in hardware and software, and verified the system operation. We show that MQTT and AWS are good technical candidates for small IoT business applications.}, booktitle = {2017 {International} {Conference} on {Platform} {Technology} and {Service} ({PlatCon})}, author = {Kang, D. H. and Park, M. S. and Kim, H. S. and Kim, D. y and Kim, S. H. and Son, H. J. and Lee, S. G.}, month = feb, year = {2017}, note = {00000}, keywords = {Actuators, Amazon web service, AWS, electronic messaging, fire alarm-suppression IoT service, fires, Internet of Things, Internet of Things services, message queue telemetry transportation, MQTT broker, queueing theory, room temperature control, room temperature monitoring, sensors, small IoT business applications, smart home scenario, smart some system, telemetry, temperature 293 K to 298 K, Web services, Wi-Fi channel, wireless LAN}, pages = {1--5} } @inproceedings{Fremantle_2014, title = {Federated {Identity} and {Access} {Management} for the {Internet} of {Things}}, doi = {10.1109/SIoT.2014.8}, abstract = {We examine the use of Federated Identity and Access Management (FIAM) approaches for the Internet of Things (IoT). We look at specific challenges that devices, sensors and actuators have, and look for approaches to address them. OAuth is a widely deployed protocol – built on top of HTTP – for applying FIAM to Web systems. We explore the use of OAuth for IoT systems that instead use the lightweight MQTT 3.1 protocol. In order to evaluate this area, we built a prototype that uses OAuth 2.0 to enable access control to information distributed via MQTT. We evaluate the results of this prototyping activity, and assess the strengths and weaknesses of this approach, and the benefits of using the FIAM approaches with IoT and Machine to Machine (M2M) scenarios. Finally we outline areas for further research.}, booktitle = {2014 {International} {Workshop} on {Secure} {Internet} of {Things}}, author = {Fremantle, P. and Aziz, B. and Kopecký, J. and Scott, P.}, month = sep, year = {2014}, note = {00026}, keywords = {access control, Authentication, authorisation, Authorization, federated identity and access management, FIAM, Hip, Internet of Things, IoT, M2M scenarios, machine to machine scenarios, MQTT 3.1 protocol, OAuth 2.0, Protocols, servers}, pages = {10--17} } @article{Bellavista_2017, title = {The {PeRvasive} {Environment} {Sensing} and {Sharing} {Solution}}, volume = {9}, copyright = {http://creativecommons.org/licenses/by/3.0/}, url = {http://www.mdpi.com/2071-1050/9/4/585}, doi = {10.3390/su9040585}, abstract = {to stimulate better user behavior and improve environmental and economic sustainability, it is of paramount importance to make citizens effectively aware of the quality of the environment in which they live every day. in particular, we claim that users could significantly benefit from cost-effective efficient internet-of-things (iot) solutions that provide them with up-to-date live information about air pollution in the areas where they live, suitably adapted to different situations and with different levels of dynamically selected granularities (e.g., at home/district/city levels). our pervasive environment sensing and sharing (press) project has the ambition of increasing users’ awareness of the natural environment they live in, as a first step towards improved sustainability; the primary target is the efficient provisioning of real-time user-centric information about environmental conditions in the surroundings, and in particular about air pollution. to this purpose, we have designed, implemented, and thoroughly evaluated the press framework, which is capable of achieving good flexibility and scalability while integrating heterogeneous monitoring data, ranging from sensed air pollution to user-provided quality perceptions. among the elements of technical originality, press exploits extended kura iot gateways with novel congestion detection and recovery mechanisms that allow us to optimize bandwidth allocation between in-the-field press components and the cloud. the reported performance results show the feasibility of the proposed solution, by pointing out not only the scalability and efficiency of the adopted message-based solution that uses message queue telemetry transport (mqtt) and websockets, but also the capability of press to quickly identify and manage traffic congestions, thus, ensuring good quality levels to final users.}, language = {en}, number = {4}, urldate = {2017-05-17}, journal = {sustainability}, author = {Bellavista, Paolo and Giannelli, Carlo and Zamagna, Riccardo}, month = apr, year = {2017}, note = {00000}, keywords = {dynamic extensibility, environmental monitoring, heterogeneous monitoring data, mqtt, scalability, traffic congestion management, websockets}, pages = {585} } ================================================ FILE: doc/joss-paper/paper.md ================================================ --- title: 'Mosquitto: server and client implementation of the MQTT protocol' tags: - Internet of Things - MQTT - Pubsub - Messaging authors: - name: Roger A Light orcid: 0000-0001-9218-7797 date: 17 May 2017 bibliography: paper.bib --- # Summary Mosquitto provides standards compliant server and client implementations of the [MQTT](http://mqtt.org/) messaging protocol. MQTT uses a publish/subscribe model, has low network overhead and can be implemented on low power devices such microcontrollers that might be used in remote Internet of Things sensors. As such, Mosquitto is intended for use in all situations where there is a need for lightweight messaging, particularly on constrained devices with limited resources. The Mosquitto project is a member of the [Eclipse Foundation](http://eclipse.org/) There are three parts to the project. * The main `mosquitto` server * The `mosquitto_pub` and `mosquitto_sub` client utilities that are one method of communicating with an MQTT server * An MQTT client library written in C, with a C++ wrapper Mosquitto allows research directly related to the MQTT protocol itself, such as comparing the performance of MQTT and the Constrained Application Protocol (CoAP) [@Thangavel_2014] or investigating the use of OAuth in MQTT [@Fremantle_2014]. Mosquitto supports other research activities as a useful block for building larger systems and has been used to evaluate MQTT for use in Smart City Services [@Antonic_2015], and in the development of an environmental monitoring system [@Bellavista_2017]. Mosquitto has also been used to support research less directly as part of a scheme for remote control of an experiment [@Schulz_2014]. Outside of academia, Mosquitto is used in other open source projects such as the [openHAB](http://www.openhab.org/) home automation project and [OwnTracks](http://owntracks.org/), the personal location tracking project, and has been integrated into commercial products. # References ================================================ FILE: docker/1.6-openssl/Dockerfile ================================================ FROM alpine:3.23 ENV VERSION=1.6.15 \ DOWNLOAD_SHA256=5ff2271512f745bf1a451072cd3768a5daed71e90c5179fae12b049d6c02aa0f \ GPG_KEYS=A0D6EEA1DCAE49A635A3B2F0779B22DFB3E717B7 LABEL \ org.opencontainers.image.authors="Roger Light " \ org.opencontainers.image.title="eclipse-mosquitto" \ org.opencontainers.image.description="Eclipse Mosquitto MQTT Broker" \ org.opencontainers.image.url="https://mosquitto.org/" \ org.opencontainers.image.documentation="https://mosquitto.org/documentation/" \ org.opencontainers.image.source="https://github.com/eclipse-mosquitto/mosquitto" \ org.opencontainers.image.licenses="EPL-2.0 OR BSD-3-Clause" \ org.opencontainers.image.version=${VERSION} RUN set -x && \ apk --no-cache add --virtual build-deps \ build-base \ cmake \ gnupg \ libwebsockets-dev \ linux-headers \ openssl-dev \ util-linux-dev && \ wget https://mosquitto.org/files/source/mosquitto-${VERSION}.tar.gz -O /tmp/mosq.tar.gz && \ echo "$DOWNLOAD_SHA256 /tmp/mosq.tar.gz" | sha256sum -c - && \ wget https://mosquitto.org/files/source/mosquitto-${VERSION}.tar.gz.asc -O /tmp/mosq.tar.gz.asc && \ export GNUPGHOME="$(mktemp -d)" && \ found=''; \ for server in \ hkps://keys.openpgp.org \ hkp://keyserver.ubuntu.com:80 \ pgp.mit.edu \ ; do \ echo "Fetching GPG key $GPG_KEYS from $server"; \ gpg --keyserver "$server" --keyserver-options timeout=10 --recv-keys "$GPG_KEYS" && found=yes && break; \ done; \ test -z "$found" && echo >&2 "error: failed to fetch GPG key $GPG_KEYS" && exit 1; \ gpg --batch --verify /tmp/mosq.tar.gz.asc /tmp/mosq.tar.gz && \ gpgconf --kill all && \ rm -rf "$GNUPGHOME" /tmp/mosq.tar.gz.asc && \ mkdir -p /build/mosq && \ tar --strip=1 -xf /tmp/mosq.tar.gz -C /build/mosq && \ rm /tmp/mosq.tar.gz && \ make -C /build/mosq -j "$(nproc)" \ CFLAGS="-Wall -O2" \ WITH_ADNS=no \ WITH_DOCS=no \ WITH_SHARED_LIBRARIES=yes \ WITH_SRV=no \ WITH_STRIP=yes \ WITH_WEBSOCKETS=yes \ prefix=/usr \ binary && \ addgroup -S -g 1883 mosquitto 2>/dev/null && \ adduser -S -u 1883 -D -H -h /var/empty -s /sbin/nologin -G mosquitto -g mosquitto mosquitto 2>/dev/null && \ mkdir -p /mosquitto/config /mosquitto/data /mosquitto/log && \ install -d /usr/sbin/ && \ install -s -m755 /build/mosq/client/mosquitto_pub /usr/bin/mosquitto_pub && \ install -s -m755 /build/mosq/client/mosquitto_rr /usr/bin/mosquitto_rr && \ install -s -m755 /build/mosq/client/mosquitto_sub /usr/bin/mosquitto_sub && \ install -s -m644 /build/mosq/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1 && \ install -s -m755 /build/mosq/src/mosquitto /usr/sbin/mosquitto && \ install -s -m755 /build/mosq/src/mosquitto_passwd /usr/bin/mosquitto_passwd && \ install -m644 /build/mosq/mosquitto.conf /mosquitto/config/mosquitto.conf && \ install -Dm644 /build/mosq/epl-v10 /usr/share/licenses/mosquitto/epl-v10 && \ install -Dm644 /build/mosq/edl-v10 /usr/share/licenses/mosquitto/edl-v10 && \ chown -R mosquitto:mosquitto /mosquitto && \ apk --no-cache add \ ca-certificates \ libwebsockets \ tzdata && \ apk del build-deps && \ rm -rf /build VOLUME ["/mosquitto/data", "/mosquitto/log"] # Set up the entry point script and default command COPY docker-entrypoint.sh / EXPOSE 1883 ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["/usr/sbin/mosquitto", "-c", "/mosquitto/config/mosquitto.conf"] ================================================ FILE: docker/1.6-openssl/README.md ================================================ # Eclipse Mosquitto Docker Image Containers built with this Dockerfile build as source from published tarballs. ## Mount Points A docker mount point has been created in the image to be used for configuration. ``` /mosquitto/config ``` Two docker volumes have been created in the image to be used for persistent storage and logs. ``` /mosquitto/data /mosquitto/log ``` ## User/Group The image runs mosquitto under the mosquitto user and group, which are created with a uid and gid of 1883. ## Configuration When creating a container from the image, the default configuration values are used. To use a custom configuration file, mount a **local** configuration file to `/mosquitto/config/mosquitto.conf` ``` docker run -it -p 1883:1883 -v :/mosquitto/config/mosquitto.conf eclipse-mosquitto: ``` :boom: if the mosquitto configuration (mosquitto.conf) was modified to use non-default ports, the docker run command will need to be updated to expose the ports that have been configured, for example: ``` docker run -it -p 1883:1883 -p 8080:8080 -v :/mosquitto/config/mosquitto.conf eclipse-mosquitto: ``` Configuration can be changed to: * persist data to `/mosquitto/data` * log to `/mosquitto/log/mosquitto.log` i.e. add the following to `mosquitto.conf`: ``` persistence true persistence_location /mosquitto/data/ log_dest file /mosquitto/log/mosquitto.log ``` **Note**: For any volume used, the data will be persistent between containers. ================================================ FILE: docker/1.6-openssl/docker-entrypoint.sh ================================================ #!/bin/ash set -e # Set permissions user="$(id -u)" if [ "$user" = '0' ]; then [ -d "/mosquitto" ] && chown -R mosquitto:mosquitto /mosquitto || true fi exec "$@" ================================================ FILE: docker/2.0-openssl/Dockerfile ================================================ FROM alpine:3.23 ENV VERSION=2.0.22 \ DOWNLOAD_SHA256=2f752589ef7db40260b633fbdb536e9a04b446a315138d64a7ff3c14e2de6b68 \ GPG_KEYS=A0D6EEA1DCAE49A635A3B2F0779B22DFB3E717B7 LABEL \ org.opencontainers.image.authors="Roger Light " \ org.opencontainers.image.title="eclipse-mosquitto" \ org.opencontainers.image.description="Eclipse Mosquitto MQTT Broker" \ org.opencontainers.image.url="https://mosquitto.org/" \ org.opencontainers.image.documentation="https://mosquitto.org/documentation/" \ org.opencontainers.image.source="https://github.com/eclipse-mosquitto/mosquitto" \ org.opencontainers.image.licenses="EPL-2.0 OR BSD-3-Clause" \ org.opencontainers.image.version=${VERSION} RUN set -x && \ apk --no-cache add --virtual build-deps \ build-base \ cmake \ cjson-dev \ gnupg \ libwebsockets-dev \ linux-headers \ openssl-dev \ util-linux-dev && \ wget https://mosquitto.org/files/source/mosquitto-${VERSION}.tar.gz -O /tmp/mosq.tar.gz && \ echo "$DOWNLOAD_SHA256 /tmp/mosq.tar.gz" | sha256sum -c - && \ wget https://mosquitto.org/files/source/mosquitto-${VERSION}.tar.gz.asc -O /tmp/mosq.tar.gz.asc && \ export GNUPGHOME="$(mktemp -d)" && \ found=''; \ for server in \ hkps://keys.openpgp.org \ hkp://keyserver.ubuntu.com:80 \ pgp.mit.edu \ ; do \ echo "Fetching GPG key $GPG_KEYS from $server"; \ gpg --keyserver "$server" --keyserver-options timeout=10 --recv-keys "$GPG_KEYS" && found=yes && break; \ done; \ test -z "$found" && echo >&2 "error: failed to fetch GPG key $GPG_KEYS" && exit 1; \ gpg --batch --verify /tmp/mosq.tar.gz.asc /tmp/mosq.tar.gz && \ gpgconf --kill all && \ rm -rf "$GNUPGHOME" /tmp/mosq.tar.gz.asc && \ mkdir -p /build/mosq && \ tar --strip=1 -xf /tmp/mosq.tar.gz -C /build/mosq && \ rm /tmp/mosq.tar.gz && \ make -C /build/mosq -j "$(nproc)" \ CFLAGS="-Wall -O2 -I/build" \ WITH_ADNS=no \ WITH_DOCS=no \ WITH_SHARED_LIBRARIES=yes \ WITH_SRV=no \ WITH_STRIP=yes \ WITH_WEBSOCKETS=yes \ prefix=/usr \ binary && \ addgroup -S -g 1883 mosquitto 2>/dev/null && \ adduser -S -u 1883 -D -H -h /var/empty -s /sbin/nologin -G mosquitto -g mosquitto mosquitto 2>/dev/null && \ mkdir -p /mosquitto/config /mosquitto/data /mosquitto/log && \ install -d /usr/sbin/ && \ install -s -m755 /build/mosq/client/mosquitto_pub /usr/bin/mosquitto_pub && \ install -s -m755 /build/mosq/client/mosquitto_rr /usr/bin/mosquitto_rr && \ install -s -m755 /build/mosq/client/mosquitto_sub /usr/bin/mosquitto_sub && \ install -s -m644 /build/mosq/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1 && \ install -s -m755 /build/mosq/src/mosquitto /usr/sbin/mosquitto && \ install -s -m755 /build/mosq/apps/mosquitto_ctrl/mosquitto_ctrl /usr/bin/mosquitto_ctrl && \ install -s -m755 /build/mosq/apps/mosquitto_passwd/mosquitto_passwd /usr/bin/mosquitto_passwd && \ install -s -m755 /build/mosq/plugins/dynamic-security/mosquitto_dynamic_security.so /usr/lib/mosquitto_dynamic_security.so && \ install -m644 /build/mosq/mosquitto.conf /mosquitto/config/mosquitto.conf && \ install -Dm644 /build/mosq/epl-v20 /usr/share/licenses/mosquitto/epl-v20 && \ install -Dm644 /build/mosq/edl-v10 /usr/share/licenses/mosquitto/edl-v10 && \ chown -R mosquitto:mosquitto /mosquitto && \ apk --no-cache add \ ca-certificates \ cjson \ libwebsockets \ tzdata && \ apk del build-deps && \ rm -rf /build VOLUME ["/mosquitto/data", "/mosquitto/log"] # Set up the entry point script and default command COPY docker-entrypoint.sh mosquitto-no-auth.conf / EXPOSE 1883 ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["/usr/sbin/mosquitto", "-c", "/mosquitto/config/mosquitto.conf"] ================================================ FILE: docker/2.0-openssl/README.md ================================================ # Eclipse Mosquitto Docker Image Containers built with this Dockerfile build as source from published tarballs. ## Mount Points A docker mount point has been created in the image to be used for configuration. ``` /mosquitto/config ``` Two docker volumes have been created in the image to be used for persistent storage and logs. ``` /mosquitto/data /mosquitto/log ``` ## User/Group The image runs mosquitto under the mosquitto user and group, which are created with a uid and gid of 1883. ## Running without a configuration file Mosquitto 2.0 requires you to configure listeners and authentication before it will allow connections from anything other than the loopback interface. In the context of a container, this means you would normally need to provide a configuration file with your settings. If you wish to run mosquitto without any authentication, and without setting any other configuration options, you can do so by using a configuration provided in the container for this purpose: ``` docker run -it -p 1883:1883 eclipse-mosquitto: mosquitto -c /mosquitto-no-auth.conf ``` ## Configuration To use a custom configuration file, mount a **local** configuration file to `/mosquitto/config/mosquitto.conf` ``` docker run -it -p 1883:1883 -v :/mosquitto/config/mosquitto.conf eclipse-mosquitto: ``` Your configuration file must include a `listener`, and you must configure some form of authentication or allow unauthenticated access. If you do not do this, clients will be unable to connect. File based authentication and authorisation: ``` listener 1883 password_file /mosquitto/data/mosquitto.password_file acl_file /mosquitto/data/mosquitto.aclfile ``` Plugin based authentication and authorisation: ``` listener 1883 plugin /usr/lib/mosquitto_dynamic_security.so plugin_opt_config_file /mosquitto/data/mosquitto-dynsec.json ``` Unauthenticated access: ``` listener 1883 allow_anonymous true ``` :boom: if the mosquitto configuration (mosquitto.conf) was modified to use non-default ports, the docker run command will need to be updated to expose the ports that have been configured, for example: ``` docker run -it -p 1883:1883 -p 8080:8080 -v :/mosquitto/config/mosquitto.conf eclipse-mosquitto: ``` **Important**: The default configuration only listens on the loopback interface. This means that there is no way to access Mosquitto in the docker container without using a custom configuration containing at least a listener. You also need to make a decision to allow anonymous connections or to set up a different method of client authentication. i.e. to configure a Mosquitto docker container as if it was running locally, add the following to `mosquitto.conf`: ``` listener 1883 allow_anonymous true ``` Configuration can be changed to: * persist data to `/mosquitto/data` * log to `/mosquitto/log/mosquitto.log` i.e. add the following to `mosquitto.conf`: ``` persistence true persistence_location /mosquitto/data/ log_dest file /mosquitto/log/mosquitto.log ``` **Note**: For any volume used, the data will be persistent between containers. ================================================ FILE: docker/2.0-openssl/docker-entrypoint.sh ================================================ #!/bin/ash set -e # Set permissions user="$(id -u)" if [ "$user" = '0' ]; then [ -d "/mosquitto" ] && chown -R mosquitto:mosquitto /mosquitto || true fi exec "$@" ================================================ FILE: docker/2.0-openssl/mosquitto-no-auth.conf ================================================ # This is a Mosquitto configuration file that creates a listener on port 1883 # that allows unauthenticated access. listener 1883 allow_anonymous true ================================================ FILE: docker/2.1-alpine/Dockerfile ================================================ FROM alpine:3.23 ENV VERSION=2.1.2 \ DOWNLOAD_SHA256=fd905380691ac65ea5a93779e8214941829e3d6e038d5edff9eac5fd74cbed02 \ GPG_KEYS=A0D6EEA1DCAE49A635A3B2F0779B22DFB3E717B7 LABEL \ org.opencontainers.image.authors="Roger Light " \ org.opencontainers.image.title="eclipse-mosquitto" \ org.opencontainers.image.description="Eclipse Mosquitto MQTT Broker" \ org.opencontainers.image.url="https://mosquitto.org/" \ org.opencontainers.image.documentation="https://mosquitto.org/documentation/" \ org.opencontainers.image.source="https://github.com/eclipse-mosquitto/mosquitto" \ org.opencontainers.image.licenses="EPL-2.0 OR BSD-3-Clause" \ org.opencontainers.image.version=${VERSION} RUN set -x && \ apk --no-cache add --virtual build-deps \ argon2-dev \ build-base \ cjson-dev \ cmake \ gnupg \ libedit-dev \ libmicrohttpd-dev \ linux-headers \ openssl-dev \ sqlite-dev \ util-linux-dev && \ wget https://mosquitto.org/files/source/mosquitto-${VERSION}.tar.gz -O /tmp/mosq.tar.gz && \ echo "$DOWNLOAD_SHA256 /tmp/mosq.tar.gz" | sha256sum -c - && \ wget https://mosquitto.org/files/source/mosquitto-${VERSION}.tar.gz.asc -O /tmp/mosq.tar.gz.asc && \ export GNUPGHOME="$(mktemp -d)" && \ found=''; \ for server in \ hkps://keys.openpgp.org \ hkp://keyserver.ubuntu.com:80 \ pgp.mit.edu \ ; do \ echo "Fetching GPG key $GPG_KEYS from $server"; \ gpg --keyserver "$server" --keyserver-options timeout=10 --recv-keys "$GPG_KEYS" && found=yes && break; \ done; \ test -z "$found" && echo >&2 "error: failed to fetch GPG key $GPG_KEYS" && exit 1; \ gpg --batch --verify /tmp/mosq.tar.gz.asc /tmp/mosq.tar.gz && \ gpgconf --kill all && \ rm -rf "$GNUPGHOME" /tmp/mosq.tar.gz.asc && \ mkdir -p /build/mosq && \ tar --strip=1 -xf /tmp/mosq.tar.gz -C /build/mosq && \ rm /tmp/mosq.tar.gz && \ make -C /build/mosq -j "$(nproc)" \ CFLAGS="-Wall -O2 -I/build -DHTTP_API_DIR=\\\"/usr/share/mosquitto/dashboard\\\"" \ WITH_ADNS=no \ WITH_DOCS=no \ WITH_SHARED_LIBRARIES=yes \ WITH_SRV=no \ WITH_STRIP=yes \ WITH_WEBSOCKETS=yes \ prefix=/usr \ binary && \ addgroup -S -g 1883 mosquitto 2>/dev/null && \ adduser -S -u 1883 -D -H -h /var/empty -s /sbin/nologin -G mosquitto -g mosquitto mosquitto 2>/dev/null && \ mkdir -p /mosquitto/config /mosquitto/data /mosquitto/log && \ install -d /usr/sbin/ && \ install -s -m755 /build/mosq/client/mosquitto_pub /usr/bin/mosquitto_pub && \ install -s -m755 /build/mosq/client/mosquitto_rr /usr/bin/mosquitto_rr && \ install -s -m755 /build/mosq/client/mosquitto_sub /usr/bin/mosquitto_sub && \ install -s -m644 /build/mosq/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1 && \ install -s -m755 /build/mosq/src/mosquitto /usr/sbin/mosquitto && \ install -s -m755 /build/mosq/apps/mosquitto_ctrl/mosquitto_ctrl /usr/bin/mosquitto_ctrl && \ install -s -m755 /build/mosq/apps/mosquitto_passwd/mosquitto_passwd /usr/bin/mosquitto_passwd && \ install -s -m755 /build/mosq/apps/mosquitto_signal/mosquitto_signal /usr/bin/mosquitto_signal && \ install -s -m755 /build/mosq/plugins/acl-file/mosquitto_acl_file.so /usr/lib/mosquitto_acl_file.so && \ install -s -m755 /build/mosq/plugins/dynamic-security/mosquitto_dynamic_security.so /usr/lib/mosquitto_dynamic_security.so && \ install -s -m755 /build/mosq/plugins/password-file/mosquitto_password_file.so /usr/lib/mosquitto_password_file.so && \ install -s -m755 /build/mosq/plugins/persist-sqlite/mosquitto_persist_sqlite.so /usr/lib/mosquitto_persist_sqlite.so && \ install -s -m755 /build/mosq/plugins/sparkplug-aware/mosquitto_sparkplug_aware.so /usr/lib/mosquitto_sparkplug_aware.so && \ install -m644 /build/mosq/docker/2.1-alpine/mosquitto.conf /mosquitto/config/mosquitto.conf && \ install -m644 /build/mosq/docker/2.1-ubuntu/mosquitto.conf /mosquitto-no-auth.conf && \ install -d /usr/share/mosquitto && \ cp -r /build/mosq/dashboard/src /usr/share/mosquitto/dashboard && \ install -Dm644 /build/mosq/epl-v20 /usr/share/licenses/mosquitto/epl-v20 && \ install -Dm644 /build/mosq/edl-v10 /usr/share/licenses/mosquitto/edl-v10 && \ chown -R mosquitto:mosquitto /mosquitto && \ apk --no-cache add \ argon2-libs \ ca-certificates \ cjson \ libedit \ libmicrohttpd \ sqlite-libs \ tzdata && \ apk del build-deps && \ rm -rf /build VOLUME ["/mosquitto/data", "/mosquitto/log"] # Set up the entry point script and default command COPY docker-entrypoint.sh / EXPOSE 1883 ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["/usr/sbin/mosquitto", "-c", "/mosquitto/config/mosquitto.conf"] ================================================ FILE: docker/2.1-alpine/README.md ================================================ # Eclipse Mosquitto Docker Image Containers built with this Dockerfile build as source from published tarballs. ## Mount Points A docker mount point has been created in the image to be used for configuration. ``` /mosquitto/config ``` Two docker volumes have been created in the image to be used for persistent storage and logs. ``` /mosquitto/data /mosquitto/log ``` ## User/Group The image runs mosquitto under the mosquitto user and group, which are created with a uid and gid of 1883. ## Running without a configuration file Mosquitto 2.0 and up requires you to configure listeners and authentication before it will allow connections from anything other than the loopback interface. In the context of a container, this means you would normally need to provide a configuration file with your settings. However, this container provides a default configuration which listens on port 1883 for unauthenticated access, and port 9883 for the local http dashboard. If you wish to run mosquitto without any authentication, and without setting any other configuration options, you can run without a configuration by binding the appropriate network ports: ``` docker run -it -p 1883:1883 -p localhost:9883:9883 eclipse-mosquitto: ``` ## Configuration To use a custom configuration file, create a **local** config directory with a mosquitto.conf inside, then mount this directory to `/mosquitto/config` ``` docker run -it -p 1883:1883 -v :/mosquitto/config eclipse-mosquitto: ``` Your configuration file must include a `listener`, and you must configure some form of authentication or allow unauthenticated access. If you do not do this, clients will be unable to connect. File based authentication and authorisation: ``` listener 1883 plugin /usr/lib/mosquitto_password_file.so plugin_opt_password_file /mosquitto/data/mosquitto.password_file plugin /usr/lib/mosquitto_acl_file.so plugin_opt_acl_file /mosquitto/data/mosquitto.aclfile ``` Plugin based authentication and authorisation: ``` listener 1883 plugin /usr/lib/mosquitto_dynamic_security.so plugin_opt_config_file /mosquitto/data/mosquitto-dynsec.json ``` Unauthenticated access: ``` listener 1883 allow_anonymous true ``` :boom: if the mosquitto configuration (mosquitto.conf) was modified to use non-default ports, the docker run command will need to be updated to expose the ports that have been configured, for example: ``` docker run -it -p 1883:1883 -p 8080:8080 -v :/mosquitto/config eclipse-mosquitto: ``` Configuration can be changed to: * persist data to `/mosquitto/data` * log to `/mosquitto/log/mosquitto.log` i.e. add the following to `mosquitto.conf`: ``` persistence_location /mosquitto/data/ plugin /usr/lib/mosquitto_persist_sqlite.so log_dest file /mosquitto/log/mosquitto.log ``` **Note**: For any volume used, the data will be persistent between containers. ================================================ FILE: docker/2.1-alpine/docker-entrypoint.sh ================================================ #!/bin/ash set -e # Set permissions user="$(id -u)" if [ "$PUID" = "" ]; then PUID="1883" fi if [ "$PGID" = "" ]; then PGID="1883" fi if [ "$user" = '0' ]; then [ -d "/mosquitto/data" ] && chown -R ${PUID}:${PGID} /mosquitto/data || true fi exec "$@" ================================================ FILE: docker/2.1-alpine/mosquitto.conf ================================================ # This is a Mosquitto configuration file that creates a listener on port 1883 # that allows unauthenticated access. listener 1883 allow_anonymous true listener 9883 protocol http_api http_dir /usr/share/mosquitto/dashboard ================================================ FILE: docker/2.1-ubuntu/Dockerfile ================================================ FROM ubuntu:24.04 ENV VERSION=2.1.2 \ DOWNLOAD_SHA256=fd905380691ac65ea5a93779e8214941829e3d6e038d5edff9eac5fd74cbed02 \ GPG_KEYS=A0D6EEA1DCAE49A635A3B2F0779B22DFB3E717B7 LABEL \ org.opencontainers.image.authors="Roger Light " \ org.opencontainers.image.title="eclipse-mosquitto" \ org.opencontainers.image.description="Eclipse Mosquitto MQTT Broker" \ org.opencontainers.image.url="https://mosquitto.org/" \ org.opencontainers.image.documentation="https://mosquitto.org/documentation/" \ org.opencontainers.image.source="https://github.com/eclipse-mosquitto/mosquitto" \ org.opencontainers.image.licenses="EPL-2.0 OR BSD-3-Clause" \ org.opencontainers.image.version=${VERSION} RUN set -x && \ apt-get update && \ apt-get install -y \ build-essential \ cmake \ gnupg \ libargon2-dev \ libcjson-dev \ libedit-dev \ libmicrohttpd-dev \ libssl-dev \ libsqlite3-dev \ wget && \ wget https://mosquitto.org/files/source/mosquitto-${VERSION}.tar.gz -O /tmp/mosq.tar.gz && \ echo "$DOWNLOAD_SHA256 /tmp/mosq.tar.gz" | sha256sum -c - && \ wget https://mosquitto.org/files/source/mosquitto-${VERSION}.tar.gz.asc -O /tmp/mosq.tar.gz.asc && \ export GNUPGHOME="$(mktemp -d)" && \ found=''; \ for server in \ hkps://keys.openpgp.org \ hkp://keyserver.ubuntu.com:80 \ pgp.mit.edu \ ; do \ echo "Fetching GPG key $GPG_KEYS from $server"; \ gpg --keyserver "$server" --keyserver-options timeout=10 --recv-keys "$GPG_KEYS" && found=yes && break; \ done; \ test -z "$found" && echo >&2 "error: failed to fetch GPG key $GPG_KEYS" && exit 1; \ gpg --batch --verify /tmp/mosq.tar.gz.asc /tmp/mosq.tar.gz && \ gpgconf --kill all && \ rm -rf "$GNUPGHOME" /tmp/mosq.tar.gz.asc && \ mkdir -p /build/mosq && \ tar --strip=1 -xf /tmp/mosq.tar.gz -C /build/mosq && \ rm /tmp/mosq.tar.gz && \ make -C /build/mosq -j "$(nproc)" \ CFLAGS="-Wall -O2 -I/build -DHTTP_API_DIR=\\\"/usr/share/mosquitto/dashboard\\\"" \ WITH_ADNS=no \ WITH_DOCS=no \ WITH_SHARED_LIBRARIES=yes \ WITH_SRV=no \ WITH_STRIP=yes \ WITH_WEBSOCKETS=yes \ prefix=/usr \ binary && \ addgroup --system --quiet --gid 1883 mosquitto 2>/dev/null && \ adduser --system --quiet --no-create-home --ingroup mosquitto --uid 1883 --home /var/empty --shell /usr/sbin/nologin mosquitto 2>/dev/null && \ mkdir -p /mosquitto/config /mosquitto/data /mosquitto/log && \ install -d /usr/sbin/ && \ install -s -m755 /build/mosq/client/mosquitto_pub /usr/bin/mosquitto_pub && \ install -s -m755 /build/mosq/client/mosquitto_rr /usr/bin/mosquitto_rr && \ install -s -m755 /build/mosq/client/mosquitto_sub /usr/bin/mosquitto_sub && \ install -s -m644 /build/mosq/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1 && \ install -s -m755 /build/mosq/src/mosquitto /usr/sbin/mosquitto && \ install -s -m755 /build/mosq/apps/mosquitto_ctrl/mosquitto_ctrl /usr/bin/mosquitto_ctrl && \ install -s -m755 /build/mosq/apps/mosquitto_passwd/mosquitto_passwd /usr/bin/mosquitto_passwd && \ install -s -m755 /build/mosq/apps/mosquitto_signal/mosquitto_signal /usr/bin/mosquitto_signal && \ install -s -m755 /build/mosq/plugins/acl-file/mosquitto_acl_file.so /usr/lib/mosquitto_acl_file.so && \ install -s -m755 /build/mosq/plugins/dynamic-security/mosquitto_dynamic_security.so /usr/lib/mosquitto_dynamic_security.so && \ install -s -m755 /build/mosq/plugins/password-file/mosquitto_password_file.so /usr/lib/mosquitto_password_file.so && \ install -s -m755 /build/mosq/plugins/persist-sqlite/mosquitto_persist_sqlite.so /usr/lib/mosquitto_persist_sqlite.so && \ install -s -m755 /build/mosq/plugins/sparkplug-aware/mosquitto_sparkplug_aware.so /usr/lib/mosquitto_sparkplug_aware.so && \ install -m644 /build/mosq/docker/2.1-ubuntu/mosquitto.conf /mosquitto/config/mosquitto.conf && \ install -m644 /build/mosq/docker/2.1-ubuntu/mosquitto.conf /mosquitto-no-auth.conf && \ install -d /usr/share/mosquitto && \ cp -r /build/mosq/dashboard/src /usr/share/mosquitto/dashboard && \ install -Dm644 /build/mosq/epl-v20 /usr/share/licenses/mosquitto/epl-v20 && \ install -Dm644 /build/mosq/edl-v10 /usr/share/licenses/mosquitto/edl-v10 && \ chown -R mosquitto:mosquitto /mosquitto && \ apt-get install \ ca-certificates \ libargon2-1 \ libcjson1 \ libedit2 \ libmicrohttpd12 \ libsqlite3-0 && \ apt-get clean && \ apt-get remove --purge --auto-remove -y build-essential cmake gnupg && \ rm -rf /var/lib/apt/lists/* && \ rm -rf /build VOLUME ["/mosquitto/data", "/mosquitto/log"] # Set up the entry point script and default command COPY docker-entrypoint.sh / EXPOSE 1883 ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["/usr/sbin/mosquitto", "-c", "/mosquitto/config/mosquitto.conf"] ================================================ FILE: docker/2.1-ubuntu/README.md ================================================ # Eclipse Mosquitto Docker Image Containers built with this Dockerfile build as source from published tarballs. ## Mount Points A docker mount point has been created in the image to be used for configuration. ``` /mosquitto/config ``` Two docker volumes have been created in the image to be used for persistent storage and logs. ``` /mosquitto/data /mosquitto/log ``` ## User/Group The image runs mosquitto under the mosquitto user and group, which are created with a uid and gid of 1883. ## Running without a configuration file Mosquitto 2.0 and up requires you to configure listeners and authentication before it will allow connections from anything other than the loopback interface. In the context of a container, this means you would normally need to provide a configuration file with your settings. However, this container provides a default configuration which listens on port 1883 for unauthenticated access, and port 9883 for the local http dashboard. If you wish to run mosquitto without any authentication, and without setting any other configuration options, you can run without a configuration by binding the appropriate network ports: ``` docker run -it -p 1883:1883 -p localhost:9883:9883 eclipse-mosquitto: ``` ## Configuration To use a custom configuration file, create a **local** config directory with a mosquitto.conf inside, then mount this directory to `/mosquitto/config` ``` docker run -it -p 1883:1883 -v :/mosquitto/config eclipse-mosquitto: ``` Your configuration file must include a `listener`, and you must configure some form of authentication or allow unauthenticated access. If you do not do this, clients will be unable to connect. File based authentication and authorisation: ``` listener 1883 plugin /usr/lib/mosquitto_password_file.so plugin_opt_password_file /mosquitto/data/mosquitto.password_file plugin /usr/lib/mosquitto_acl_file.so plugin_opt_acl_file /mosquitto/data/mosquitto.aclfile ``` Plugin based authentication and authorisation: ``` listener 1883 plugin /usr/lib/mosquitto_dynamic_security.so plugin_opt_config_file /mosquitto/data/mosquitto-dynsec.json ``` Unauthenticated access: ``` listener 1883 allow_anonymous true ``` :boom: if the mosquitto configuration (mosquitto.conf) was modified to use non-default ports, the docker run command will need to be updated to expose the ports that have been configured, for example: ``` docker run -it -p 1883:1883 -p 8080:8080 -v :/mosquitto/config eclipse-mosquitto: ``` Configuration can be changed to: * persist data to `/mosquitto/data` * log to `/mosquitto/log/mosquitto.log` i.e. add the following to `mosquitto.conf`: ``` persistence_location /mosquitto/data/ plugin /usr/lib/mosquitto_persist_sqlite.so log_dest file /mosquitto/log/mosquitto.log ``` **Note**: For any volume used, the data will be persistent between containers. ================================================ FILE: docker/2.1-ubuntu/docker-entrypoint.sh ================================================ #!/bin/sh set -e # Set permissions user="$(id -u)" if [ "$PUID" = "" ]; then PUID="1883" fi if [ "$PGID" = "" ]; then PGID="1883" fi if [ "$user" = '0' ]; then [ -d "/mosquitto/data" ] && chown -R ${PUID}:${PGID} /mosquitto/data || true fi exec "$@" ================================================ FILE: docker/2.1-ubuntu/mosquitto.conf ================================================ # This is a Mosquitto configuration file that creates a listener on port 1883 # that allows unauthenticated access. listener 1883 allow_anonymous true listener 9883 protocol http_api http_dir /usr/share/mosquitto/dashboard ================================================ FILE: docker/README.md ================================================ # Docker Images This directory contains Docker files for Mosquitto. The `2.0` directory contains the latest version of Mosquitto for that series, it uses libressl. The `2.0-openssl` directory is identical except that it uses openssl instead of libressl, and enables TLS-PSK and TLS v1.3 cipher support. The `1.6` directory contains the version of Mosquitto based on the 1.6 branch. It uses libressl. The `1.6-openssl` directory is identical except that it uses openssl instead of libressl, and enables TLS-PSK support. The `1.5` directory contains the version of Mosquitto based on the 1.5 branch. It uses libressl. The `1.5-openssl` directory is identical except that it uses openssl instead of libressl, and enables TLS-PSK support. The `generic` directory contains a generic Dockerfile that can be used to build arbitrary versions of Mosquitto based on the released tarballs as follows: ``` cd generic docker build -t eclipse-mosquitto:1.5.1 --build-arg VERSION="1.5.1" . docker run --rm -it eclipse-mosquitto:1.5.1 ``` The `local` directory can be used to build an image based on the files in the working directory by using `make localdocker` from the root of the repository. ================================================ FILE: docker/generic/Dockerfile ================================================ FROM alpine:3.23 LABEL maintainer="Roger Light " \ description="Eclipse Mosquitto MQTT Broker" ARG VERSION RUN test -n "${VERSION}" ENV \ GPG_KEYS=A0D6EEA1DCAE49A635A3B2F0779B22DFB3E717B7 \ LWS_VERSION=4.2.1 \ LWS_SHA256=842da21f73ccba2be59e680de10a8cce7928313048750eb6ad73b6fa50763c51 \ CJSON_VERSION=1.7.14 \ CJSON_SHA256=fb50a663eefdc76bafa80c82bc045af13b1363e8f45cec8b442007aef6a41343 LABEL \ org.opencontainers.image.authors="Roger Light " \ org.opencontainers.image.title="eclipse-mosquitto" \ org.opencontainers.image.description="Eclipse Mosquitto MQTT Broker" \ org.opencontainers.image.url="https://mosquitto.org/" \ org.opencontainers.image.documentation="https://mosquitto.org/documentation/" \ org.opencontainers.image.source="https://github.com/eclipse-mosquitto/mosquitto" \ org.opencontainers.image.licenses="EPL-2.0 OR BSD-3-Clause" \ org.opencontainers.image.version=${VERSION} RUN set -x && \ apk --no-cache add --virtual build-deps \ build-base \ cmake \ gnupg \ linux-headers \ openssl-dev \ util-linux-dev && \ wget https://github.com/warmcat/libwebsockets/archive/v${LWS_VERSION}.tar.gz -O /tmp/lws.tar.gz && \ echo "$LWS_SHA256 /tmp/lws.tar.gz" | sha256sum -c - && \ mkdir -p /build/lws && \ tar --strip=1 -xf /tmp/lws.tar.gz -C /build/lws && \ rm /tmp/lws.tar.gz && \ cd /build/lws && \ cmake . \ -DCMAKE_BUILD_TYPE=MinSizeRel \ -DCMAKE_INSTALL_PREFIX=/usr \ -DDISABLE_WERROR=ON \ -DLWS_IPV6=ON \ -DLWS_WITHOUT_BUILTIN_GETIFADDRS=ON \ -DLWS_WITHOUT_CLIENT=ON \ -DLWS_WITHOUT_EXTENSIONS=ON \ -DLWS_WITHOUT_TESTAPPS=ON \ -DLWS_WITH_EXTERNAL_POLL=ON \ -DLWS_WITH_HTTP2=OFF \ -DLWS_WITH_SHARED=OFF \ -DLWS_WITH_ZIP_FOPS=OFF \ -DLWS_WITH_ZLIB=OFF && \ make -j "$(nproc)" && \ rm -rf /root/.cmake && \ wget https://github.com/DaveGamble/cJSON/archive/v${CJSON_VERSION}.tar.gz -O /tmp/cjson.tar.gz && \ echo "$CJSON_SHA256 /tmp/cjson.tar.gz" | sha256sum -c - && \ mkdir -p /build/cjson && \ tar --strip=1 -xf /tmp/cjson.tar.gz -C /build/cjson && \ rm /tmp/cjson.tar.gz && \ cd /build/cjson && \ cmake . \ -DCMAKE_BUILD_TYPE=MinSizeRel \ -DBUILD_SHARED_AND_STATIC_LIBS=OFF \ -DBUILD_SHARED_LIBS=OFF \ -DCJSON_BUILD_SHARED_LIBS=OFF \ -DCJSON_OVERRIDE_BUILD_SHARED_LIBS=OFF \ -DCMAKE_INSTALL_PREFIX=/usr && \ make -j "$(nproc)" && \ rm -rf /root/.cmake && \ wget https://mosquitto.org/files/source/mosquitto-${VERSION}.tar.gz -O /tmp/mosq.tar.gz && \ wget https://mosquitto.org/files/source/mosquitto-${VERSION}.tar.gz.asc -O /tmp/mosq.tar.gz.asc && \ export GNUPGHOME="$(mktemp -d)" && \ found=''; \ for server in \ hkps://keys.openpgp.org \ hkp://keyserver.ubuntu.com:80 \ pgp.mit.edu \ ; do \ echo "Fetching GPG key $GPG_KEYS from $server"; \ gpg --keyserver "$server" --keyserver-options timeout=10 --recv-keys "$GPG_KEYS" && found=yes && break; \ done; \ test -z "$found" && echo >&2 "error: failed to fetch GPG key $GPG_KEYS" && exit 1; \ gpg --batch --verify /tmp/mosq.tar.gz.asc /tmp/mosq.tar.gz && \ gpgconf --kill all && \ rm -rf "$GNUPGHOME" /tmp/mosq.tar.gz.asc && \ mkdir -p /build/mosq && \ tar --strip=1 -xf /tmp/mosq.tar.gz -C /build/mosq && \ rm /tmp/mosq.tar.gz && \ make -C /build/mosq -j "$(nproc)" \ CFLAGS="-Wall -O2 -I/build/lws/include -I/build" \ LDFLAGS="-L/build/lws/lib -L/build/cjson" \ WITH_ADNS=no \ WITH_DOCS=no \ WITH_SHARED_LIBRARIES=yes \ WITH_SRV=no \ WITH_STRIP=yes \ WITH_TLS_PSK=no \ WITH_WEBSOCKETS=yes \ prefix=/usr \ binary && \ addgroup -S -g 1883 mosquitto 2>/dev/null && \ adduser -S -u 1883 -D -H -h /var/empty -s /sbin/nologin -G mosquitto -g mosquitto mosquitto 2>/dev/null && \ mkdir -p /mosquitto/config /mosquitto/data /mosquitto/log && \ install -d /usr/sbin/ && \ install -s -m755 /build/mosq/client/mosquitto_pub /usr/bin/mosquitto_pub && \ install -s -m755 /build/mosq/client/mosquitto_rr /usr/bin/mosquitto_rr && \ install -s -m755 /build/mosq/client/mosquitto_sub /usr/bin/mosquitto_sub && \ install -s -m644 /build/mosq/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1 && \ install -s -m755 /build/mosq/src/mosquitto /usr/sbin/mosquitto && \ install -s -m755 /build/mosq/apps/mosquitto_ctrl/mosquitto_ctrl /usr/bin/mosquitto_ctrl && \ install -s -m755 /build/mosq/apps/mosquitto_passwd/mosquitto_passwd /usr/bin/mosquitto_passwd && \ install -s -m755 /build/mosq/plugins/dynamic-security/mosquitto_dynamic_security.so /usr/lib/mosquitto_dynamic_security.so && \ install -m644 /build/mosq/mosquitto.conf /mosquitto/config/mosquitto.conf && \ install -Dm644 /build/cjson/LICENSE /usr/share/licenses/cJSON/LICENSE && \ install -Dm644 /build/lws/LICENSE /usr/share/licenses/libwebsockets/LICENSE && \ install -Dm644 /build/mosq/epl-v20 /usr/share/licenses/mosquitto/epl-v20 && \ install -Dm644 /build/mosq/edl-v10 /usr/share/licenses/mosquitto/edl-v10 && \ chown -R mosquitto:mosquitto /mosquitto && \ apk --no-cache add \ ca-certificates \ tzdata && \ apk del build-deps && \ rm -rf /build VOLUME ["/mosquitto/data", "/mosquitto/log"] # Set up the entry point script and default command COPY docker-entrypoint.sh mosquitto-no-auth.conf / EXPOSE 1883 ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["/usr/sbin/mosquitto", "-c", "/mosquitto/config/mosquitto.conf"] ================================================ FILE: docker/generic/README.md ================================================ # Eclipse Mosquitto Docker Image Containers built with this Dockerfile build as source from published tarballs. ## Mount Points A docker mount point has been created in the image to be used for configuration. ``` /mosquitto/config ``` Two docker volumes have been created in the image to be used for persistent storage and logs. ``` /mosquitto/data /mosquitto/log ``` ## User/Group The image runs mosquitto under the mosquitto user and group, which are created with a uid and gid of 1883. ## Running without a configuration file Mosquitto 2.0 requires you to configure listeners and authentication before it will allow connections from anything other than the loopback interface. In the context of a container, this means you would normally need to provide a configuration file with your settings. If you wish to run mosquitto without any authentication, and without setting any other configuration options, you can do so by using a configuration provided in the container for this purpose: ``` docker run -it -p 1883:1883 eclipse-mosquitto: mosquitto -c /mosquitto-no-auth.conf ``` ## Configuration When creating a container from the image, the default configuration values are used. To use a custom configuration file, mount a **local** configuration file to `/mosquitto/config/mosquitto.conf` ``` docker run -it -p 1883:1883 -v :/mosquitto/config/mosquitto.conf eclipse-mosquitto: ``` Configuration can be changed to: * persist data to `/mosquitto/data` * log to `/mosquitto/log/mosquitto.log` i.e. add the following to `mosquitto.conf`: ``` persistence true persistence_location /mosquitto/data/ log_dest file /mosquitto/log/mosquitto.log ``` **Note**: For any volume used, the data will be persistent between containers. ## Build Build and tag the docker image for a specific version: ``` docker build -t eclipse-mosquitto: --build-arg VERSION="" . ``` ## Run Run a container using the new image: ``` docker run -it -p 1883:1883 -v :/mosquitto/config/mosquitto.conf -v /mosquitto/data -v /mosquitto/log eclipse-mosquitto: ``` :boom: if the mosquitto configuration (mosquitto.conf) was modified to use non-default ports, the docker run command will need to be updated to expose the ports that have been configured. **Important**: The default configuration only listens on the loopback interface. This means that there is no way to access Mosquitto in the docker container without using a custom configuration containing at least a listener. You also need to make a decision to allow anonymous connections or to set up a different method of client authentication. i.e. to configure a Mosquitto docker container as if it was running locally, add the following to `mosquitto.conf`: ``` listener 1883 allow_anonymous true ``` ================================================ FILE: docker/generic/docker-entrypoint.sh ================================================ #!/bin/ash set -e # Set permissions user="$(id -u)" if [ "$user" = '0' ]; then [ -d "/mosquitto" ] && chown -R mosquitto:mosquitto /mosquitto || true fi exec "$@" ================================================ FILE: docker/generic/mosquitto-no-auth.conf ================================================ # This is a Mosquitto configuration file that creates a listener on port 1883 # that allows unauthenticated access. listener 1883 allow_anonymous true ================================================ FILE: docker/local/Dockerfile ================================================ FROM alpine:3.23 ARG VERSION LABEL \ org.opencontainers.image.authors="Roger Light " \ org.opencontainers.image.title="eclipse-mosquitto" \ org.opencontainers.image.description="Eclipse Mosquitto MQTT Broker" \ org.opencontainers.image.url="https://mosquitto.org/" \ org.opencontainers.image.documentation="https://mosquitto.org/documentation/" \ org.opencontainers.image.source="https://github.com/eclipse-mosquitto/mosquitto" \ org.opencontainers.image.licenses="EPL-2.0 OR BSD-3-Clause" \ org.opencontainers.image.version=${VERSION} COPY mosq.tar.gz /tmp RUN set -x && \ apk --no-cache add --virtual build-deps \ argon2-dev \ build-base \ cjson-dev \ cmake \ gnupg \ libedit-dev \ libmicrohttpd-dev \ linux-headers \ openssl-dev \ sqlite-dev \ util-linux-dev && \ mkdir -p /build/mosq && \ tar --strip=1 -xf /tmp/mosq.tar.gz -C /build/mosq && \ rm /tmp/mosq.tar.gz && \ make -C /build/mosq -j "$(nproc)" \ CFLAGS="-Wall -O2 -I/build -DHTTP_API_DIR=\\\"/usr/share/mosquitto/dashboard\\\"" \ WITH_ADNS=no \ WITH_DOCS=no \ WITH_SHARED_LIBRARIES=yes \ WITH_SRV=no \ WITH_STRIP=yes \ WITH_WEBSOCKETS=yes \ prefix=/usr \ binary && \ addgroup -S -g 1883 mosquitto 2>/dev/null && \ adduser -S -u 1883 -D -H -h /var/empty -s /sbin/nologin -G mosquitto -g mosquitto mosquitto 2>/dev/null && \ mkdir -p /mosquitto/config /mosquitto/data /mosquitto/log && \ install -d /usr/sbin/ && \ install -s -m755 /build/mosq/client/mosquitto_pub /usr/bin/mosquitto_pub && \ install -s -m755 /build/mosq/client/mosquitto_rr /usr/bin/mosquitto_rr && \ install -s -m755 /build/mosq/client/mosquitto_sub /usr/bin/mosquitto_sub && \ install -s -m644 /build/mosq/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1 && \ install -s -m755 /build/mosq/src/mosquitto /usr/sbin/mosquitto && \ install -s -m755 /build/mosq/apps/mosquitto_ctrl/mosquitto_ctrl /usr/bin/mosquitto_ctrl && \ install -s -m755 /build/mosq/apps/mosquitto_passwd/mosquitto_passwd /usr/bin/mosquitto_passwd && \ install -s -m755 /build/mosq/apps/mosquitto_signal/mosquitto_signal /usr/bin/mosquitto_signal && \ install -s -m755 /build/mosq/plugins/acl-file/mosquitto_acl_file.so /usr/lib/mosquitto_acl_file.so && \ install -s -m755 /build/mosq/plugins/dynamic-security/mosquitto_dynamic_security.so /usr/lib/mosquitto_dynamic_security.so && \ install -s -m755 /build/mosq/plugins/password-file/mosquitto_password_file.so /usr/lib/mosquitto_password_file.so && \ install -s -m755 /build/mosq/plugins/persist-sqlite/mosquitto_persist_sqlite.so /usr/lib/mosquitto_persist_sqlite.so && \ install -s -m755 /build/mosq/plugins/sparkplug-aware/mosquitto_sparkplug_aware.so /usr/lib/mosquitto_sparkplug_aware.so && \ install -m644 /build/mosq/docker/local/mosquitto.conf /mosquitto/config/mosquitto.conf && \ install -d /usr/share/mosquitto && \ cp -r /build/mosq/dashboard/src /usr/share/mosquitto/dashboard && \ install -Dm644 /build/mosq/epl-v20 /usr/share/licenses/mosquitto/epl-v20 && \ install -Dm644 /build/mosq/edl-v10 /usr/share/licenses/mosquitto/edl-v10 && \ chown -R mosquitto:mosquitto /mosquitto && \ apk --no-cache add \ argon2-libs \ ca-certificates \ cjson \ libedit \ libmicrohttpd \ sqlite-libs \ tzdata && \ apk del build-deps && \ rm -rf /build VOLUME ["/mosquitto/data", "/mosquitto/log"] # Set up the entry point script and default command COPY docker-entrypoint.sh / EXPOSE 1883 ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["/usr/sbin/mosquitto", "-c", "/mosquitto/config/mosquitto.conf"] ================================================ FILE: docker/local/README.md ================================================ # Eclipse Mosquitto Docker Image Containers built with this Dockerfile build from a source tarball "mosq.tar.gz" placed in the local directory. Running `make localdocker` from the root of the repository will generate the source tar and build the docker image. ## Mount Points A docker mount point has been created in the image to be used for configuration. ``` /mosquitto/config ``` Two docker volumes have been created in the image to be used for persistent storage and logs. ``` /mosquitto/data /mosquitto/log ``` ## User/Group The image runs mosquitto under the mosquitto user and group, which are created with a uid and gid of 1883. ## Configuration When creating a container from the image, the default configuration values are used. To use a custom configuration file, mount a **local** configuration file to `/mosquitto/config/mosquitto.conf` ``` docker run -it -p 1883:1883 -v :/mosquitto/config/mosquitto.conf eclipse-mosquitto: ``` :boom: if the mosquitto configuration (mosquitto.conf) was modified to use non-default ports, the docker run command will need to be updated to expose the ports that have been configured, for example if you use port 8080 for websockets as well as port 1883: ``` docker run -it -p 1883:1883 -p 8080:8080 -v :/mosquitto/config/mosquitto.conf eclipse-mosquitto: ``` Configuration can be changed to: * persist data to `/mosquitto/data` * log to `/mosquitto/log/mosquitto.log` i.e. add the following to `mosquitto.conf`: ``` persistence true persistence_location /mosquitto/data/ log_dest file /mosquitto/log/mosquitto.log ``` **Note**: For any volume used, the data will be persistent between containers. ================================================ FILE: docker/local/docker-entrypoint.sh ================================================ #!/bin/ash set -e # Set permissions user="$(id -u)" if [ "$PUID" = "" ]; then PUID="mosquitto" fi if [ "$PGID" = "" ]; then PGID="mosquitto" fi if [ "$user" = '0' ]; then [ -d "/mosquitto/data" ] && chown -R ${PUID}:${PGID} /mosquitto/data || true fi exec "$@" ================================================ FILE: docker/local/mosquitto.conf ================================================ # This is a Mosquitto configuration file that creates a listener on port 1883 # that allows unauthenticated access. listener 1883 allow_anonymous true listener 9883 protocol http_api http_dir /usr/share/mosquitto/dashboard ================================================ FILE: edl-v10 ================================================ Eclipse 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. ================================================ FILE: epl-v20 ================================================ Eclipse 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. ================================================ FILE: examples/mysql_log/Makefile ================================================ R=../.. LOCAL_CFLAGS=-Wall -ggdb LOCAL_LDFLAGS=${LIBMOSQ} -lmysqlclient .PHONY: all clean all : mosquitto_mysql_log mosquitto_mysql_log : mysql_log.o ${CC} $^ -o $@ ${LOCAL_LDFLAGS} mysql_log.o : mysql_log.c ${CC} -c $^ -o $@ ${LOCAL_CFLAGS} -I${R}/lib clean : -rm -f *.o mosquitto_mysql_log ================================================ FILE: examples/mysql_log/mysql_log.c ================================================ #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; } ================================================ FILE: examples/publish/Makefile ================================================ R=../.. include ${R}/config.mk .PHONY: all all : basic-1 basic-websockets-1 basic-1 : basic-1.o ${CROSS_COMPILE}${CC} $^ -o $@ ${LIBMOSQ} basic-websockets-1 : basic-websockets-1.o ${CROSS_COMPILE}${CC} $^ -o $@ ${LIBMOSQ} basic-1.o : basic-1.c ${LIBMOSQ} ${CROSS_COMPILE}${CC} -c $< -o $@ -I${R}/include ${LOCAL_CPPFLAGS} ${LOCAL_CFLAGS} basic-websockets-1.o : basic-websockets-1.c ${LIBMOSQ} ${CROSS_COMPILE}${CC} -c $< -o $@ -I${R}/include ${LOCAL_CPPFLAGS} ${LOCAL_CFLAGS} ${LIBMOSQ} : $(MAKE) -C ${R}/lib clean : -rm -f *.o sub_single sub_multiple ================================================ FILE: examples/publish/basic-1.c ================================================ /* * This example shows how to publish messages from outside of the Mosquitto network loop. */ #include #include #include #include #include #ifndef UNUSED # define UNUSED(A) (void)(A) #endif /* Callback called when the client receives a CONNACK message from the broker. */ void on_connect(struct mosquitto *mosq, void *obj, int reason_code) { UNUSED(obj); /* 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) { UNUSED(mosq); UNUSED(obj); 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 (int)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", (int)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; UNUSED(argc); UNUSED(argv); /* 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; } ================================================ FILE: examples/publish/basic-websockets-1.c ================================================ /* * This example shows how to publish messages from outside of the Mosquitto network loop. * * This is identical to basic-1.c apart from that it uses WebSockets. */ #include #include #include #include #include #ifndef UNUSED # define UNUSED(A) (void)(A) #endif /* Callback called when the client receives a CONNACK message from the broker. */ void on_connect(struct mosquitto *mosq, void *obj, int reason_code) { UNUSED(obj); /* 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) { UNUSED(mosq); UNUSED(obj); 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 (int)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", (int)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; UNUSED(argc); UNUSED(argv); /* 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; } mosquitto_int_option(mosq, MOSQ_OPT_TRANSPORT, MOSQ_T_WEBSOCKETS); /* 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", 8080, 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; } ================================================ FILE: examples/subscribe/basic-1.c ================================================ /* * 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; } ================================================ FILE: examples/subscribe_simple/Makefile ================================================ R=../.. include ${R}/config.mk .PHONY: all all : sub_callback sub_single sub_multiple sub_callback : callback.o ${CROSS_COMPILE}${CC} $^ -o $@ ${LIBMOSQ} sub_single : single.o ${CROSS_COMPILE}${CC} $^ -o $@ ${LIBMOSQ} sub_multiple : multiple.o ${CROSS_COMPILE}${CC} $^ -o $@ ${LIBMOSQ} callback.o : callback.c ${LIBMOSQ} ${CROSS_COMPILE}${CC} -c $< -o $@ -I${R}/lib ${LOCAL_CFLAGS} single.o : single.c ${LIBMOSQ} ${CROSS_COMPILE}${CC} -c $< -o $@ -I${R}/lib ${LOCAL_CFLAGS} multiple.o : multiple.c ${LIBMOSQ} ${CROSS_COMPILE}${CC} -c $< -o $@ -I${R}/lib ${LOCAL_CFLAGS} ${LIBMOSQ}: $(MAKE) -C ${R}/lib clean : -rm -f *.o sub_single sub_multiple ================================================ FILE: examples/subscribe_simple/callback.c ================================================ #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; } ================================================ FILE: examples/subscribe_simple/multiple.c ================================================ #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; i #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; } ================================================ FILE: examples/temperature_conversion/Makefile ================================================ R=../.. LOCAL_CFLAGS=-Wall -ggdb -I${R}/lib -I${R}/lib/cpp LOCAL_LDFLAGS=-L${R}/lib ${R}/lib/cpp/libmosquittopp.so.1 ${LIBMOSQ} .PHONY: all clean all : mqtt_temperature_conversion mqtt_temperature_conversion : main.o temperature_conversion.o ${CXX} $^ -o $@ ${LOCAL_LDFLAGS} main.o : main.cpp ${CXX} -c $^ -o $@ ${LOCAL_CFLAGS} temperature_conversion.o : temperature_conversion.cpp ${CXX} -c $^ -o $@ ${LOCAL_CFLAGS} clean : -rm -f *.o mqtt_temperature_conversion ================================================ FILE: examples/temperature_conversion/main.cpp ================================================ #include "temperature_conversion.h" int main(int argc, char *argv[]) { class mqtt_tempconv *tempconv; int rc; mosqpp::lib_init(); tempconv = new mqtt_tempconv("tempconv", "localhost", 1883); tempconv->loop_forever(); mosqpp::lib_cleanup(); return 0; } ================================================ FILE: examples/temperature_conversion/readme.txt ================================================ This 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. ================================================ FILE: examples/temperature_conversion/temperature_conversion.cpp ================================================ #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"); } ================================================ FILE: examples/temperature_conversion/temperature_conversion.h ================================================ #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 ================================================ FILE: format.sh ================================================ #!/bin/bash find -name '*.c' -exec uncrustify -c .uncrustify.cfg --no-backup {} \; find -name '*.cpp' -exec uncrustify -c .uncrustify.cfg --no-backup {} \; find -name '*.h' -exec uncrustify -c .uncrustify.cfg --no-backup {} \; git checkout deps/picohttpparser/picohttpparser.h git checkout deps/picohttpparser/picohttpparser.c git checkout deps/utlist.h git checkout deps/uthash.h rm -f deps/uthash.h.uncrustify ================================================ FILE: fuzzing/Makefile ================================================ .PHONY: all clean all: ./generate_packet_corpora.py zip -r corpora/db_dump_seed_corpus.zip ../test/apps/db_dump/data/ $(MAKE) -C apps $@ $(MAKE) -C broker $@ $(MAKE) -C libcommon $@ $(MAKE) -C plugins $@ clean: -rm -rf corpora/broker corpora/client -rm -f corpora/broker_packet_seed_corpus.zip corpora/client_packet_seed_corpus.zip -rm -f corpora/db_dump_seed_corpus.zip $(MAKE) -C apps $@ $(MAKE) -C broker $@ $(MAKE) -C libcommon $@ $(MAKE) -C plugins $@ ================================================ FILE: fuzzing/apps/Makefile ================================================ .PHONY: all clean all: $(MAKE) -C db_dump $@ $(MAKE) -C mosquitto_passwd $@ clean: $(MAKE) -C db_dump $@ $(MAKE) -C mosquitto_passwd $@ ================================================ FILE: fuzzing/apps/db_dump/Makefile ================================================ R=../../.. include ${R}/fuzzing/config.mk .PHONY: all clean FUZZERS:= \ db_dump_fuzz_load \ db_dump_fuzz_load_client_stats \ db_dump_fuzz_load_stats LOCAL_CPPFLAGS+= LOCAL_CXXFLAGS+=-g -Wall -Werror -pthread LOCAL_LDFLAGS+= LOCAL_LIBADD+=$(LIB_FUZZING_ENGINE) ${R}/apps/db_dump/mosquitto_db_dump.a ${R}/libcommon/libmosquitto_common.a -Wl,-Bstatic -largon2 -Wl,-Bdynamic -lcjson -lcrypto all: $(FUZZERS) db_dump_fuzz_load : db_dump_fuzz_load.cpp $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) install $@ ${OUT}/$@ cp ${R}/fuzzing/corpora/db_dump_seed_corpus.zip ${OUT}/$@_seed_corpus.zip db_dump_fuzz_load_client_stats : db_dump_fuzz_load_client_stats.cpp $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) install $@ ${OUT}/$@ cp ${R}/fuzzing/corpora/db_dump_seed_corpus.zip ${OUT}/$@_seed_corpus.zip db_dump_fuzz_load_stats : db_dump_fuzz_load_stats.cpp $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) install $@ ${OUT}/$@ cp ${R}/fuzzing/corpora/db_dump_seed_corpus.zip ${OUT}/$@_seed_corpus.zip clean: rm -f *.o $(FUZZERS) ================================================ FILE: fuzzing/apps/db_dump/db_dump_fuzz_load.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 /* * Test loading a file */ /* The fuzz-only main function. */ extern "C" int db_dump_fuzz_main(int argc, char *argv[]); void run_db_dump(char *filename) { char *argv[2]; int argc = 2; argv[0] = strdup("mosquitto_db_dump"); argv[1] = filename; db_dump_fuzz_main(argc, argv); free(argv[0]); } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { char filename[100]; FILE *fptr; umask(0077); snprintf(filename, sizeof(filename), "db_dump_%d.db", getpid()); fptr = fopen(filename, "wb"); if(!fptr){ return 1; } fwrite(data, 1, size, fptr); fclose(fptr); run_db_dump(filename); unlink(filename); return 0; } ================================================ FILE: fuzzing/apps/db_dump/db_dump_fuzz_load_client_stats.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 /* * Test loading a file, with client stats */ /* The fuzz-only main function. */ extern "C" int db_dump_fuzz_main(int argc, char *argv[]); void run_db_dump(char *filename) { char *argv[3]; int argc = 3; argv[0] = strdup("mosquitto_db_dump"); argv[1] = strdup("--client-stats"); argv[2] = filename; db_dump_fuzz_main(argc, argv); free(argv[0]); free(argv[1]); } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { char filename[100]; FILE *fptr; umask(0077); snprintf(filename, sizeof(filename), "db_dump_client_stats_%d.db", getpid()); fptr = fopen(filename, "wb"); if(!fptr){ return 1; } fwrite(data, 1, size, fptr); fclose(fptr); run_db_dump(filename); unlink(filename); return 0; } ================================================ FILE: fuzzing/apps/db_dump/db_dump_fuzz_load_stats.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 /* * Test loading a file */ /* The fuzz-only main function. */ extern "C" int db_dump_fuzz_main(int argc, char *argv[]); void run_db_dump(char *filename) { char *argv[3]; int argc = 3; argv[0] = strdup("mosquitto_db_dump"); argv[1] = strdup("--stats"); argv[2] = filename; db_dump_fuzz_main(argc, argv); free(argv[0]); free(argv[1]); } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { char filename[100]; FILE *fptr; umask(0077); snprintf(filename, sizeof(filename), "db_dump_stats_%d.db", getpid()); fptr = fopen(filename, "wb"); if(!fptr){ return 1; } fwrite(data, 1, size, fptr); fclose(fptr); run_db_dump(filename); unlink(filename); return 0; } ================================================ FILE: fuzzing/apps/mosquitto_passwd/Makefile ================================================ R=../../.. include ${R}/fuzzing/config.mk .PHONY: all clean FUZZERS:= \ mosquitto_passwd_fuzz_load LOCAL_CPPFLAGS+= LOCAL_CXXFLAGS+=-g -Wall -Werror -pthread LOCAL_LDFLAGS+= LOCAL_LIBADD+=$(LIB_FUZZING_ENGINE) ${R}/apps/mosquitto_passwd/mosquitto_passwd.a -lssl -lcrypto ${R}/libcommon/libmosquitto_common.a -Wl,-Bstatic -largon2 -Wl,-Bdynamic all: $(FUZZERS) mosquitto_passwd_fuzz_load : mosquitto_passwd_fuzz_load.cpp $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) install $@ ${OUT}/$@ cp ${R}/fuzzing/corpora/db_dump_seed_corpus.zip ${OUT}/$@_seed_corpus.zip clean: rm -f *.o $(FUZZERS) ================================================ FILE: fuzzing/apps/mosquitto_passwd/mosquitto_passwd_fuzz_load.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 /* * Test loading a file */ /* The fuzz-only main function. */ extern "C" int mosquitto_passwd_fuzz_main(int argc, char *argv[]); void run_mosquitto_passwd(char *filename) { char *argv[5]; int argc = 5; argv[0] = strdup("mosquitto_passwd"); argv[1] = strdup("-b"); argv[2] = filename; argv[3] = strdup("username"); argv[4] = strdup("password"); mosquitto_passwd_fuzz_main(argc, argv); free(argv[0]); free(argv[1]); free(argv[3]); free(argv[4]); } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { char filename[100]; FILE *fptr; umask(0077); snprintf(filename, sizeof(filename), "mosquitto_passwd_%d", getpid()); fptr = fopen(filename, "wb"); if(!fptr){ return 1; } fwrite(data, 1, size, fptr); fclose(fptr); run_mosquitto_passwd(filename); unlink(filename); return 0; } ================================================ FILE: fuzzing/broker/Makefile ================================================ R=../.. include ${R}/fuzzing/config.mk .PHONY: all clean FUZZERS:= \ broker_fuzz_acl_file \ broker_fuzz_password_file \ broker_fuzz_proxy_v1 \ broker_fuzz_proxy_v2 \ broker_fuzz_psk_file \ broker_fuzz_queue_msg \ broker_fuzz_read_handle \ broker_fuzz_test_config LOCAL_CPPFLAGS+=-I${R}/include/ -I${R}/src -I${R}/lib -I${R} -I${R}/common -I${R}/deps \ -DWITH_BRIDGE -DWITH_BROKER -DWITH_CONTROL -DWITH_EPOLL \ -DWITH_MEMORY_TRACKING -DWITH_PERSISTENCE -DWITH_SOCKS -DWITH_SYSTEMD \ -DWITH_SYS_TREE -DWITH_TLS -DWITH_TLS_PSK -DWITH_UNIX_SOCKETS -DWITH_WEBSOCKETS=WS_IS_BUILTIN LOCAL_CXXFLAGS+=-g -Wall -Werror -pthread LOCAL_CFLAGS+=-g -Wall -Werror -pthread LOCAL_LDFLAGS+= LOCAL_LIBADD+=$(LIB_FUZZING_ENGINE) -lssl -lcrypto -lcjson -lm ${R}/libcommon/libmosquitto_common.a -Wl,-Bdynamic -Wl,-Bstatic -largon2 -Wl,-Bdynamic BROKER_A=${R}/src/mosquitto_broker.a PACKET_FUZZERS:= \ broker_fuzz_handle_auth \ broker_fuzz_handle_connect \ broker_fuzz_handle_publish \ broker_fuzz_handle_subscribe \ broker_fuzz_handle_unsubscribe all: $(FUZZERS) $(PACKET_FUZZERS) ${PACKET_FUZZERS} : %: %.cpp fuzz_packet_read_base.o ${R}/src/mosquitto_broker.a $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $< fuzz_packet_read_base.o $(BROKER_A) $(LOCAL_LIBADD) install $@ ${OUT}/$@ fuzz_packet_read_base.o : fuzz_packet_read_base.c $(CC) $(LOCAL_CFLAGS) $(LOCAL_CPPFLAGS) -c -o $@ $< broker_fuzz_acl_file : broker_fuzz_acl_file.cpp ${R}/src/mosquitto_broker.a $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $< $(BROKER_A) $(LOCAL_LIBADD) install $@ ${OUT}/$@ cp ${R}/fuzzing/corpora/broker_acl_file_seed_corpus.zip ${OUT}/$@_seed_corpus.zip cp ${R}/fuzzing/corpora/broker_acl_file.dict ${OUT}/$@.dict broker_fuzz_password_file : broker_fuzz_password_file.cpp ${R}/src/mosquitto_broker.a $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $< $(BROKER_A) $(LOCAL_LIBADD) install $@ ${OUT}/$@ cp ${R}/fuzzing/corpora/broker_password_file_seed_corpus.zip ${OUT}/$@_seed_corpus.zip broker_fuzz_proxy_v1 : broker_fuzz_proxy_v1.cpp ${R}/src/proxy_v1.o $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $< ${R}/src/proxy_v1.o $(LOCAL_LIBADD) cp ${R}/fuzzing/corpora/broker_fuzz_proxy_v1_seed_corpus.zip ${OUT}/$@_seed_corpus.zip install $@ ${OUT}/$@ broker_fuzz_proxy_v2 : broker_fuzz_proxy_v2.cpp ${R}/src/proxy_v2.o $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $< ${R}/src/proxy_v2.o $(LOCAL_LIBADD) cp ${R}/fuzzing/corpora/broker_fuzz_proxy_v2_seed_corpus.zip ${OUT}/$@_seed_corpus.zip install $@ ${OUT}/$@ broker_fuzz_psk_file : broker_fuzz_psk_file.cpp ${R}/src/mosquitto_broker.a $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $< $(BROKER_A) $(LOCAL_LIBADD) install $@ ${OUT}/$@ cp ${R}/fuzzing/corpora/broker_psk_file_seed_corpus.zip ${OUT}/$@_seed_corpus.zip broker_fuzz_queue_msg : broker_fuzz_queue_msg.cpp ${R}/src/mosquitto_broker.a $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $< $(BROKER_A) $(LOCAL_LIBADD) install $@ ${OUT}/$@ cp ${R}/fuzzing/corpora/broker_queue_msg_seed_corpus.zip ${OUT}/$@_seed_corpus.zip broker_fuzz_read_handle : broker_fuzz_read_handle.cpp fuzz_packet_read_base.o ${R}/src/mosquitto_broker.a $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(BROKER_A) $(LOCAL_LIBADD) install $@ ${OUT}/$@ cp ${R}/fuzzing/corpora/broker_packet_seed_corpus.zip ${OUT}/$@_seed_corpus.zip broker_fuzz_test_config : broker_fuzz_test_config.cpp ${R}/src/mosquitto_broker.a $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $< $(BROKER_A) $(LOCAL_LIBADD) install $@ ${OUT}/$@ cp ${R}/fuzzing/corpora/broker_fuzz_test_config_seed_corpus.zip ${OUT}/$@_seed_corpus.zip cp ${R}/fuzzing/corpora/broker_conf.dict ${OUT}/$@.dict clean: rm -f *.o $(FUZZERS) $(PACKET_FUZZERS) ================================================ FILE: fuzzing/broker/broker_fuzz.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 #include "broker_fuzz.h" #define PORT 1883 /* The broker fuzz-only main function. */ extern "C" int mosquitto_fuzz_main(int argc, char *argv[]); void *run_broker(void *args) { char *argv[4]; int argc = 4; argv[0] = strdup("mosquitto"); argv[1] = strdup("-v"); argv[2] = strdup("-c"); argv[3] = strdup("/tmp/mosquitto.conf"); mosquitto_fuzz_main(argc, argv); for(int i=0; i kMaxInputLength){ return 0; } signal(SIGPIPE, SIG_IGN); umask(0077); memset(&fuzz, 0, sizeof(fuzz)); fuzz.port = PORT; fuzz.size = size; fuzz.data = (uint8_t *)data; fptr = fopen("/tmp/mosquitto.conf", "wb"); if(!fptr){ printf("FILE %s\n", strerror(errno)); abort(); } fprintf(fptr, "user root\n"); fprintf(fptr, "listener %d\n", PORT); fprintf(fptr, "allow_anonymous true\n"); fclose(fptr); pthread_create(&thread, NULL, run_broker, &fuzz); run_client(&fuzz); pthread_join(thread, NULL); unlink("/tmp/mosquitto.conf"); return 0; } ================================================ FILE: fuzzing/broker/broker_fuzz.h ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 BROKER_FUZZ_H #define BROKER_FUZZ_H #define kMinInputLength 5 #define kMaxInputLength 10000 struct fuzz_data { uint8_t *data; size_t size; uint16_t port; }; void *run_broker(void *args); void recv_timeout(int sock, void *buf, size_t len, int timeout_us); int connect_retrying(int port); void run_client(struct fuzz_data *fuzz); #endif ================================================ FILE: fuzzing/broker/broker_fuzz_acl_file.cpp ================================================ /* Copyright (c) 2024 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 /* * Broker check of acl file */ extern "C" { #include "mosquitto_broker_internal.h" } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { char filename[100]; FILE *fptr; struct mosquitto__config config = {0}; db.config = &config; config.log_type = 0; config.log_dest = 0; umask(0077); snprintf(filename, sizeof(filename), "/tmp/acl_file_%d", getpid()); fptr = fopen(filename, "wb"); if(!fptr){ return 1; } fwrite(data, 1, size, fptr); fclose(fptr); config.security_options.acl_data.acl_file = strdup(filename); log__init(&config); mosquitto_security_init_default(); mosquitto_security_cleanup_default(); config__cleanup(&config); unlink(filename); return 0; } ================================================ FILE: fuzzing/broker/broker_fuzz_handle_auth.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 kMaxInputLength 100000 #include "fuzz_packet_read_base.h" extern "C" int fuzz_packet_read_init(struct mosquitto *context) { context->protocol = mosq_p_mqtt5; context->auth_method = strdup("FUZZ"); return !context->auth_method; } extern "C" void fuzz_packet_read_cleanup(struct mosquitto *context) { free(context->auth_method); context->auth_method = NULL; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { int rc = fuzz_packet_read_base(data, size, handle__auth); return rc; } ================================================ FILE: fuzzing/broker/broker_fuzz_handle_connect.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 kMaxInputLength 100000 #include "fuzz_packet_read_base.h" extern "C" int fuzz_basic_auth(int event, void *event_data, void *userdata) { struct mosquitto_evt_basic_auth *ed = (struct mosquitto_evt_basic_auth *)event_data; /* This is a check that is ultimately determined by the fuzz input data, so * the fuzzer can discover how to access both the fail/success cases. */ if(ed->client->id && (ed->client->id[0]%2 == 0)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } extern "C" int fuzz_packet_read_init(struct mosquitto *context) { context->listener->security_options->pid = (mosquitto_plugin_id_t *)calloc(1, sizeof(mosquitto_plugin_id_t)); if(!context->listener->security_options->pid){ return 1; } mosquitto_callback_register(context->listener->security_options->pid, MOSQ_EVT_BASIC_AUTH, fuzz_basic_auth, NULL, NULL); return 0; } extern "C" void fuzz_packet_read_cleanup(struct mosquitto *context) { mosquitto_callback_unregister(context->listener->security_options->pid, MOSQ_EVT_BASIC_AUTH, fuzz_basic_auth, NULL); free(context->listener->security_options->pid); context->listener->security_options->pid = NULL; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { return fuzz_packet_read_base(data, size, handle__connect); } ================================================ FILE: fuzzing/broker/broker_fuzz_handle_publish.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 "fuzz_packet_read_base.h" extern "C" int fuzz_acl_check(int event, void *event_data, void *userdata) { struct mosquitto_evt_acl_check *ed = (struct mosquitto_evt_acl_check *)event_data; /* This is a check that is ultimately determined by the fuzz input data, so * the fuzzer can discover how to access both the fail/success cases. */ if(ed->topic && (ed->topic[0]%2 == 0)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } extern "C" int fuzz_packet_read_init(struct mosquitto *context) { context->listener->security_options->pid = (mosquitto_plugin_id_t *)calloc(1, sizeof(mosquitto_plugin_id_t)); if(!context->listener->security_options->pid){ return 1; } mosquitto_callback_register(context->listener->security_options->pid, MOSQ_EVT_ACL_CHECK, fuzz_acl_check, NULL, NULL); return 0; } extern "C" void fuzz_packet_read_cleanup(struct mosquitto *context) { mosquitto_callback_unregister(context->listener->security_options->pid, MOSQ_EVT_ACL_CHECK, fuzz_acl_check, NULL); free(context->listener->security_options->pid); context->listener->security_options->pid = NULL; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { return fuzz_packet_read_base(data, size, handle__publish); } ================================================ FILE: fuzzing/broker/broker_fuzz_handle_subscribe.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 kMaxInputLength 100000 #include "fuzz_packet_read_base.h" extern "C" int fuzz_acl_check(int event, void *event_data, void *userdata) { struct mosquitto_evt_acl_check *ed = (struct mosquitto_evt_acl_check *)event_data; /* This is a check that is ultimately determined by the fuzz input data, so * the fuzzer can discover how to access both the fail/success cases. */ if(ed->topic && (ed->topic[0]%2 == 0)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } extern "C" int fuzz_packet_read_init(struct mosquitto *context) { context->listener->security_options->pid = (mosquitto_plugin_id_t *)calloc(1, sizeof(mosquitto_plugin_id_t)); if(!context->listener->security_options->pid){ return 1; } mosquitto_callback_register(context->listener->security_options->pid, MOSQ_EVT_ACL_CHECK, fuzz_acl_check, NULL, NULL); return 0; } extern "C" void fuzz_packet_read_cleanup(struct mosquitto *context) { mosquitto_callback_unregister(context->listener->security_options->pid, MOSQ_EVT_ACL_CHECK, fuzz_acl_check, NULL); free(context->listener->security_options->pid); context->listener->security_options->pid = NULL; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { return fuzz_packet_read_base(data, size, handle__subscribe); } ================================================ FILE: fuzzing/broker/broker_fuzz_handle_unsubscribe.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 kMaxInputLength 100000 #include "fuzz_packet_read_base.h" extern "C" int fuzz_acl_check(int event, void *event_data, void *userdata) { struct mosquitto_evt_acl_check *ed = (struct mosquitto_evt_acl_check *)event_data; /* This is a check that is ultimately determined by the fuzz input data, so * the fuzzer can discover how to access both the fail/success cases. */ if(ed->topic && (ed->topic[0]%2 == 0)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } extern "C" int fuzz_packet_read_init(struct mosquitto *context) { context->listener->security_options->pid = (mosquitto_plugin_id_t *)calloc(1, sizeof(mosquitto_plugin_id_t)); if(!context->listener->security_options->pid){ return 1; } mosquitto_callback_register(context->listener->security_options->pid, MOSQ_EVT_ACL_CHECK, fuzz_acl_check, NULL, NULL); return 0; } extern "C" void fuzz_packet_read_cleanup(struct mosquitto *context) { mosquitto_callback_unregister(context->listener->security_options->pid, MOSQ_EVT_ACL_CHECK, fuzz_acl_check, NULL); free(context->listener->security_options->pid); context->listener->security_options->pid = NULL; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { return fuzz_packet_read_base(data, size, handle__unsubscribe); } ================================================ FILE: fuzzing/broker/broker_fuzz_password_file.cpp ================================================ /* Copyright (c) 2024 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 /* * Broker check of password file */ extern "C" { #include "mosquitto_broker_internal.h" } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { char filename[100]; FILE *fptr; struct mosquitto__config config = {0}; db.config = &config; config.log_type = 0; config.log_dest = 0; umask(0077); snprintf(filename, sizeof(filename), "/tmp/password_file_%d", getpid()); fptr = fopen(filename, "wb"); if(!fptr){ return 1; } fwrite(data, 1, size, fptr); fclose(fptr); config.security_options.password_data.password_file = strdup(filename); log__init(&config); mosquitto_security_init_default(); mosquitto_security_cleanup_default(); config__cleanup(&config); unlink(filename); return 0; } ================================================ FILE: fuzzing/broker/broker_fuzz_proxy_v1.cpp ================================================ /* Copyright (c) 2025 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 static const uint8_t *packet_data = NULL; static int packet_data_pos = 0; static int packet_data_remaining = 0; extern "C" { #include "mosquitto_broker_internal.h" ssize_t net__read(struct mosquitto *mosq, void *buf, size_t count) { int res = count < packet_data_remaining?count:packet_data_remaining; memcpy(buf, &packet_data[packet_data_pos], res); packet_data_remaining -= res; return res; } int net__socket_get_address(mosq_sock_t sock, char *buf, size_t len, uint16_t *remote_port) { snprintf(buf, len, "localhost"); *remote_port = 1883; return MOSQ_ERR_SUCCESS; } int http__context_init(struct mosquitto *context) { context->transport = mosq_t_http; return MOSQ_ERR_SUCCESS; } int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { return MOSQ_ERR_SUCCESS; } } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { struct mosquitto context {}; struct mosquitto__listener listener {}; packet_data = data; packet_data_pos = 0; packet_data_remaining = size; context.listener = &listener; context.proxy.cmd = -1; context.transport = mosq_t_proxy_v1; while(packet_data_remaining > 0 && context.transport != mosq_t_tcp){ int rc = proxy_v1__read(&context); if(rc){ break; } } free(context.address); free(context.proxy.buf); free(context.proxy.tls_version); free(context.proxy.cipher); return 0; } ================================================ FILE: fuzzing/broker/broker_fuzz_proxy_v2.cpp ================================================ /* Copyright (c) 2025 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 static const uint8_t *packet_data = NULL; static int packet_data_pos = 0; static int packet_data_remaining = 0; extern "C" { #include "mosquitto_broker_internal.h" ssize_t net__read(struct mosquitto *mosq, void *buf, size_t count) { int res = count < packet_data_remaining?count:packet_data_remaining; memcpy(buf, &packet_data[packet_data_pos], res); packet_data_remaining -= res; return res; } int http__context_init(struct mosquitto *context) { context->transport = mosq_t_http; return MOSQ_ERR_SUCCESS; } int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { return MOSQ_ERR_SUCCESS; } } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { struct mosquitto context {}; struct mosquitto__listener listener {}; packet_data = data; packet_data_pos = 0; packet_data_remaining = size; context.listener = &listener; context.proxy.cmd = -1; context.transport = mosq_t_proxy_v2; while(packet_data_remaining > 0 && context.transport != mosq_t_tcp){ int rc = proxy_v2__read(&context); if(rc){ break; } } free(context.address); free(context.proxy.buf); free(context.proxy.tls_version); free(context.proxy.cipher); return 0; } ================================================ FILE: fuzzing/broker/broker_fuzz_psk_file.cpp ================================================ /* Copyright (c) 2024 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 /* * Broker check of psk file */ extern "C" { #include "mosquitto_broker_internal.h" } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { char filename[100]; FILE *fptr; struct mosquitto__config config = {0}; db.config = &config; config.log_type = 0; config.log_dest = 0; umask(0077); snprintf(filename, sizeof(filename), "/tmp/psk_file_%d", getpid()); fptr = fopen(filename, "wb"); if(!fptr){ return 1; } fwrite(data, 1, size, fptr); fclose(fptr); config.security_options.psk_file = strdup(filename); log__init(&config); mosquitto_security_init_default(); mosquitto_security_cleanup_default(); config__cleanup(&config); unlink(filename); return 0; } ================================================ FILE: fuzzing/broker/broker_fuzz_queue_msg.cpp ================================================ /* Copyright (c) 2024 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 /* * Broker check of acl file */ extern "C" { #include "mosquitto_broker_internal.h" } //int sub__messages_queue(const char *source_id, const char *topic, uint8_t qos, int retain, struct mosquitto__base_msg **stored) extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { struct mosquitto__config config = {0}; struct mosquitto__base_msg basemsg, *pbasemsg; if(mosquitto_pub_topic_check2((const char *)data, size)){ /* sub__messages_queue only receives topics that have already been * checked with mosquitto_pub_topic_check2(), so we give it that benefit * here. */ return 0; } memset(&basemsg, 0, sizeof(basemsg)); basemsg.ref_count = 1; pbasemsg = &basemsg; db.config = &config; config.log_type = 0; config.log_dest = 0; log__init(&config); db__open(&config); char *data0 = (char *)calloc(1, size+1); memcpy(data0, data, size); sub__messages_queue("fuzzer", data0, 0, 1, &pbasemsg); free(data0); db__close(); return 0; } ================================================ FILE: fuzzing/broker/broker_fuzz_read_handle.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 "fuzz_packet_read_base.h" extern "C" int fuzz_packet_read_init(struct mosquitto *context) { return 0; } extern "C" void fuzz_packet_read_cleanup(struct mosquitto *context) { } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { return fuzz_packet_read_base(data, size, handle__packet); } ================================================ FILE: fuzzing/broker/broker_fuzz_test_config.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 "broker_fuzz.h" /* * Broker check of config only, the config isn't used */ /* The broker fuzz-only main function. */ extern "C" int mosquitto_fuzz_main(int argc, char *argv[]); void run_broker(char *filename) { char *argv[5]; int argc = 5; argv[0] = strdup("mosquitto"); argv[1] = strdup("--test-config"); argv[2] = strdup("-q"); argv[3] = strdup("-c"); argv[4] = strdup(filename); mosquitto_fuzz_main(argc, argv); for(int i=0; i #include #include #include #include #include #include #include #include #include #include #include "broker_fuzz.h" #define PORT 1883 /* The broker fuzz-only main function. */ extern "C" int mosquitto_fuzz_main(int argc, char *argv[]); void *run_broker(void *args) { char *argv[4]; int argc = 4; argv[0] = strdup("mosquitto"); argv[1] = strdup("-q"); argv[2] = strdup("-c"); argv[3] = strdup("/tmp/mosquitto.conf"); mosquitto_fuzz_main(argc, argv); for(int i=0; i kMaxInputLength){ return 0; } memset(&fuzz, 0, sizeof(fuzz)); fuzz.port = PORT; fuzz.size = size; fuzz.data = (uint8_t *)data; run_client(&fuzz); return 0; } ================================================ FILE: fuzzing/broker/fuzz_packet_read_base.c ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 __cplusplus extern "C" { #endif #include "fuzz_packet_read_base.h" #include "mosquitto_broker_internal.h" #include "mosquitto_internal.h" #define kMinInputLength 3 #define kMaxInputLength 268435455U int fuzz_packet_read_base(const uint8_t *data, size_t size, int (*packet_func)(struct mosquitto *)) { struct mosquitto *context = NULL; uint8_t *data_heap; struct mosquitto__listener listener; struct mosquitto__security_options secopts; if(size < kMinInputLength || size > kMaxInputLength){ return 0; } db.config = (struct mosquitto__config *)calloc(1, sizeof(struct mosquitto__config)); log__init(db.config); memset(&listener, 0, sizeof(listener)); memset(&secopts, 0, sizeof(secopts)); context = context__init(); if(!context){ return 1; } listener.security_options = &secopts; context->listener = &listener; context->bridge = (struct mosquitto__bridge *)calloc(1, sizeof(struct mosquitto__bridge));; context->state = (enum mosquitto_client_state )data[0]; context->protocol = (enum mosquitto__protocol )data[1]; size -= 2; data_heap = (uint8_t *)malloc(size); if(!data_heap){ free(context->bridge); context->bridge = NULL; free(db.config); db.config = NULL; return 1; } memcpy(data_heap, &data[2], size); context->in_packet.command = data_heap[0]; context->in_packet.payload = (uint8_t *)data_heap; context->in_packet.packet_length = (uint32_t )size; /* Safe cast, because we've already limited the size */ context->in_packet.remaining_length = (uint32_t )(size-1); context->in_packet.pos = 1; if(fuzz_packet_read_init(context)){ free(context->bridge); context->bridge = NULL; free(db.config); return 1; } packet_func(context); fuzz_packet_read_cleanup(context); free(context->bridge); context->bridge = NULL; context__cleanup(context, true); free(db.config); return 0; } #ifdef __cplusplus } #endif ================================================ FILE: fuzzing/broker/fuzz_packet_read_base.h ================================================ #ifndef FUZZ_PACKET_READ_BASE_H /* Copyright (c) 2023 Cedalo GmbH 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 __cplusplus extern "C" { #endif #include #include "mosquitto_broker_internal.h" #include "mosquitto_internal.h" #include "read_handle.h" #define kMinInputLength 3 #ifndef kMaxInputLength # define kMaxInputLength 268435455U #endif int fuzz_packet_read_base(const uint8_t *data, size_t size, int (*packet_func)(struct mosquitto *)); int fuzz_packet_read_init(struct mosquitto *context); void fuzz_packet_read_cleanup(struct mosquitto *context); #ifdef __cplusplus } #endif #endif ================================================ FILE: fuzzing/config.mk ================================================ LOCAL_CPPFLAGS:=$(CPPFLAGS) LOCAL_CFLAGS:=$(CFLAGS) LOCAL_CXXFLAGS:=$(CXXFLAGS) LOCAL_LDFLAGS:=$(LDFLAGS) LOCAL_LIBADD:=$(LIBADD) LOCAL_CPPFLAGS+=-I${R} -I. -I${R}/include -I${R}/common LOCAL_CFLAGS+= LOCAL_LDFLAGS+=$(LOCAL_CFLAGS) ================================================ FILE: fuzzing/corpora/broker_acl_file.dict ================================================ "deny" "pattern" "read" "readwrite" "topic" "user" "write" ================================================ FILE: fuzzing/corpora/broker_conf.dict ================================================ "0" "1" "3" "4" "5" "accept_protocol_versions" "acl_file" "address" "addresses" "all" "allow_anonymous" "allow_duplicate_messages" "allow_zero_length_clientid" "android" "auth_plugin" "auth_plugin_deny_special_chars" "auto_id_prefix" "automatic" "autosave_interval" "autosave_on_changes" "bind_address" "bind_interface" "bridge_alpn" "bridge_attempt_unsubscribe" "bridge_bind_address" "bridge_cafile" "bridge_capath" "bridge_certfile" "bridge_ciphers" "bridge_ciphers_tls1.3" "bridge_identity" "bridge_insecure" "bridge_keyfile" "bridge_max_packet_size" "bridge_max_topic_alias" "bridge_outgoing_retain" "bridge_protocol_version" "bridge_psk" "bridge_receive_maximum" "bridge_reload_type" "bridge_require_ocsp" "bridge_session_expiry_interval" "bridge_tcp_keepalive" "bridge_tcp_user_timeout" "bridge_tls_use_os_certs" "bridge_tls_version" "cafile" "capath" "certfile" "check_retain_source" "ciphers" "ciphers_tls1.3" "cleansession" "clientid" "clientid_prefixes" "connection" "connection_messages" "crlfile" "debug" "dhparamfile" "disable_client_cert_date_checks" "dlt" "enable_control_api" "engine" "error" "false" "file" "global_max_clients" "global_max_connections" "global_plugin" "http_dir" "idle_timeout" "immediate" "include_dir" "information" "internal" "ipv4" "ipv6" "keepalive_interval" "keyfile" "lazy" "listener" "local_cleansession" "local_clientid" "local_password" "local_username" "log_dest" "log_facility" "log_timestamp" "log_timestamp_format" "log_type" "manual" "max_connections" "max_inflight_bytes" "max_inflight_messages" "max_keepalive" "max_packet_size" "max_qos" "max_queued_bytes" "max_queued_messages" "max_topic_alias" "max_topic_alias_broker" "maximum_qos" "memory_limit" "message_size_limit" "mount_point" "mqtt" "mqttsn" "mqttv31" "mqttv311" "mqttv50" "none" "notice" "notification_topic" "notifications" "notifications_local_only" "once" "password" "password_file" "per_listener_settings" "persistence" "persistence_file" "persistence_location" "persistent_client_expiration" "pid_file" "plugin" "plugin_load" "plugin_use" "port" "protocol" "psk_file" "psk_hint" "queue_qos0_messages" "remote_clientid" "remote_password" "remote_username" "require_certificate" "restart_timeout" "retain_available" "retained_persistence" "retry_interval" "round_robin" "set_tcp_nodelay" "socket_domain" "start_type" "stderr" "stdout" "subscribe" "sys_interval" "syslog" "threshold" "tls_engine" "tls_engine_kpass_sha1" "tls_keyform" "tls_version" "topic" "true" "try_private" "unsubscribe" "upgrade_outgoing_qos" "use_identity_as_username" "use_subject_as_username" "use_username_as_clientid" "user" "username" "warning" "websockets" "websockets_headers_size" "websockets_log_level" "websockets_origin" ================================================ FILE: fuzzing/generate_packet_corpora.py ================================================ #!/usr/bin/env python3 import 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], "../test/broker") ) ) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder) from collections import deque from os import mkdir,walk from pathlib import Path import json import re import shutil import msg_sequence_test def gen_packet_corpus(packet_type, input_path): try: mkdir("corpora") except FileExistsError: pass try: mkdir(f"corpora/{packet_type}") except FileExistsError: pass data_path=Path(input_path) rc = 0 sequences = [] for (_, _, filenames) in walk(data_path): sequences.extend(filenames) break written_packets = {} for seq in sorted(sequences): if seq[-5:] != ".json": continue with open(data_path/seq, "r") as f: test_file = json.load(f) for g in test_file: group_name = g["group"] tests = g["tests"] for t in tests: tname = group_name + " " + t["name"] fuzzi = 1 for m in t["msgs"]: if m["type"] == "send" or m["type"] == "recv": fname = re.sub(r'[\/ \[\]\(\)]+', '-', tname) + str(fuzzi) + ".raw" payload = m["payload"] # No duplicates please if payload not in written_packets: written_packets[payload] = 1 with open(f"corpora/{packet_type}/{fname}", "wb") as f: f.write(msg_sequence_test.parse_message(payload)) fuzzi += 1 shutil.make_archive(f"corpora/{packet_type}_packet_seed_corpus", 'zip', f"corpora/{packet_type}") gen_packet_corpus("broker", "../test/broker/data") gen_packet_corpus("client", "../test/lib/data") ================================================ FILE: fuzzing/libcommon/Makefile ================================================ R=../.. include ${R}/fuzzing/config.mk .PHONY: all clean FUZZERS:= \ libcommon_fuzz_property \ libcommon_fuzz_pub_topic_check2 \ libcommon_fuzz_sub_topic_check2 \ libcommon_fuzz_topic_matching \ libcommon_fuzz_topic_tokenise \ libcommon_fuzz_utf8 LOCAL_CPPFLAGS+=-I${R}/include/ -I${SRC}/libprotobuf-mutator -I${SRC}/LPM/external.protobuf/include LOCAL_CXXFLAGS+=-g -Wall -Werror -pthread -Wno-deprecated-builtins LOCAL_LDFLAGS+= LOCAL_LIBADD+=$(LIB_FUZZING_ENGINE) -lssl -lcrypto ${R}/libcommon/libmosquitto_common.a -Wl,-Bstatic -largon2 -Wl,-Bdynamic PROTOBUF_LIBS=${SRC}/LPM/src/libfuzzer/libprotobuf-mutator-libfuzzer.a \ ${SRC}/LPM/src/libprotobuf-mutator.a \ -Wl,--start-group \ ${SRC}/LPM/external.protobuf/lib/lib*.a \ -Wl,--end-group PROTOC?=${SRC}/LPM/external.protobuf/bin/protoc all: $(FUZZERS) libcommon_fuzz_property.pb.cc : libcommon_fuzz_property.proto $(PROTOC) --cpp_out=. $^ libcommon_fuzz_property : libcommon_fuzz_property.cpp libcommon_fuzz_property.pb.cc $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) $(PROTOBUF_LIBS) install $@ ${OUT}/$@ libcommon_fuzz_pub_topic_check2 : libcommon_fuzz_pub_topic_check2.cpp $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) install $@ ${OUT}/$@ libcommon_fuzz_sub_topic_check2 : libcommon_fuzz_sub_topic_check2.cpp $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) install $@ ${OUT}/$@ libcommon_fuzz_topic_matching : libcommon_fuzz_topic_matching.cpp libcommon_fuzz_topic_matching.pb.cc $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) $(PROTOBUF_LIBS) install $@ ${OUT}/$@ libcommon_fuzz_topic_matching.pb.cc : libcommon_fuzz_topic_matching.proto $(PROTOC) --cpp_out=. $^ libcommon_fuzz_topic_tokenise : libcommon_fuzz_topic_tokenise.cpp $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) install $@ ${OUT}/$@ libcommon_fuzz_utf8 : libcommon_fuzz_utf8.cpp $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) install $@ ${OUT}/$@ clean: rm -f *.o $(FUZZERS) ================================================ FILE: fuzzing/libcommon/libcommon_fuzz_property.cpp ================================================ #include "src/libfuzzer/libfuzzer_macro.h" #include "libcommon_fuzz_property.pb.h" #include "mosquitto.h" DEFINE_PROTO_FUZZER(const fuzz_property::FuzzerInput& fuzzer_input) { mosquitto_property *prop_list = nullptr; mosquitto_property *prop_copy = nullptr; for(const fuzz_property::Property& property : fuzzer_input.properties()){ int identifier = property.identifier(); switch(property.data_case()){ case fuzz_property::Property::DataCase::kUint8Value: mosquitto_property_add_byte(&prop_list, identifier, property.uint8_value() % 256); break; case fuzz_property::Property::DataCase::kUint16Value: mosquitto_property_add_int16(&prop_list, identifier, property.uint16_value() % 65536); break; case fuzz_property::Property::DataCase::kUint32Value: mosquitto_property_add_int32(&prop_list, identifier, property.uint32_value()); break; case fuzz_property::Property::DataCase::kVarintValue: mosquitto_property_add_varint(&prop_list, identifier, property.varint_value()); break; case fuzz_property::Property::DataCase::kBinaryValue: mosquitto_property_add_binary(&prop_list, identifier, property.binary_value().c_str(), property.binary_value().size()); break; case fuzz_property::Property::DataCase::kStringValue: mosquitto_property_add_string(&prop_list, identifier, property.string_value().c_str()); break; case fuzz_property::Property::DataCase::kStringpairValue: mosquitto_property_add_string_pair(&prop_list, identifier, property.stringpair_value().name().c_str(), property.stringpair_value().value().c_str()); break; case fuzz_property::Property::DataCase::DATA_NOT_SET: break; } } mosquitto_property_copy_all(&prop_copy, prop_list); mosquitto_property_free_all(&prop_list); mosquitto_property_free_all(&prop_copy); } ================================================ FILE: fuzzing/libcommon/libcommon_fuzz_property.proto ================================================ syntax = "proto2"; package fuzz_property; message Property { message StringPair { required string name = 1; required string value = 2; } required uint32 identifier = 1; oneof data { uint32 uint8_value = 2; uint32 uint16_value = 3; uint32 uint32_value = 4; uint32 varint_value = 5; bytes binary_value = 6; string string_value = 7; StringPair stringpair_value = 8; } } message FuzzerInput { repeated Property properties = 1; } ================================================ FILE: fuzzing/libcommon/libcommon_fuzz_pub_topic_check2.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { mosquitto_pub_topic_check2((const char *)data, size); return 0; } ================================================ FILE: fuzzing/libcommon/libcommon_fuzz_sub_topic_check2.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { mosquitto_sub_topic_check2((const char *)data, size); return 0; } ================================================ FILE: fuzzing/libcommon/libcommon_fuzz_topic_matching.cpp ================================================ #include "src/libfuzzer/libfuzzer_macro.h" #include "libcommon_fuzz_topic_matching.pb.h" #include "mosquitto.h" DEFINE_PROTO_FUZZER(const fuzz_topic_matches_sub::FuzzerInput& fuzzer_input) { bool result; const char *string1 = fuzzer_input.string1().c_str(); const char *string2 = fuzzer_input.string2().c_str(); const char *username = nullptr; const char *clientid = nullptr; if(fuzzer_input.has_username()){ username = fuzzer_input.username().c_str(); } if(fuzzer_input.has_clientid()){ clientid = fuzzer_input.clientid().c_str(); } //targeted_function_1(fuzzer_input.arg1(), fuzzer_input.arg2(), fuzzer_input.arg3()); mosquitto_topic_matches_sub(string1, string2, &result); mosquitto_topic_matches_sub2(string1, strlen(string1), string2, strlen(string2), &result); mosquitto_topic_matches_sub_with_pattern(string1, string2, clientid, username, &result); mosquitto_sub_matches_acl(string1, string2, &result); mosquitto_sub_matches_acl_with_pattern(string1, string2, clientid, username, &result); } ================================================ FILE: fuzzing/libcommon/libcommon_fuzz_topic_matching.proto ================================================ syntax = "proto2"; package fuzz_topic_matches_sub; message FuzzerInput { required string string1 = 1; required string string2 = 2; optional string username = 3; optional string clientid = 4; } ================================================ FILE: fuzzing/libcommon/libcommon_fuzz_topic_tokenise.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { char *buf; buf = (char *)calloc(1, size+1); /* ensure ull terminated */ if(buf){ char **topics = NULL;; int count; memcpy(buf, data, size); mosquitto_sub_topic_tokenise(buf, &topics, &count); mosquitto_sub_topic_tokens_free(&topics, count); free(buf); } return 0; } ================================================ FILE: fuzzing/libcommon/libcommon_fuzz_utf8.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { mosquitto_validate_utf8((const char *)data, (int)size); return 0; } ================================================ FILE: fuzzing/plugins/Makefile ================================================ .PHONY: all clean all: $(MAKE) -C dynamic-security $@ clean: $(MAKE) -C dynamic-security $@ ================================================ FILE: fuzzing/plugins/dynamic-security/Makefile ================================================ R=../../.. include ${R}/fuzzing/config.mk .PHONY: all clean FUZZERS:= \ dynsec_fuzz_load LOCAL_CPPFLAGS+= \ -I${R} -I${R}/common -I${R}/include -I${R}/lib -I${R}/src -I${R}/deps -I${R}/plugins/dynamic-security \ -DWITH_BRIDGE -DWITH_BROKER -DWITH_CONTROL -DWITH_EPOLL \ -DWITH_MEMORY_TRACKING -DWITH_PERSISTENCE -DWITH_SOCKS -DWITH_SYSTEMD \ -DWITH_SYS_TREE -DWITH_TLS -DWITH_TLS_PSK -DWITH_UNIX_SOCKETS -DWITH_WEBSOCKETS=WS_IS_BUILTIN LOCAL_CXXFLAGS+=-g -Wall -Werror -pthread LOCAL_LDFLAGS+= LOCAL_LIBADD+=$(LIB_FUZZING_ENGINE) \ ${R}/plugins/dynamic-security/mosquitto_dynamic_security.a \ ${R}/src/mosquitto_broker.a \ ${R}/libcommon/libmosquitto_common.a \ -lssl -lcrypto -lcjson -lm \ -Wl,-Bdynamic -Wl,-Bstatic -largon2 -Wl,-Bdynamic all: $(FUZZERS) dynsec_fuzz_load : dynsec_fuzz_load.cpp $(CXX) $(LOCAL_CXXFLAGS) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) install $@ ${OUT}/$@ cp ${R}/fuzzing/corpora/dynsec_config_seed_corpus.zip ${OUT}/$@_seed_corpus.zip clean: rm -f *.o $(FUZZERS) *.gcno *.gcda ================================================ FILE: fuzzing/plugins/dynamic-security/dynsec_fuzz_load.cpp ================================================ /* Copyright (c) 2023 Cedalo GmbH 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 #ifdef __cplusplus extern "C" { #endif #include #include #ifdef __cplusplus } #endif /* * Test loading a file */ extern struct mosquitto_db db; void run_dynsec(char *filename) { struct mosquitto_plugin_id_t identifier; struct mosquitto_opt options[1]; db.config = (struct mosquitto__config *)calloc(1, sizeof(struct mosquitto__config)); log__init(db.config); memset(&identifier, 0, sizeof(identifier)); options[0].key = strdup("config_file"); options[0].value = filename; mosquitto_plugin_init(&identifier, NULL, options, 1); mosquitto_plugin_cleanup(NULL, options, 1); free(options[0].key); free(db.config); free(identifier.plugin_name); free(identifier.plugin_version); db.config = NULL; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { char filename[100]; FILE *fptr; umask(0077); snprintf(filename, sizeof(filename), "/tmp/dynsec%d.conf", getpid()); fptr = fopen(filename, "wb"); if(!fptr){ return 1; } fwrite(data, 1, size, fptr); fclose(fptr); run_dynsec(filename); unlink(filename); return 0; } ================================================ FILE: fuzzing/scripts/oss-fuzz-build.sh ================================================ #!/bin/bash -eu # # Copyright (c) 2023 Cedalo GmbH # # 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. export CC="${CC:-clang}" export CXX="${CXX:-clang++}" export CFLAGS export CXXFLAGS export LDFLAGS # Build direct broker dependency - cJSON # Note that other dependencies, i.e. sqlite are not yet built because they are # only used by plugins and not currently otherwise used. cd ${SRC}/cJSON cmake \ -DBUILD_SHARED_LIBS=OFF \ -DCMAKE_C_FLAGS=-fPIC \ -DENABLE_CJSON_TEST=OFF \ . make -j $(nproc) make install # Build broker and library static libraries cd ${SRC}/mosquitto make \ WITH_STATIC_LIBRARIES=yes \ WITH_DOCS=no \ WITH_FUZZING=yes \ WITH_EDITLINE=no \ WITH_HTTP_API=no \ -j $(nproc) ================================================ FILE: fuzzing/scripts/oss-fuzz-dependencies.sh ================================================ #!/bin/bash -eu # # Copyright (c) 2023 Cedalo GmbH # # 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. set -e # Note that sqlite3 is required as a build dep of a plugin which is not # currently part of fuzz testing. Once it is part of fuzz testing, sqlite will # need to be built statically. apt-get update && apt-get install -y \ cmake \ libargon2-dev \ libedit-dev \ liblzma-dev \ libmicrohttpd-dev \ libsqlite3-dev \ libtool-bin \ libz-dev \ make \ ninja-build \ pkg-config git clone https://github.com/ralight/cJSON ${SRC}/cJSON # If building outside of oss-fuzz, we need LPM if [ ! -d ${SRC}/LPM ]; then git clone https://github.com/google/libprotobuf-mutator ${SRC}/libprotobuf-mutator mkdir ${SRC}/LPM \ && cd ${SRC}/LPM \ && cmake ../libprotobuf-mutator -GNinja -DLIB_PROTO_MUTATOR_DOWNLOAD_PROTOBUF=ON -DLIB_PROTO_MUTATOR_TESTING=OFF -DCMAKE_BUILD_TYPE=Release \ && ninja fi ================================================ FILE: include/mosquitto/broker.h ================================================ /* Copyright (c) 2009-2021 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 #include #include enum mosquitto_protocol { mp_mqtt, mp_mqttsn, mp_websockets, mp_http_api, }; enum mosquitto_broker_msg_direction { mosq_bmd_in = 0, mosq_bmd_out = 1, mosq_bmd_all = 2, }; /* ========================================================================= * * Section: General structs * * ========================================================================= */ struct mosquitto_client { char *clientid; char *username; char *auth_method; time_t will_delay_time; time_t session_expiry_time; uint32_t will_delay_interval; uint32_t session_expiry_interval; uint32_t max_packet_size; uint16_t listener_port; uint8_t max_qos; bool retain_available; void *future2[8]; }; struct mosquitto_subscription { char *clientid; char *topic_filter; mosquitto_property *properties; uint32_t identifier; uint8_t options; uint8_t padding[3]; void *future2[8]; }; struct mosquitto_base_msg { uint64_t store_id; int64_t expiry_time; char *topic; void *payload; char *source_id; char *source_username; mosquitto_property *properties; uint32_t payloadlen; uint16_t source_mid; uint16_t source_port; uint8_t qos; bool retain; uint8_t padding[6]; void *future2[8]; }; struct mosquitto_client_msg { const char *clientid; uint64_t cmsg_id; uint64_t store_id; uint32_t subscription_identifier; uint16_t mid; uint8_t qos; bool retain; uint8_t dup; uint8_t direction; uint8_t state; uint8_t padding[5]; void *future2[8]; }; struct mosquitto_will_msg { const char *clientid; void *payload; char *topic; mosquitto_property *properties; uint32_t payloadlen; uint8_t qos; bool retain; }; /* ========================================================================= * * 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, // deprecated name MOSQ_EVT_MESSAGE_IN = 7, MOSQ_EVT_PSK_KEY = 8, MOSQ_EVT_TICK = 9, MOSQ_EVT_DISCONNECT = 10, MOSQ_EVT_CONNECT = 11, MOSQ_EVT_SUBSCRIBE = 12, MOSQ_EVT_UNSUBSCRIBE = 13, MOSQ_EVT_PERSIST_RESTORE = 14, MOSQ_EVT_PERSIST_BASE_MSG_ADD = 15, MOSQ_EVT_PERSIST_BASE_MSG_DELETE = 16, MOSQ_EVT_PERSIST_RETAIN_MSG_SET = 17, MOSQ_EVT_PERSIST_RETAIN_MSG_DELETE = 18, MOSQ_EVT_PERSIST_CLIENT_ADD = 19, MOSQ_EVT_PERSIST_CLIENT_DELETE = 20, MOSQ_EVT_PERSIST_CLIENT_UPDATE = 21, MOSQ_EVT_PERSIST_SUBSCRIPTION_ADD = 22, MOSQ_EVT_PERSIST_SUBSCRIPTION_DELETE = 23, MOSQ_EVT_PERSIST_CLIENT_MSG_ADD = 24, MOSQ_EVT_PERSIST_CLIENT_MSG_DELETE = 25, MOSQ_EVT_PERSIST_CLIENT_MSG_UPDATE = 26, MOSQ_EVT_MESSAGE_OUT = 27, MOSQ_EVT_CLIENT_OFFLINE = 28, MOSQ_EVT_PERSIST_WILL_ADD = 29, MOSQ_EVT_PERSIST_WILL_DELETE = 30, }; /* 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; union { void *future2[4]; struct { uint16_t password_len; }; }; }; /* 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; uint8_t padding; void *future2[4]; }; /* Data for the MOSQ_EVT_MESSAGE_IN and MOSQ_EVT_MESSAGE_OUT events */ 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; uint8_t padding; void *future2[4]; }; /* Data for the MOSQ_EVT_TICK event */ struct mosquitto_evt_tick { void *future; long now_ns; long next_ms; time_t now_s; time_t next_s; void *future2[4]; }; /* Data for the MOSQ_EVT_CONNECT event */ struct mosquitto_evt_connect { void *future; struct mosquitto *client; void *future2[4]; }; /* Data for the MOSQ_EVT_DISCONNECT event */ struct mosquitto_evt_disconnect { void *future; struct mosquitto *client; int reason; void *future2[4]; }; /* Data for the MOSQ_EVT_CLIENT_OFFLINE event */ struct mosquitto_evt_client_offline { void *future; struct mosquitto *client; int reason; void *future2[4]; }; /* Data for the MOSQ_EVT_SUBSCRIBE event */ struct mosquitto_evt_subscribe { void *future; struct mosquitto *client; struct mosquitto_subscription data; void *future2[8]; }; /* Data for the MOSQ_EVT_UNSUBSCRIBE event */ struct mosquitto_evt_unsubscribe { void *future; struct mosquitto *client; struct mosquitto_subscription data; void *future2[8]; }; /* Data for the MOSQ_EVT_PERSIST_RESTORE event */ /* NOTE: The persistence interface is currently marked as unstable, which means * it may change in a future minor release. */ struct mosquitto_evt_persist_restore { void *future[8]; }; /* Data for the MOSQ_EVT_PERSIST_CLIENT_ADD/_DELETE/_UPDATE event */ /* NOTE: The persistence interface is currently marked as unstable, which means * it may change in a future minor release. */ struct mosquitto_evt_persist_client { void *future; struct mosquitto_client data; void *future2[8]; }; /* Data for the MOSQ_EVT_PERSIST_SUBSCRIPTION_ADD/_DELETE event */ /* NOTE: The persistence interface is currently marked as unstable, which means * it may change in a future minor release. */ struct mosquitto_evt_persist_subscription { void *future; struct mosquitto_subscription data; void *future2[8]; }; /* Data for the MOSQ_EVT_PERSIST_CLIENT_MSG_ADD/_DELETE/_UPDATE event */ /* NOTE: The persistence interface is currently marked as unstable, which means * it may change in a future minor release. */ struct mosquitto_evt_persist_client_msg { void *future; struct mosquitto_client_msg data; void *future2[8]; }; /* Data for the MOSQ_EVT_PERSIST_BASE_MSG_ADD/_DELETE/_LOAD event */ /* NOTE: The persistence interface is currently marked as unstable, which means * it may change in a future minor release. */ struct mosquitto_evt_persist_base_msg { void *future; struct mosquitto_base_msg data; void *future2[8]; }; /* Data for the MOSQ_EVT_PERSIST_RETAIN_MSG_SET/_DELETE event */ /* NOTE: The persistence interface is currently marked as unstable, which means * it may change in a future minor release. */ struct mosquitto_evt_persist_retain_msg { void *future; const char *topic; uint64_t store_id; void *future2[8]; }; /* Data for the MOSQ_EVT_PERSIST_WILL_ADD/_DELETE */ /* NOTE: The persistence interface is currently marked as unstable, which means * it may change in a future minor release. */ struct mosquitto_evt_persist_will_msg { void *future; struct mosquitto_will_msg data; void *future2[8]; }; /* Callback definition */ typedef int (*MOSQ_FUNC_generic_callback)(int, void *, void *); typedef struct mosquitto_plugin_id_t mosquitto_plugin_id_t; /* * Function: mosquitto_plugin_set_info * * Set plugin name and version information for the broker to report. It is * recommended this is used in the mosquitto_plugin_init() call. */ mosq_EXPORT int mosquitto_plugin_set_info( mosquitto_plugin_id_t *identifier, const char *plugin_name, const char *plugin_version); /* * 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 * Called when the broker is sent a signal indicating it should * reload its configuration. * * MOSQ_EVT_ACL_CHECK * Called when a publish/subscribe/unsubscribe command is received * and the broker wants to check when the client is allowed to carry * out this command. * * MOSQ_EVT_BASIC_AUTH * Called when a client connects to the broker, to allow the * username/password/clientid to be authenticated. * * MOSQ_EVT_EXT_AUTH_START * Called when an MQTT v5 client connects, if it is using extended * authentication. * * MOSQ_EVT_EXT_AUTH_CONTINUE * Called when an MQTT v5 client connects, if it is using extended * authentication. * * MOSQ_EVT_CONTROL * Called on receipt of a $CONTROL message that the plugin has * registered for. * * MOSQ_EVT_MESSAGE_IN * Called for each incoming PUBLISH message after it has been received * and authorised. The contents of the message can be modified. * * MOSQ_EVT_MESSAGE_OUT * Called for each outgoing PUBLISH message after it has been authorised, * but before it is sent to each subscribing client. The contents of the * message can be modified. * * MOSQ_EVT_PSK_KEY * Called when a client connects with TLS-PSK and the broker needs * the PSK information. * * MOSQ_EVT_TICK * Called periodically by the broker. The next_s and next_ms * values of the event data can be used to set a minimum interval * that the broker will wait before calling the tick event again * for this callback. * * MOSQ_EVT_DISCONNECT * Called when a client disconnects from the broker. * * MOSQ_EVT_CONNECT * Called when a client has successfully connected to the broker, * i.e. has been authenticated. * * MOSQ_EVT_SUBSCRIBE * Called when a client has made a successful subscription * request, but before the subscription is applied. The * subscription request can be modified, although this is not * recommended. * * MOSQ_EVT_UNSUBSCRIBE * Called when a client has made a successful unsubscription * request, but before the unsubscription is applied. The * unsubscription request can be modified, although this is not * recommended. * * MOSQ_EVT_PERSIST_RESTORE * Called on startup when a persistence plugin should restore * persistence data. * * MOSQ_EVT_PERSIST_BASE_MSG_ADD * Called when a persistence plugin must add a base message to its * store. * * MOSQ_EVT_PERSIST_BASE_MSG_DELETE * Called when a persistence plugin must delete a base message * from its store. * * MOSQ_EVT_PERSIST_RETAIN_MSG_SET * Called when a persistence plugin must set or update a retained * message in its store. * * MOSQ_EVT_PERSIST_RETAIN_MSG_DELETE * Called when a persistence plugin must delete a retained message * from its store. * * MOSQ_EVT_PERSIST_CLIENT_ADD * Called when a persistence plugin must add a client session to * its store. * * MOSQ_EVT_PERSIST_CLIENT_DELETE * Called when a persistence plugin must delete a client session * from its store. * * MOSQ_EVT_PERSIST_CLIENT_UPDATE * Called when a persistence plugin must update a client session * in its store. * * MOSQ_EVT_PERSIST_SUBSCRIPTION_ADD * Called when a persistence plugin must add a client subscription * to its store. * * MOSQ_EVT_PERSIST_SUBSCRIPTION_DELETE * Called when a persistence plugin must delete a client * subscription from its store. * * MOSQ_EVT_PERSIST_CLIENT_MSG_ADD * Called when a persistence plugin must add a client message to * its store. * * MOSQ_EVT_PERSIST_CLIENT_MSG_DELETE * Called when a persistence plugin must delete a client message * from its store. * * MOSQ_EVT_PERSIST_CLIENT_MSG_UPDATE * Called when a persistence plugin must update a client message * in its store. * * 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_IN * * MOSQ_EVT_MESSAGE_OUT * * MOSQ_EVT_PSK_KEY * * MOSQ_EVT_TICK * * MOSQ_EVT_DISCONNECT * * MOSQ_EVT_CONNECT * * MOSQ_EVT_SUBSCRIBE * * MOSQ_EVT_UNSUBSCRIBE * * MOSQ_EVT_PERSIST_RESTORE * * MOSQ_EVT_PERSIST_BASE_MSG_ADD * * MOSQ_EVT_PERSIST_BASE_MSG_DELETE * * MOSQ_EVT_PERSIST_RETAIN_MSG_SET * * MOSQ_EVT_PERSIST_RETAIN_MSG_DELETE * * MOSQ_EVT_PERSIST_CLIENT_ADD * * MOSQ_EVT_PERSIST_CLIENT_DELETE * * MOSQ_EVT_PERSIST_CLIENT_UPDATE * * MOSQ_EVT_PERSIST_SUBSCRIPTION_ADD * * MOSQ_EVT_PERSIST_SUBSCRIPTION_DELETE * * MOSQ_EVT_PERSIST_CLIENT_MSG_ADD * * MOSQ_EVT_PERSIST_CLIENT_MSG_DELETE * * MOSQ_EVT_PERSIST_CLIENT_MSG_UPDATE * 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: 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 * * Retrieve the struct mosquitto for a client id, or NULL if the client is not connected. */ mosq_EXPORT struct mosquitto *mosquitto_client(const char *clientid); /* * 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_port * * Retrieve the network port number the client connected to, or 0 on error. */ mosq_EXPORT int mosquitto_client_port(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_id_hashv * * Retrieve the hash value associated with a client id. */ mosq_EXPORT unsigned mosquitto_client_id_hashv(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); /* Function: mosquitto_set_clientid * * Set the client id for a client. * * This effectively forces the client onto another message queue. * Can be used to scope client ids by prefixing the client id with some user-specific data. * eg. "client1" could become "user1-client1". * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if client is NULL, or if clientid is not a valid utf-8 string * MOSQ_ERR_NOMEM - on out of memory */ mosq_EXPORT int mosquitto_set_clientid(struct mosquitto *client, const char *clientid); /* ========================================================================= * * 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); /* Function: mosquitto_apply_on_all_clients * * Apply a given functor to all clients * * The functor will be applied to all existing client structures. If the functor * returns an error code the iteration over the clients will be stopped. The * functor_context pointer maybe used to pass additional data structures into * the functor as second argument. * * The result value will be the result of the last functor invoked. */ mosq_EXPORT int mosquitto_apply_on_all_clients(int (*FUNC_client_functor)(const struct mosquitto *, void *), void *functor_context); /* ========================================================================= * * 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); /* Function: mosquitto_complete_basic_auth * * Complete a delayed authentication request. * * Useful for plugins that subscribe to the MOSQ_EVT_BASIC_AUTH event. If your * plugin makes authentication requests that are not "instant", in particular * if they communicate with an external service, then instead of blocking for a * reply and returning MOSQ_ERR_SUCCESS or MOSQ_ERR_AUTH, the plugin can return * MOSQ_ERR_AUTH_DELAYED. This means that the plugin is promising to tell the * broker the authentication result in the future. Once the plugin has an * answer, it should call `mosquitto_complete_basic_auth()` passing the client * id and the result. * * Result: * MOSQ_ERR_SUCCESS - the client successfully authenticated * MOSQ_ERR_AUTH - the client authentication failed * * Other error codes can be used if more appropriate, and the client connection * will still be rejected, e.g. MOSQ_ERR_NOMEM. * * The plugin may use extra threads to handle the authentication requests, but * the call to `mosquitto_complete_basic_auth()` must happen in the main * mosquitto thread. Using the MOSQ_EVT_TICK event for this is suggested. */ mosq_EXPORT void mosquitto_complete_basic_auth(const char *clientid, int result); /* Function: mosquitto_broker_node_id_set * * Set a node ID for this broker between 0-1023 inclusive. This is used to help * generate unique client message IDs and hence can be useful for persistence * plugins where brokers are sharing a database. It is down to the plugin to ensure * this ID is unique. * * Result: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - the value was > 1023. */ mosq_EXPORT int mosquitto_broker_node_id_set(uint16_t id); /* ================================================================= * * Persistence interface * * ================================================================= */ /* NOTE: The persistence interface is currently marked as unstable, which means * it may change in a future minor release. */ /* Function: mosquitto_persist_client_add * * Use to add a new client session, in particular when restoring on starting * the broker. * * Parameters: * client->clientid - the client id of the client to add. * This must be allocated on the heap and becomes the property of the * broker immediately this call is made. Must not be NULL. * client->username - the username for the client session, or NULL. Must * be allocated on the heap and becomes the property of the broker * immediately this call is made. * client->auth_method - the MQTT v5 extended authentication method, * or NULL. Must be allocated on the heap and becomes the property of * the broker immediately this call is made. * client->will_delay_time - the actual will delay time for this client * client->session_expiry_time - the actual session expiry time for this * client * client->will_delay_interval - the MQTT v5 will delay interval for this * client * client->maximum_packet_size - the MQTT v5 maximum packet size parameter * for this client * client->listener_port - the listener port that this client last connected to * client->max_qos - the MQTT v5 maximum QoS parameter for this client * client->retain_available - the MQTT v5 retain available parameter for this * client * * All other members of struct mosquitto_client are unused. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if client or client->plugin_clientid is NULL, or if a * client with the same ID already exists. * MOSQ_ERR_NOMEM - on out of memory */ mosq_EXPORT int mosquitto_persist_client_add(struct mosquitto_client *client); /* Function: mosquitto_persist_client_update * * Use to update client session parameters * * Parameters: * client->clientid - the client id of the client to update * The broker will *not* modify this string and it remains the * property of the plugin. * client->username - the new username for the client session, or NULL. Must * be allocated on the heap and becomes the property of the broker * immediately this call is made. * client->will_delay_time - the actual will delay time for this client * client->session_expiry_time - the actual session expiry time for this * client * client->will_delay_interval - the MQTT v5 will delay interval for this * client * client->maximum_packet_size - the MQTT v5 maximum packet size parameter * for this client * client->listener_port - the listener port that this client last connected to * client->max_qos - the MQTT v5 maximum QoS parameter for this client * client->retain_available - the MQTT v5 retain available parameter for this * client * * All other members of struct mosquitto_client are unused. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if client or client->clientid is NULL * MOSQ_ERR_NOT_FOUND - the client is not found */ mosq_EXPORT int mosquitto_persist_client_update(struct mosquitto_client *client); /* Function: mosquitto_persist_client_delete * * Use to delete client session for a client from the broker * * Parameters: * clientid - the client id of the client to delete * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if clientid is NULL * MOSQ_ERR_NOT_FOUND - the referenced client is not found */ mosq_EXPORT int mosquitto_persist_client_delete(const char *clientid); /* Function: mosquitto_persist_client_msg_add * * Use to add a client message for a particular client. * * Parameters: * client_msg->clientid - the client id of the client that the * message belongs to. * client_msg->cmsg_id - the ID of this client message. * client_msg->store_id - the ID of the base message that this client * message references. * client_msg->subscription_identifier - the MQTT v5 subscription identifier, * for outgoing messages only. * client_msg->mid - the MQTT message ID of the new message * client_msg->qos - the MQTT QoS of the new message * client_msg->retain - the retain flag of the message * client_msg->dup - the dup flag of the message * client_msg->direction - the direction of the new message from the perspective * of the broker (mosq_bmd_in / mosq_bmd_out) * client_msg->state - the current message state * * All other members of struct mosquitto_client_msg are unused. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if client_msg or client_msg->plugin_clientid is NULL * MOSQ_ERR_NOT_FOUND - the client or base message is not found */ mosq_EXPORT int mosquitto_persist_client_msg_add(struct mosquitto_client_msg *client_msg); /* Function: mosquitto_persist_client_msg_delete * * Use to delete a client message for a particular client. * * Parameters: * client_msg->clientid - the client id of the client that the * message belongs to. * client_msg->cmsg_id - the client message id of the affected message * client_msg->mid - the MQTT message id of the affected message * client_msg->qos - the MQTT QoS of the affected message * client_msg->direction - the direction of the message from the perspective * of the broker (mosq_bmd_in / mosq_bmd_out) * * All other members of struct mosquitto_client_msg are unused. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if client_msg or client_msg->clientid is NULL * MOSQ_ERR_NOT_FOUND - the client is not found */ mosq_EXPORT int mosquitto_persist_client_msg_delete(struct mosquitto_client_msg *client_msg); /* Function: mosquitto_persist_client_msg_update * * Use to update the state of a client message for a particular client. * * Parameters: * client_msg->clientid - the client id of the client that the * message belongs to. * client_msg->cmsg_id - the client message id of the affected message * client_msg->mid - the MQTT message id of the affected message * client_msg->qos - the MQTT QoS of the affected message * client_msg->direction - the direction of the message from the perspective * of the broker (mosq_bmd_in / mosq_bmd_out) * client_msg->state - the new state of the message * * All other members of struct mosquitto_client_msg are unused. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if client_msg or client_msg->clientid is NULL * MOSQ_ERR_NOT_FOUND - the client is not found */ mosq_EXPORT int mosquitto_persist_client_msg_update(struct mosquitto_client_msg *client_msg); /* Function: mosquitto_persist_client_msg_clear * * Clear all messages for the listed client and direction. * * Parameters: * client_msg->clientid - the client id of the client that the * message belongs to. * client_msg->direction - the direction of the messages to be cleared, from * the perspective of the broker (mosq_bmd_in / mosq_bmd_out / mosq_bmd_all) * * All other members of struct mosquitto_client_msg are unused. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if client_msg or client_msg->clientid is NULL * MOSQ_ERR_NOT_FOUND - the client is not found */ mosq_EXPORT int mosquitto_persist_client_msg_clear(struct mosquitto_client_msg *client_msg); /* Function: mosquitto_persist_base_msg_add * * Use to add a new base message. Any client messages or retained messages * refering to this base message must be added afterwards. * * Parameters: * msg->store_id - the base message ID * msg->expiry_time - the time at which the message expires, or 0. * msg->topic - the message topic. * Must be allocated on the heap and becomes the property of the * broker immediately this call is made. * msg->payload - the message payload. * Must be allocated on the heap and becomes the property of the * broker immediately this call is made. * msg->source_id - the client id of the client that the * message originated with, or NULL. * The broker will *not* modify this string and it remains the * property of the plugin. * msg->source_username - the username of the client that the * message originated with, or NULL. * The broker will *not* modify this string and it remains the * property of the plugin. * msg->properties - list of MQTT v5 message properties for this message. * Must be allocated on the heap and becomes the property of the * broker immediately this call is made. * msg->payloadlen - the length of the payload, in bytes * msg->source_mid - the mid of the source message * msg->source_port - the network port number that the originating client was * connected to, or 0. * msg->qos - the message QoS as delivered to the broker * msg->retain - the message retain flag as delivered to the broker * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_NOMEM - on out of memory */ mosq_EXPORT int mosquitto_persist_base_msg_add(struct mosquitto_base_msg *msg); /* Function: mosquitto_persist_base_msg_delete * * Use to delete a base message. * * Parameters: * store_id - the base message ID * * Returns: * MOSQ_ERR_SUCCESS - on success */ mosq_EXPORT int mosquitto_persist_base_msg_delete(uint64_t store_id); /* Function: mosquitto_persist_subscription_add * * Use to add a new subscription for a client * * Parameters: * sub->clientid - the client id of the client the new subscription is for * sub->topic_filter - the topic filter for the subscription * sub->options - the QoS and other flags for this subscription * sub->identifier - the MQTT v5 subscription id, or 0 * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if sub, clientid, or topic_filter are NULL, or are zero length * MOSQ_ERR_NOT_FOUND - the referenced client was not found * MOSQ_ERR_NOMEM - on out of memory */ mosq_EXPORT int mosquitto_subscription_add(const struct mosquitto_subscription *sub); /* Function: mosquitto_persist_subscription_delete * * Use to delete a subscription for a client * * Parameters: * clientid - the client id of the client the new subscription is for * topic_filter - the topic filter for the subscription * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if clientid or topic are NULL, or are zero length * MOSQ_ERR_NOT_FOUND - the referenced client was not found * MOSQ_ERR_NOMEM - on out of memory */ mosq_EXPORT int mosquitto_subscription_delete(const char *clientid, const char *topic_filter); /* Function: mosquitto_persist_retain_msg_set * * Use to set a retained message. It is not required to delete a retained * message for an existing topic first. * * Parameters: * topic - the topic that the message references * store_id - the ID of the base message that is to be retained * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if topic is NULL * MOSQ_ERR_NOT_FOUND - the referenced base message was not found * MOSQ_ERR_NOMEM - on out of memory */ mosq_EXPORT int mosquitto_persist_retain_msg_set(const char *topic, uint64_t store_id); /* Function: mosquitto_persist_retain_msg_delete * * Use to delete a retained message. * * Parameters: * topic - the topic that the message references * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if topic is NULL * MOSQ_ERR_NOMEM - on out of memory */ mosq_EXPORT int mosquitto_persist_retain_msg_delete(const char *topic); /* Function: mosquitto_persistence_location * * Returns the `persistence_location` config option, or the contents of the * MOSQUITTO_PERSISTENCE_LOCATION environment variable, if set. * * This location should be used by plugins needing to store persistent data. * Use of sub directories is recommended. * * Returns: * A valid pointer to the persistence location string * A NULL pointer if neither the option nor the variable are set */ mosq_EXPORT const char *mosquitto_persistence_location(void); /* Function: mosquitto_client_will_set * * Set a will message for the client. * * Parameters: * clientid - clientid of the sesion to set the will message for. * 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. The payload will be copied. * 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. The property list * becomes the property of the broker and will be freed by the * broker, if the function call was successfull. * * Returns: * MOSQ_ERR_SUCCESS - on success. * MOSQ_ERR_NOT_FOUND - if the client is not found. * 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_EXPORT int mosquitto_client_will_set(const char *clientid, const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/broker_control.h ================================================ /* Copyright (c) 2009-2021 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_control.h * * This header contains functions for use by plugins using the CONTROL event. */ #ifndef MOSQUITTO_BROKER_CONTROL_H #define MOSQUITTO_BROKER_CONTROL_H #ifdef __cplusplus extern "C" { #endif #include #include #include #include /* ========================================================================= * * Section: $CONTROL event helpers * * ========================================================================= */ struct mosquitto_control_cmd { struct mosquitto *client; cJSON *j_responses; cJSON *j_command; char *correlation_data; const char *command_name; }; mosq_EXPORT void mosquitto_control_command_reply(struct mosquitto_control_cmd *cmd, const char *error); mosq_EXPORT void mosquitto_control_send_response(cJSON *tree, const char *topic); mosq_EXPORT int mosquitto_control_generic_callback(struct mosquitto_evt_control *event_data, const char *response_topic, void *userdata, int (*cmd_cb)(struct mosquitto_control_cmd *cmd, void *userdata)); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/broker_plugin.h ================================================ /* Copyright (c) 2012-2021 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_BROKER_PLUGIN_H #define MOSQUITTO_BROKER_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 #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 * */ /* ========================================================================= * * 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. * * HELPER: If you only wish to declare support for a single version, you can * use the helper macro: * * MOSQUITTO_PLUGIN_DECLARE_VERSION(5); */ mosq_plugin_EXPORT int mosquitto_plugin_version(int supported_version_count, const int *supported_versions); #define MOSQUITTO_PLUGIN_DECLARE_VERSION(A) \ int mosquitto_plugin_version(int supported_version_count, const int *supported_versions) \ { \ int i; \ for(i=0; i * 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. * * If you do not need to do any of your own cleanup, this function is not * required. The broker will automatically unregister your callbacks. * * 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. * * 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. * ========================================================================= */ /* * 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 ================================================ FILE: include/mosquitto/defs.h ================================================ /* Copyright (c) 2010-2021 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_DEFS_H #define MOSQUITTO_DEFS_H /* * File: mosquitto/defs.h * * This header contains defines and enums used by the mosquitto broker and * libmosquitto, the Mosquitto client library. */ #ifdef __cplusplus extern "C" { #endif #include /* 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 /* Enum: mosq_err_t * Integer values returned from many libmosquitto functions. */ enum mosq_err_t { MOSQ_ERR_QUOTA_EXCEEDED = -6, MOSQ_ERR_AUTH_DELAYED = -5, 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, /* 28, 29, 30 - was internal only, moved to MQTT v5 section. */ MOSQ_ERR_ALREADY_EXISTS = 31, MOSQ_ERR_PLUGIN_IGNORE = 32, MOSQ_ERR_HTTP_BAD_ORIGIN = 33, /* MQTT v5 direct equivalents 128-255 */ MOSQ_ERR_UNSPECIFIED = 128, /* MOSQ_ERR_MALFORMED_PACKET = 129, // 21 above */ MOSQ_ERR_IMPLEMENTATION_SPECIFIC = 131, MOSQ_ERR_UNSUPPORTED_PROTOCOL_VERSION = 132, MOSQ_ERR_CLIENT_IDENTIFIER_NOT_VALID = 133, MOSQ_ERR_BAD_USERNAME_OR_PASSWORD = 134, /* MOSQ_ERR_NOT_AUTHORIZED = 135, // 11 above */ MOSQ_ERR_SERVER_UNAVAILABLE = 136, MOSQ_ERR_SERVER_BUSY = 137, MOSQ_ERR_BANNED = 138, MOSQ_ERR_SERVER_SHUTTING_DOWN = 139, MOSQ_ERR_BAD_AUTHENTICATION_METHOD = 140, /* MOSQ_ERR_KEEP_ALIVE_TIMEOUT = 141, // 19 above */ MOSQ_ERR_SESSION_TAKEN_OVER = 142, MOSQ_ERR_TOPIC_FILTER_INVALID = 143, MOSQ_ERR_TOPIC_NAME_INVALID = 144, MOSQ_ERR_PACKET_ID_IN_USE = 145, MOSQ_ERR_PACKET_ID_NOT_FOUND = 146, MOSQ_ERR_RECEIVE_MAXIMUM_EXCEEDED = 147, MOSQ_ERR_TOPIC_ALIAS_INVALID = 148, /* MOSQ_ERR_PACKET_TOO_LARGE = 149, // 25 above */ MOSQ_ERR_MESSAGE_RATE_TOO_HIGH = 150, /* MOSQ_ERR_QUOTA_EXCEEDED = 151, */ MOSQ_ERR_ADMINISTRATIVE_ACTION = 152, MOSQ_ERR_PAYLOAD_FORMAT_INVALID = 153, MOSQ_ERR_RETAIN_NOT_SUPPORTED = 154, /* MOSQ_ERR_QOS_NOT_SUPPORTED = 155, // 24 above */ MOSQ_ERR_USE_ANOTHER_SERVER = 156, MOSQ_ERR_SERVER_MOVED = 157, MOSQ_ERR_SHARED_SUBS_NOT_SUPPORTED = 158, MOSQ_ERR_CONNECTION_RATE_EXCEEDED = 159, MOSQ_ERR_MAXIMUM_CONNECT_TIME = 160, MOSQ_ERR_SUBSCRIPTION_IDS_NOT_SUPPORTED = 161, MOSQ_ERR_WILDCARD_SUBS_NOT_SUPPORTED = 162, }; enum mosq_transport_t { MOSQ_T_TCP = 1, MOSQ_T_WEBSOCKETS = 2, }; /* 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; typedef struct mqtt5__property mosquitto_property; #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon.h ================================================ /* Copyright (c) 2010-2021 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_LIBCOMMON_H #define MOSQUITTO_LIBCOMMON_H /* * File: mosquitto/libcommon.h */ #ifdef __cplusplus extern "C" { #endif #ifdef WIN32 # ifdef libmosquitto_common_EXPORTS # define libmosqcommon_EXPORT __declspec(dllexport) # else # define libmosqcommon_EXPORT __declspec(dllimport) # endif #else # define libmosqcommon_EXPORT #endif #include #include #include #include #include #include #include #include #include #include #include #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon_base64.h ================================================ /* Copyright (c) 2010-2021 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_LIBCOMMON_BASE64_H #define MOSQUITTO_LIBCOMMON_BASE64_H /* * File: mosquitto/libcommon_base64.h * * This header contains functions for handling base64 */ #ifdef __cplusplus extern "C" { #endif libmosqcommon_EXPORT int mosquitto_base64_encode(const unsigned char *in, size_t in_len, char **encoded); libmosqcommon_EXPORT int mosquitto_base64_decode(const char *in, unsigned char **decoded, unsigned int *decoded_len); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon_cjson.h ================================================ /* Copyright (c) 2010-2021 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_LIBCOMMON_CJSON_H #define MOSQUITTO_LIBCOMMON_CJSON_H /* * File: mosquitto/libcommon_cjson.h * * This header contains functions for handling cJSON objects */ #ifdef __cplusplus extern "C" { #endif #include libmosqcommon_EXPORT cJSON *mosquitto_properties_to_json(const mosquitto_property *properties); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon_file.h ================================================ /* Copyright (c) 2010-2021 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_LIBCOMMON_FILE_H #define MOSQUITTO_LIBCOMMON_FILE_H #include #include #include /* * File: mosquitto/libcommon_file.h * * This header contains functions and definitions for reading/writing files. */ #ifdef __cplusplus extern "C" { #endif /* * Function: mosquitto_fopen */ libmosqcommon_EXPORT FILE *mosquitto_fopen(const char *path, const char *mode, bool restrict_read); /* * Function: mosquitto_fgets */ libmosqcommon_EXPORT char *mosquitto_fgets(char **buf, int *buflen, FILE *stream); /* * Function: mosquitto_write_file */ libmosqcommon_EXPORT int mosquitto_write_file(const char *target_path, bool restrict_read, int (*write_fn)(FILE *fptr, void *user_data), void *user_data, void (*log_fn)(const char *msg)); /* * Function: mosquitto_read_file */ libmosqcommon_EXPORT int mosquitto_read_file(const char *file, bool restrict_read, char **buf, size_t *buflen); /* * Function: mosquitto_trimblanks * * Removes blanks from the end of a string. */ libmosqcommon_EXPORT char *mosquitto_trimblanks(char *str); libmosqcommon_EXPORT extern void (*libcommon_vprintf)(const char *fmt, va_list va); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon_memory.h ================================================ /* Copyright (c) 2010-2021 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_LIBCOMMON_MEMORY_H #define MOSQUITTO_LIBCOMMON_MEMORY_H /* * File: mosquitto/libcommon_memory.h * * This header contains functions and definitions for allocating and freeing * memory in broker plugins */ #ifdef __cplusplus extern "C" { #endif /* ========================================================================= * * 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 */ libmosqcommon_EXPORT void *mosquitto_calloc(size_t nmemb, size_t size); /* * Function: mosquitto_free */ libmosqcommon_EXPORT void mosquitto_free(void *mem); /* * Function: mosquitto_malloc */ libmosqcommon_EXPORT void *mosquitto_malloc(size_t size); /* * Function: mosquitto_realloc */ libmosqcommon_EXPORT void *mosquitto_realloc(void *ptr, size_t size); /* * Function: mosquitto_strdup */ libmosqcommon_EXPORT char *mosquitto_strdup(const char *s); /* * Function: mosquitto_strndup */ libmosqcommon_EXPORT char *mosquitto_strndup(const char *s, size_t n); libmosqcommon_EXPORT void mosquitto_memory_set_limit(size_t lim); libmosqcommon_EXPORT unsigned long mosquitto_memory_used(void); libmosqcommon_EXPORT unsigned long mosquitto_max_memory_used(void); #define mosquitto_FREE(A) do{ mosquitto_free(A); (A) = NULL;}while(0) #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon_password.h ================================================ /* Copyright (c) 2010-2021 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_LIBCOMMON_PASSWORD_H #define MOSQUITTO_LIBCOMMON_PASSWORD_H /* * File: mosquitto/libcommon_password.h */ #ifdef __cplusplus extern "C" { #endif enum mosquitto_pwhash_type { MOSQ_PW_DEFAULT, MOSQ_PW_SHA512 = 6, MOSQ_PW_SHA512_PBKDF2 = 7, MOSQ_PW_ARGON2ID = 8, }; enum mosquitto_pw_params { MOSQ_PW_PARAM_ITERATIONS = 1, }; struct mosquitto_pw; libmosqcommon_EXPORT void mosquitto_pw_set_valid(struct mosquitto_pw *pw, bool valid); libmosqcommon_EXPORT bool mosquitto_pw_is_valid(struct mosquitto_pw *pw); libmosqcommon_EXPORT int mosquitto_pw_new(struct mosquitto_pw **pw, enum mosquitto_pwhash_type hashtype); libmosqcommon_EXPORT void mosquitto_pw_cleanup(struct mosquitto_pw *pw); libmosqcommon_EXPORT int mosquitto_pw_hash_encoded(struct mosquitto_pw *pw, const char *password); libmosqcommon_EXPORT const char *mosquitto_pw_get_encoded(struct mosquitto_pw *pw); libmosqcommon_EXPORT int mosquitto_pw_verify(struct mosquitto_pw *pw, const char *password); libmosqcommon_EXPORT int mosquitto_pw_set_param(struct mosquitto_pw *pw, int param, int value); libmosqcommon_EXPORT int mosquitto_pw_decode(struct mosquitto_pw *pw, const char *encoded_password); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon_properties.h ================================================ /* Copyright (c) 2010-2021 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_LIBCOMMON_PROPERTIES_H #define MOSQUITTO_LIBCOMMON_PROPERTIES_H #ifdef __cplusplus extern "C" { #endif /* ============================================================================= * * 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); */ libmosqcommon_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); */ libmosqcommon_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); */ libmosqcommon_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); */ libmosqcommon_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); */ libmosqcommon_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"); */ libmosqcommon_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 - MQTT property identifier (e.g. MQTT_PROP_USER_PROPERTY from ) * 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"); */ libmosqcommon_EXPORT int mosquitto_property_add_string_pair(mosquitto_property **proplist, int identifier, const char *name, const char *value); /* * Function: mosquitto_property_remove * * Remove a property from a property list. The property will not be freed. * * Parameters: * proplist - pointer to mosquitto_property pointer, the list of properties * property - pointer to the property to remove * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if proplist is NULL or property is NULL * MOSQ_ERR_NOT_FOUND - if the property was not found */ libmosqcommon_EXPORT int mosquitto_property_remove(mosquitto_property **proplist, const mosquitto_property *property); /* * 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 */ libmosqcommon_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. */ libmosqcommon_EXPORT 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) */ libmosqcommon_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 */ libmosqcommon_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 */ libmosqcommon_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 */ libmosqcommon_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. * Will be set to NULL if the value has zero length. * 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 */ libmosqcommon_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. * Will be set to NULL if the value has zero length. * 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 */ libmosqcommon_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. * Will be set to NULL if the name has zero length. * value - pointer to char*, for the property data to be stored in, or NULL if * the value is not required. * Will be set to NULL if the value has zero length. * 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 */ libmosqcommon_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_type * * Return the property type for a single property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * A valid property type on success * 0 - on error */ libmosqcommon_EXPORT int mosquitto_property_type(const mosquitto_property *property); /* * Function: mosquitto_property_byte_value * * Return the property value for a byte type property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * Byte value on success * 0 - on error (property is NULL, or not a byte) */ libmosqcommon_EXPORT uint8_t mosquitto_property_byte_value(const mosquitto_property *property); /* * Function: mosquitto_property_int16_value * * Return the property value for an int16 type property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * Int16 value on success * 0 - on error (property is NULL, or not a int16) */ libmosqcommon_EXPORT uint16_t mosquitto_property_int16_value(const mosquitto_property *property); /* * Function: mosquitto_property_int32_value * * Return the property value for an int32 type property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * Int32 value on success * 0 - on error (property is NULL, or not a int32) */ libmosqcommon_EXPORT uint32_t mosquitto_property_int32_value(const mosquitto_property *property); /* * Function: mosquitto_property_varint_value * * Return the property value for a varint type property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * Varint value on success * 0 - on error (property is NULL, or not a varint) */ libmosqcommon_EXPORT uint32_t mosquitto_property_varint_value(const mosquitto_property *property); /* * Function: mosquitto_property_binary_value * * Return the property value for a binary type property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * Binary value on success * NULL - on error (property is NULL, or not a binary) */ libmosqcommon_EXPORT const void *mosquitto_property_binary_value(const mosquitto_property *property); /* * Function: mosquitto_property_byte_value_length * * Return the property value for a byte type property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * Binary value length on success * 0 - on error (property is NULL, or not a binary) */ libmosqcommon_EXPORT uint16_t mosquitto_property_binary_value_length(const mosquitto_property *property); /* * Function: mosquitto_property_string_value * * Return the property value for a string or string pair type property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * String value on success * NULL - on error (property is NULL, or not a string or string pair) */ libmosqcommon_EXPORT const char *mosquitto_property_string_value(const mosquitto_property *property); /* * Function: mosquitto_property_string_value_length * * Return the length of the property value for a string or string pair type property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * Value length on success * 0 - on error (property is NULL, or not a string or string pair) */ libmosqcommon_EXPORT uint16_t mosquitto_property_string_value_length(const mosquitto_property *property); /* * Function: mosquitto_property_string_value * * Return the property name for a string pair type property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * String name on success * NULL - on error (property is NULL, or not a string pair) */ libmosqcommon_EXPORT const char *mosquitto_property_string_name(const mosquitto_property *property); /* * Function: mosquitto_property_string_name_length * * Return the property name length for a string pair type property. * * Parameters: * property - pointer to a valid mosquitto_property pointer. * * Returns: * Name length on success * 0 - on error (property is NULL, or not a string pair) */ libmosqcommon_EXPORT uint16_t mosquitto_property_string_name_length(const mosquitto_property *property); /* * 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); */ libmosqcommon_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) */ libmosqcommon_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 identifier (e.g. MQTT_PROP_USER_PROPERTY from ) * * Returns: * MOSQ_ERR_SUCCESS - if the identifier is valid for command * MOSQ_ERR_PROTOCOL - if the identifier is not valid for use with command. */ libmosqcommon_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 */ libmosqcommon_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 - MQTT property identifier (e.g. MQTT_PROP_USER_PROPERTY from ) * * Returns: * A const string to the property name on success * NULL on failure */ libmosqcommon_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) */ libmosqcommon_EXPORT int mosquitto_string_to_property_info(const char *propname, int *identifier, int *type); libmosqcommon_EXPORT void mosquitto_property_free(mosquitto_property **property); libmosqcommon_EXPORT unsigned int mosquitto_property_get_length(const mosquitto_property *property); libmosqcommon_EXPORT unsigned int mosquitto_property_get_length_all(const mosquitto_property *property); libmosqcommon_EXPORT unsigned int mosquitto_property_get_remaining_length(const mosquitto_property *props); libmosqcommon_EXPORT unsigned int mosquitto_varint_bytes(uint32_t word); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon_random.h ================================================ /* Copyright (c) 2010-2021 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_LIBCOMMON_RANDOM_H #define MOSQUITTO_LIBCOMMON_RANDOM_H /* * File: mosquitto/libcommon_random.h * * This header contains functions for obtaining random numbers. */ #ifdef __cplusplus extern "C" { #endif /* * Function: mosquitto_getrandom * * Get random bytes. * * Parameters: * bytes - a buffer to store the random bytes, at least count bytes long. * count - the number or bytes to retrieve * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_UNKNOWN - if an error occurred */ libmosqcommon_EXPORT int mosquitto_getrandom(void *bytes, int count); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon_string.h ================================================ /* Copyright (c) 2010-2021 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_LIBCOMMON_STRING_H #define MOSQUITTO_LIBCOMMON_STRING_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 /* * 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. */ libmosqcommon_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. */ libmosqcommon_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. */ libmosqcommon_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) */ libmosqcommon_EXPORT int mosquitto_string_to_command(const char *str, int *cmd); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon_time.h ================================================ #ifndef LIBMOSQUITTO_COMMON_TIME_H #define LIBMOSQUITTO_COMMON_TIME_H #ifdef __cplusplus extern "C" { #endif #include /* Function: mosquitto_time_init * * Initialises the time source to use the best source available at run time. */ libmosqcommon_EXPORT void mosquitto_time_init(void); /* Function: mosquitto_time * * Returns an indication of the current time in seconds. The exact type of * value varies depending on the platform in use, but in most cases will be a * monotonically increasing value that does not relate to the real clock time. * * Returns: * Indication of the current time, in seconds */ libmosqcommon_EXPORT time_t mosquitto_time(void); /* Function: mosquitto_time_ns * * Returns the current clock time in seconds and nanoseconds. The resolution of * the nanosecond value varies depending on the platform in use. * * The value returned may be decrease as well as increase in response to system * clock changes. * * Parameters: * s - the output pointer for the number of seconds * ns - the output pointer for the number of nanoseconds */ libmosqcommon_EXPORT void mosquitto_time_ns(time_t *s, long *ns); /* Function: mosquitto_time_cmp * * Returns < 0 if the time t1 is smaller (earlier) than t2 * Returns > 0 if the time t1 is greater (later) than t2 * Returns == 0 if the time t1 is exactly equal to t2 */ libmosqcommon_EXPORT long mosquitto_time_cmp(time_t t1_s, long t1_ns, time_t t2_s, long t2_ns); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon_topic.h ================================================ /* Copyright (c) 2010-2021 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_LIBCOMMON_TOPIC_H #define MOSQUITTO_LIBCOMMON_TOPIC_H /* * File: mosquitto/libcommon_topic.h * * This header contains functions and definitions for checking and manipulating topic strings. */ #ifdef __cplusplus extern "C" { #endif /* * 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: * */ libmosqcommon_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: * */ libmosqcommon_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. */ libmosqcommon_EXPORT int mosquitto_topic_matches_sub(const char *sub, const char *topic, bool *result); /* * Function: mosquitto_topic_matches_sub2 * * Identical to . The sublen and topiclen * parameters are *IGNORED*. */ libmosqcommon_EXPORT int mosquitto_topic_matches_sub2(const char *sub, size_t sublen, const char *topic, size_t topiclen, bool *result); /* * Function: mosquitto_topic_matches_sub_with_pattern * * Check whether a topic matches a subscription, with client id/username * pattern substitution. * * Any instances of a subscriptions hierarchy that are exactly %c or %u will be * replaced with the client id or username respectively. * * For example: * * mosquitto_topic_matches_sub_with_pattern("sensors/%c/temperature", "sensors/kitchen/temperature", "kitchen", NULL, &result) * -> this will match * * mosquitto_topic_matches_sub_with_pattern("sensors/%c/temperature", "sensors/bathroom/temperature", "kitchen", NULL, &result) * -> this will not match * * mosquitto_topic_matches_sub_with_pattern("sensors/%count/temperature", "sensors/kitchen/temperature", "kitchen", NULL, &result) * -> this will not match - the `%count` is not treated as a pattern * * mosquitto_topic_matches_sub_with_pattern("%c/%c/%u/%u", "kitchen/kitchen/bathroom/bathroom", "kitchen", "bathroom", &result) * -> this will match * * Parameters: * sub - subscription string to check topic against. * topic - topic to check. * clientid - client id to substitute in patterns. If NULL, then any %c patterns will not match. * username - username to substitute in patterns. If NULL, then any %u patterns will not match. * 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. */ libmosqcommon_EXPORT int mosquitto_topic_matches_sub_with_pattern(const char *sub, const char *topic, const char *clientid, const char *username, bool *result); /* * Function: mosquitto_sub_matches_acl * * Check whether a subscription matches an ACL topic filter * * For example: * * The subscription $SYS/broker/# would match against the ACL $SYS/# * The subscription $SYS/broker/# would not match against the ACL $SYS/broker/uptime * * Parameters: * acl - topic filter string to check sub against. * sub - subscription topic to check. * result - bool pointer to hold result. Will be set to true if the subscription * matches the acl. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if the input parameters were invalid. */ libmosqcommon_EXPORT int mosquitto_sub_matches_acl(const char *acl, const char *sub, bool *result); /* * Function: mosquitto_sub_matches_acl_with_pattern * * Check whether a subscription (a topic filter with wildcards) matches an ACL * (a topic filter with wildcards) , with client id/username pattern * substitution. * * Any instances of an ACL hierarchy that are exactly %c or %u will be * replaced with the client id or username respectively. * * For example: * * mosquitto_sub_matches_acl_with_pattern("sensors/%c/+", "sensors/kitchen/temperature", "kitchen", NULL, &result) * -> this will match * * mosquitto_sub_matches_acl_with_pattern("sensors/%c/+", "sensors/bathroom/temperature", "kitchen", NULL, &result) * -> this will not match * * mosquitto_sub_matches_acl_with_pattern("sensors/%count/+", "sensors/kitchen/temperature", "kitchen", NULL, &result) * -> this will not match - the `%count` is not treated as a pattern * * mosquitto_sub_matches_acl_with_pattern("%c/%c/%u/+", "kitchen/kitchen/bathroom/bathroom", "kitchen", "bathroom", &result) * -> this will match * * Parameters: * acl - ACL topic filter string to check sub against. * sub - subscription to check. * clientid - client id to substitute in patterns. If NULL, then any %c patterns will not match. * username - username to substitute in patterns. If NULL, then any %u patterns will not match. * result - bool pointer to hold result. Will be set to true if the subscription * matches the ACL. * * Returns: * MOSQ_ERR_SUCCESS - on success * MOSQ_ERR_INVAL - if the input parameters were invalid. */ libmosqcommon_EXPORT int mosquitto_sub_matches_acl_with_pattern(const char *acl, const char *sub, const char *clientid, const char *username, 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: * */ libmosqcommon_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: * */ libmosqcommon_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: * */ libmosqcommon_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: * */ libmosqcommon_EXPORT int mosquitto_sub_topic_check2(const char *topic, size_t topiclen); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libcommon_utf8.h ================================================ /* Copyright (c) 2010-2021 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_LIBCOMMON_UTF8_H #define MOSQUITTO_LIBCOMMON_UTF8_H /* * File: mosquitto/libcommon_utf8.h */ #ifdef __cplusplus extern "C" { #endif /* * 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 */ libmosqcommon_EXPORT int mosquitto_validate_utf8(const char *str, int len); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_H #define MOSQUITTO_LIBMOSQUITTO_H /* * File: mosquitto/libmosquitto.h * * This header contains functions and definitions for use with libmosquitto, the Mosquitto client library. */ #ifdef __cplusplus extern "C" { #endif #ifdef WIN32 # ifndef LIBMOSQUITTO_STATIC # ifdef libmosquitto_EXPORTS # define libmosq_EXPORT __declspec(dllexport) # else # define libmosq_EXPORT __declspec(dllimport) # endif # else # define libmosq_EXPORT # 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 #include #include #define LIBMOSQUITTO_MAJOR 2 #define LIBMOSQUITTO_MINOR 1 #define LIBMOSQUITTO_REVISION 0 /* 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) /* Enum: mosq_opt_t * * Client options. * * See , , and . */ 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, MOSQ_OPT_DISABLE_SOCKETPAIR = 14, MOSQ_OPT_TRANSPORT = 15, MOSQ_OPT_HTTP_PATH = 16, MOSQ_OPT_HTTP_HEADER_SIZE = 17, }; /* Struct: mosquitto_message * * Contains details of a PUBLISH message. * * int mid - the message/packet ID of the PUBLISH message, assuming this is a * QoS 1 or 2 message. Will be set to 0 for QoS 0 messages. * * char *topic - the topic the message was delivered on. * * void *payload - the message payload. This will be payloadlen bytes long, and * may be NULL if a zero length payload was sent. * * int payloadlen - the length of the payload, in bytes. * * int qos - the quality of service of the message, 0, 1, or 2. * * bool retain - set to true for stale retained messages. */ struct mosquitto_message { int mid; char *topic; void *payload; int payloadlen; int qos; bool retain; }; struct mosquitto_message_v5 { void *payload; char *topic; mosquitto_property *properties; uint32_t payloadlen; uint8_t qos; bool retain; uint8_t padding[2]; }; /* * 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); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_auth.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_AUTH_H #define MOSQUITTO_LIBMOSQUITTO_AUTH_H /* * File: mosquitto/libmosquitto_auth.h * * This header contains functions for setting client authentication parameters in libmosquitto. */ #ifdef __cplusplus extern "C" { #endif /* ====================================================================== * * 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); /* * Function: mosquitto_ext_auth_continue * * Use within an on_ext_auth callback only. * * Call to continue the MQTT v5 extended authentication flow. * * Parameters: * mosq - a valid mosquitto instance. * auth_method - the authentication method as provided in the on_ext_auth callback * auth_data - authentication data to send to the broker, or NULL * auth_data_len - the length of auth_data, in bytes, or 0 * * 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_ext_auth_continue(struct mosquitto *context, const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *props); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_callbacks.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_CALLBACKS_H #define MOSQUITTO_LIBMOSQUITTO_CALLBACKS_H /* * File: mosquitto/libmosquitto_callbacks.h * * This header contains functions for handling libmosquitto client callbacks. */ #ifdef __cplusplus extern "C" { #endif #include #include #include #include /* ====================================================================== * * 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 * * See Also: * */ typedef void (*LIBMOSQ_CB_connect)(struct mosquitto *mosq, void *obj, int rc); libmosq_EXPORT void mosquitto_connect_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_connect on_connect); /* * 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. * * See Also: * */ typedef void (*LIBMOSQ_CB_connect_with_flags)(struct mosquitto *mosq, void *obj, int rc, int flags); libmosq_EXPORT void mosquitto_connect_with_flags_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_connect_with_flags on_connect); /* * 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 * * See Also: * */ typedef void (*LIBMOSQ_CB_connect_v5)(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *props); libmosq_EXPORT void mosquitto_connect_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_connect_v5 on_connect); /* * Function: mosquitto_pre_connect_callback_set * * Set the pre-connect callback. The pre-connect callback is called just before an attempt is made to connect to the broker. This may be useful if you are using , or * , because when your client disconnects the library * will by default automatically reconnect. Using the pre-connect callback * allows you to set usernames, passwords, and TLS related parameters. * * Parameters: * mosq - a valid mosquitto instance. * on_pre_connect - 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 */ typedef void (*LIBMOSQ_CB_pre_connect)(struct mosquitto *mosq, void *obj); libmosq_EXPORT void mosquitto_pre_connect_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_pre_connect on_pre_connect); /* * 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. */ typedef void (*LIBMOSQ_CB_disconnect)(struct mosquitto *mosq, void *obj, int rc); libmosq_EXPORT void mosquitto_disconnect_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_disconnect on_disconnect); /* * 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 */ typedef void (*LIBMOSQ_CB_disconnect_v5)(struct mosquitto *mosq, void *obj, int rc, const mosquitto_property *props); libmosq_EXPORT void mosquitto_disconnect_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_disconnect_v5 on_disconnect); /* * 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. */ typedef void (*LIBMOSQ_CB_publish)(struct mosquitto *mosq, void *obj, int mid); libmosq_EXPORT void mosquitto_publish_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_publish on_publish); /* * 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 */ typedef void (*LIBMOSQ_CB_publish_v5)(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *props); libmosq_EXPORT void mosquitto_publish_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_publish_v5 on_publish); /* * 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: * */ typedef void (*LIBMOSQ_CB_message)(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message); libmosq_EXPORT void mosquitto_message_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_message on_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: * */ typedef void (*LIBMOSQ_CB_message_v5)(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message, const mosquitto_property *props); libmosq_EXPORT void mosquitto_message_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_message_v5 on_message); /* * 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. */ typedef void (*LIBMOSQ_CB_subscribe)(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos); libmosq_EXPORT void mosquitto_subscribe_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_subscribe on_subscribe); /* * 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 */ typedef void (*LIBMOSQ_CB_subscribe_v5)(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos, const mosquitto_property *props); libmosq_EXPORT void mosquitto_subscribe_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_subscribe_v5 on_subscribe); /* * 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. */ typedef void (*LIBMOSQ_CB_unsubscribe)(struct mosquitto *mosq, void *obj, int mid); libmosq_EXPORT void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe on_unsubscribe); /* * 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, const mosquitto_property *props) * * 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 */ typedef void (*LIBMOSQ_CB_unsubscribe_v5)(struct mosquitto *mosq, void *obj, int mid, const mosquitto_property *props); libmosq_EXPORT void mosquitto_unsubscribe_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe_v5 on_unsubscribe); /* * Function: mosquitto_unsubscribe2_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, * int reason_code_count, const int *reason_codes, const mosquitto_property *props) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * mid - the message id of the unsubscribe message. * reason_code_count - the count of reason code responses * reason_codes - an array of integers indicating the reason codes for each of * the unsubscription requests. * mid - the message id of the unsubscribe message. * props - list of MQTT 5 properties, or NULL */ typedef void (*LIBMOSQ_CB_unsubscribe2_v5)(struct mosquitto *mosq, void *obj, int mid, int reason_code_count, const int *reason_codes, const mosquitto_property *props); libmosq_EXPORT void mosquitto_unsubscribe2_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe2_v5 on_unsubscribe); /* * Function: mosquitto_ext_auth_callback_set * * Set the callback for extended authentication. This should be used if you * want to support MQTT v5.0 extended authentication. * * mosq - a valid mosquitto instance. * on_ext_auth - a callback function in the following form: * void callback(struct mosquitto *mosq, void *obj, const char *auth_method, int auth_data_len, const void *auth_data, const mosquitto_property *props) * * Callback Parameters: * mosq - the mosquitto instance making the callback. * obj - the user data provided in * auth_method - the authentication method provided by the broker * auth_data_len - the length of auth_data in bytes * auth_data - the authentication data, or NULL * props - list of MQTT 5 properties sent * note that this includes the auth-method and auth-data * properties, so you cannot use it directly with * mosquitto_ext_auth_continue and must instead create your * own property list * * Callback Return: * MOSQ_ERR_SUCCESS - if you accept the authentication data * MOSQ_ERR_AUTH - if the authentication should fail * MOSQ_ERR_NOMEM - on out of memory * * See Also: * */ typedef int (*LIBMOSQ_CB_ext_auth)(struct mosquitto *mosq, void *obj, const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *props); libmosq_EXPORT void mosquitto_ext_auth_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_ext_auth on_ext_auth); /* * 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. */ typedef void (*LIBMOSQ_CB_log)(struct mosquitto *mosq, void *obj, int level, const char *str); libmosq_EXPORT void mosquitto_log_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_log on_log); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_connect.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_CONNECT_H #define MOSQUITTO_LIBMOSQUITTO_CONNECT_H /* * File: mosquitto/libmosquitto_connect.h * * This header contains functions for connect/disconnecting/reconnectng clients in libmosquitto. */ #ifdef __cplusplus extern "C" { #endif /* ====================================================================== * * 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 client should send a PING * message to the broker 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 (keepalive == 0 is allowed, for an infinite keepalive) * 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 client should send a PING * message to the broker 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 client should send a PING * message to the broker 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 (keepalive == 0 is allowed, for an infinite keepalive) * 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 client should send a PING * message to the broker 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 client should send a PING * message to the broker 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 client should send a PING * message to the broker 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); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_create_delete.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_CREATE_DELETE_H #define MOSQUITTO_LIBMOSQUITTO_CREATE_DELETE_H /* * File: mosquitto/libmosquitto_create_delete.h * * This header contains functions for creating/deleting/reinitialising mosquitto clients. */ #ifdef __cplusplus extern "C" { #endif /* ====================================================================== * * 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. * MOSQ_ERR_MALFORMED_UTF8 - if the client id is not valid UTF-8. * * See Also: * , */ libmosq_EXPORT int mosquitto_reinitialise(struct mosquitto *mosq, const char *id, bool clean_session, void *obj); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_helpers.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_HELPERS_H #define MOSQUITTO_LIBMOSQUITTO_HELPERS_H #ifdef __cplusplus extern "C" { #endif #include #include /* ============================================================================= * * 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. * clientid - 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 *clientid, 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. * clientid - 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 *clientid, int keepalive, bool clean_session, const char *username, const char *password, const struct libmosquitto_will *will, const struct libmosquitto_tls *tls); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_loop.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_LOOP_H #define MOSQUITTO_LIBMOSQUITTO_LOOP_H /* * File: mosquitto/libmosquitto_loop.h * * This header contains functions for handling the libmosquitto network loop. */ #ifdef __cplusplus extern "C" { #endif #include #include #include #include /* ====================================================================== * * 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); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_message.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_MESSAGE_H #define MOSQUITTO_LIBMOSQUITTO_MESSAGE_H /* * File: mosquitto/libmosquitto_message.h * * This header contains functions for handling mosquitto_message structs. */ #ifdef __cplusplus extern "C" { #endif /* ====================================================================== * * 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); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_options.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_OPTIONS_H #define MOSQUITTO_LIBMOSQUITTO_OPTIONS_H /* * File: mosquitto/libmosquitto_options.h * * This header contains functions for setting client options in libmosquitto. */ #ifdef __cplusplus extern "C" { #endif /* ====================================================================== * * 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. * * MOSQ_OPT_DISABLE_SOCKETPAIR - By default, each client connected will create * an internal pair of connected sockets to allow the network thread * to be notified and woken up if another thread calls * or other similar command. If you are * operating with an external loop, this is not necessary and * consumes an extra two sockets per client. Set this option to 1 to * disable the use of the socket pair. * * MOSQ_OPT_TRANSPORT - Have the client connect with either MQTT over TCP as * normal, or MQTT over WebSockets. Set the value to MOSQ_T_TCP or * MOSQ_T_WEBSOCKETS. * * MOSQ_OPT_HTTP_HEADER_SIZE - Size the size of buffer that will be allocated * to store the incoming HTTP header when using Websocket transport. * Defaults to 4096. Setting to below 100 will result in a return * value of MOSQ_ERR_INVAL. This should be set before starting the * connection. If you try to set this when the initial http request * is underway then it will return MOSQ_ERR_INVAL. */ 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 . * Must be a valid engine, and note that the string will not be used * until a connection attempt is made so this function will return * success even if an invalid engine string is passed. * * 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_ENGINE_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 deprecated. 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); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_publish.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_PUBLISH_H #define MOSQUITTO_LIBMOSQUITTO_PUBLISH_H /* * File: mosquitto/libmosquitto_publish.h * * This header contains functions for publishing with libmosquitto. */ #ifdef __cplusplus extern "C" { #endif /* * 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); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_socks.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_SOCKS_H #define MOSQUITTO_LIBMOSQUITTO_SOCKS_H /* * File: mosquitto/libmosquitto_socks.h * * This header contains functions for controlling SOCKSv5 in libmosquitto. */ #ifdef __cplusplus extern "C" { #endif /* ============================================================================= * * 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); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_subscribe.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_SUBSCRIBE_H #define MOSQUITTO_LIBMOSQUITTO_SUBSCRIBE_H /* * File: mosquitto/libmosquitto_subscribe.h * * This header contains functions for subscribing in libmosquitto. */ #ifdef __cplusplus extern "C" { #endif /* * 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 - must not be NULL or an empty string. * 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 - must not be NULL or an empty string. * 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. * Each string must not be NULL nor an empty string. * 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); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_tls.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_TLS_H #define MOSQUITTO_LIBMOSQUITTO_TLS_H /* * File: mosquitto/libmosquitto_tls.h * * This header contains functions for setting TLS options in libmosquitto. */ #ifdef __cplusplus extern "C" { #endif /* ====================================================================== * * 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. The available options are * tlsv1.3 and tlsv1.2, with tlsv1.2 as the default. * 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); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_unsubscribe.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_UNSUBSCRIBE_H #define MOSQUITTO_LIBMOSQUITTO_UNSUBSCRIBE_H /* * File: mosquitto/libmosquitto_unsubscribe.h * * This header contains functions for client unsubscribing in libmosquitto. */ #ifdef __cplusplus extern "C" { #endif /* * 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 - must not by NULL or an empty string. * * 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 - must not by NULL or an empty string. * 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. * Each sub must not be NULL nor an empty string. * 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); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquitto_will.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTO_WILL_H #define MOSQUITTO_LIBMOSQUITTO_WILL_H /* * File: mosquitto/libmosquitto_will.h * * This header contains functions for manipulating client Wills in libmosquitto. */ #ifdef __cplusplus extern "C" { #endif /* ====================================================================== * * 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); #ifdef __cplusplus } #endif #endif ================================================ FILE: include/mosquitto/libmosquittopp.h ================================================ /* Copyright (c) 2010-2021 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_LIBMOSQUITTOPP_H #define MOSQUITTO_LIBMOSQUITTOPP_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 const char *reason_string(int reason_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 topic_matches_sub_with_pattern(const char *sub, const char *topic, const char *clientid, const char *username, bool *result); mosqpp_EXPORT int sub_matches_acl(const char *acl, const char *sub, bool *result); mosqpp_EXPORT int sub_matches_acl_with_pattern(const char *acl, const char *sub, const char *clientid, const char *username, 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 *clientid=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, const char *host="localhost", int port=1883, const char *clientid=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 property_check_command(int command, int identifier); mosqpp_EXPORT int property_check_all(int command, const mosquitto_property *properties); /* * 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_set_v5(const char *topic, int payloadlen=0, const void *payload=NULL, int qos=0, bool retain=false, mosquitto_property *properties=NULL); 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(const char *host, int port, int keepalive, const char *bind_address); int connect_v5(const char *host, int port, int keepalive, const char *bind_address, const mosquitto_property *properties); int connect_async(const char *host, int port=1883, int keepalive=60); int connect_async(const char *host, int port, int keepalive, const char *bind_address); int reconnect(); int reconnect_async(); int disconnect(); int disconnect_v5(int reason_code, const mosquitto_property *properties); int publish(int *mid, const char *topic, int payloadlen=0, const void *payload=NULL, int qos=0, bool retain=false); int publish_v5(int *mid, const char *topic, int payloadlen=0, const void *payload=NULL, int qos=0, bool retain=false, const mosquitto_property *properties=NULL); int subscribe(int *mid, const char *sub, int qos=0); int subscribe_v5(int *mid, const char *sub, int qos=0, int options=0, const mosquitto_property *properties=NULL); int unsubscribe(int *mid, const char *sub); int unsubscribe_v5(int *mid, const char *sub, const mosquitto_property *properties); 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 ext_auth_continue(const char *auth_method, uint16_t auth_data_len=0, const void *auth_data=NULL, const mosquitto_property *properties=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 int_option(enum mosq_opt_t option, int value); int string_option(enum mosq_opt_t option, const char *value); int void_option(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 MOSQ_USED on_pre_connect() {return;} virtual void MOSQ_USED on_connect(int /*rc*/) {return;} virtual void MOSQ_USED on_connect_with_flags(int /*rc*/, int /*flags*/) {return;} virtual void MOSQ_USED on_connect_v5(int /*rc*/, int /*flags*/, const mosquitto_property * /*props*/) {return;} virtual void MOSQ_USED on_disconnect(int /*rc*/) {return;} virtual void MOSQ_USED on_disconnect_v5(int /*rc*/, const mosquitto_property * /*props*/) {return;} virtual void MOSQ_USED on_publish(int /*mid*/) {return;} virtual void MOSQ_USED on_publish_v5(int /*mid*/, int /*reason_code*/, const mosquitto_property * /*props*/) {return;} virtual void MOSQ_USED on_message(const struct mosquitto_message * /*message*/) {return;} virtual void MOSQ_USED on_message_v5(const struct mosquitto_message * /*message*/, const mosquitto_property * /*props*/) {return;} virtual void MOSQ_USED on_subscribe(int /*mid*/, int /*qos_count*/, const int * /*granted_qos*/) {return;} virtual void MOSQ_USED on_subscribe_v5(int /*mid*/, int /*qos_count*/, const int * /*granted_qos*/, const mosquitto_property * /*props*/) {return;} virtual void MOSQ_USED on_unsubscribe(int /*mid*/) {return;} virtual void MOSQ_USED on_unsubscribe_v5(int /*mid*/, const mosquitto_property * /*props*/) {return;} virtual void MOSQ_USED on_log(int /*level*/, const char * /*str*/) {return;} virtual void MOSQ_USED on_error() {return;} virtual int MOSQ_USED on_ext_auth(const char * /*auth_method*/, uint16_t /*auth_data_len*/, const void * /*auth_data*/, const mosquitto_property * /*props*/) {return MOSQ_ERR_AUTH;} }; } #endif ================================================ FILE: include/mosquitto/mqtt_protocol.h ================================================ /* Copyright (c) 2009-2021 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 #include /* * File: mosquitto/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_RESERVED 0x00U #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, PUBACK, PUBREC, 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 #define MQTT_SUB_OPT_GET_QOS(opt) ((opt) & 0x03) #define MQTT_SUB_OPT_GET_NO_LOCAL(opt) ((opt)&MQTT_SUB_OPT_NO_LOCAL) #define MQTT_SUB_OPT_GET_RETAIN_AS_PUBLISHED(opt) ((opt)&MQTT_SUB_OPT_RETAIN_AS_PUBLISHED) #define MQTT_SUB_OPT_GET_SEND_RETAIN(opt) ((opt) & (MQTT_SUB_OPT_SEND_RETAIN_NEW | MQTT_SUB_OPT_SEND_RETAIN_NEVER)) #define MQTT_SUB_OPT_GET_RETAIN_HANDLING(opt) ((opt) & (MQTT_SUB_OPT_SEND_RETAIN_NEW | MQTT_SUB_OPT_SEND_RETAIN_NEVER)) #define MQTT_SUB_OPT_SET_QOS(opt, qos) ((opt) = ((opt) & 0xFC) | ((qos) & 0x03)) #define MQTT_SUB_OPT_SET_NO_LOCAL(opt, qos) ((opt) = ((opt) & 0xFC) | ((qos) & 0x03)) #define MQTT_SUB_OPT_SET_RETAIN_HANDLING(opt, rh) ((opt) = ((opt) & 0xCF) | ((rh) & 0x30)) #define MQTT_SUB_OPT_SET(opt, val) ((opt) |= val) #define MQTT_SUB_OPT_CLEAR(opt, val) ((opt) = (opt) & !val) #define MQTT_SESSION_EXPIRY_IMMEDIATE 0 #define MQTT_SESSION_EXPIRY_NEVER UINT32_MAX #endif ================================================ FILE: include/mosquitto.h ================================================ /* Copyright (c) 2010-2021 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 #ifndef _MSC_VER # define MOSQ_USED __attribute__((used)) #else # define MOSQ_USED #endif #include #include #include #include #include #include #endif ================================================ FILE: include/mosquitto_broker.h ================================================ #include #warning "Please replace '#include with #include " ================================================ FILE: include/mosquitto_plugin.h ================================================ #include #warning "Please replace '#include with #include " ================================================ FILE: include/mosquittopp.h ================================================ #include #warning "Please replace '#include with #include " ================================================ FILE: include/mqtt_protocol.h ================================================ #include #warning "Please replace '#include with #include " ================================================ FILE: installer/mosquitto.nsi ================================================ ; NSIS installer script for mosquitto Unicode True SetCompressor /SOLID lzma !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.1.2 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 ExecWait 'sc stop mosquitto' Sleep 1000 SetOutPath "$INSTDIR" File "..\logo\mosquitto.ico" File "..\build\src\Release\mosquitto.exe" File "..\build\apps\db_dump\Release\mosquitto_db_dump.exe" File "..\build\apps\mosquitto_ctrl\Release\mosquitto_ctrl.exe" File "..\build\apps\mosquitto_passwd\Release\mosquitto_passwd.exe" File "..\build\apps\mosquitto_signal\Release\mosquitto_signal.exe" File "..\build\client\Release\mosquitto_pub.exe" File "..\build\client\Release\mosquitto_sub.exe" File "..\build\client\Release\mosquitto_rr.exe" File "..\build\libcommon\Release\mosquitto_common.dll" File "..\build\lib\Release\mosquitto.dll" File "..\build\lib\cpp\Release\mosquittopp.dll" File "..\build\plugins\acl-file\Release\mosquitto_acl_file.dll" File "..\build\plugins\dynamic-security\Release\mosquitto_dynamic_security.dll" File "..\build\plugins\password-file\Release\mosquitto_password_file.dll" File "..\build\plugins\persist-sqlite\Release\mosquitto_persist_sqlite.dll" File "..\build\plugins\sparkplug-aware\Release\mosquitto_sparkplug_aware.dll" File "..\aclfile.example" File "..\ChangeLog.txt" File "..\NOTICE.md" File "..\pskfile.example" File "..\pwfile.example" File "..\README.md" File "..\README-windows.txt" File "..\README-letsencrypt.md" File "..\SECURITY.md" File "..\edl-v10" File "..\epl-v20" SetOverwrite off File "..\mosquitto.conf" SetOverwrite on File "..\build\vcpkg_installed\x86-windows\bin\cjson.dll" File "..\build\vcpkg_installed\x86-windows\bin\libcrypto-3.dll" File "..\build\vcpkg_installed\x86-windows\bin\libmicrohttpd-dll.dll" File "..\build\vcpkg_installed\x86-windows\bin\libssl-3.dll" File "..\build\vcpkg_installed\x86-windows\bin\pthreadVC3.dll" File "..\build\vcpkg_installed\x86-windows\bin\sqlite3.dll" SetOutPath "$INSTDIR\devel" File "..\build\lib\Release\mosquitto.lib" File "..\build\lib\cpp\Release\mosquittopp.lib" File "..\build\src\Release\mosquitto_broker.lib" File "..\include\mosquitto.h" File "..\include\mosquitto_broker.h" File "..\include\mosquitto_plugin.h" File "..\include\mosquittopp.h" file "..\include\mqtt_protocol.h" SetOutPath "$INSTDIR\devel\mosquitto" File "..\include\mosquitto\broker.h" File "..\include\mosquitto\broker_control.h" File "..\include\mosquitto\broker_plugin.h" File "..\include\mosquitto\defs.h" File "..\include\mosquitto\libcommon.h" File "..\include\mosquitto\libcommon_base64.h" File "..\include\mosquitto\libcommon_cjson.h" File "..\include\mosquitto\libcommon_file.h" File "..\include\mosquitto\libcommon_memory.h" File "..\include\mosquitto\libcommon_password.h" File "..\include\mosquitto\libcommon_properties.h" File "..\include\mosquitto\libcommon_random.h" File "..\include\mosquitto\libcommon_string.h" File "..\include\mosquitto\libcommon_string.h" File "..\include\mosquitto\libcommon_time.h" File "..\include\mosquitto\libcommon_topic.h" File "..\include\mosquitto\libcommon_utf8.h" File "..\include\mosquitto\libmosquitto.h" File "..\include\mosquitto\libmosquitto_auth.h" File "..\include\mosquitto\libmosquitto_callbacks.h" File "..\include\mosquitto\libmosquitto_connect.h" File "..\include\mosquitto\libmosquitto_create_delete.h" File "..\include\mosquitto\libmosquitto_helpers.h" File "..\include\mosquitto\libmosquitto_loop.h" File "..\include\mosquitto\libmosquitto_message.h" File "..\include\mosquitto\libmosquitto_options.h" File "..\include\mosquitto\libmosquitto_publish.h" File "..\include\mosquitto\libmosquitto_socks.h" File "..\include\mosquitto\libmosquitto_subscribe.h" File "..\include\mosquitto\libmosquitto_tls.h" File "..\include\mosquitto\libmosquitto_unsubscribe.h" File "..\include\mosquitto\libmosquitto_will.h" File "..\include\mosquitto\libmosquittopp.h" File "..\include\mosquitto\mqtt_protocol.h" SetOutPath "$INSTDIR\dashboard" File "..\dashboard\src\index.html" File "..\dashboard\src\listeners.html" SetOutPath "$INSTDIR\dashboard\app" File "..\dashboard\src\app\consts.js" File "..\dashboard\src\app\dashboard.js" File "..\dashboard\src\app\index.js" File "..\dashboard\src\app\listeners.js" File "..\dashboard\src\app\sidebar.js" SetOutPath "$INSTDIR\dashboard\css" File "..\dashboard\src\css\styles.css" SetOutPath "$INSTDIR\dashboard\lib" File "..\dashboard\src\lib\chart.umd.js" File "..\dashboard\src\lib\chartjs-plugin-zoom.min.js" File "..\dashboard\src\lib\hammer.min.js" SetOutPath "$INSTDIR\dashboard\media" File "..\dashboard\src\media\banner.svg" File "..\dashboard\src\media\favicon-16x16.png" File "..\dashboard\src\media\favicon-32x32.png" File "..\dashboard\src\media\mosquitto-logo.png" SetOutPath "$INSTDIR\dashboard\tailwind" File "..\dashboard\src\tailwind.config.js" File "..\dashboard\src\tailwind\styles.css" SetOutPath "$INSTDIR\dashboard\utils" File "..\dashboard\src\utils\assert.js" File "..\dashboard\src\utils\queue.js" File "..\dashboard\src\utils\utils.js" WriteUninstaller "$INSTDIR\Uninstall.exe" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto" "DisplayName" "Eclipse Mosquitto MQTT broker (32 bit)" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\Mosquitto" "DisplayIcon" "$INSTDIR\mosquitto.ico" 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 "Visual Studio Runtime" SetOutPath "$INSTDIR" File "VC_redist.x86.exe" ExecWait '"$INSTDIR\VC_redist.x86.exe" /quiet /norestart' Delete "$INSTDIR\VC_redist.x86.exe" SectionEnd Section "Service" SecService ExecWait '"$INSTDIR\mosquitto.exe" install' ExecWait 'sc start mosquitto' SectionEnd Section "Uninstall" ExecWait 'sc stop mosquitto' Sleep 1000 ExecWait '"$INSTDIR\mosquitto.exe" uninstall' Sleep 1000 Delete "$INSTDIR\mosquitto.dll" Delete "$INSTDIR\mosquitto.exe" Delete "$INSTDIR\mosquitto_common.dll" Delete "$INSTDIR\mosquitto_ctrl.exe" Delete "$INSTDIR\mosquitto_db_dump.exe" Delete "$INSTDIR\mosquitto_passwd.exe" Delete "$INSTDIR\mosquitto_pub.exe" Delete "$INSTDIR\mosquitto_rr.exe" Delete "$INSTDIR\mosquitto_signal.exe" Delete "$INSTDIR\mosquitto_sub.exe" Delete "$INSTDIR\mosquittopp.dll" Delete "$INSTDIR\mosquitto_acl_file.dll" Delete "$INSTDIR\mosquitto_dynamic_security.dll" Delete "$INSTDIR\mosquitto_password_file.dll" Delete "$INSTDIR\mosquitto_persist_sqlite.dll" Delete "$INSTDIR\mosquitto_sparkplug_aware.dll" Delete "$INSTDIR\aclfile.example" Delete "$INSTDIR\ChangeLog.txt" Delete "$INSTDIR\mosquitto.conf" Delete "$INSTDIR\pskfile.example" Delete "$INSTDIR\pwfile.example" Delete "$INSTDIR\NOTICE.md" Delete "$INSTDIR\README.md" Delete "$INSTDIR\README-windows.txt" Delete "$INSTDIR\README-letsencrypt.md" Delete "$INSTDIR\SECURITY.md" Delete "$INSTDIR\edl-v10" Delete "$INSTDIR\epl-v20" Delete "$INSTDIR\mosquitto.ico" Delete "$INSTDIR\argon2.dll" Delete "$INSTDIR\cjson.dll" Delete "$INSTDIR\libcrypto-3.dll" Delete "$INSTDIR\libmicrohttpd-dll.dll" Delete "$INSTDIR\libssl-3.dll" Delete "$INSTDIR\pthreadVC3.dll" Delete "$INSTDIR\sqlite3.dll" Delete "$INSTDIR\devel\mosquitto.h" Delete "$INSTDIR\devel\mosquitto\broker.h" Delete "$INSTDIR\devel\mosquitto\broker_control.h" Delete "$INSTDIR\devel\mosquitto\broker_plugin.h" Delete "$INSTDIR\devel\mosquitto\defs.h" Delete "$INSTDIR\devel\mosquitto\libcommon.h" Delete "$INSTDIR\devel\mosquitto\libcommon_base64.h" Delete "$INSTDIR\devel\mosquitto\libcommon_cjson.h" Delete "$INSTDIR\devel\mosquitto\libcommon_file.h" Delete "$INSTDIR\devel\mosquitto\libcommon_memory.h" Delete "$INSTDIR\devel\mosquitto\libcommon_password.h" Delete "$INSTDIR\devel\mosquitto\libcommon_properties.h" Delete "$INSTDIR\devel\mosquitto\libcommon_random.h" Delete "$INSTDIR\devel\mosquitto\libcommon_string.h" Delete "$INSTDIR\devel\mosquitto\libcommon_time.h" Delete "$INSTDIR\devel\mosquitto\libcommon_topic.h" Delete "$INSTDIR\devel\mosquitto\libcommon_utf8.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_auth.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_callbacks.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_connect.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_create_delete.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_helpers.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_loop.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_message.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_options.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_publish.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_socks.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_subscribe.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_tls.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_unsubscribe.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_will.h" Delete "$INSTDIR\devel\mosquitto\libmosquittopp.h" Delete "$INSTDIR\devel\mosquitto\mqtt_protocol.h" Delete "$INSTDIR\devel\mosquitto_broker.h" Delete "$INSTDIR\devel\mosquitto_plugin.h" Delete "$INSTDIR\devel\mosquittopp.h" Delete "$INSTDIR\devel\mqtt_protocol.h" Delete "$INSTDIR\devel\mosquitto.lib" Delete "$INSTDIR\devel\mosquitto_broker.lib" Delete "$INSTDIR\devel\mosquittopp.lib" RMDir "$INSTDIR\devel\mosquitto" RMDir "$INSTDIR\devel" Delete "$INSTDIR\dashboard\app\consts.js" Delete "$INSTDIR\dashboard\app\dashboard.js" Delete "$INSTDIR\dashboard\app\index.js" Delete "$INSTDIR\dashboard\app\listeners.js" Delete "$INSTDIR\dashboard\app\sidebar.js" RMDir "$INSTDIR\dashboard\app" Delete "$INSTDIR\dashboard\css\styles.css" RMDir "$INSTDIR\dashboard\css" Delete "$INSTDIR\dashboard\index.html" Delete "$INSTDIR\dashboard\lib\chart.umd.js" Delete "$INSTDIR\dashboard\lib\chartjs-plugin-zoom.min.js" Delete "$INSTDIR\dashboard\lib\hammer.min.js" RMDir "$INSTDIR\dashboard\lib" Delete "$INSTDIR\dashboard\listeners.html" Delete "$INSTDIR\dashboard\media\banner.svg" Delete "$INSTDIR\dashboard\media\favicon-16x16.png" Delete "$INSTDIR\dashboard\media\favicon-32x32.png" Delete "$INSTDIR\dashboard\media\mosquitto-logo.png" RMDir "$INSTDIR\dashboard\media" Delete "$INSTDIR\dashboard\tailwind.config.js" Delete "$INSTDIR\dashboard\tailwind\styles.css" RMDir "$INSTDIR\dashboard\tailwind" Delete "$INSTDIR\dashboard\utils\assert.js" Delete "$INSTDIR\dashboard\utils\queue.js" Delete "$INSTDIR\dashboard\utils\utils.js" RMDir "$INSTDIR\dashboard\utils" RMDir "$INSTDIR\dashboard" 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 ================================================ FILE: installer/mosquitto64.nsi ================================================ ; NSIS installer script for mosquitto Unicode True SetCompressor /SOLID lzma !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.1.2 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 ExecWait 'sc stop mosquitto' Sleep 1000 SetOutPath "$INSTDIR" File "..\logo\mosquitto.ico" File "..\build64\src\Release\mosquitto.exe" File "..\build64\apps\db_dump\Release\mosquitto_db_dump.exe" File "..\build64\apps\mosquitto_ctrl\Release\mosquitto_ctrl.exe" File "..\build64\apps\mosquitto_passwd\Release\mosquitto_passwd.exe" File "..\build64\apps\mosquitto_signal\Release\mosquitto_signal.exe" File "..\build64\client\Release\mosquitto_pub.exe" File "..\build64\client\Release\mosquitto_sub.exe" File "..\build64\client\Release\mosquitto_rr.exe" File "..\build64\libcommon\Release\mosquitto_common.dll" File "..\build64\lib\Release\mosquitto.dll" File "..\build64\lib\cpp\Release\mosquittopp.dll" File "..\build64\plugins\acl-file\Release\mosquitto_acl_file.dll" File "..\build64\plugins\dynamic-security\Release\mosquitto_dynamic_security.dll" File "..\build64\plugins\password-file\Release\mosquitto_password_file.dll" File "..\build64\plugins\persist-sqlite\Release\mosquitto_persist_sqlite.dll" File "..\build64\plugins\sparkplug-aware\Release\mosquitto_sparkplug_aware.dll" File "..\aclfile.example" File "..\ChangeLog.txt" File "..\NOTICE.md" File "..\pskfile.example" File "..\pwfile.example" File "..\README.md" File "..\README-windows.txt" File "..\README-letsencrypt.md" File "..\SECURITY.md" File "..\edl-v10" File "..\epl-v20" SetOverwrite off File "..\mosquitto.conf" SetOverwrite on File "..\build64\vcpkg_installed\x64-windows-release\bin\cjson.dll" File "..\build64\vcpkg_installed\x64-windows-release\bin\libcrypto-3-x64.dll" File "..\build64\vcpkg_installed\x64-windows-release\bin\libmicrohttpd-dll.dll" File "..\build64\vcpkg_installed\x64-windows-release\bin\libssl-3-x64.dll" File "..\build64\vcpkg_installed\x64-windows-release\bin\pthreadVC3.dll" File "..\build64\vcpkg_installed\x64-windows-release\bin\sqlite3.dll" SetOutPath "$INSTDIR\devel" File "..\build64\lib\Release\mosquitto.lib" File "..\build64\lib\cpp\Release\mosquittopp.lib" File "..\build64\src\Release\mosquitto_broker.lib" File "..\include\mosquitto.h" File "..\include\mosquitto_broker.h" File "..\include\mosquitto_plugin.h" File "..\include\mosquittopp.h" file "..\include\mqtt_protocol.h" SetOutPath "$INSTDIR\devel\mosquitto" File "..\include\mosquitto\broker.h" File "..\include\mosquitto\broker_control.h" File "..\include\mosquitto\broker_plugin.h" File "..\include\mosquitto\defs.h" File "..\include\mosquitto\libcommon.h" File "..\include\mosquitto\libcommon_base64.h" File "..\include\mosquitto\libcommon_cjson.h" File "..\include\mosquitto\libcommon_file.h" File "..\include\mosquitto\libcommon_memory.h" File "..\include\mosquitto\libcommon_password.h" File "..\include\mosquitto\libcommon_properties.h" File "..\include\mosquitto\libcommon_random.h" File "..\include\mosquitto\libcommon_string.h" File "..\include\mosquitto\libcommon_string.h" File "..\include\mosquitto\libcommon_time.h" File "..\include\mosquitto\libcommon_topic.h" File "..\include\mosquitto\libcommon_utf8.h" File "..\include\mosquitto\libmosquitto.h" File "..\include\mosquitto\libmosquitto_auth.h" File "..\include\mosquitto\libmosquitto_callbacks.h" File "..\include\mosquitto\libmosquitto_connect.h" File "..\include\mosquitto\libmosquitto_create_delete.h" File "..\include\mosquitto\libmosquitto_helpers.h" File "..\include\mosquitto\libmosquitto_loop.h" File "..\include\mosquitto\libmosquitto_message.h" File "..\include\mosquitto\libmosquitto_options.h" File "..\include\mosquitto\libmosquitto_publish.h" File "..\include\mosquitto\libmosquitto_socks.h" File "..\include\mosquitto\libmosquitto_subscribe.h" File "..\include\mosquitto\libmosquitto_tls.h" File "..\include\mosquitto\libmosquitto_unsubscribe.h" File "..\include\mosquitto\libmosquitto_will.h" File "..\include\mosquitto\libmosquittopp.h" File "..\include\mosquitto\mqtt_protocol.h" SetOutPath "$INSTDIR\dashboard" File "..\dashboard\src\index.html" File "..\dashboard\src\listeners.html" SetOutPath "$INSTDIR\dashboard\app" File "..\dashboard\src\app\consts.js" File "..\dashboard\src\app\dashboard.js" File "..\dashboard\src\app\index.js" File "..\dashboard\src\app\listeners.js" File "..\dashboard\src\app\sidebar.js" SetOutPath "$INSTDIR\dashboard\css" File "..\dashboard\src\css\styles.css" SetOutPath "$INSTDIR\dashboard\lib" File "..\dashboard\src\lib\chart.umd.js" File "..\dashboard\src\lib\chartjs-plugin-zoom.min.js" File "..\dashboard\src\lib\hammer.min.js" SetOutPath "$INSTDIR\dashboard\media" File "..\dashboard\src\media\banner.svg" File "..\dashboard\src\media\favicon-16x16.png" File "..\dashboard\src\media\favicon-32x32.png" File "..\dashboard\src\media\mosquitto-logo.png" SetOutPath "$INSTDIR\dashboard\tailwind" File "..\dashboard\src\tailwind.config.js" File "..\dashboard\src\tailwind\styles.css" SetOutPath "$INSTDIR\dashboard\utils" File "..\dashboard\src\utils\assert.js" File "..\dashboard\src\utils\queue.js" File "..\dashboard\src\utils\utils.js" 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" "DisplayIcon" "$INSTDIR\mosquitto.ico" 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 "Visual Studio Runtime" SetOutPath "$INSTDIR" File "VC_redist.x64.exe" ExecWait '"$INSTDIR\VC_redist.x64.exe" /quiet /norestart' Delete "$INSTDIR\VC_redist.x64.exe" SectionEnd Section "Service" SecService ExecWait '"$INSTDIR\mosquitto.exe" install' ExecWait 'sc start mosquitto' SectionEnd Section "Uninstall" ExecWait 'sc stop mosquitto' Sleep 1000 ExecWait '"$INSTDIR\mosquitto.exe" uninstall' Sleep 1000 Delete "$INSTDIR\mosquitto.dll" Delete "$INSTDIR\mosquitto.exe" Delete "$INSTDIR\mosquitto_common.dll" Delete "$INSTDIR\mosquitto_ctrl.exe" Delete "$INSTDIR\mosquitto_db_dump.exe" Delete "$INSTDIR\mosquitto_passwd.exe" Delete "$INSTDIR\mosquitto_pub.exe" Delete "$INSTDIR\mosquitto_rr.exe" Delete "$INSTDIR\mosquitto_signal.exe" Delete "$INSTDIR\mosquitto_sub.exe" Delete "$INSTDIR\mosquittopp.dll" Delete "$INSTDIR\mosquitto_acl_file.dll" Delete "$INSTDIR\mosquitto_dynamic_security.dll" Delete "$INSTDIR\mosquitto_password_file.dll" Delete "$INSTDIR\mosquitto_persist_sqlite.dll" Delete "$INSTDIR\mosquitto_sparkplug_aware.dll" Delete "$INSTDIR\aclfile.example" Delete "$INSTDIR\ChangeLog.txt" Delete "$INSTDIR\mosquitto.conf" Delete "$INSTDIR\pskfile.example" Delete "$INSTDIR\pwfile.example" Delete "$INSTDIR\NOTICE.md" Delete "$INSTDIR\README.md" Delete "$INSTDIR\README-windows.txt" Delete "$INSTDIR\README-letsencrypt.md" Delete "$INSTDIR\SECURITY.md" Delete "$INSTDIR\edl-v10" Delete "$INSTDIR\epl-v20" Delete "$INSTDIR\mosquitto.ico" Delete "$INSTDIR\argon2.dll" Delete "$INSTDIR\cjson.dll" Delete "$INSTDIR\libcrypto-3-x64.dll" Delete "$INSTDIR\libmicrohttpd-dll.dll" Delete "$INSTDIR\libssl-3-x64.dll" Delete "$INSTDIR\pthreadVC3.dll" Delete "$INSTDIR\sqlite3.dll" Delete "$INSTDIR\devel\mosquitto.h" Delete "$INSTDIR\devel\mosquitto\broker.h" Delete "$INSTDIR\devel\mosquitto\broker_control.h" Delete "$INSTDIR\devel\mosquitto\broker_plugin.h" Delete "$INSTDIR\devel\mosquitto\defs.h" Delete "$INSTDIR\devel\mosquitto\libcommon.h" Delete "$INSTDIR\devel\mosquitto\libcommon_base64.h" Delete "$INSTDIR\devel\mosquitto\libcommon_cjson.h" Delete "$INSTDIR\devel\mosquitto\libcommon_file.h" Delete "$INSTDIR\devel\mosquitto\libcommon_memory.h" Delete "$INSTDIR\devel\mosquitto\libcommon_password.h" Delete "$INSTDIR\devel\mosquitto\libcommon_properties.h" Delete "$INSTDIR\devel\mosquitto\libcommon_random.h" Delete "$INSTDIR\devel\mosquitto\libcommon_string.h" Delete "$INSTDIR\devel\mosquitto\libcommon_time.h" Delete "$INSTDIR\devel\mosquitto\libcommon_topic.h" Delete "$INSTDIR\devel\mosquitto\libcommon_utf8.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_auth.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_callbacks.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_connect.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_create_delete.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_helpers.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_loop.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_message.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_options.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_publish.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_socks.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_subscribe.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_tls.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_unsubscribe.h" Delete "$INSTDIR\devel\mosquitto\libmosquitto_will.h" Delete "$INSTDIR\devel\mosquitto\libmosquittopp.h" Delete "$INSTDIR\devel\mosquitto\mqtt_protocol.h" Delete "$INSTDIR\devel\mosquitto_broker.h" Delete "$INSTDIR\devel\mosquitto_plugin.h" Delete "$INSTDIR\devel\mosquittopp.h" Delete "$INSTDIR\devel\mqtt_protocol.h" Delete "$INSTDIR\devel\mosquitto.lib" Delete "$INSTDIR\devel\mosquitto_broker.lib" Delete "$INSTDIR\devel\mosquittopp.lib" RMDir "$INSTDIR\devel\mosquitto" RMDir "$INSTDIR\devel" Delete "$INSTDIR\dashboard\app\consts.js" Delete "$INSTDIR\dashboard\app\dashboard.js" Delete "$INSTDIR\dashboard\app\index.js" Delete "$INSTDIR\dashboard\app\listeners.js" Delete "$INSTDIR\dashboard\app\sidebar.js" RMDir "$INSTDIR\dashboard\app" Delete "$INSTDIR\dashboard\css\styles.css" RMDir "$INSTDIR\dashboard\css" Delete "$INSTDIR\dashboard\index.html" Delete "$INSTDIR\dashboard\lib\chart.umd.js" Delete "$INSTDIR\dashboard\lib\chartjs-plugin-zoom.min.js" Delete "$INSTDIR\dashboard\lib\hammer.min.js" RMDir "$INSTDIR\dashboard\lib" Delete "$INSTDIR\dashboard\listeners.html" Delete "$INSTDIR\dashboard\media\banner.svg" Delete "$INSTDIR\dashboard\media\favicon-16x16.png" Delete "$INSTDIR\dashboard\media\favicon-32x32.png" Delete "$INSTDIR\dashboard\media\mosquitto-logo.png" RMDir "$INSTDIR\dashboard\media" Delete "$INSTDIR\dashboard\tailwind.config.js" Delete "$INSTDIR\dashboard\tailwind\styles.css" RMDir "$INSTDIR\dashboard\tailwind" Delete "$INSTDIR\dashboard\utils\assert.js" Delete "$INSTDIR\dashboard\utils\queue.js" Delete "$INSTDIR\dashboard\utils\utils.js" RMDir "$INSTDIR\dashboard\utils" RMDir "$INSTDIR\dashboard" 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 ================================================ FILE: lib/CMakeLists.txt ================================================ if(WITH_LIB_CPP) add_subdirectory(cpp) endif() set(C_SRC actions_publish.c actions_subscribe.c actions_unsubscribe.c alias_mosq.c alias_mosq.h callbacks.c connect.c extended_auth.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 http_client.c http_client.h libmosquitto.c logging_mosq.c logging_mosq.h loop.c messages_mosq.c messages_mosq.h mosquitto_internal.h ../include/mosquitto.h ../include/mosquitto/mqtt_protocol.h net_mosq_ocsp.c net_mosq.c net_mosq.h net_ws.c options.c packet_datatypes.c packet_mosq.c packet_mosq.h property_mosq.c property_mosq.h read_handle.c read_handle.h send_connect.c send_disconnect.c send_mosq.c send_publish.c send_subscribe.c send_unsubscribe.c send_mosq.c send_mosq.h socks_mosq.c srv_mosq.c thread_mosq.c tls_mosq.c util_mosq.c util_mosq.h will_mosq.c will_mosq.h) set(LIBRARIES common-options libmosquitto_common) if(WITH_TLS) set (LIBRARIES ${LIBRARIES} OpenSSL::SSL) endif() if(WIN32) set (LIBRARIES ${LIBRARIES} ws2_32) endif() 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() message(WARNING "c-ares library not found.") endif() endif() if(WITH_WEBSOCKETS AND WITH_WEBSOCKETS_BUILTIN) add_definitions("-DWITH_WEBSOCKETS=WS_IS_BUILTIN") set(C_SRC ${C_SRC} ../deps/picohttpparser/picohttpparser.c http_client.c http_client.h net_ws.c ) endif() add_library(libmosquitto SHARED ${C_SRC} ) if(WITH_WEBSOCKETS AND WITH_WEBSOCKETS_BUILTIN) target_include_directories(libmosquitto PRIVATE "${mosquitto_SOURCE_DIR}/deps/picohttpparser") endif() target_include_directories(libmosquitto PUBLIC "${mosquitto_SOURCE_DIR}/include" "${mosquitto_SOURCE_DIR}/lib" PRIVATE "${mosquitto_SOURCE_DIR}/common" "${mosquitto_SOURCE_DIR}/libcommon" "${OPENSSL_INCLUDE_DIR}" # Required for cross compilation ) if(WITH_THREADING) if(WIN32) set (LIBRARIES ${LIBRARIES} PThreads4W::PThreads4W) else() set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) set (LIBRARIES ${LIBRARIES} Threads::Threads) endif() endif() target_link_libraries(libmosquitto PUBLIC ${LIBRARIES}) set_target_properties(libmosquitto PROPERTIES OUTPUT_NAME mosquitto VERSION ${VERSION} SOVERSION 1 POSITION_INDEPENDENT_CODE 1 ) if(UNIX AND NOT APPLE AND NOT AIX) set_target_properties(libmosquitto PROPERTIES LINK_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/linker.version LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/linker.version" ) endif() install(TARGETS libmosquitto RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" 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() if(WITH_WEBSOCKETS AND WITH_WEBSOCKETS_BUILTIN) target_include_directories(libmosquitto_static PRIVATE "${mosquitto_SOURCE_DIR}/deps/picohttpparser") endif() target_link_libraries(libmosquitto_static PRIVATE ${LIBRARIES}) target_include_directories(libmosquitto_static PRIVATE "${mosquitto_SOURCE_DIR}" "${mosquitto_SOURCE_DIR}/include" "${mosquitto_SOURCE_DIR}/lib" "${mosquitto_SOURCE_DIR}/libcommon" ) 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() ================================================ FILE: lib/Makefile ================================================ R=.. include ${R}/config.mk LOCAL_CFLAGS+=-fPIC LOCAL_CPPFLAGS+=-I${R}/libcommon LOCAL_LDFLAGS+=-Wl,--version-script=linker.version -Wl,-soname,libmosquitto.so.$(SOVERSION) -fPIC -shared LOCAL_LIBADD+=-lcjson -lc ${LIBMOSQ_COMMON} STATIC_LIB_DEPS:= # ------------------------------------------ # Compile time options # ------------------------------------------ ifeq ($(WITH_SOCKS),yes) LOCAL_CPPFLAGS+=-DWITH_SOCKS endif ifeq ($(WITH_SRV),yes) LOCAL_CPPFLAGS+=-DWITH_SRV LOCAL_LIBADD+=-lcares STATIC_LIB_DEPS+=-lcares endif ifeq ($(WITH_THREADING),yes) LOCAL_CFLAGS+=-pthread LOCAL_CPPFLAGS+=-DWITH_THREADING LOCAL_LDFLAGS+=-pthread STATIC_LIB_DEPS+=-pthread endif ifeq ($(WITH_TLS),yes) LOCAL_LIBADD+=-lssl -lcrypto STATIC_LIB_DEPS:=$(STATIC_LIB_DEPS) -lssl -lcrypto endif # ------------------------------------------ # Targets # ------------------------------------------ .PHONY : really clean install OBJS= \ libmosquitto.o \ actions_publish.o \ actions_subscribe.o \ actions_unsubscribe.o \ alias_mosq.o \ callbacks.o \ connect.o \ extended_auth.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 \ http_client.o \ logging_mosq.o \ loop.o \ messages_mosq.o \ net_mosq_ocsp.o \ net_mosq.o \ net_ws.o \ options.o \ packet_datatypes.o \ packet_mosq.o \ property_mosq.o \ read_handle.o \ send_connect.o \ send_disconnect.o \ send_mosq.o \ send_publish.o \ send_subscribe.o \ send_unsubscribe.o \ socks_mosq.o \ srv_mosq.o \ thread_mosq.o \ tls_mosq.o \ util_mosq.o \ will_mosq.o OBJS_EXTERNAL= ifeq ($(WITH_WEBSOCKETS),yes) OBJS_EXTERNAL+=${R}/deps/picohttpparser/picohttpparser.o endif 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}${libdir}/pkgconfig" $(INSTALL) -m644 ${R}/libmosquitto.pc.in "${DESTDIR}${libdir}/pkgconfig/libmosquitto.pc" sed ${SEDINPLACE} -e "s#@CMAKE_INSTALL_PREFIX@#${prefix}#" -e "s#@CMAKE_INSTALL_LIBDIR@#lib${LIB_SUFFIX}#" -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 ${OBJS} ${OBJS_EXTERNAL} libmosquitto.so.${SOVERSION} libmosquitto.so libmosquitto.a *.gcno *.gcda $(MAKE) -C cpp clean libmosquitto.so.${SOVERSION} : ${OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}$(CC) $(LOCAL_LDFLAGS) $^ -o $@ ${LOCAL_LIBADD} libmosquitto.a : ${OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}$(AR) cr $@ $^ ${OBJS} : %.o: %.c ${R}/include/mosquitto.h mosquitto_internal.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ ${R}/deps/picohttpparser/picohttpparser.o : ${R}/deps/picohttpparser/picohttpparser.c ${CROSS_COMPILE}$(CC) $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ ================================================ FILE: lib/actions_publish.c ================================================ /* Copyright (c) 2010-2021 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 "messages_mosq.h" #include "mosquitto_internal.h" #include "mosquitto/mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "property_common.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(mosquitto_property_identifier(p) == MQTT_PROP_TOPIC_ALIAS){ have_topic_alias = true; break; } p = mosquitto_property_next(p); } 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 + mosquitto_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, 0, outgoing_properties, 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->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; COMPAT_pthread_mutex_lock(&mosq->msgs_out.mutex); message->state = mosq_ms_invalid; rc = message__queue(mosq, message, mosq_md_out); COMPAT_pthread_mutex_unlock(&mosq->msgs_out.mutex); return rc; } } ================================================ FILE: lib/actions_subscribe.c ================================================ /* Copyright (c) 2010-2021 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/mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_common.h" #include "send_mosq.h" 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(!net__is_connected(mosq)){ 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 + mosquitto_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); } ================================================ FILE: lib/actions_unsubscribe.c ================================================ /* Copyright (c) 2010-2021 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/mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "property_common.h" #include "send_mosq.h" 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(!net__is_connected(mosq)){ 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 + mosquitto_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); } ================================================ FILE: lib/alias_mosq.c ================================================ /* Copyright (c) 2019-2021 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 "alias_mosq.h" static void alias__free_r2l(struct mosquitto *mosq); static void alias__free_l2r(struct mosquitto *mosq); int alias__add_l2r(struct mosquitto *mosq, const char *topic, uint16_t *alias) { struct mosquitto__alias *aliases_new; if(mosq->alias_count_l2r < mosq->alias_max_l2r){ aliases_new = mosquitto_realloc(mosq->aliases_l2r, sizeof(struct mosquitto__alias)*(size_t)(mosq->alias_count_l2r+1)); if(!aliases_new){ return MOSQ_ERR_NOMEM; } mosq->aliases_l2r = aliases_new; mosq->alias_count_l2r++; *alias = mosq->alias_count_l2r; mosq->aliases_l2r[mosq->alias_count_l2r-1].alias = *alias; mosq->aliases_l2r[mosq->alias_count_l2r-1].topic = mosquitto_strdup(topic); if(!mosq->aliases_l2r[mosq->alias_count_l2r-1].topic){ *alias = 0; return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } *alias = 0; return MOSQ_ERR_INVAL; } int alias__add_r2l(struct mosquitto *mosq, const char *topic, uint16_t alias) { int i; struct mosquitto__alias *aliases_new; for(i=0; ialias_count_r2l; i++){ if(mosq->aliases_r2l[i].alias == alias){ mosquitto_FREE(mosq->aliases_r2l[i].topic); mosq->aliases_r2l[i].topic = mosquitto_strdup(topic); if(mosq->aliases_r2l[i].topic){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOMEM; } } } /* New alias */ aliases_new = mosquitto_realloc(mosq->aliases_r2l, sizeof(struct mosquitto__alias)*(size_t)(mosq->alias_count_r2l+1)); if(!aliases_new){ return MOSQ_ERR_NOMEM; } mosq->aliases_r2l = aliases_new; mosq->alias_count_r2l++; mosq->aliases_r2l[mosq->alias_count_r2l-1].alias = alias; mosq->aliases_r2l[mosq->alias_count_r2l-1].topic = mosquitto_strdup(topic); if(!mosq->aliases_r2l[mosq->alias_count_r2l-1].topic){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } int alias__find_by_alias(struct mosquitto *mosq, int direction, uint16_t alias, char **topic) { int i; struct mosquitto__alias *aliases; int alias_count; if(direction == ALIAS_DIR_R2L){ aliases = mosq->aliases_r2l; alias_count = mosq->alias_count_r2l; }else{ aliases = mosq->aliases_l2r; alias_count = mosq->alias_count_l2r; } for(i=0; ialiases_r2l; alias_count = mosq->alias_count_r2l; }else{ aliases = mosq->aliases_l2r; alias_count = mosq->alias_count_l2r; } for(i=0; ialias_count_r2l; i++){ mosquitto_FREE(mosq->aliases_r2l[i].topic); } mosquitto_FREE(mosq->aliases_r2l); mosq->alias_count_r2l = 0; } static void alias__free_l2r(struct mosquitto *mosq) { int i; for(i=0; ialias_count_l2r; i++){ mosquitto_FREE(mosq->aliases_l2r[i].topic); } mosquitto_FREE(mosq->aliases_l2r); mosq->alias_count_l2r = 0; } void alias__free_all(struct mosquitto *mosq) { alias__free_r2l(mosq); alias__free_l2r(mosq); } ================================================ FILE: lib/alias_mosq.h ================================================ /* Copyright (c) 2019-2021 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 ALIAS_MOSQ_H #define ALIAS_MOSQ_H #include "mosquitto_internal.h" int alias__add_r2l(struct mosquitto *mosq, const char *topic, uint16_t alias); int alias__add_l2r(struct mosquitto *mosq, const char *topic, uint16_t *alias); int alias__find_by_alias(struct mosquitto *mosq, int direction, uint16_t alias, char **topic); int alias__find_by_topic(struct mosquitto *mosq, int direction, const char *topic, uint16_t *alias); void alias__free_all(struct mosquitto *mosq); #endif ================================================ FILE: lib/callbacks.c ================================================ /* Copyright (c) 2010-2021 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 "callbacks.h" #include "mosquitto.h" #include "mosquitto_internal.h" void mosquitto_connect_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_connect on_connect) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_connect = on_connect; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_connect_with_flags_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_connect_with_flags on_connect) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_connect_with_flags = on_connect; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_connect_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_connect_v5 on_connect) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_connect_v5 = on_connect; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_pre_connect_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_pre_connect on_pre_connect) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_pre_connect = on_pre_connect; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_disconnect_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_disconnect on_disconnect) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_disconnect = on_disconnect; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_disconnect_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_disconnect_v5 on_disconnect) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_disconnect_v5 = on_disconnect; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_publish_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_publish on_publish) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_publish = on_publish; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_publish_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_publish_v5 on_publish) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_publish_v5 = on_publish; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_message_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_message on_message) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_message = on_message; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_message_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_message_v5 on_message) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_message_v5 = on_message; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_subscribe_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_subscribe on_subscribe) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_subscribe = on_subscribe; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_subscribe_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_subscribe_v5 on_subscribe) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_subscribe_v5 = on_subscribe; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe on_unsubscribe) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_unsubscribe = on_unsubscribe; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_unsubscribe_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe_v5 on_unsubscribe) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_unsubscribe_v5 = on_unsubscribe; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_unsubscribe2_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe2_v5 on_unsubscribe) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_unsubscribe2_v5 = on_unsubscribe; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void mosquitto_log_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_log on_log) { COMPAT_pthread_mutex_lock(&mosq->log_callback_mutex); mosq->on_log = on_log; COMPAT_pthread_mutex_unlock(&mosq->log_callback_mutex); } void mosquitto_ext_auth_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_ext_auth on_ext_auth) { COMPAT_pthread_mutex_lock(&mosq->callback_mutex); mosq->on_ext_auth = on_ext_auth; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); } void callback__on_pre_connect(struct mosquitto *mosq) { LIBMOSQ_CB_pre_connect on_pre_connect; COMPAT_pthread_mutex_lock(&mosq->callback_mutex); on_pre_connect = mosq->on_pre_connect; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); mosq->callback_depth++; if(on_pre_connect){ on_pre_connect(mosq, mosq->userdata); } mosq->callback_depth--; } void callback__on_connect(struct mosquitto *mosq, uint8_t reason_code, uint8_t connect_flags, const mosquitto_property *properties) { LIBMOSQ_CB_connect on_connect; LIBMOSQ_CB_connect_with_flags on_connect_with_flags; LIBMOSQ_CB_connect_v5 on_connect_v5; COMPAT_pthread_mutex_lock(&mosq->callback_mutex); on_connect = mosq->on_connect; on_connect_with_flags = mosq->on_connect_with_flags; on_connect_v5 = mosq->on_connect_v5; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); mosq->callback_depth++; if(on_connect){ on_connect(mosq, mosq->userdata, reason_code); } if(on_connect_with_flags){ on_connect_with_flags(mosq, mosq->userdata, reason_code, connect_flags); } if(on_connect_v5){ on_connect_v5(mosq, mosq->userdata, reason_code, connect_flags, properties); } mosq->callback_depth--; } void callback__on_publish(struct mosquitto *mosq, int mid, int reason_code, const mosquitto_property *properties) { LIBMOSQ_CB_publish on_publish; LIBMOSQ_CB_publish_v5 on_publish_v5; COMPAT_pthread_mutex_lock(&mosq->callback_mutex); on_publish = mosq->on_publish; on_publish_v5 = mosq->on_publish_v5; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); mosq->callback_depth++; if(on_publish){ on_publish(mosq, mosq->userdata, mid); } if(on_publish_v5){ on_publish_v5(mosq, mosq->userdata, mid, reason_code, properties); } mosq->callback_depth--; } void callback__on_message(struct mosquitto *mosq, const struct mosquitto_message *message, const mosquitto_property *properties) { LIBMOSQ_CB_message on_message; LIBMOSQ_CB_message_v5 on_message_v5; COMPAT_pthread_mutex_lock(&mosq->callback_mutex); on_message = mosq->on_message; on_message_v5 = mosq->on_message_v5; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); mosq->callback_depth++; if(on_message){ on_message(mosq, mosq->userdata, message); } if(on_message_v5){ on_message_v5(mosq, mosq->userdata, message, properties); } mosq->callback_depth--; } void callback__on_subscribe(struct mosquitto *mosq, int mid, int qos_count, const int *granted_qos, const mosquitto_property *properties) { LIBMOSQ_CB_subscribe on_subscribe; LIBMOSQ_CB_subscribe_v5 on_subscribe_v5; COMPAT_pthread_mutex_lock(&mosq->callback_mutex); on_subscribe = mosq->on_subscribe; on_subscribe_v5 = mosq->on_subscribe_v5; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); mosq->callback_depth++; if(on_subscribe){ on_subscribe(mosq, mosq->userdata, mid, qos_count, granted_qos); } if(on_subscribe_v5){ on_subscribe_v5(mosq, mosq->userdata, mid, qos_count, granted_qos, properties); } mosq->callback_depth--; } void callback__on_unsubscribe(struct mosquitto *mosq, int mid, int reason_code_count, const int *reason_codes, const mosquitto_property *properties) { LIBMOSQ_CB_unsubscribe on_unsubscribe; LIBMOSQ_CB_unsubscribe_v5 on_unsubscribe_v5; LIBMOSQ_CB_unsubscribe2_v5 on_unsubscribe2_v5; COMPAT_pthread_mutex_lock(&mosq->callback_mutex); on_unsubscribe = mosq->on_unsubscribe; on_unsubscribe_v5 = mosq->on_unsubscribe_v5; on_unsubscribe2_v5 = mosq->on_unsubscribe2_v5; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); mosq->callback_depth++; if(on_unsubscribe){ on_unsubscribe(mosq, mosq->userdata, mid); } if(on_unsubscribe_v5){ on_unsubscribe_v5(mosq, mosq->userdata, mid, properties); } if(on_unsubscribe2_v5){ on_unsubscribe2_v5(mosq, mosq->userdata, mid, reason_code_count, reason_codes, properties); } mosq->callback_depth--; } void callback__on_disconnect(struct mosquitto *mosq, int rc, const mosquitto_property *properties) { LIBMOSQ_CB_disconnect on_disconnect; LIBMOSQ_CB_disconnect_v5 on_disconnect_v5; COMPAT_pthread_mutex_lock(&mosq->callback_mutex); on_disconnect = mosq->on_disconnect; on_disconnect_v5 = mosq->on_disconnect_v5; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); mosq->callback_depth++; if(on_disconnect){ on_disconnect(mosq, mosq->userdata, rc); } if(on_disconnect_v5){ on_disconnect_v5(mosq, mosq->userdata, rc, properties); } mosq->callback_depth--; } int callback__on_ext_auth(struct mosquitto *mosq, const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *properties) { int rc = MOSQ_ERR_AUTH; LIBMOSQ_CB_ext_auth on_ext_auth; COMPAT_pthread_mutex_lock(&mosq->callback_mutex); on_ext_auth = mosq->on_ext_auth; COMPAT_pthread_mutex_unlock(&mosq->callback_mutex); mosq->callback_depth++; if(on_ext_auth){ rc = on_ext_auth(mosq, mosq->userdata, auth_method, auth_data_len, auth_data, properties); } mosq->callback_depth--; return rc; } ================================================ FILE: lib/callbacks.h ================================================ /* Copyright (c) 2021 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ #ifndef CALLBACKS_H #define CALLBACKS_H #include "mosquitto.h" void callback__on_pre_connect(struct mosquitto *mosq); void callback__on_connect(struct mosquitto *mosq, uint8_t reason_code, uint8_t connect_flags, const mosquitto_property *properties); void callback__on_publish(struct mosquitto *mosq, int mid, int reason_code, const mosquitto_property *properties); void callback__on_message(struct mosquitto *mosq, const struct mosquitto_message *message, const mosquitto_property *properties); void callback__on_subscribe(struct mosquitto *mosq, int mid, int qos_count, const int *granted_qos, const mosquitto_property *props); void callback__on_unsubscribe(struct mosquitto *mosq, int mid, int reason_code_count, const int *reason_codes, const mosquitto_property *props); void callback__on_disconnect(struct mosquitto *mosq, int rc, const mosquitto_property *props); int callback__on_ext_auth(struct mosquitto *mosq, const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *properties); #endif ================================================ FILE: lib/connect.c ================================================ /* Copyright (c) 2010-2021 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 WIN32 # include # include #else # include # include #endif #include "callbacks.h" #include "http_client.h" #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "messages_mosq.h" #include "packet_mosq.h" #include "property_common.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 = mosquitto_getrandom(&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; mosquitto__set_request_disconnect(mosq, false); 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); } int 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; } } } return 1; } 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; } } COMPAT_pthread_mutex_lock(&mosq->msgtime_mutex); mosq->last_msg_in = mosquitto_time(); mosq->next_msg_out = mosq->last_msg_in + mosq->keepalive; COMPAT_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(net__is_connected(mosq)){ net__socket_close(mosq); } callback__on_pre_connect(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); } char address[1024]; uint16_t port; get_address(mosq->sock, address, 1024, &port); 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); #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN if(mosq->transport == mosq_t_ws){ http_c__context_init(mosq); }else #endif { rc = send__connect(mosq, mosq->keepalive, mosq->clean_start, outgoing_properties); if(rc){ packet__cleanup_all(mosq); net__socket_close(mosq); } } 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); mosquitto__set_request_disconnect(mosq, true); if(!net__is_connected(mosq)){ 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 */ packet__cleanup_all(mosq); COMPAT_pthread_mutex_lock(&mosq->msgtime_mutex); mosq->next_msg_out = mosquitto_time() + mosq->keepalive; COMPAT_pthread_mutex_unlock(&mosq->msgtime_mutex); callback__on_disconnect(mosq, reason_code, properties); } ================================================ FILE: lib/cpp/CMakeLists.txt ================================================ set(CPP_SRC mosquittopp.cpp ../../include/mosquitto/libmosquittopp.h) add_library(mosquittopp SHARED ${CPP_SRC} ) set_target_properties(mosquittopp PROPERTIES POSITION_INDEPENDENT_CODE 1 ) target_include_directories(mosquittopp PUBLIC "${mosquitto_SOURCE_DIR}/include" ) target_link_libraries(mosquittopp PUBLIC libmosquitto PRIVATE common-options ) if (WITH_THREADING AND NOT WIN32) set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) target_link_libraries(mosquittopp PRIVATE Threads::Threads) endif() set_target_properties(mosquittopp PROPERTIES VERSION ${VERSION} SOVERSION 1 ) install(TARGETS mosquittopp RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" 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() target_include_directories(mosquittopp_static PRIVATE "${mosquitto_SOURCE_DIR}/include" "${mosquitto_SOURCE_DIR}/lib" "${mosquitto_SOURCE_DIR}/lib/cpp" ) target_link_libraries(mosquittopp_static PRIVATE ${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() ================================================ FILE: lib/cpp/Makefile ================================================ R=../.. include ${R}/config.mk ifeq ($(or $(findstring $(UNAME),SunOS), $(findstring $(UNAME),AIX)),) LOCAL_LDFLAGS+=-Wl,-soname,libmosquittopp.so.${SOVERSION} endif LOCAL_CPPFLAGS+= LOCAL_CXXFLAGS+=-fPIC LOCAL_LIBADD+= .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" ifneq ($(UNAME),AIX) ${CROSS_COMPILE}${STRIP} -g --strip-unneeded "${DESTDIR}${libdir}/libmosquittopp.a" endif endif $(INSTALL) -d "${DESTDIR}${libdir}/pkgconfig/" $(INSTALL) -m644 ${R}/libmosquittopp.pc.in "${DESTDIR}${libdir}/pkgconfig/libmosquittopp.pc" sed ${SEDINPLACE} -e "s#@CMAKE_INSTALL_PREFIX@#${prefix}#" -e "s#@CMAKE_INSTALL_LIBDIR@#lib${LIB_SUFFIX}#" -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" clean : -rm -f *.o libmosquittopp.so.${SOVERSION} libmosquittopp.a libmosquittopp.so.${SOVERSION} : mosquittopp.o ${CROSS_COMPILE}$(CXX) -shared $(LOCAL_LDFLAGS) $< -o $@ ../libmosquitto.so.${SOVERSION} $(LOCAL_LIDADD) libmosquittopp.a : mosquittopp.o ${CROSS_COMPILE}$(AR) cr $@ $^ mosquittopp.o : mosquittopp.cpp ${R}/include/mosquitto/libmosquittopp.h ${CROSS_COMPILE}$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_CXXFLAGS) -c $< -o $@ ================================================ FILE: lib/cpp/mosquittopp.cpp ================================================ /* 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_pre_connect_wrapper(struct mosquitto *mosq, void *userdata) { class mosquittopp *m = (class mosquittopp *) userdata; UNUSED(mosq); m->on_pre_connect(); } 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_connect_v5_wrapper(struct mosquitto *mosq, void *userdata, int rc, int flags, const mosquitto_property *props) { class mosquittopp *m = (class mosquittopp *) userdata; UNUSED(mosq); m->on_connect_v5(rc, flags, props); } 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_disconnect_v5_wrapper(struct mosquitto *mosq, void *userdata, int rc, const mosquitto_property *props) { class mosquittopp *m = (class mosquittopp *) userdata; UNUSED(mosq); m->on_disconnect_v5(rc, props); } 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_publish_v5_wrapper(struct mosquitto *mosq, void *userdata, int mid, int reason_code, const mosquitto_property *props) { class mosquittopp *m = (class mosquittopp *) userdata; UNUSED(mosq); m->on_publish_v5(mid, reason_code, props); } 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_message_v5_wrapper(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message, const mosquitto_property *props) { class mosquittopp *m = (class mosquittopp *) userdata; UNUSED(mosq); m->on_message_v5(message, props); } 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_subscribe_v5_wrapper(struct mosquitto *mosq, void *userdata, int mid, int qos_count, const int *granted_qos, const mosquitto_property *props) { class mosquittopp *m = (class mosquittopp *) userdata; UNUSED(mosq); m->on_subscribe_v5(mid, qos_count, granted_qos, props); } 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_unsubscribe_v5_wrapper(struct mosquitto *mosq, void *userdata, int mid, const mosquitto_property *props) { class mosquittopp *m = (class mosquittopp *) userdata; UNUSED(mosq); m->on_unsubscribe_v5(mid, props); } static int on_ext_auth_wrapper(struct mosquitto *mosq, void *userdata, const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *props) { class mosquittopp *m = (class mosquittopp *) userdata; UNUSED(mosq); return m->on_ext_auth(auth_method, auth_data_len, auth_data, props); } 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 property_check_command(int command, int identifier) { return mosquitto_property_check_command(command, identifier); } int property_check_all(int command, const mosquitto_property *properties) { return mosquitto_property_check_all(command, properties); } const char *reason_string(int reason_code) { return mosquitto_reason_string(reason_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 topic_matches_sub_with_pattern(const char *sub, const char *topic, const char *clientid, const char *username, bool *result) { return mosquitto_topic_matches_sub_with_pattern(sub, topic, clientid, username, result); } int sub_matches_acl(const char *acl, const char *sub, bool *result) { return mosquitto_sub_matches_acl(acl, sub, result); } int sub_matches_acl_with_pattern(const char *acl, const char *sub, const char *clientid, const char *username, bool *result) { return mosquitto_sub_matches_acl_with_pattern(acl, sub, clientid, username, 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 *clientid, 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, clientid, 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 *clientid, 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, clientid, keepalive, clean_session, username, password, will, tls); } namespace { void mosquitto_callbacks_set(struct mosquitto *mosq) { mosquitto_pre_connect_callback_set(mosq, on_pre_connect_wrapper); mosquitto_connect_callback_set(mosq, on_connect_wrapper); mosquitto_connect_with_flags_callback_set(mosq, on_connect_with_flags_wrapper); mosquitto_connect_v5_callback_set(mosq, on_connect_v5_wrapper); mosquitto_disconnect_callback_set(mosq, on_disconnect_wrapper); mosquitto_disconnect_v5_callback_set(mosq, on_disconnect_v5_wrapper); mosquitto_publish_callback_set(mosq, on_publish_wrapper); mosquitto_publish_v5_callback_set(mosq, on_publish_v5_wrapper); mosquitto_message_callback_set(mosq, on_message_wrapper); mosquitto_message_v5_callback_set(mosq, on_message_v5_wrapper); mosquitto_subscribe_callback_set(mosq, on_subscribe_wrapper); mosquitto_subscribe_v5_callback_set(mosq, on_subscribe_v5_wrapper); mosquitto_unsubscribe_callback_set(mosq, on_unsubscribe_wrapper); mosquitto_unsubscribe_v5_callback_set(mosq, on_unsubscribe_v5_wrapper); mosquitto_ext_auth_callback_set(mosq, on_ext_auth_wrapper); mosquitto_log_callback_set(mosq, on_log_wrapper); } } mosquittopp::mosquittopp(const char *id, bool clean_session) { m_mosq = mosquitto_new(id, clean_session, this); if(m_mosq){ mosquitto_callbacks_set(m_mosq); } } 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_callbacks_set(m_mosq); } 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_v5(const char *host, int port, int keepalive, const char *bind_address, const mosquitto_property *properties) { return mosquitto_connect_bind_v5(m_mosq, host, port, keepalive, bind_address, properties); } 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::disconnect_v5(int reason_code, const mosquitto_property *properties) { return mosquitto_disconnect_v5(m_mosq, reason_code, properties); } int mosquittopp::ext_auth_continue(const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *properties) { return mosquitto_ext_auth_continue(m_mosq, auth_method, auth_data_len, auth_data, properties); } 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_set_v5(const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties) { return mosquitto_will_set_v5(m_mosq, topic, payloadlen, payload, qos, retain, properties); } 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); } int mosquittopp::publish_v5(int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain, const mosquitto_property *properties) { return mosquitto_publish_v5(m_mosq, mid, topic, payloadlen, payload, qos, retain, properties); } 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::subscribe_v5(int *mid, const char *sub, int qos, int options, const mosquitto_property *properties) { return mosquitto_subscribe_v5(m_mosq, mid, sub, qos, options, properties); } int mosquittopp::unsubscribe(int *mid, const char *sub) { return mosquitto_unsubscribe(m_mosq, mid, sub); } int mosquittopp::unsubscribe_v5(int *mid, const char *sub, const mosquitto_property *properties) { return mosquitto_unsubscribe_v5(m_mosq, mid, sub, properties); } 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::int_option(enum mosq_opt_t option, int value) { return mosquitto_int_option(m_mosq, option, value); } int mosquittopp::string_option(enum mosq_opt_t option, const char *value) { return mosquitto_string_option(m_mosq, option, value); } int mosquittopp::void_option(enum mosq_opt_t option, void *value) { return mosquitto_void_option(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); } } ================================================ FILE: lib/extended_auth.c ================================================ /* Copyright (c) 2019-2024 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/mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "util_mosq.h" int mosquitto_ext_auth_continue(struct mosquitto *context, const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *input_props) { struct mosquitto__packet *packet = NULL; int rc; uint32_t remaining_length; mosquitto_property *properties = NULL; rc = mosquitto_property_copy_all(&properties, input_props); if(rc){ return rc; } if(!context || context->protocol != mosq_p_mqtt5 || !auth_method){ return MOSQ_ERR_PROTOCOL; } remaining_length = 1; rc = mosquitto_property_add_string(&properties, MQTT_PROP_AUTHENTICATION_METHOD, auth_method); if(rc){ goto error; } 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){ goto error; } } remaining_length += mosquitto_property_get_remaining_length(properties); rc = packet__check_oversize(context, remaining_length); if(rc){ goto error; } rc = packet__alloc(&packet, CMD_AUTH, remaining_length); if(rc){ goto error; } packet__write_byte(packet, MQTT_RC_CONTINUE_AUTHENTICATION); property__write_all(packet, properties, true); mosquitto_property_free_all(&properties); return packet__queue(context, packet); error: mosquitto_property_free_all(&properties); return rc; } ================================================ FILE: lib/handle_auth.c ================================================ /* Copyright (c) 2018-2021 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 "callbacks.h" #include "logging_mosq.h" #include "mosquitto_internal.h" #include "mosquitto/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; char *auth_method = NULL; void *auth_data = NULL; uint16_t auth_data_len = 0; mosquitto_property *properties = NULL; if(!mosq){ return MOSQ_ERR_INVAL; } log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received AUTH", SAFE_PRINT(mosq->id)); if(mosq->protocol != mosq_p_mqtt5){ return MOSQ_ERR_PROTOCOL; } if(mosq->in_packet.command != CMD_AUTH){ return MOSQ_ERR_MALFORMED_PACKET; } 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_read_string(properties, MQTT_PROP_AUTHENTICATION_METHOD, &auth_method, false); mosquitto_property_read_binary(properties, MQTT_PROP_AUTHENTICATION_DATA, &auth_data, &auth_data_len, false); rc = callback__on_ext_auth(mosq, auth_method, auth_data_len, auth_data, properties); mosquitto_property_free_all(&properties); return rc; } ================================================ FILE: lib/handle_connack.c ================================================ /* Copyright (c) 2009-2021 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 "callbacks.h" #include "logging_mosq.h" #include "messages_mosq.h" #include "mosquitto/mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "read_handle.h" #include "util_mosq.h" int handle__connack(struct mosquitto *mosq) { uint8_t connect_flags; uint8_t reason_code; int rc; mosquitto_property *properties = NULL; char *clientid = NULL; enum mosquitto_client_state state; assert(mosq); state = mosquitto__get_state(mosq); if(state != mosq_cs_new && state != mosq_cs_connected){ log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received duplicate CONNACK", mosq->id); return MOSQ_ERR_PROTOCOL; } if(mosq->in_packet.command != CMD_CONNACK || ((mosq->protocol == 3 || mosq->protocol == 4) && mosq->in_packet.remaining_length != 2)){ return MOSQ_ERR_MALFORMED_PACKET; } rc = packet__read_byte(&mosq->in_packet, &connect_flags); if(rc){ return rc; } if((mosq->protocol == mosq_p_mqtt311 || mosq->protocol == mosq_p_mqtt5) && (connect_flags & 0xFE)){ log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received CONNACK with invalid connect flags (%d)", mosq->id, connect_flags); return MOSQ_ERR_PROTOCOL; } if(mosq->clean_start && connect_flags){ log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received CONNACK with session present when clean start was set", mosq->id); return MOSQ_ERR_PROTOCOL; } 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. */ log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received CONNACK (%d)", mosq->id, reason_code); callback__on_connect(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. */ mosquitto_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_int16(properties, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, &mosq->alias_max_l2r, 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); log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received CONNACK (%d)", mosq->id, reason_code); if(reason_code == MQTT_RC_SUCCESS){ mosq->reconnects = 0; } callback__on_connect(mosq, reason_code, connect_flags, properties); mosquitto_property_free_all(&properties); switch(reason_code){ case 0: COMPAT_pthread_mutex_lock(&mosq->state_mutex); if(mosq->state != mosq_cs_disconnecting){ mosq->state = mosq_cs_active; } COMPAT_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; } } ================================================ FILE: lib/handle_disconnect.c ================================================ /* Copyright (c) 2009-2021 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/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__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; } if(mosq->in_packet.command != CMD_DISCONNECT){ return MOSQ_ERR_MALFORMED_PACKET; } 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; } ================================================ FILE: lib/handle_ping.c ================================================ /* Copyright (c) 2009-2021 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 "messages_mosq.h" #include "mosquitto/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){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PINGREQ before session is active.", mosq->id); #endif return MOSQ_ERR_PROTOCOL; } if(mosq->in_packet.command != CMD_PINGREQ || mosq->in_packet.remaining_length != 0){ return MOSQ_ERR_MALFORMED_PACKET; } #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Received PINGREQ from %s", SAFE_PRINT(mosq->id)); return send__pingresp(mosq); #else return MOSQ_ERR_PROTOCOL; #endif } int handle__pingresp(struct mosquitto *mosq) { assert(mosq); if(mosquitto__get_state(mosq) != mosq_cs_active){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PINGRESP before session is active.", mosq->id); #endif return MOSQ_ERR_PROTOCOL; } if(mosq->in_packet.command != CMD_PINGRESP || mosq->in_packet.remaining_length != 0){ return MOSQ_ERR_MALFORMED_PACKET; } mosq->ping_t = 0; /* No longer waiting for a PINGRESP. */ #ifdef WITH_BROKER if(mosq->bridge == NULL){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PINGRESP when not a bridge.", mosq->id); return MOSQ_ERR_PROTOCOL; } log__printf(NULL, MOSQ_LOG_DEBUG, "Received PINGRESP from %s", SAFE_PRINT(mosq->id)); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received PINGRESP", SAFE_PRINT(mosq->id)); #endif return MOSQ_ERR_SUCCESS; } ================================================ FILE: lib/handle_pubackcomp.c ================================================ /* Copyright (c) 2009-2021 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 "callbacks.h" #include "mosquitto.h" #include "logging_mosq.h" #include "messages_mosq.h" #include "mosquitto/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){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: %s before session is active.", mosq->id, type); #endif return MOSQ_ERR_PROTOCOL; } if(mosq->protocol != mosq_p_mqtt31){ if((mosq->in_packet.command&0x0F) != 0x00){ return MOSQ_ERR_MALFORMED_PACKET; } } COMPAT_pthread_mutex_lock(&mosq->msgs_out.mutex); util__increment_send_quota(mosq); COMPAT_pthread_mutex_unlock(&mosq->msgs_out.mutex); rc = packet__read_uint16(&mosq->in_packet, &mid); if(rc){ return rc; } if(type[3] == 'A'){ /* pubAck or pubComp */ if(mosq->in_packet.command != CMD_PUBACK){ return MOSQ_ERR_MALFORMED_PACKET; } qos = 1; }else{ if(mosq->in_packet.command != CMD_PUBCOMP){ return MOSQ_ERR_MALFORMED_PACKET; } qos = 2; } if(mid == 0){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: %s with mid = 0.", mosq->id, type); #endif 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; } } if(type[3] == 'A'){ /* pubAck or pubComp */ if(reason_code != MQTT_RC_SUCCESS && reason_code != MQTT_RC_NO_MATCHING_SUBSCRIBERS && reason_code != MQTT_RC_UNSPECIFIED && reason_code != MQTT_RC_IMPLEMENTATION_SPECIFIC && reason_code != MQTT_RC_NOT_AUTHORIZED && reason_code != MQTT_RC_TOPIC_NAME_INVALID && reason_code != MQTT_RC_PACKET_ID_IN_USE && reason_code != MQTT_RC_QUOTA_EXCEEDED && reason_code != MQTT_RC_PAYLOAD_FORMAT_INVALID ){ mosquitto_property_free_all(&properties); #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: %s with reason code = %d.", mosq->id, type, reason_code); #endif return MOSQ_ERR_PROTOCOL; } }else{ if(reason_code != MQTT_RC_SUCCESS && reason_code != MQTT_RC_PACKET_ID_NOT_FOUND ){ mosquitto_property_free_all(&properties); #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: %s with reason code = %d.", mosq->id, type, reason_code); #endif return MOSQ_ERR_PROTOCOL; } } } if(mosq->in_packet.pos < mosq->in_packet.remaining_length){ mosquitto_property_free_all(&properties); return MOSQ_ERR_MALFORMED_PACKET; } #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Received %s from %s (Mid: %d, RC:%d)", type, SAFE_PRINT(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, SAFE_PRINT(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)", SAFE_PRINT(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. */ callback__on_publish(mosq, mid, reason_code, properties); mosquitto_property_free_all(&properties); }else{ mosquitto_property_free_all(&properties); if(rc != MOSQ_ERR_NOT_FOUND){ return rc; } } COMPAT_pthread_mutex_lock(&mosq->msgs_out.mutex); message__release_to_inflight(mosq, mosq_md_out); COMPAT_pthread_mutex_unlock(&mosq->msgs_out.mutex); return MOSQ_ERR_SUCCESS; #endif } ================================================ FILE: lib/handle_publish.c ================================================ /* Copyright (c) 2009-2021 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 "alias_mosq.h" #include "callbacks.h" #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "mosquitto/mqtt_protocol.h" #include "messages_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "util_mosq.h" static int property__process_publish(struct mosquitto *mosq, mosquitto_property *props, struct mosquitto_message_all *message, uint16_t *topic_alias) { while(props){ switch(mosquitto_property_identifier(props)){ 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: case MQTT_PROP_USER_PROPERTY: /* Allowed */ break; case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: /* Allowed */ if(mosquitto_property_varint_value(props) == 0){ return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_TOPIC_ALIAS: { *topic_alias = mosquitto_property_int16_value(props); if(*topic_alias == 0 || *topic_alias > mosq->alias_max_l2r){ return MOSQ_ERR_TOPIC_ALIAS_INVALID; } if(message->msg.topic){ /* Set a new topic alias */ if(alias__add_r2l(mosq, message->msg.topic, *topic_alias)){ return MOSQ_ERR_NOMEM; } }else{ /* Retrieve an existing topic alias */ mosquitto_FREE(message->msg.topic); if(alias__find_by_alias(mosq, ALIAS_DIR_R2L, *topic_alias, &message->msg.topic)){ return MOSQ_ERR_PROTOCOL; } } } break; default: return MOSQ_ERR_PROTOCOL; } props = mosquitto_property_next(props); } return MOSQ_ERR_SUCCESS; } 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; uint16_t topic_alias = 0; 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(mosq->protocol != mosq_p_mqtt5 && slen == 0){ 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; } rc = property__process_publish(mosq, properties, message, &topic_alias); if(rc){ message__cleanup(&message); mosquitto_property_free_all(&properties); return rc; } } /* If we haven't got a topic at this point, it's a protocol error. */ if(topic_alias == 0 && message->msg.topic == NULL){ message__cleanup(&message); mosquitto_property_free_all(&properties); return MOSQ_ERR_PROTOCOL; } if(mosquitto_pub_topic_check(message->msg.topic) != MOSQ_ERR_SUCCESS){ message__cleanup(&message); mosquitto_property_free_all(&properties); return MOSQ_ERR_MALFORMED_PACKET; } 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))", SAFE_PRINT(mosq->id), message->dup, message->msg.qos, message->msg.retain, message->msg.mid, message->msg.topic, (long)message->msg.payloadlen); switch(message->msg.qos){ case 0: callback__on_message(mosq, &message->msg, properties); 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); callback__on_message(mosq, &message->msg, properties); 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); COMPAT_pthread_mutex_lock(&mosq->msgs_in.mutex); message->state = mosq_ms_wait_for_pubrel; message__queue(mosq, message, mosq_md_in); COMPAT_pthread_mutex_unlock(&mosq->msgs_in.mutex); return rc; default: message__cleanup(&message); mosquitto_property_free_all(&properties); return MOSQ_ERR_PROTOCOL; } } ================================================ FILE: lib/handle_pubrec.c ================================================ /* Copyright (c) 2009-2021 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 "callbacks.h" #include "mosquitto.h" #include "logging_mosq.h" #include "messages_mosq.h" #include "mosquitto/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){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBREC before session is active.", mosq->id); #endif return MOSQ_ERR_PROTOCOL; } if(mosq->in_packet.command != CMD_PUBREC){ return MOSQ_ERR_MALFORMED_PACKET; } rc = packet__read_uint16(&mosq->in_packet, &mid); if(rc){ return rc; } if(mid == 0){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBREC with mid = 0.", mosq->id); #endif 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(reason_code != MQTT_RC_SUCCESS && reason_code != MQTT_RC_NO_MATCHING_SUBSCRIBERS && reason_code != MQTT_RC_UNSPECIFIED && reason_code != MQTT_RC_IMPLEMENTATION_SPECIFIC && reason_code != MQTT_RC_NOT_AUTHORIZED && reason_code != MQTT_RC_TOPIC_NAME_INVALID && reason_code != MQTT_RC_PACKET_ID_IN_USE && reason_code != MQTT_RC_QUOTA_EXCEEDED && reason_code != MQTT_RC_PAYLOAD_FORMAT_INVALID){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBREC with reason code = %d.", mosq->id, reason_code); #endif return MOSQ_ERR_PROTOCOL; } if(mosq->in_packet.remaining_length > 3){ rc = property__read_all(CMD_PUBREC, &mosq->in_packet, &properties); if(rc){ if(rc == MOSQ_ERR_PROTOCOL){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBREC with invalid properties.", mosq->id); #endif } return rc; } /* Immediately free, we don't do anything with Reason String or User Property at the moment */ mosquitto_property_free_all(&properties); } } if(mosq->in_packet.pos < mosq->in_packet.remaining_length){ #ifdef WITH_BROKER mosquitto_property_free_all(&properties); #endif return MOSQ_ERR_MALFORMED_PACKET; } #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Received PUBREC from %s (Mid: %d)", SAFE_PRINT(mosq->id), mid); if(reason_code < 0x80){ rc = db__message_update_outgoing(mosq, mid, mosq_ms_wait_for_pubcomp, 2, true); }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)", SAFE_PRINT(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. */ callback__on_publish(mosq, mid, reason_code, properties); } util__increment_send_quota(mosq); COMPAT_pthread_mutex_lock(&mosq->msgs_out.mutex); message__release_to_inflight(mosq, mosq_md_out); COMPAT_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.", SAFE_PRINT(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; } ================================================ FILE: lib/handle_pubrel.c ================================================ /* Copyright (c) 2009-2021 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 "callbacks.h" #include "mosquitto.h" #include "logging_mosq.h" #include "messages_mosq.h" #include "mosquitto/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){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBREL before session is active.", mosq->id); #endif return MOSQ_ERR_PROTOCOL; } if(mosq->protocol != mosq_p_mqtt31 && mosq->in_packet.command != (CMD_PUBREL|2)){ return MOSQ_ERR_MALFORMED_PACKET; } if(mosq->protocol != mosq_p_mqtt31){ if((mosq->in_packet.command&0x0F) != 0x02){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBREL with non-zero reserved flags (%02X).", mosq->id, mosq->in_packet.command); #endif return MOSQ_ERR_PROTOCOL; } } rc = packet__read_uint16(&mosq->in_packet, &mid); if(rc){ return rc; } if(mid == 0){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBREL with mid = 0.", mosq->id); #endif 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(reason_code != MQTT_RC_SUCCESS && reason_code != MQTT_RC_PACKET_ID_NOT_FOUND){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBREL with reason code = %d.", mosq->id, reason_code); #endif return MOSQ_ERR_PROTOCOL; } if(mosq->in_packet.remaining_length > 3){ rc = property__read_all(CMD_PUBREL, &mosq->in_packet, &properties); /* Immediately free, we don't do anything with Reason String or * User Property at the moment */ mosquitto_property_free_all(&properties); if(rc){ if(rc == MOSQ_ERR_PROTOCOL){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBREL with invalid properties.", mosq->id); #endif } return rc; } } } if(mosq->in_packet.pos < mosq->in_packet.remaining_length){ return MOSQ_ERR_MALFORMED_PACKET; } #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Received PUBREL from %s (Mid: %d)", SAFE_PRINT(mosq->id), mid); 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)", SAFE_PRINT(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. */ callback__on_message(mosq, &message->msg, message->properties); message__cleanup(&message); }else if(rc == MOSQ_ERR_NOT_FOUND){ return MOSQ_ERR_SUCCESS; }else{ return rc; } #endif return MOSQ_ERR_SUCCESS; } ================================================ FILE: lib/handle_suback.c ================================================ /* Copyright (c) 2009-2021 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 "callbacks.h" #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "mosquitto/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){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: SUBACK before session is active.", mosq->id); #endif return MOSQ_ERR_PROTOCOL; } if(mosq->in_packet.command != CMD_SUBACK){ return MOSQ_ERR_MALFORMED_PACKET; } #ifdef WITH_BROKER if(mosq->bridge == NULL){ /* Client is not a bridge, so shouldn't be sending SUBACK */ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: SUBACK when not a bridge.", mosq->id); return MOSQ_ERR_PROTOCOL; } log__printf(NULL, MOSQ_LOG_DEBUG, "Received SUBACK from %s", SAFE_PRINT(mosq->id)); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received SUBACK", SAFE_PRINT(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); if(qos_count == 0){ mosquitto_property_free_all(&properties); return MOSQ_ERR_PROTOCOL; } granted_qos = mosquitto_malloc((size_t)qos_count*sizeof(int)); if(!granted_qos){ mosquitto_property_free_all(&properties); 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); mosquitto_property_free_all(&properties); 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 callback__on_subscribe(mosq, mid, qos_count, granted_qos, properties); mosquitto_property_free_all(&properties); #endif mosquitto_FREE(granted_qos); return MOSQ_ERR_SUCCESS; } ================================================ FILE: lib/handle_unsuback.c ================================================ /* Copyright (c) 2009-2021 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 "callbacks.h" #include "mosquitto.h" #include "logging_mosq.h" #include "messages_mosq.h" #include "mosquitto/mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "util_mosq.h" int handle__unsuback(struct mosquitto *mosq) { uint16_t mid; int rc; mosquitto_property *properties = NULL; int *reason_codes = NULL; int reason_code_count = 0; assert(mosq); if(mosquitto__get_state(mosq) != mosq_cs_active){ #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: UNSUBACK before session is active.", mosq->id); #endif return MOSQ_ERR_PROTOCOL; } if(mosq->in_packet.command != CMD_UNSUBACK){ return MOSQ_ERR_MALFORMED_PACKET; } #ifdef WITH_BROKER if(mosq->bridge == NULL){ /* Client is not a bridge, so shouldn't be sending SUBACK */ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: UNSUBACK when not a bridge.", mosq->id); return MOSQ_ERR_PROTOCOL; } log__printf(NULL, MOSQ_LOG_DEBUG, "Received UNSUBACK from %s", SAFE_PRINT(mosq->id)); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s received UNSUBACK", SAFE_PRINT(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; } uint8_t byte; reason_code_count = (int)(mosq->in_packet.remaining_length - mosq->in_packet.pos); reason_codes = mosquitto_malloc((size_t)reason_code_count*sizeof(int)); if(!reason_codes){ mosquitto_property_free_all(&properties); return MOSQ_ERR_NOMEM; } for(int i=0; iin_packet, &byte); if(rc){ mosquitto_FREE(reason_codes); mosquitto_property_free_all(&properties); return rc; } reason_codes[i] = (int)byte; } } #ifndef WITH_BROKER callback__on_unsubscribe(mosq, mid, reason_code_count, reason_codes, properties); #endif mosquitto_property_free_all(&properties); mosquitto_FREE(reason_codes); return MOSQ_ERR_SUCCESS; } ================================================ FILE: lib/helpers.c ================================================ /* Copyright (c) 2016-2021 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 *clientid, 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 = mosquitto_calloc((size_t)msg_count, sizeof(struct mosquitto_message)); 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, clientid, 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; } ================================================ FILE: lib/http_client.c ================================================ /* Copyright (c) 2021 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN #include #include #include #include "mosquitto_internal.h" #include "http_client.h" #include "mosquitto/mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "read_handle.h" #include "send_mosq.h" #include "util_mosq.h" #include "picohttpparser.h" static int create_request_key(char **encoded) { uint8_t bytes[16]; mosquitto_getrandom(bytes, sizeof(bytes)); return mosquitto_base64_encode(bytes, sizeof(bytes), encoded); } int http_c__context_init(struct mosquitto *context) { struct mosquitto__packet *packet; char *key; const char *path; context->transport = mosq_t_http; context->http_request = mosquitto_calloc(1, (size_t)context->wsd.http_header_size + 1); if(context->http_request == NULL){ return MOSQ_ERR_NOMEM; } if(create_request_key(&key)){ return MOSQ_ERR_UNKNOWN; } if(ws__create_accept_key(key, strlen(key), &context->wsd.accept_key)){ return MOSQ_ERR_UNKNOWN; } packet = mosquitto_calloc(1, sizeof(struct mosquitto__packet) + 1024 + WS_PACKET_OFFSET); if(!packet){ return MOSQ_ERR_NOMEM; } path = context->wsd.http_path?context->wsd.http_path:"/mqtt"; packet->packet_length = (uint32_t )snprintf((char *)&packet->payload[WS_PACKET_OFFSET], 1024, "GET %s HTTP/1.1\r\n" "Host: %s\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Key: %s\r\n" "Sec-WebSocket-Protocol: mqtt\r\n" "Sec-WebSocket-Version: 13\r\n" "\r\n", path, context->host, key); mosquitto_FREE(key); packet->packet_length += WS_PACKET_OFFSET; packet->to_process = packet->packet_length; context->http_request[0] = '\0'; return packet__queue(context, packet); } int http_c__context_cleanup(struct mosquitto *context) { mosquitto_FREE(context->wsd.accept_key); mosquitto_FREE(context->http_request); return MOSQ_ERR_SUCCESS; } int http_c__read(struct mosquitto *mosq) { ssize_t read_length; enum mosquitto_client_state state; size_t hlen; int http_status; const char *http_msg; size_t http_msg_len; int http_minor_version; size_t http_header_count = 100; struct phr_header http_headers[100]; const char *client_key = NULL; size_t client_key_len = 0; size_t i; bool header_have_upgrade; bool header_have_connection; bool header_have_subprotocol; int rc = MOSQ_ERR_SUCCESS; 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; } hlen = strlen(mosq->http_request); read_length = net__read(mosq, &mosq->http_request[hlen], (size_t)mosq->wsd.http_header_size-hlen); if(read_length <= 0){ if(read_length == 0){ return MOSQ_ERR_CONN_LOST; /* EOF */ } WINDOWS_SET_ERRNO_RW(); 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; } } } hlen += (size_t)read_length; mosq->http_request[hlen] = '\0'; read_length = phr_parse_response(mosq->http_request, hlen, &http_minor_version, &http_status, &http_msg, &http_msg_len, http_headers, &http_header_count, 0); if(read_length == -2){ // Partial read return MOSQ_ERR_SUCCESS; }else if(read_length == -1){ // Error return MOSQ_ERR_UNKNOWN; } if(http_status != 101){ mosquitto_FREE(mosq->http_request); /* FIXME Not supported - send 501 response */ return MOSQ_ERR_UNKNOWN; } header_have_upgrade = false; header_have_connection = false; header_have_subprotocol = false; for(i=0; iwsd.accept_key, client_key, client_key_len)){ // FIXME - 50x return MOSQ_ERR_UNKNOWN; } http_c__context_cleanup(mosq); ws__context_init(mosq); //* FIXME outgoing properites rc = send__connect(mosq, mosq->keepalive, mosq->clean_start, NULL); if(rc){ packet__cleanup_all(mosq); net__socket_close(mosq); mosquitto__set_state(mosq, mosq_cs_new); } return rc; } #endif ================================================ FILE: lib/http_client.h ================================================ /* Copyright (c) 2021 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ #ifndef HTTP_CLIENT_H #define HTTP_CLIENT_H #include "config.h" #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN #include "mosquitto_internal.h" int http_c__context_init(struct mosquitto *context); int http_c__context_cleanup(struct mosquitto *context); int http_c__read(struct mosquitto *mosq); #endif #endif ================================================ FILE: lib/libmosquitto.c ================================================ /* Copyright (c) 2010-2021 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 "messages_mosq.h" #include "mosquitto/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){ mosquitto_time_init(); 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; } static int alloc_packet_buffer(struct mosquitto *mosq) { mosq->in_packet.packet_buffer_size = 4096; mosq->in_packet.packet_buffer = mosquitto_calloc(1, mosq->in_packet.packet_buffer_size); return !mosq->in_packet.packet_buffer; } 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; } mosq = (struct mosquitto *)mosquitto_calloc(1, sizeof(struct mosquitto)); if(mosq){ mosq->sock = INVALID_SOCKET; #ifdef WITH_THREADING # ifndef WIN32 /* Windows doesn't have pthread_cancel, so no need to record self */ mosq->thread_id = pthread_self(); # endif #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)); #ifdef WITH_THREADING COMPAT_pthread_mutex_init(&mosq->callback_mutex, NULL); COMPAT_pthread_mutex_init(&mosq->log_callback_mutex, NULL); COMPAT_pthread_mutex_init(&mosq->state_mutex, NULL); COMPAT_pthread_mutex_init(&mosq->out_packet_mutex, NULL); COMPAT_pthread_mutex_init(&mosq->msgtime_mutex, NULL); COMPAT_pthread_mutex_init(&mosq->msgs_in.mutex, NULL); COMPAT_pthread_mutex_init(&mosq->msgs_out.mutex, NULL); COMPAT_pthread_mutex_init(&mosq->mid_mutex, NULL); mosq->thread_id = pthread_self(); #endif if(userdata){ mosq->userdata = userdata; }else{ mosq->userdata = mosq; } #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN memset(&mosq->wsd, 0, sizeof(mosq->wsd)); mosq->wsd.opcode = UINT8_MAX; mosq->wsd.mask = UINT8_MAX; mosq->wsd.disconnect_reason = 0xE8; mosq->wsd.is_client = true; mosq->wsd.http_header_size = 4096; #endif if(alloc_packet_buffer(mosq)){ return MOSQ_ERR_NOMEM; } mosq->transport = mosq_t_tcp; mosq->protocol = mosq_p_mqtt311; mosq->sock = INVALID_SOCKET; mosq->sockpairR = INVALID_SOCKET; mosq->sockpairW = INVALID_SOCKET; mosq->keepalive = 60; mosq->clean_start = clean_start; if(id){ if(STREMPTY(id)){ return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(id, (int)strlen(id))){ return MOSQ_ERR_MALFORMED_UTF8; } mosq->id = mosquitto_strdup(id); if(!mosq->id){ return MOSQ_ERR_NOMEM; } } packet__cleanup(&mosq->in_packet); mosq->out_packet = NULL; mosq->out_packet_count = 0; mosq->out_packet_bytes = 0; 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->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; #ifndef WITH_BROKER mosq->user_ssl_ctx = NULL; #endif mosq->tls_cert_reqs = SSL_VERIFY_PEER; mosq->tls_insecure = false; mosq->want_write = false; mosq->tls_ocsp_required = false; #endif if(mosq->disable_socketpair == false){ /* 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())){ COMPAT_pthread_cancel(mosq->thread_id); COMPAT_pthread_join(mosq->thread_id, NULL); mosq->threaded = mosq_ts_none; } # endif COMPAT_pthread_mutex_destroy(&mosq->callback_mutex); COMPAT_pthread_mutex_destroy(&mosq->log_callback_mutex); COMPAT_pthread_mutex_destroy(&mosq->state_mutex); COMPAT_pthread_mutex_destroy(&mosq->out_packet_mutex); COMPAT_pthread_mutex_destroy(&mosq->msgtime_mutex); COMPAT_pthread_mutex_destroy(&mosq->msgs_in.mutex); COMPAT_pthread_mutex_destroy(&mosq->msgs_out.mutex); COMPAT_pthread_mutex_destroy(&mosq->mid_mutex); #endif if(net__is_connected(mosq)){ net__socket_close(mosq); } message__cleanup_all(mosq); will__clear(mosq); #ifdef WITH_TLS if(mosq->ssl){ SSL_free(mosq->ssl); } #ifndef WITH_BROKER if(mosq->user_ssl_ctx){ SSL_CTX_free(mosq->user_ssl_ctx); }else if(mosq->ssl_ctx){ SSL_CTX_free(mosq->ssl_ctx); } #else if(mosq->ssl_ctx){ SSL_CTX_free(mosq->ssl_ctx); } #endif mosquitto_FREE(mosq->tls_cafile); mosquitto_FREE(mosq->tls_capath); mosquitto_FREE(mosq->tls_certfile); mosquitto_FREE(mosq->tls_keyfile); 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); #ifndef OPENSSL_NO_ENGINE mosquitto_FREE(mosq->tls_engine); #endif #endif mosquitto_FREE(mosq->address); mosquitto_FREE(mosq->id); mosquitto_FREE(mosq->username); mosquitto_FREE(mosq->password); mosquitto_FREE(mosq->host); mosquitto_FREE(mosq->bind_address); mosquitto_FREE(mosq->in_packet.packet_buffer); mosq->in_packet.packet_buffer_size = 4096; 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) { return mosq->out_packet || mosq->want_write; } ================================================ FILE: lib/linker.version ================================================ /* 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; MOSQ_2.1 { global: mosquitto_ext_auth_callback_set; mosquitto_ext_auth_continue; mosquitto_pre_connect_callback_set; mosquitto_topic_matches_sub_with_pattern; mosquitto_sub_matches_acl; mosquitto_sub_matches_acl_with_pattern; mosquitto_unsubscribe2_v5_callback_set; mosquitto_property_remove; mosquitto_property_type; mosquitto_property_byte_value; mosquitto_property_int16_value; mosquitto_property_int32_value; mosquitto_property_varint_value; mosquitto_property_binary_value; mosquitto_property_binary_value_length; mosquitto_property_string_value; mosquitto_property_string_value_length; mosquitto_property_string_name; mosquitto_property_string_name_length; } MOSQ_1.7; ================================================ FILE: lib/logging_mosq.c ================================================ /* Copyright (c) 2009-2021 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" int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { va_list va; char *s; size_t len; void (*on_log)(struct mosquitto *, void *userdata, int level, const char *str); assert(mosq); assert(fmt); COMPAT_pthread_mutex_lock(&mosq->log_callback_mutex); on_log = mosq->on_log; COMPAT_pthread_mutex_unlock(&mosq->log_callback_mutex); if(on_log){ len = strlen(fmt) + 500; s = mosquitto_malloc(len*sizeof(char)); if(!s){ 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. */ on_log(mosq, mosq->userdata, (int)priority, s); mosquitto_FREE(s); } return MOSQ_ERR_SUCCESS; } ================================================ FILE: lib/logging_mosq.h ================================================ /* Copyright (c) 2009-2021 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 ================================================ FILE: lib/loop.c ================================================ /* Copyright (c) 2010-2021 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 "callbacks.h" #include "http_client.h" #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(__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(net__is_connected(mosq)){ maxfd = mosq->sock; FD_SET(mosq->sock, &readfds); if(mosq->want_write){ FD_SET(mosq->sock, &writefds); }else{ #ifdef WITH_TLS if(mosq->ssl == NULL || SSL_is_init_finished(mosq->ssl)) #endif { COMPAT_pthread_mutex_lock(&mosq->out_packet_mutex); if(mosq->out_packet){ FD_SET(mosq->sock, &writefds); } COMPAT_pthread_mutex_unlock(&mosq->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(); COMPAT_pthread_mutex_lock(&mosq->msgtime_mutex); if(mosq->next_msg_out && now + timeout_ms/1000 > mosq->next_msg_out){ timeout_ms = (mosq->next_msg_out - now)*1000; } COMPAT_pthread_mutex_unlock(&mosq->msgtime_mutex); 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){ WINDOWS_SET_ERRNO(); if(errno == EINTR){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ERRNO; } }else{ if(net__is_connected(mosq)){ 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(net__is_connected(mosq)){ FD_SET(mosq->sock, &writefds); } } if(net__is_connected(mosq) && FD_ISSET(mosq->sock, &writefds)){ rc = mosquitto_loop_write(mosq, max_packets); if(rc || !net__is_connected(mosq)){ 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){ WINDOWS_SET_ERRNO(); 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 rc = MOSQ_ERR_SUCCESS; unsigned long reconnect_delay; if(!mosq){ return MOSQ_ERR_INVAL; } mosq->reconnects = 0; mosq->run = true; while(mosq->run){ do{ #ifdef HAVE_PTHREAD_CANCEL COMPAT_pthread_testcancel(); #endif rc = mosquitto_loop(mosq, timeout, max_packets); }while(mosq->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 COMPAT_pthread_testcancel(); #endif rc = MOSQ_ERR_SUCCESS; if(mosquitto__get_request_disconnect(mosq)){ mosq->run = false; }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; } if(mosquitto__get_request_disconnect(mosq)){ mosq->run = false; }else{ rc = mosquitto_reconnect(mosq); } } }while(mosq->run && rc != MOSQ_ERR_SUCCESS); } return rc; } int mosquitto_loop_misc(struct mosquitto *mosq) { if(!mosq){ return MOSQ_ERR_INVAL; } if(!net__is_connected(mosq)){ 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; } callback__on_disconnect(mosq, rc, NULL); } 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; } COMPAT_pthread_mutex_lock(&mosq->msgs_out.mutex); max_packets = mosq->msgs_out.queue_len; COMPAT_pthread_mutex_unlock(&mosq->msgs_out.mutex); COMPAT_pthread_mutex_lock(&mosq->msgs_in.mutex); max_packets += mosq->msgs_in.queue_len; COMPAT_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 { switch(mosq->transport){ case mosq_t_tcp: case mosq_t_ws: rc = packet__read(mosq); break; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN case mosq_t_http: rc = http_c__read(mosq); break; #endif default: return MOSQ_ERR_INVAL; } } 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. */ #include "config.h" #include #include #include #include #include "mosquitto_internal.h" #include "mosquitto.h" #include "messages_mosq.h" #include "send_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); COMPAT_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++; 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); } } COMPAT_pthread_mutex_unlock(&mosq->msgs_in.mutex); COMPAT_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++; 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; } } COMPAT_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, 0, cur->properties, 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){ COMPAT_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){ COMPAT_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; } } COMPAT_pthread_mutex_unlock(&mosq->msgs_out.mutex); if(found){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOT_FOUND; } }else{ COMPAT_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){ COMPAT_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; } } COMPAT_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; assert(mosq); #ifdef WITH_THREADING COMPAT_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->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, 0, msg->properties, 0); break; case mosq_ms_wait_for_pubrel: 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->dup = true; send__pubrel(mosq, (uint16_t)msg->msg.mid, NULL); break; default: break; } } #ifdef WITH_THREADING COMPAT_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); COMPAT_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){ COMPAT_pthread_mutex_unlock(&mosq->msgs_out.mutex); return MOSQ_ERR_PROTOCOL; } message->state = state; COMPAT_pthread_mutex_unlock(&mosq->msgs_out.mutex); return MOSQ_ERR_SUCCESS; } } COMPAT_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); } ================================================ FILE: lib/messages_mosq.h ================================================ /* Copyright (c) 2010-2021 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 ================================================ FILE: lib/mosquitto_internal.h ================================================ /* Copyright (c) 2010-2021 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 #include #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 "mosquitto/libcommon_time.h" #ifdef WITH_BROKER # ifdef __linux__ # include # endif # include "uthash.h" struct mosquitto__client_msg; #endif #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS # include # define WS_PACKET_OFFSET LWS_PRE #else # define WS_PACKET_OFFSET 16 #endif #ifdef WIN32 typedef SOCKET mosq_sock_t; #else typedef int mosq_sock_t; #endif #ifdef WIN32 # define WINDOWS_SET_ERRNO() \ do{ \ errno = WSAGetLastError(); \ }while(0) # define WINDOWS_SET_ERRNO_RW() \ if(errno != EAGAIN){ \ errno = WSAGetLastError(); \ } #else # define WINDOWS_SET_ERRNO() # define WINDOWS_SET_ERRNO_RW() #endif #define SAFE_PRINT(A) (A)?(A):"null" #define SAFE_FREE(A) do{ free(A); (A) = NULL;}while(0) #define MSG_EXPIRY_INFINITE UINT32_MAX 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, mosq_ms_any = 255, /* max value allowed is 255 */ }; 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 */ mosq_cs_delayed_auth = 22, /* Client is awaiting an authentication result from a plugin */ }; enum mosquitto__protocol { mosq_p_invalid = 0, mosq_p_mqtts = 1, mosq_p_mqtt31 = 3, mosq_p_mqtt311 = 4, 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, mosq_t_http = 4, /* not valid for MQTT, just as a ws precursor */ mosq_t_proxy_v2 = 5, /* not valid for MQTT, just as a PROXY protocol v2 precursor */ mosq_t_proxy_v1 = 6, /* not valid for MQTT, just as a PROXY protocol v1 precursor */ }; /* Alias direction - local <-> remote */ #define ALIAS_DIR_L2R 1 #define ALIAS_DIR_R2L 2 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 { struct mosquitto__packet *next; 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; uint8_t payload[]; }; struct mosquitto__packet_in { uint8_t *payload; uint32_t remaining_mult; uint32_t remaining_length; uint32_t packet_length; uint32_t to_process; uint32_t pos; uint16_t packet_buffer_to_process; uint16_t packet_buffer_pos; uint16_t packet_buffer_size; uint8_t command; uint8_t *packet_buffer; int8_t remaining_count; }; struct mosquitto_message_all { struct mosquitto_message_all *next; struct mosquitto_message_all *prev; mosquitto_property *properties; 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 inflight_bytes; long inflight_bytes12; int inflight_count; int inflight_count12; long queued_bytes; long queued_bytes12; int queued_count; int queued_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; }; #define WS_CONTINUATION 0x00 #define WS_TEXT 0x01 #define WS_BINARY 0x02 #define WS_CLOSE 0x08 #define WS_PING 0x09 #define WS_PONG 0x0A #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN struct ws_data { struct mosquitto__packet *out_packet; char *http_path; char *accept_key; uint64_t payloadlen; ssize_t pos; int http_header_size; uint8_t maskingkey[4]; uint8_t disconnect_reason; uint8_t opcode; uint8_t mask; uint8_t mask_bytes; uint8_t payloadlen_bytes; bool is_client; }; #endif struct proxy_data { uint8_t *buf; char *cipher; char *tls_version; uint16_t len; uint16_t pos; int8_t cmd; uint8_t fam; bool have_tls; }; struct client_stats { uint64_t messages_received; uint64_t messages_sent; uint64_t messages_dropped; }; struct mosquitto { #if defined(WITH_BROKER) && (defined(WITH_EPOLL) || defined(WITH_KQUEUE)) /* 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 uint64_t last_cmsg_id; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN struct ws_data wsd; #endif enum mosquitto__protocol protocol; char *address; char *id; char *username; char *password; unsigned id_hashv; uint16_t keepalive; uint16_t last_mid; uint16_t password_len; enum mosquitto_client_state state; uint8_t transport; time_t last_msg_in; time_t next_msg_out; time_t ping_t; struct mosquitto__packet_in in_packet; struct mosquitto__packet *out_packet; struct mosquitto_message_all *will; struct mosquitto__alias *aliases_l2r; struct mosquitto__alias *aliases_r2l; struct will_delay_list *will_delay_entry; uint16_t alias_count_l2r; uint16_t alias_count_r2l; uint16_t alias_max_l2r; uint32_t will_delay_interval; int out_packet_count; int64_t out_packet_bytes; time_t will_delay_time; #ifdef WITH_TLS SSL *ssl; SSL_CTX *ssl_ctx; #ifndef WITH_BROKER SSL_CTX *user_ssl_ctx; #endif 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_13_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 run; #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 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 in_by_id; bool is_dropping; bool is_bridge; bool is_persisted; 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__subleaf **subs; char *auth_method; int subs_capacity; /* allocated size of the subs instance */ int subs_count; /* number of currently active subscriptions */ # ifndef WITH_EPOLL int pollfd_index; # endif # ifdef WITH_WEBSOCKETS # if WITH_WEBSOCKETS == WS_IS_LWS struct lws *wsi; # endif # endif bool assigned_id; #else # ifdef WITH_SOCKS char *socks5_host; uint16_t socks5_port; char *socks5_username; char *socks5_password; # endif void *userdata; struct mosquitto_msg_data msgs_in; struct mosquitto_msg_data msgs_out; LIBMOSQ_CB_pre_connect on_pre_connect; LIBMOSQ_CB_connect on_connect; LIBMOSQ_CB_connect_with_flags on_connect_with_flags; LIBMOSQ_CB_connect_v5 on_connect_v5; LIBMOSQ_CB_disconnect on_disconnect; LIBMOSQ_CB_disconnect_v5 on_disconnect_v5; LIBMOSQ_CB_publish on_publish; LIBMOSQ_CB_publish_v5 on_publish_v5; LIBMOSQ_CB_message on_message; LIBMOSQ_CB_message_v5 on_message_v5; LIBMOSQ_CB_subscribe on_subscribe; LIBMOSQ_CB_subscribe_v5 on_subscribe_v5; LIBMOSQ_CB_unsubscribe on_unsubscribe; LIBMOSQ_CB_unsubscribe_v5 on_unsubscribe_v5; LIBMOSQ_CB_unsubscribe2_v5 on_unsubscribe2_v5; LIBMOSQ_CB_ext_auth on_ext_auth; LIBMOSQ_CB_log on_log; /*void (*on_error)();*/ char *host; char *bind_address; unsigned int reconnects; unsigned int reconnect_delay; unsigned int reconnect_delay_max; int callback_depth; uint16_t port; bool disable_socketpair; bool reconnect_exponential_backoff; bool request_disconnect; 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; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN char *http_request; #endif #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; # ifndef WITH_OLD_KEEPALIVE struct mosquitto *keepalive_next; struct mosquitto *keepalive_prev; time_t keepalive_add_time; # endif struct client_stats stats; #endif #ifdef WITH_EPOLL uint32_t events; #elif defined(WITH_KQUEUE) short events; #else uint32_t events; #endif struct proxy_data proxy; }; #define STREMPTY(str) (str[0] == '\0') void do_client_disconnect(struct mosquitto *mosq, int reason_code, const mosquitto_property *properties); #endif ================================================ FILE: lib/net_mosq.c ================================================ /* Copyright (c) 2009-2021 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 # ifdef WIN32 # include # else # include # endif #endif #ifdef __QNX__ #include #endif #ifdef WITH_TLS #include #include #include #include #include #endif #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" # if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS # include # endif #else # include "read_handle.h" #endif #include "logging_mosq.h" #include "mosquitto/mqtt_protocol.h" #include "net_mosq.h" #include "packet_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) { if(!_ui_method){ setup_ui_method(); } 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 cleanup_ui_method(); if(is_tls_initialized){ is_tls_initialized = false; } #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 !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 ENGINE_load_builtin_engines(); #endif if(tls_ex_index_mosq == -1){ tls_ex_index_mosq = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL); } is_tls_initialized = true; } #endif bool net__is_connected(struct mosquitto *mosq) { #if defined(WITH_BROKER) && defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS return mosq->sock != INVALID_SOCKET || mosq->wsi != NULL; #else return mosq->sock != INVALID_SOCKET; #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 #if defined(WITH_BROKER) && defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS 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 #if defined(WITH_BROKER) && defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS if(mosq->wsi){ if(mosq->state != mosq_cs_disconnecting){ mosquitto__set_state(mosq, mosq_cs_disconnect_ws); } lws_callback_on_writable(mosq->wsi); if(mosq->listener){ mosq->listener->client_count--; } }else #endif { if(net__is_connected(mosq)){ #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); } if(mosq->listener && mosq->state != mosq_cs_disused){ mosq->listener->client_count--; } #endif rc = COMPAT_CLOSE(mosq->sock); mosq->sock = INVALID_SOCKET; } } return rc; } /* Shutdown a socket. * Returns 1 on failure (context is NULL) * Returns 0 on success. */ int net__socket_shutdown(struct mosquitto *mosq) { int rc = 0; assert(mosq); if(net__is_connected(mosq)){ rc = COMPAT_SHUTDOWN(mosq->sock); } 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; struct addrinfo *ar_request; if(mosq->adns){ gai_cancel(mosq->adns); ar_request = (struct addrinfo *)mosq->adns->ar_request; mosquitto_FREE(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); 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){ ar_request = (struct addrinfo *)mosq->adns->ar_request; mosquitto_FREE(ar_request); mosquitto_FREE(mosq->adns); } 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; struct addrinfo *ar_request; 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); WINDOWS_SET_ERRNO(); 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; ar_request = (struct addrinfo *)mosq->adns->ar_request; mosquitto_FREE(ar_request); mosquitto_FREE(mosq->adns); 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); WINDOWS_SET_ERRNO(); 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; mosq_sock_t 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; } #ifndef WIN32 rc = net__socket_nonblock(&s); if(rc){ return rc; } #endif rc = connect(s, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)); if(rc < 0){ COMPAT_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, const char *msg) { char ebuf[256]; unsigned long e; int num = 0; const char *msg_disp = msg == NULL ? "" : msg; e = ERR_get_error(); while(e){ log__printf(mosq, MOSQ_LOG_ERR, "OpenSSL Error %s[%d]: %s", msg_disp, num, ERR_error_string(e, ebuf)); e = ERR_get_error(); num++; } } int net__socket_connect_tls(struct mosquitto *mosq) { 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; } } SSL_set_connect_state(mosq->ssl); 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; #if !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 ENGINE *engine = NULL; EVP_PKEY *pkey; #endif uint8_t tls_alpn_wire[256]; uint8_t tls_alpn_len; net__init_tls(); net__init_tls(); #ifndef WITH_BROKER if(mosq->user_ssl_ctx){ mosq->ssl_ctx = mosq->user_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: If you use MOSQ_OPT_SSL_CTX then MOSQ_OPT_SSL_CTX_WITH_DEFAULTS must be true, or at least one of cafile, capath or psk must be specified."); return MOSQ_ERR_INVAL; } } #endif /* 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){ mosq->ssl_ctx = SSL_CTX_new(TLS_client_method()); if(!mosq->ssl_ctx){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to create TLS context."); net__print_ssl_error(mosq, "while trying to create a SSL ctx"); return MOSQ_ERR_TLS; } } #ifdef SSL_OP_NO_TLSv1_3 if(mosq->tls_psk){ SSL_CTX_set_options(mosq->ssl_ctx, SSL_OP_NO_TLSv1_3); } #endif 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{ log__printf(mosq, MOSQ_LOG_ERR, "Error: Protocol %s not supported.", mosq->tls_version); return MOSQ_ERR_INVAL; } /* Allow use of DHE ciphers */ SSL_CTX_set_dh_auto(mosq->ssl_ctx, 1); /* 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) && OPENSSL_API_LEVEL < 30000 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) && OPENSSL_API_LEVEL < 30000 ENGINE_FINISH(engine); #endif net__print_ssl_error(mosq, "while trying to set the cipher list"); return MOSQ_ERR_TLS; } } if(mosq->tls_13_ciphers){ ret = SSL_CTX_set_ciphersuites(mosq->ssl_ctx, mosq->tls_13_ciphers); if(ret == 0){ log__printf(mosq, MOSQ_LOG_ERR, "Error: Unable to set TLS 1.3 ciphersuites. Check cipher_tls13 list \"%s\".", mosq->tls_13_ciphers); 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) && OPENSSL_API_LEVEL < 30000 ENGINE_FINISH(engine); # endif net__print_ssl_error(mosq, "while trying to load the ca"); 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) && OPENSSL_API_LEVEL < 30000 ENGINE_FINISH(engine); #endif net__print_ssl_error(mosq, "while trying to use the certificate chain file"); return MOSQ_ERR_TLS; } } if(mosq->tls_keyfile){ if(mosq->tls_keyform == mosq_k_engine){ #if !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 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, "while trying to set the engine ctrl cmd SECRET_MODE"); 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, "while trying to set the engine ctrl cmd PIN"); 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, "while trying to load the private key"); 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, "while trying to use the private key"); 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) && OPENSSL_API_LEVEL < 30000 ENGINE_FINISH(engine); #endif net__print_ssl_error(mosq, "while trying to use the private key file"); 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) && OPENSSL_API_LEVEL < 30000 ENGINE_FINISH(engine); #endif net__print_ssl_error(mosq, "while trying to check the private key"); 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); if(mosq->tls_ciphers == NULL){ SSL_CTX_set_cipher_list(mosq->ssl_ctx, "PSK"); } #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, "while creating a SSL object"); return MOSQ_ERR_TLS; } if(!SSL_set_ex_data(mosq->ssl, tls_ex_index_mosq, mosq)){ net__socket_close(mosq); net__print_ssl_error(mosq, "while setting SSL ex data"); return MOSQ_ERR_TLS; } bio = BIO_new_socket(mosq->sock, BIO_NOCLOSE); if(!bio){ net__socket_close(mosq); net__print_ssl_error(mosq, "while trying to create a new socket"); 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(tls__set_verify_hostname(mosq, host)){ return MOSQ_ERR_TLS; } if(net__socket_connect_tls(mosq)){ net__socket_close(mosq); return MOSQ_ERR_TLS; } } #else UNUSED(mosq); UNUSED(host); #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 && port){ 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 void net__handle_ssl(struct mosquitto *mosq, int ret) { int err; err = SSL_get_error(mosq->ssl, ret); if(err == SSL_ERROR_WANT_READ){ errno = EAGAIN; }else if(err == SSL_ERROR_WANT_WRITE){ #ifdef WITH_BROKER mux__add_out(mosq); #else mosq->want_write = true; #endif errno = EAGAIN; }else if(err == SSL_ERROR_SSL){ net__print_ssl_error(mosq, "while trying to get the error"); errno = EPROTO; /* else if SSL_ERROR_SYSCALL leave errno alone */ } ERR_clear_error(); #ifdef WIN32 WSASetLastError(errno); #endif } #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){ ERR_clear_error(); ret = SSL_read(mosq->ssl, buf, (int)count); if(ret <= 0){ net__handle_ssl(mosq, ret); } return (ssize_t )ret; }else #endif { /* Call normal read/recv */ #ifndef WIN32 return read(mosq->sock, buf, count); #else return recv(mosq->sock, buf, count, 0); #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){ ERR_clear_error(); mosq->want_write = false; ret = SSL_write(mosq->ssl, buf, (int)count); if(ret < 0){ net__handle_ssl(mosq, ret); } return (ssize_t )ret; }else /* Call normal write/send */ #endif { return send(mosq->sock, buf, count, MSG_NOSIGNAL); } } 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){ WINDOWS_SET_ERRNO(); if(errno != EINPROGRESS && errno != COMPAT_EWOULDBLOCK){ COMPAT_CLOSE(spR); COMPAT_CLOSE(listensock); continue; } } spW = accept(listensock, NULL, 0); if(spW == -1){ WINDOWS_SET_ERRNO(); 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 UNUSED(mosq); return NULL; #endif } #endif ================================================ FILE: lib/net_mosq.h ================================================ /* Copyright (c) 2010-2021 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 # 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_SHUTDOWN(a) shutdown(a, SD_SEND) # 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_SHUTDOWN(a) shutdown(a, SHUT_WR) # 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 #ifndef MSG_NOSIGNAL # define MSG_NOSIGNAL 0 #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__socket_shutdown(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); bool net__is_connected(struct mosquitto *mosq); ssize_t net__read(struct mosquitto *mosq, void *buf, size_t count); ssize_t net__read_ws(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, const char *msg); 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 #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN void ws__context_init(struct mosquitto *mosq); void ws__prepare_packet(struct mosquitto *mosq, struct mosquitto__packet *packet); int ws__create_accept_key(const char *client_key, size_t client_key_len, char **encoded); #endif #endif ================================================ FILE: lib/net_mosq_ocsp.c ================================================ /* Copyright (c) 2009-2021 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 ================================================ FILE: lib/net_ws.c ================================================ /* Copyright (c) 2021 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN #ifndef WITH_TLS # error "Builtin websockets support requires WITH_TLS=yes and openssl to be available" #endif #include #include #include #include "mosquitto_internal.h" #include "mosquitto/mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "util_mosq.h" void ws__context_init(struct mosquitto *mosq) { mosq->transport = mosq_t_ws; mosq->state = mosq_cs_new; } void ws__prepare_packet(struct mosquitto *mosq, struct mosquitto__packet *packet) { uint8_t opcode; uint32_t masking_offset = mosq->wsd.is_client?4:0; packet->next = NULL; if(mosq->wsd.opcode == UINT8_MAX){ opcode = WS_BINARY; }else if(mosq->wsd.opcode == WS_PING){ opcode = WS_PONG; }else{ opcode = mosq->wsd.opcode; } if(packet->packet_length - WS_PACKET_OFFSET < 126){ if(mosq->wsd.is_client){ packet->payload[WS_PACKET_OFFSET-masking_offset-1] = (uint8_t)(packet->packet_length-WS_PACKET_OFFSET) | 0x80; }else{ packet->payload[WS_PACKET_OFFSET-masking_offset-1] = (uint8_t)(packet->packet_length-WS_PACKET_OFFSET); } packet->payload[WS_PACKET_OFFSET - masking_offset-2] = 0x80 | opcode; packet->pos = WS_PACKET_OFFSET - masking_offset - 2; packet->to_process = packet->packet_length - WS_PACKET_OFFSET + masking_offset + 2; }else if(packet->packet_length - WS_PACKET_OFFSET < 65536){ uint16_t plen = (uint16_t )(packet->packet_length - WS_PACKET_OFFSET); packet->payload[WS_PACKET_OFFSET-masking_offset-1] = MOSQ_LSB(plen); packet->payload[WS_PACKET_OFFSET-masking_offset-2] = MOSQ_MSB(plen);; if(mosq->wsd.is_client){ packet->payload[WS_PACKET_OFFSET-masking_offset-3] = 126 | 0x80; }else{ packet->payload[WS_PACKET_OFFSET-masking_offset-3] = 126; } packet->payload[WS_PACKET_OFFSET-masking_offset-4] = 0x80 | opcode; packet->pos = WS_PACKET_OFFSET-masking_offset - 4; packet->to_process = packet->packet_length - WS_PACKET_OFFSET + masking_offset + 4; }else{ uint64_t plen = packet->packet_length - WS_PACKET_OFFSET; packet->payload[WS_PACKET_OFFSET-masking_offset-1] = (uint8_t)((plen & 0x00000000000000FF) >> 0); packet->payload[WS_PACKET_OFFSET-masking_offset-2] = (uint8_t)((plen & 0x000000000000FF00) >> 8); packet->payload[WS_PACKET_OFFSET-masking_offset-3] = (uint8_t)((plen & 0x0000000000FF0000) >> WS_PACKET_OFFSET); packet->payload[WS_PACKET_OFFSET-masking_offset-4] = (uint8_t)((plen & 0x00000000FF000000) >> 24); packet->payload[WS_PACKET_OFFSET-masking_offset-5] = (uint8_t)((plen & 0x000000FF00000000) >> 32); packet->payload[WS_PACKET_OFFSET-masking_offset-6] = (uint8_t)((plen & 0x0000FF0000000000) >> 40); packet->payload[WS_PACKET_OFFSET-masking_offset-7] = (uint8_t)((plen & 0x00FF000000000000) >> 48); packet->payload[WS_PACKET_OFFSET-masking_offset-8] = (uint8_t)((plen & 0xFF00000000000000) >> 56); if(mosq->wsd.is_client){ packet->payload[WS_PACKET_OFFSET-masking_offset-9] = 127 | 0x80; }else{ packet->payload[WS_PACKET_OFFSET-masking_offset-9] = 127; } packet->payload[WS_PACKET_OFFSET-masking_offset-10] = 0x80 | opcode; packet->pos = WS_PACKET_OFFSET-masking_offset - 10; packet->to_process = packet->packet_length - WS_PACKET_OFFSET + masking_offset + 10; } if(mosq->wsd.is_client){ mosquitto_getrandom(&packet->payload[WS_PACKET_OFFSET-sizeof(uint32_t)], sizeof(uint32_t)); for(uint32_t i=0; ipacket_length - WS_PACKET_OFFSET; i++){ packet->payload[WS_PACKET_OFFSET + i] ^= packet->payload[WS_PACKET_OFFSET-sizeof(uint32_t)+(i%4)]; } } } static ssize_t read_ws_opcode(struct mosquitto *mosq) { ssize_t len; uint8_t opcode; uint8_t fin; uint8_t hbuf; mosq->wsd.mask_bytes = 4; mosq->wsd.pos = 0; mosq->wsd.mask = UINT8_MAX; mosq->wsd.payloadlen_bytes = UINT8_MAX; len = net__read(mosq, &hbuf, 1); if(len <= 0){ return len; } if((hbuf & 0x70) != 0x00){ mosq->wsd.disconnect_reason = 0xEA; errno = EPROTO; return -1; } opcode = (hbuf & 0x0F); fin = (hbuf & 0x80); switch(opcode){ case WS_CONTINUATION: case WS_BINARY: case WS_PING: case WS_PONG: case WS_CLOSE: mosq->wsd.opcode = opcode; break; case WS_TEXT: mosq->wsd.disconnect_reason = 0xEB; errno = EPROTO; return -1; default: mosq->wsd.disconnect_reason = 0xEA; errno = EPROTO; return -1; break; } if((opcode & 0x08) && fin == 0){ /* Control packets may not be fragmented */ mosq->wsd.disconnect_reason = 0xEA; errno = EPROTO; return -1; } return len; } static ssize_t read_ws_payloadlen_short(struct mosquitto *mosq) { ssize_t len; uint8_t hbuf; uint8_t plen; len = net__read(mosq, &hbuf, 1); if(len <= 0){ return len; } mosq->wsd.mask = (hbuf & 0x80) >> 7; plen = hbuf & 0x7F; if(plen == 126){ mosq->wsd.payloadlen_bytes = 2; mosq->wsd.payloadlen = 0; }else if(plen == 127){ mosq->wsd.payloadlen_bytes = 8; mosq->wsd.payloadlen = 0; }else{ mosq->wsd.payloadlen_bytes = 0; mosq->wsd.payloadlen = plen; } return len; } static ssize_t read_ws_payloadlen_extended(struct mosquitto *mosq) { uint8_t hbuf[8]; ssize_t len; len = net__read(mosq, hbuf, mosq->wsd.payloadlen_bytes); if(len <= 0){ return len; } for(ssize_t i=0; iwsd.payloadlen = (mosq->wsd.payloadlen << 8) + hbuf[i]; } mosq->wsd.payloadlen_bytes = (uint8_t)(mosq->wsd.payloadlen_bytes - len); return len; } static ssize_t read_ws_mask(struct mosquitto *mosq) { ssize_t len; len = net__read(mosq, &mosq->wsd.maskingkey[4-mosq->wsd.mask_bytes], mosq->wsd.mask_bytes); if(len <= 0){ return len; } mosq->wsd.mask_bytes = (uint8_t)(mosq->wsd.mask_bytes - len); if(mosq->wsd.mask_bytes > 0){ errno = EAGAIN; return -1; } return len; } ssize_t net__read_ws(struct mosquitto *mosq, void *buf, size_t count) { ssize_t len = 0; if(mosq->wsd.payloadlen == 0){ if(mosq->wsd.opcode == UINT8_MAX){ len = read_ws_opcode(mosq); if(len <= 0){ return len; } } if(mosq->wsd.mask == UINT8_MAX){ len = read_ws_payloadlen_short(mosq); if(len <= 0){ return len; } } if(mosq->wsd.payloadlen_bytes > 0){ len = read_ws_payloadlen_extended(mosq); if(len <= 0){ return len; } } if(mosq->wsd.mask == 1 && mosq->wsd.mask_bytes > 0){ len = read_ws_mask(mosq); if(len <= 0){ return len; } } if(mosq->wsd.opcode == WS_CLOSE && mosq->wsd.payloadlen == 1){ mosq->wsd.disconnect_reason = 0xEA; errno = EPROTO; return -1; }else if(mosq->wsd.payloadlen > 125 && mosq->wsd.opcode != WS_BINARY && mosq->wsd.opcode != WS_CONTINUATION){ mosq->wsd.disconnect_reason = 0xEA; errno = EPROTO; return -1; } if(mosq->wsd.payloadlen > MQTT_MAX_PAYLOAD){ errno = EPROTO; return -1; } #ifndef WS_TESTING if(mosq->wsd.opcode == WS_PING || (mosq->wsd.opcode == WS_CLOSE && mosq->wsd.payloadlen >= 2)) /* Always allocate payload for testing case, otherwise just for pings */ #endif { mosq->wsd.out_packet = mosquitto_calloc(1, sizeof(struct mosquitto__packet) + WS_PACKET_OFFSET + mosq->wsd.payloadlen + 1); if(mosq->wsd.out_packet == NULL){ errno = ENOMEM; return -1; } mosq->wsd.out_packet->packet_length = (uint32_t)mosq->wsd.payloadlen + WS_PACKET_OFFSET; } } if(mosq->wsd.out_packet){ /* This means we are either dealing with protocol level messages (and * hence won't be returning MQTT data to the context), or we are * testing and should be echoing data back to the client. * So ignore what data is being asked for, and try and read the whole * lot at once. */ count = mosq->wsd.payloadlen - (uint64_t)mosq->wsd.pos; buf = &mosq->wsd.out_packet->payload[WS_PACKET_OFFSET + mosq->wsd.pos]; } if(mosq->wsd.payloadlen > 0){ if(count > mosq->wsd.payloadlen - (uint64_t)mosq->wsd.pos){ count = mosq->wsd.payloadlen - (uint64_t)mosq->wsd.pos; } len = net__read(mosq, buf, count); if(len > 0){ for(ssize_t i=0; iwsd.maskingkey[(i+mosq->wsd.pos)%4]; } mosq->wsd.pos += len; } } if(mosq->wsd.pos == (ssize_t)mosq->wsd.payloadlen){ if(mosq->wsd.opcode == WS_CLOSE){ mosquitto_FREE(mosq->wsd.out_packet); /* Testing or PING - so we haven't read any data for the application yet. */ len = -1; errno = EAGAIN; }else if(mosq->wsd.opcode == WS_PONG){ mosquitto_FREE(mosq->wsd.out_packet); /* Testing or PING - so we haven't read any data for the application yet. */ len = -1; errno = EAGAIN; }else if(mosq->wsd.out_packet){ packet__queue(mosq, mosq->wsd.out_packet); mosq->wsd.out_packet = NULL; /* Testing or PING - so we haven't read any data for the application yet. * Simulate that situation. This has to be done *after* the call to * packet__queue. */ len = -1; errno = EAGAIN; } mosq->wsd.payloadlen = 0; mosq->wsd.opcode = UINT8_MAX; mosq->wsd.mask = UINT8_MAX; }else if(mosq->wsd.out_packet){ /* Testing or PING - so we haven't read any data for the application yet. * Simulate that situation.*/ len = -1; errno = EAGAIN; } return len; } int ws__create_accept_key(const char *client_key, size_t client_key_len, char **encoded) { const EVP_MD *digest; EVP_MD_CTX *evp = NULL; uint8_t accept_key_hash[EVP_MAX_MD_SIZE]; unsigned int accept_key_hash_len; digest = EVP_get_digestbyname("sha1"); if(!digest){ return MOSQ_ERR_UNKNOWN; } evp = EVP_MD_CTX_new(); if(evp && EVP_DigestInit_ex(evp, digest, NULL) != 0){ if(EVP_DigestUpdate(evp, client_key, client_key_len) != 0){ if(EVP_DigestUpdate(evp, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", strlen("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")) != 0){ if(EVP_DigestFinal_ex(evp, accept_key_hash, &accept_key_hash_len) != 0){ EVP_MD_CTX_free(evp); return mosquitto_base64_encode(accept_key_hash, accept_key_hash_len, encoded); } } } } EVP_MD_CTX_free(evp); return MOSQ_ERR_UNKNOWN; } #endif ================================================ FILE: lib/options.c ================================================ /* Copyright (c) 2010-2021 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 "mosquitto/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); mosquitto_FREE(mosq->password); 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); 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); 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); if(capath){ mosq->tls_capath = mosquitto_strdup(capath); if(!mosq->tls_capath){ return MOSQ_ERR_NOMEM; } } mosquitto_FREE(mosq->tls_certfile); if(certfile){ fptr = mosquitto_fopen(certfile, "rt", false); if(fptr){ fclose(fptr); }else{ mosquitto_FREE(mosq->tls_cafile); mosquitto_FREE(mosq->tls_capath); return MOSQ_ERR_INVAL; } mosq->tls_certfile = mosquitto_strdup(certfile); if(!mosq->tls_certfile){ return MOSQ_ERR_NOMEM; } } mosquitto_FREE(mosq->tls_keyfile); if(keyfile){ if(mosq->tls_keyform == mosq_k_pem){ 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 UNUSED(mosq); UNUSED(cafile); UNUSED(capath); UNUSED(certfile); UNUSED(keyfile); UNUSED(pw_callback); 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")){ mosquitto_FREE(mosq->tls_version); mosq->tls_version = mosquitto_strdup(tls_version); if(!mosq->tls_version){ return MOSQ_ERR_NOMEM; } }else{ return MOSQ_ERR_INVAL; } }else{ mosquitto_FREE(mosq->tls_version); mosq->tls_version = mosquitto_strdup("tlsv1.2"); if(!mosq->tls_version){ return MOSQ_ERR_NOMEM; } } if(ciphers){ mosquitto_FREE(mosq->tls_ciphers); mosq->tls_ciphers = mosquitto_strdup(ciphers); if(!mosq->tls_ciphers){ return MOSQ_ERR_NOMEM; } }else{ mosquitto_FREE(mosq->tls_ciphers); mosq->tls_ciphers = NULL; } mosquitto_FREE(mosq->tls_ciphers); mosquitto_FREE(mosq->tls_13_ciphers); if(ciphers){ if(!strcasecmp(mosq->tls_version, "tlsv1.3")){ mosq->tls_13_ciphers = mosquitto_strdup(ciphers); if(!mosq->tls_13_ciphers){ return MOSQ_ERR_NOMEM; } }else{ mosq->tls_ciphers = mosquitto_strdup(ciphers); if(!mosq->tls_ciphers){ return MOSQ_ERR_NOMEM; } } } return MOSQ_ERR_SUCCESS; #else UNUSED(mosq); UNUSED(cert_reqs); UNUSED(tls_version); UNUSED(ciphers); 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 UNUSED(mosq); UNUSED(value); return MOSQ_ERR_NOT_SUPPORTED; #endif } int mosquitto_string_option(struct mosquitto *mosq, enum mosq_opt_t option, const char *value) { #if defined(WITH_TLS) && !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 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) && OPENSSL_API_LEVEL < 30000 mosquitto_FREE(mosq->tls_engine); if(value){ /* The "Dynamic" OpenSSL engine is not initialized by default but is required by ENGINE_by_id() to find dynamically loadable engines */ OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_DYNAMIC, NULL); 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: #if defined(WITH_TLS) && !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 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: #if defined(WITH_TLS) && !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 mosquitto_FREE(mosq->tls_engine_kpass_sha1); 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 mosquitto_FREE(mosq->tls_alpn); 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; } case MOSQ_OPT_HTTP_PATH: #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN mosquitto_FREE(mosq->wsd.http_path); if(value){ mosq->wsd.http_path = mosquitto_strdup(value); if(mosq->wsd.http_path){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOMEM; } }else{ return MOSQ_ERR_SUCCESS; } #else return MOSQ_ERR_NOT_SUPPORTED; #endif 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 UNUSED(mosq); UNUSED(psk); UNUSED(identity); UNUSED(ciphers); return MOSQ_ERR_NOT_SUPPORTED; #endif } int mosquitto_opts_set(struct mosquitto *mosq, enum mosq_opt_t option, void *value) { int ival; if(!mosq){ return MOSQ_ERR_INVAL; } switch(option){ case MOSQ_OPT_PROTOCOL_VERSION: if(value == NULL){ return MOSQ_ERR_INVAL; } ival = *((int *)value); return mosquitto_int_option(mosq, option, ival); case MOSQ_OPT_SSL_CTX: return mosquitto_void_option(mosq, option, value); 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_DISABLE_SOCKETPAIR: mosq->disable_socketpair = (bool)value; break; 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) 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; case MOSQ_OPT_TRANSPORT: #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN if(value == mosq_t_tcp || value == mosq_t_ws){ mosq->transport = (uint8_t)value; }else{ return MOSQ_ERR_INVAL; } #else return MOSQ_ERR_NOT_SUPPORTED; #endif break; case MOSQ_OPT_HTTP_HEADER_SIZE: #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN if(value < 100){ /* arbitrary limit */ return MOSQ_ERR_INVAL; }else if(mosq->http_request){ /* Don't want to resize if part way through the handshake */ return MOSQ_ERR_INVAL; } mosq->wsd.http_header_size = value; #else return MOSQ_ERR_NOT_SUPPORTED; #endif break; default: return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } int mosquitto_void_option(struct mosquitto *mosq, enum mosq_opt_t option, void *value) { if(!mosq){ return MOSQ_ERR_INVAL; } switch(option){ case MOSQ_OPT_SSL_CTX: #ifdef WITH_TLS mosq->user_ssl_ctx = (SSL_CTX *)value; if(mosq->user_ssl_ctx){ SSL_CTX_up_ref(mosq->user_ssl_ctx); } break; #else UNUSED(value); 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; } ================================================ FILE: lib/packet_datatypes.c ================================================ /* Copyright (c) 2009-2021 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 #ifdef WITH_BROKER # include "mosquitto_broker_internal.h" # if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS # include # endif #else # include "read_handle.h" #endif #include "mosquitto/mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "read_handle.h" int packet__read_byte(struct mosquitto__packet_in *packet, uint8_t *byte) { assert(packet); if(packet->pos+1 > packet->remaining_length){ return MOSQ_ERR_MALFORMED_PACKET; } *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_in *packet, void *bytes, uint32_t count) { assert(packet); if(packet->pos+count > packet->remaining_length){ return MOSQ_ERR_MALFORMED_PACKET; } 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); if(count > 0){ memcpy(&(packet->payload[packet->pos]), bytes, count); packet->pos += count; } } int packet__read_binary(struct mosquitto__packet_in *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_MALFORMED_PACKET; } *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_in *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); *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_in *packet, uint16_t *word) { uint16_t val; assert(packet); if(packet->pos+2 > packet->remaining_length){ return MOSQ_ERR_MALFORMED_PACKET; } memcpy(&val, &packet->payload[packet->pos], sizeof(uint16_t)); packet->pos = packet->pos + (uint32_t)sizeof(uint16_t); *word = ntohs(val); return MOSQ_ERR_SUCCESS; } void packet__write_uint16(struct mosquitto__packet *packet, uint16_t word) { uint16_t bigendian = htons(word); assert(packet); assert(packet->pos+2 <= packet->packet_length); memcpy(&packet->payload[packet->pos], &bigendian, 2); packet->pos += 2; } int packet__read_uint32(struct mosquitto__packet_in *packet, uint32_t *word) { uint32_t val = 0; assert(packet); if(packet->pos+4 > packet->remaining_length){ return MOSQ_ERR_MALFORMED_PACKET; } memcpy(&val, &packet->payload[packet->pos], sizeof(uint32_t)); packet->pos = packet->pos + (uint32_t)sizeof(uint32_t); *word = ntohl(val); return MOSQ_ERR_SUCCESS; } void packet__write_uint32(struct mosquitto__packet *packet, uint32_t word) { uint32_t bigendian = htonl(word); assert(packet); assert(packet->pos+4 <= packet->packet_length); memcpy(&packet->payload[packet->pos], &bigendian, 4); packet->pos += 4; } int packet__read_varint(struct mosquitto__packet_in *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_MALFORMED_PACKET; }else{ *word = lword; if(bytes){ (*bytes) = lbytes; } return MOSQ_ERR_SUCCESS; } } }else{ return MOSQ_ERR_MALFORMED_PACKET; } } return MOSQ_ERR_MALFORMED_PACKET; } 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_MALFORMED_PACKET; } return MOSQ_ERR_SUCCESS; } ================================================ FILE: lib/packet_mosq.c ================================================ /* Copyright (c) 2009-2021 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" # if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS # include # endif #else # include "read_handle.h" #endif #include "callbacks.h" #include "mosquitto/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 metrics__int_inc(stat, val) # define metrics__int_dec(stat, val) #endif int packet__alloc(struct mosquitto__packet **packet, uint8_t command, uint32_t remaining_length) { uint8_t remaining_bytes[5] = {0}, byte; int8_t remaining_count; uint32_t packet_length; uint32_t remaining_length_stored; int i; assert(packet); remaining_length_stored = remaining_length; 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[remaining_count] = byte; remaining_count++; }while(remaining_length > 0 && remaining_count < 5); if(remaining_count == 5){ return MOSQ_ERR_PAYLOAD_SIZE; } packet_length = remaining_length_stored + 1 + (uint8_t)remaining_count; (*packet) = mosquitto_malloc(sizeof(struct mosquitto__packet) + packet_length + WS_PACKET_OFFSET); if((*packet) == NULL){ return MOSQ_ERR_NOMEM; } /* Clear memory for everything but the payload - that will be set to valid * values when the actual payload is copied in. */ memset((*packet), 0, sizeof(struct mosquitto__packet)); (*packet)->command = command; (*packet)->remaining_length = remaining_length_stored; (*packet)->remaining_count = remaining_count; (*packet)->packet_length = packet_length + WS_PACKET_OFFSET; (*packet)->payload[WS_PACKET_OFFSET] = (*packet)->command; for(i=0; i<(*packet)->remaining_count; i++){ (*packet)->payload[WS_PACKET_OFFSET+i+1] = remaining_bytes[i]; } (*packet)->pos = WS_PACKET_OFFSET + 1U + (uint8_t)(*packet)->remaining_count; return MOSQ_ERR_SUCCESS; } void packet__cleanup(struct mosquitto__packet_in *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->to_process = 0; packet->pos = 0; } void packet__cleanup_all_no_locks(struct mosquitto *mosq) { struct mosquitto__packet *packet; /* Out packet cleanup */ while(mosq->out_packet){ packet = mosq->out_packet; /* Free data and reset values */ mosq->out_packet = mosq->out_packet->next; mosquitto_FREE(packet); } metrics__int_dec(mosq_gauge_out_packets, mosq->out_packet_count); metrics__int_dec(mosq_gauge_out_packet_bytes, mosq->out_packet_bytes); mosq->out_packet_count = 0; mosq->out_packet_bytes = 0; mosq->out_packet_last = NULL; packet__cleanup(&mosq->in_packet); } void packet__cleanup_all(struct mosquitto *mosq) { COMPAT_pthread_mutex_lock(&mosq->out_packet_mutex); packet__cleanup_all_no_locks(mosq); COMPAT_pthread_mutex_unlock(&mosq->out_packet_mutex); } static void packet__queue_append(struct mosquitto *mosq, struct mosquitto__packet *packet) { #ifdef WITH_BROKER if(db.config->max_queued_messages > 0 && mosq->out_packet_count >= db.config->max_queued_messages){ mosquitto_free(packet); if(mosq->is_dropping == false){ mosq->is_dropping = true; log__printf(NULL, MOSQ_LOG_NOTICE, "Outgoing messages are being dropped for client %s.", mosq->id); } metrics__int_inc(mosq_counter_mqtt_publish_dropped, 1); return; } #endif COMPAT_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++; mosq->out_packet_bytes += packet->packet_length; metrics__int_inc(mosq_gauge_out_packets, 1); metrics__int_inc(mosq_gauge_out_packet_bytes, packet->packet_length); COMPAT_pthread_mutex_unlock(&mosq->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); #if defined(WITH_BROKER) && defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS if(mosq->wsi){ packet->next = NULL; packet->pos = WS_PACKET_OFFSET; packet->to_process = packet->packet_length - WS_PACKET_OFFSET; packet__queue_append(mosq, packet); lws_callback_on_writable(mosq->wsi); return MOSQ_ERR_SUCCESS; }else #elif defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN if(mosq->transport == mosq_t_ws){ ws__prepare_packet(mosq, packet); }else #endif { /* Normal TCP */ packet->next = NULL; packet->pos = WS_PACKET_OFFSET; packet->to_process = packet->packet_length - WS_PACKET_OFFSET; } packet__queue_append(mosq, packet); #ifdef WITH_BROKER return packet__write(mosq); #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->callback_depth == 0 && 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 = 1 + remaining_length + mosquitto_varint_bytes(remaining_length); if(len > mosq->maximum_packet_size){ return MOSQ_ERR_OVERSIZE_PACKET; }else{ return MOSQ_ERR_SUCCESS; } } struct mosquitto__packet *packet__get_next_out(struct mosquitto *mosq) { struct mosquitto__packet *packet = NULL; COMPAT_pthread_mutex_lock(&mosq->out_packet_mutex); if(mosq->out_packet){ mosq->out_packet_count--; mosq->out_packet_bytes -= mosq->out_packet->packet_length; metrics__int_dec(mosq_gauge_out_packets, 1); metrics__int_dec(mosq_gauge_out_packet_bytes, mosq->out_packet->packet_length); mosq->out_packet = mosq->out_packet->next; if(!mosq->out_packet){ mosq->out_packet_last = NULL; } packet = mosq->out_packet; } COMPAT_pthread_mutex_unlock(&mosq->out_packet_mutex); return packet; } int packet__write(struct mosquitto *mosq) { ssize_t write_length; struct mosquitto__packet *packet, *next_packet; enum mosquitto_client_state state; if(!mosq){ return MOSQ_ERR_INVAL; } if(!net__is_connected(mosq)){ return MOSQ_ERR_NO_CONN; } COMPAT_pthread_mutex_lock(&mosq->out_packet_mutex); packet = mosq->out_packet; COMPAT_pthread_mutex_unlock(&mosq->out_packet_mutex); if(packet == NULL){ return MOSQ_ERR_SUCCESS; } #ifdef WITH_BROKER mux__add_out(mosq); #endif state = mosquitto__get_state(mosq); if(state == mosq_cs_connect_pending){ return MOSQ_ERR_SUCCESS; } while(packet){ while(packet->to_process > 0){ write_length = net__write(mosq, &(packet->payload[packet->pos]), packet->to_process); if(write_length > 0){ metrics__int_inc(mosq_counter_bytes_sent, write_length); packet->to_process -= (uint32_t)write_length; packet->pos += (uint32_t)write_length; }else{ WINDOWS_SET_ERRNO_RW(); if(errno == EAGAIN || errno == COMPAT_EWOULDBLOCK #ifdef WIN32 || errno == WSAENOTCONN #endif ){ return MOSQ_ERR_SUCCESS; }else{ switch(errno){ case COMPAT_ECONNRESET: return MOSQ_ERR_CONN_LOST; case COMPAT_EINTR: return MOSQ_ERR_SUCCESS; case EPROTO: return MOSQ_ERR_TLS; default: return MOSQ_ERR_ERRNO; } } } } metrics__int_inc(mosq_counter_messages_sent, 1); if(((packet->command)&0xF6) == CMD_PUBLISH){ #ifndef WITH_BROKER callback__on_publish(mosq, packet->mid, 0, NULL); }else if(((packet->command)&0xF0) == CMD_DISCONNECT){ net__socket_shutdown(mosq); return MOSQ_ERR_SUCCESS; #endif } next_packet = packet__get_next_out(mosq); mosquitto_FREE(packet); packet = next_packet; #ifdef WITH_BROKER mosq->next_msg_out = db.now_s + mosq->keepalive; #else COMPAT_pthread_mutex_lock(&mosq->msgtime_mutex); mosq->next_msg_out = mosquitto_time() + mosq->keepalive; COMPAT_pthread_mutex_unlock(&mosq->msgtime_mutex); #endif } #ifdef WITH_BROKER if(mosq->out_packet == NULL){ mux__remove_out(mosq); } #endif return MOSQ_ERR_SUCCESS; } static int read_header(struct mosquitto *mosq, ssize_t (*func_read)(struct mosquitto *, void *, size_t)) { ssize_t read_length; mosq->in_packet.packet_buffer_pos = 0; mosq->in_packet.packet_buffer_to_process = 0; read_length = func_read(mosq, mosq->in_packet.packet_buffer, mosq->in_packet.packet_buffer_size); if(read_length > 0){ mosq->in_packet.packet_buffer_to_process = (uint16_t)read_length; #ifdef WITH_BROKER metrics__int_inc(mosq_counter_bytes_received, read_length); #endif }else{ if(read_length == 0){ return MOSQ_ERR_CONN_LOST; /* EOF */ } WINDOWS_SET_ERRNO_RW(); 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; } } } return MOSQ_ERR_SUCCESS; } #ifdef WITH_BROKER static int packet__check_in_packet_oversize(struct mosquitto *mosq) { uint32_t packet_length = 1 + mosquitto_varint_bytes(mosq->in_packet.remaining_length) + mosq->in_packet.remaining_length; switch(mosq->in_packet.command & 0xF0){ case CMD_CONNECT: if(packet_length > db.config->packet_max_connect){ return MOSQ_ERR_OVERSIZE_PACKET; } break; case CMD_PUBACK: case CMD_PUBREC: case CMD_PUBREL: case CMD_PUBCOMP: case CMD_UNSUBACK: if(mosq->protocol == mosq_p_mqtt5){ if(packet_length > db.config->packet_max_simple){ return MOSQ_ERR_OVERSIZE_PACKET; } }else{ if(mosq->in_packet.remaining_length != 2){ return MOSQ_ERR_MALFORMED_PACKET; } } break; case CMD_PINGREQ: case CMD_PINGRESP: if(mosq->in_packet.remaining_length != 0){ return MOSQ_ERR_MALFORMED_PACKET; } break; case CMD_DISCONNECT: if(mosq->protocol == mosq_p_mqtt5){ if(packet_length > db.config->packet_max_simple){ return MOSQ_ERR_OVERSIZE_PACKET; } }else{ if(mosq->in_packet.remaining_length != 0){ return MOSQ_ERR_MALFORMED_PACKET; } } break; case CMD_SUBSCRIBE: case CMD_UNSUBSCRIBE: if(mosq->protocol == mosq_p_mqtt5 && packet_length > db.config->packet_max_sub){ return MOSQ_ERR_OVERSIZE_PACKET; } break; case CMD_AUTH: if(packet_length > db.config->packet_max_auth){ return MOSQ_ERR_OVERSIZE_PACKET; } break; } if(db.config->max_packet_size > 0 && packet_length > 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; } return MOSQ_ERR_SUCCESS; } #endif static int packet__read_single(struct mosquitto *mosq, enum mosquitto_client_state state, ssize_t (*local__read)(struct mosquitto *, void *, size_t)) { ssize_t read_length; int rc = 0; if(!mosq->in_packet.command){ if(mosq->in_packet.packet_buffer_to_process == 0){ rc = read_header(mosq, local__read); if(rc){ return rc; } } if(mosq->in_packet.packet_buffer_to_process > 0){ mosq->in_packet.command = mosq->in_packet.packet_buffer[mosq->in_packet.packet_buffer_pos]; mosq->in_packet.packet_buffer_to_process--; mosq->in_packet.packet_buffer_pos++; #ifdef WITH_BROKER /* Clients must send CONNECT as their first command. */ if(!(mosq->bridge) && state == mosq_cs_new && (mosq->in_packet.command&0xF0) != CMD_CONNECT){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: First packet not CONNECT (%02X).", mosq->address, mosq->remote_port, mosq->in_packet.command); return MOSQ_ERR_PROTOCOL; }else if((mosq->in_packet.command&0xF0) == CMD_RESERVED){ if(mosq->protocol == mosq_p_mqtt5){ send__disconnect(mosq, MQTT_RC_PROTOCOL_ERROR, NULL); } log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: RESERVED packet.", mosq->address, mosq->remote_port); return MOSQ_ERR_PROTOCOL; } #else UNUSED(state); #endif }else{ return MOSQ_ERR_SUCCESS; } } /* 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){ uint8_t byte; do{ if(mosq->in_packet.packet_buffer_to_process == 0){ rc = read_header(mosq, local__read); if(rc){ return rc; } } if(mosq->in_packet.packet_buffer_to_process > 0){ 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_MALFORMED_PACKET; } byte = mosq->in_packet.packet_buffer[mosq->in_packet.packet_buffer_pos]; mosq->in_packet.packet_buffer_pos++; mosq->in_packet.packet_buffer_to_process--; mosq->in_packet.remaining_length += (byte & 127) * mosq->in_packet.remaining_mult; mosq->in_packet.remaining_mult *= 128; }else{ return MOSQ_ERR_SUCCESS; } }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 rc = packet__check_in_packet_oversize(mosq); if(rc){ return rc; } #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.pos = 0; mosq->in_packet.to_process = mosq->in_packet.remaining_length; if(mosq->in_packet.packet_buffer_to_process > 0){ uint32_t len; if(mosq->in_packet.packet_buffer_to_process > mosq->in_packet.remaining_length){ len = mosq->in_packet.remaining_length; }else{ len = mosq->in_packet.packet_buffer_to_process; } memcpy(mosq->in_packet.payload, &mosq->in_packet.packet_buffer[mosq->in_packet.packet_buffer_pos], len); if(len < mosq->in_packet.packet_buffer_to_process){ mosq->in_packet.packet_buffer_pos = (uint16_t)(mosq->in_packet.packet_buffer_pos + len); mosq->in_packet.packet_buffer_to_process = (uint16_t)(mosq->in_packet.packet_buffer_to_process - len); }else{ mosq->in_packet.packet_buffer_pos = 0; mosq->in_packet.packet_buffer_to_process = 0; } mosq->in_packet.pos += len; mosq->in_packet.to_process -= len; } } } while(mosq->in_packet.to_process>0){ read_length = local__read(mosq, &(mosq->in_packet.payload[mosq->in_packet.pos]), mosq->in_packet.to_process); if(read_length > 0){ metrics__int_inc(mosq_counter_bytes_received, read_length); mosq->in_packet.to_process -= (uint32_t)read_length; mosq->in_packet.pos += (uint32_t)read_length; }else{ WINDOWS_SET_ERRNO_RW(); 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 COMPAT_pthread_mutex_lock(&mosq->msgtime_mutex); mosq->last_msg_in = mosquitto_time(); COMPAT_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 metrics__int_inc(mosq_counter_messages_received, 1); #endif rc = handle__packet(mosq); /* Free data and reset values */ packet__cleanup(&mosq->in_packet); #ifdef WITH_BROKER keepalive__update(mosq); #else COMPAT_pthread_mutex_lock(&mosq->msgtime_mutex); mosq->last_msg_in = mosquitto_time(); COMPAT_pthread_mutex_unlock(&mosq->msgtime_mutex); #endif return rc; } int packet__read(struct mosquitto *mosq) { int rc = 0; enum mosquitto_client_state state; ssize_t (*local__read)(struct mosquitto *, void *, size_t); if(!mosq){ return MOSQ_ERR_INVAL; } if(!net__is_connected(mosq)){ return MOSQ_ERR_NO_CONN; } #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN if(mosq->transport == mosq_t_ws){ local__read = net__read_ws; }else #endif { local__read = net__read; } /* 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 packet_buffer 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. */ do{ state = mosquitto__get_state(mosq); if(state == mosq_cs_connect_pending){ return MOSQ_ERR_SUCCESS; } rc = packet__read_single(mosq, state, local__read); if(rc){ return rc; } }while(mosq->in_packet.packet_buffer_to_process > 0); return MOSQ_ERR_SUCCESS; } ================================================ FILE: lib/packet_mosq.h ================================================ /* Copyright (c) 2010-2021 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, uint8_t command, uint32_t remaining_length); void packet__cleanup(struct mosquitto__packet_in *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); struct mosquitto__packet *packet__get_next_out(struct mosquitto *mosq); int packet__check_oversize(struct mosquitto *mosq, uint32_t remaining_length); int packet__read_byte(struct mosquitto__packet_in *packet, uint8_t *byte); int packet__read_bytes(struct mosquitto__packet_in *packet, void *bytes, uint32_t count); int packet__read_binary(struct mosquitto__packet_in *packet, uint8_t **data, uint16_t *length); int packet__read_string(struct mosquitto__packet_in *packet, char **str, uint16_t *length); int packet__read_uint16(struct mosquitto__packet_in *packet, uint16_t *word); int packet__read_uint32(struct mosquitto__packet_in *packet, uint32_t *word); int packet__read_varint(struct mosquitto__packet_in *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); int packet__write(struct mosquitto *mosq); int packet__read(struct mosquitto *mosq); #endif ================================================ FILE: lib/property_mosq.c ================================================ /* Copyright (c) 2018-2021 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 #ifndef WIN32 # include #endif #include "logging_mosq.h" #include "mosquitto/mqtt_protocol.h" #include "packet_mosq.h" #include "property_common.h" #include "property_mosq.h" static int property__read(struct mosquitto__packet_in *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 -= mosquitto_varint_bytes(property_identifier); 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; property->property_type = MQTT_PROP_TYPE_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; property->property_type = MQTT_PROP_TYPE_INT16; 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; property->property_type = MQTT_PROP_TYPE_INT32; 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; property->property_type = MQTT_PROP_TYPE_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; property->property_type = MQTT_PROP_TYPE_STRING; 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; property->property_type = MQTT_PROP_TYPE_BINARY; 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; property->property_type = MQTT_PROP_TYPE_STRING_PAIR; break; default: #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Unsupported property type: %d", property_identifier); #endif return MOSQ_ERR_MALFORMED_PACKET; } return MOSQ_ERR_SUCCESS; } int property__read_all(int command, struct mosquitto__packet_in *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; } static int property__write(struct mosquitto__packet *packet, const mosquitto_property *property) { int rc; rc = packet__write_varint(packet, (uint32_t)mosquitto_property_identifier(property)); if(rc){ return rc; } switch(property->property_type){ case MQTT_PROP_TYPE_BYTE: packet__write_byte(packet, property->value.i8); break; case MQTT_PROP_TYPE_INT16: packet__write_uint16(packet, property->value.i16); break; case MQTT_PROP_TYPE_INT32: packet__write_uint32(packet, property->value.i32); break; case MQTT_PROP_TYPE_VARINT: return packet__write_varint(packet, property->value.varint); case MQTT_PROP_TYPE_STRING: packet__write_string(packet, property->value.s.v, property->value.s.len); break; case MQTT_PROP_TYPE_BINARY: packet__write_uint16(packet, property->value.bin.len); packet__write_bytes(packet, property->value.bin.v, property->value.bin.len); break; case MQTT_PROP_TYPE_STRING_PAIR: packet__write_string(packet, property->name.v, property->name.len); packet__write_string(packet, property->value.s.v, property->value.s.len); break; default: #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Unsupported property type: %d", property->identifier); #endif 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, mosquitto_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; } ================================================ FILE: lib/property_mosq.h ================================================ /* Copyright (c) 2018-2021 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" int property__read_all(int command, struct mosquitto__packet_in *packet, mosquitto_property **property); int property__write_all(struct mosquitto__packet *packet, const mosquitto_property *property, bool write_len); #endif ================================================ FILE: lib/pthread_compat.h ================================================ #ifndef PTHREAD_COMPAT_ #define PTHREAD_COMPAT_ #if defined(WITH_THREADING) && !defined(WITH_BROKER) # include # define COMPAT_pthread_create(A, B, C, D) pthread_create((A), (B), (C), (D)) # define COMPAT_pthread_join(A, B) pthread_join((A), (B)) # define COMPAT_pthread_cancel(A) pthread_cancel((A)) # define COMPAT_pthread_testcancel() pthread_testcancel() # define COMPAT_pthread_mutex_init(A, B) pthread_mutex_init((A), (B)) # define COMPAT_pthread_mutex_destroy(A) pthread_mutex_destroy((A)) # define COMPAT_pthread_mutex_lock(A) pthread_mutex_lock((A)) # define COMPAT_pthread_mutex_unlock(A) pthread_mutex_unlock((A)) #else # define COMPAT_pthread_create(A, B, C, D) # define COMPAT_pthread_join(A, B) # define COMPAT_pthread_cancel(A) # define COMPAT_pthread_testcancel() # define COMPAT_pthread_mutex_init(A, B) # define COMPAT_pthread_mutex_destroy(A) # define COMPAT_pthread_mutex_lock(A) # define COMPAT_pthread_mutex_unlock(A) #endif #endif ================================================ FILE: lib/read_handle.c ================================================ /* Copyright (c) 2009-2021 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 "messages_mosq.h" #include "mosquitto/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__packet(struct mosquitto *mosq) { int rc = MOSQ_ERR_INVAL; assert(mosq); switch((mosq->in_packet.command)&0xF0){ case CMD_PINGREQ: rc = handle__pingreq(mosq); break; case CMD_PINGRESP: rc = handle__pingresp(mosq); break; case CMD_PUBACK: rc = handle__pubackcomp(mosq, "PUBACK"); break; case CMD_PUBCOMP: rc = handle__pubackcomp(mosq, "PUBCOMP"); break; case CMD_PUBLISH: rc = handle__publish(mosq); break; case CMD_PUBREC: rc = handle__pubrec(mosq); break; case CMD_PUBREL: rc = handle__pubrel(mosq); break; case CMD_CONNACK: rc = handle__connack(mosq); break; case CMD_SUBACK: rc = handle__suback(mosq); break; case CMD_UNSUBACK: rc = handle__unsuback(mosq); break; case CMD_DISCONNECT: rc = handle__disconnect(mosq); break; case CMD_AUTH: rc = handle__auth(mosq); break; 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); rc = MOSQ_ERR_PROTOCOL; break; } if(mosq->protocol == mosq_p_mqtt5){ if(rc == MOSQ_ERR_PROTOCOL || rc == MOSQ_ERR_DUPLICATE_PROPERTY){ send__disconnect(mosq, MQTT_RC_PROTOCOL_ERROR, NULL); }else if(rc == MOSQ_ERR_MALFORMED_PACKET || rc == MOSQ_ERR_MALFORMED_UTF8){ send__disconnect(mosq, MQTT_RC_MALFORMED_PACKET, NULL); }else if(rc == MOSQ_ERR_QOS_NOT_SUPPORTED){ send__disconnect(mosq, MQTT_RC_QOS_NOT_SUPPORTED, NULL); }else if(rc == MOSQ_ERR_RETAIN_NOT_SUPPORTED){ send__disconnect(mosq, MQTT_RC_RETAIN_NOT_SUPPORTED, NULL); }else if(rc == MOSQ_ERR_TOPIC_ALIAS_INVALID){ send__disconnect(mosq, MQTT_RC_TOPIC_ALIAS_INVALID, NULL); }else if(rc == MOSQ_ERR_RECEIVE_MAXIMUM_EXCEEDED){ send__disconnect(mosq, MQTT_RC_RECEIVE_MAXIMUM_EXCEEDED, NULL); }else if(rc == MOSQ_ERR_UNKNOWN || rc == MOSQ_ERR_NOMEM){ send__disconnect(mosq, MQTT_RC_UNSPECIFIED, NULL); } } return rc; } ================================================ FILE: lib/read_handle.h ================================================ /* Copyright (c) 2010-2021 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 ================================================ FILE: lib/send_connect.c ================================================ /* Copyright (c) 2009-2021 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" #endif #include "logging_mosq.h" #include "mosquitto.h" #include "mosquitto_internal.h" #include "mosquitto/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 += mosquitto_property_get_length_all(properties); proplen += mosquitto_property_get_length_all(local_props); varbytes = mosquitto_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; } 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 += mosquitto_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){ return MOSQ_ERR_INVAL; } } if(username){ payloadlen += (uint32_t)(2+strlen(username)); } if(password){ payloadlen += (uint32_t)(2+strlen(password)); } rc = packet__alloc(&packet, CMD_CONNECT, headerlen + payloadlen); 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", SAFE_PRINT(clientid)); # endif metrics__int_inc(mosq_counter_mqtt_connect_sent, 1); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending CONNECT", SAFE_PRINT(clientid)); #endif return packet__queue(mosq, packet); } ================================================ FILE: lib/send_disconnect.c ================================================ /* Copyright (c) 2009-2021 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" # include "sys_tree.h" #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "mosquitto/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; uint32_t remaining_length = 0; assert(mosq); #ifdef WITH_BROKER # ifdef WITH_BRIDGE if(mosq->bridge){ log__printf(mosq, MOSQ_LOG_DEBUG, "Bridge %s sending DISCONNECT", SAFE_PRINT(mosq->id)); }else # else { log__printf(mosq, MOSQ_LOG_DEBUG, "Sending DISCONNECT to %s (rc%d)", SAFE_PRINT(mosq->id), reason_code); } # endif #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending DISCONNECT", SAFE_PRINT(mosq->id)); #endif if(mosq->protocol == mosq_p_mqtt5 && (reason_code != 0 || properties)){ remaining_length = 1; if(properties){ remaining_length += mosquitto_property_get_remaining_length(properties); } }else{ remaining_length = 0; } rc = packet__alloc(&packet, CMD_DISCONNECT, remaining_length); if(rc){ mosquitto_FREE(packet); return rc; } if(remaining_length > 0){ packet__write_byte(packet, reason_code); if(properties){ property__write_all(packet, properties, true); } } #ifdef WITH_BROKER metrics__int_inc(mosq_counter_mqtt_disconnect_sent, 1); #endif return packet__queue(mosq, packet); } ================================================ FILE: lib/send_mosq.c ================================================ /* Copyright (c) 2009-2021 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" #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "mosquitto/mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "send_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", SAFE_PRINT(mosq->id)); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PINGREQ", SAFE_PRINT(mosq->id)); #endif rc = send__simple_command(mosq, CMD_PINGREQ); if(rc == MOSQ_ERR_SUCCESS){ mosq->ping_t = mosquitto_time(); #ifdef WITH_BROKER metrics__int_inc(mosq_counter_mqtt_pingreq_sent, 1); #endif } return rc; } int send__pingresp(struct mosquitto *mosq) { #ifdef WITH_BROKER log__printf(NULL, MOSQ_LOG_DEBUG, "Sending PINGRESP to %s", SAFE_PRINT(mosq->id)); metrics__int_inc(mosq_counter_mqtt_pingresp_sent, 1); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PINGRESP", SAFE_PRINT(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)", SAFE_PRINT(mosq->id), mid, reason_code); metrics__int_inc(mosq_counter_mqtt_puback_sent, 1); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PUBACK (m%d, rc%d)", SAFE_PRINT(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)", SAFE_PRINT(mosq->id), mid); metrics__int_inc(mosq_counter_mqtt_pubcomp_sent, 1); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PUBCOMP (m%d)", SAFE_PRINT(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)", SAFE_PRINT(mosq->id), mid, reason_code); metrics__int_inc(mosq_counter_mqtt_pubrec_sent, 1); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PUBREC (m%d, rc%d)", SAFE_PRINT(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)", SAFE_PRINT(mosq->id), mid); metrics__int_inc(mosq_counter_mqtt_pubrel_sent, 1); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PUBREL (m%d)", SAFE_PRINT(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; uint32_t remaining_length; assert(mosq); if(dup){ command |= 8; } remaining_length = 2; if(mosq->protocol == mosq_p_mqtt5){ if(reason_code != 0 || properties){ remaining_length += 1; } if(properties){ remaining_length += mosquitto_property_get_remaining_length(properties); } } rc = packet__alloc(&packet, command, remaining_length); if(rc){ 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); rc = packet__alloc(&packet, command, 0); if(rc){ return rc; } return packet__queue(mosq, packet); } ================================================ FILE: lib/send_mosq.h ================================================ /* Copyright (c) 2010-2021 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, uint32_t subscription_identifier, 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, uint32_t subscription_identifier, 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 ================================================ FILE: lib/send_publish.c ================================================ /* Copyright (c) 2009-2021 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 metrics__int_inc(stat, val) #endif #include "alias_mosq.h" #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "mosquitto/mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "property_common.h" #include "send_mosq.h" #include "utlist.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, uint32_t subscription_identifier, const mosquitto_property *store_props, uint32_t expiry_interval) { #ifdef WITH_BROKER size_t len; int rc; #ifdef WITH_BRIDGE struct mosquitto__bridge_topic *cur_topic; bool match; char *mapped_topic = NULL; char *topic_temp = NULL; #endif #endif assert(mosq); if(!net__is_connected(mosq)){ return MOSQ_ERR_NO_CONN; } #ifdef WITH_BROKER bool payload_changed = false; bool topic_changed = false; bool properties_changed = false; { struct mosquitto_base_msg tmp_msg; tmp_msg.topic = (char *)topic; tmp_msg.payloadlen = payloadlen; tmp_msg.payload = (void *)payload; tmp_msg.qos = qos; tmp_msg.retain = retain; tmp_msg.properties = (mosquitto_property *)store_props; rc = plugin__handle_message_out(mosq, &tmp_msg); if(tmp_msg.payload != payload){ payload_changed = true; } if(tmp_msg.topic != topic){ topic_changed = true; } if(tmp_msg.properties != store_props){ properties_changed = true; } topic = tmp_msg.topic; payloadlen = tmp_msg.payloadlen; payload = tmp_msg.payload; qos = tmp_msg.qos; retain = tmp_msg.retain; store_props = tmp_msg.properties; if(rc != MOSQ_ERR_SUCCESS){ if(rc == MOSQ_ERR_ACL_DENIED){ log__printf(NULL, MOSQ_LOG_DEBUG, "Denied PUBLISH to %s (q%d, r%d, '%s', ... (%ld bytes))", mosq->id, qos, retain, topic, (long)payloadlen); }else if(rc == MOSQ_ERR_QUOTA_EXCEEDED){ log__printf(NULL, MOSQ_LOG_DEBUG, "Rejected PUBLISH to %s, quota exceeded.", mosq->id); } if(payload_changed){ mosquitto_free((void *)payload); } if(topic_changed){ mosquitto_free((void *)topic); } if(properties_changed){ mosquitto_property_free_all((mosquitto_property **)&store_props); } return MOSQ_ERR_SUCCESS; } } #endif if(!mosq->retain_available){ retain = false; } #ifdef WITH_BROKER if(mosq->listener && mosq->listener->mount_point){ len = strlen(mosq->listener->mount_point); if(len < strlen(topic)){ topic += len; }else{ /* Invalid topic string. Should never happen, but silently swallow the message anyway. */ return MOSQ_ERR_SUCCESS; } } #ifdef WITH_BRIDGE if(mosq->bridge && mosq->bridge->topics && mosq->bridge->topic_remapping){ LL_FOREACH(mosq->bridge->topics, cur_topic){ 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(mosq, MOSQ_LOG_DEBUG, "Sending PUBLISH to %s (d%d, q%d, r%d, m%d, '%s', ... (%ld bytes))", SAFE_PRINT(mosq->id), dup, qos, retain, mid, mapped_topic, (long)payloadlen); metrics__int_inc(mosq_counter_pub_bytes_sent, payloadlen); rc = send__real_publish(mosq, mid, mapped_topic, payloadlen, payload, qos, retain, dup, subscription_identifier, store_props, expiry_interval); mosquitto_FREE(mapped_topic); return rc; } } } } #endif log__printf(mosq, MOSQ_LOG_DEBUG, "Sending PUBLISH to %s (d%d, q%d, r%d, m%d, '%s', ... (%ld bytes))", SAFE_PRINT(mosq->id), dup, qos, retain, mid, topic, (long)payloadlen); metrics__int_inc(mosq_counter_pub_bytes_sent, payloadlen); #else log__printf(mosq, MOSQ_LOG_DEBUG, "Client %s sending PUBLISH (d%d, q%d, r%d, m%d, '%s', ... (%ld bytes))", SAFE_PRINT(mosq->id), dup, qos, retain, mid, topic, (long)payloadlen); #endif #ifdef WITH_BROKER rc = send__real_publish(mosq, mid, topic, payloadlen, payload, qos, retain, dup, subscription_identifier, store_props, expiry_interval); if(payload_changed){ mosquitto_free((void *)payload); } if(topic_changed){ mosquitto_free((void *)topic); } if(properties_changed){ mosquitto_property_free_all((mosquitto_property **)&store_props); } return rc; #else return send__real_publish(mosq, mid, topic, payloadlen, payload, qos, retain, dup, subscription_identifier, store_props, expiry_interval); #endif } 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, uint32_t subscription_identifier, 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; #ifdef WITH_BROKER mosquitto_property topic_alias_prop; uint16_t topic_alias = 0; mosquitto_property subscription_id_prop; #endif #ifndef WITH_BROKER UNUSED(subscription_identifier); #endif assert(mosq); #ifdef WITH_BROKER if(mosq->protocol == mosq_p_mqtt5){ if(alias__find_by_topic(mosq, ALIAS_DIR_L2R, topic, &topic_alias) == MOSQ_ERR_SUCCESS){ /* If we have an existing alias, no need to send the topic */ topic = NULL; }else{ /* Try to add a new alias - if this succeeds, topic_alias will be * set to the new alias but we still need to send the topic. If it * fails, topic_alias will be set to 0. */ alias__add_l2r(mosq, topic, &topic_alias); } } #endif 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 += mosquitto_property_get_length_all(store_props); if(expiry_interval > 0 && expiry_interval != MSG_EXPIRY_INFINITE){ expiry_prop.next = NULL; expiry_prop.value.i32 = expiry_interval; expiry_prop.identifier = MQTT_PROP_MESSAGE_EXPIRY_INTERVAL; expiry_prop.property_type = MQTT_PROP_TYPE_INT32; expiry_prop.client_generated = false; proplen += mosquitto_property_get_length_all(&expiry_prop); } #ifdef WITH_BROKER if(topic_alias != 0){ topic_alias_prop.next = NULL; topic_alias_prop.value.i16 = topic_alias; topic_alias_prop.identifier = MQTT_PROP_TOPIC_ALIAS; topic_alias_prop.property_type = MQTT_PROP_TYPE_INT16; topic_alias_prop.client_generated = false; proplen += mosquitto_property_get_length_all(&topic_alias_prop); } if(subscription_identifier){ subscription_id_prop.next = NULL; subscription_id_prop.value.varint = subscription_identifier; subscription_id_prop.identifier = MQTT_PROP_SUBSCRIPTION_IDENTIFIER; subscription_id_prop.property_type = MQTT_PROP_TYPE_VARINT; subscription_id_prop.client_generated = false; proplen += mosquitto_property_get_length_all(&subscription_id_prop); } #endif varbytes = mosquitto_varint_bytes(proplen); if(varbytes > 4){ /* FIXME - Properties too big, don't publish any - should remove some first really */ store_props = NULL; expiry_interval = 0; }else{ packetlen += proplen + varbytes; } } if(packet__check_oversize(mosq, packetlen)){ #ifdef WITH_BROKER log__printf(mosq, MOSQ_LOG_NOTICE, "Dropping too large outgoing PUBLISH for %s (%d bytes)", SAFE_PRINT(mosq->id), packetlen); #else log__printf(mosq, MOSQ_LOG_NOTICE, "Dropping too large outgoing PUBLISH (%d bytes)", packetlen); #endif return MOSQ_ERR_OVERSIZE_PACKET; } rc = packet__alloc(&packet, (uint8_t)(CMD_PUBLISH | (uint8_t)((dup&0x1)<<3) | (uint8_t)(qos<<1) | retain), packetlen); if(rc){ return rc; } packet->mid = mid; /* 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, store_props, false); if(expiry_interval > 0 && expiry_interval != MSG_EXPIRY_INFINITE){ property__write_all(packet, &expiry_prop, false); } #ifdef WITH_BROKER if(topic_alias != 0){ property__write_all(packet, &topic_alias_prop, false); } if(subscription_identifier != 0){ property__write_all(packet, &subscription_id_prop, false); } #endif } #if defined(WITH_BROKER) && defined(WITH_SYS_TREE) metrics__int_inc(mosq_counter_mqtt_publish_sent, 1); #endif /* Payload */ if(payloadlen && payload){ packet__write_bytes(packet, payload, payloadlen); } return packet__queue(mosq, packet); } ================================================ FILE: lib/send_subscribe.c ================================================ /* Copyright (c) 2009-2021 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" #endif #include "mosquitto.h" #include "mosquitto_internal.h" #include "logging_mosq.h" #include "mosquitto/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 += mosquitto_property_get_remaining_length(properties); } for(i=0; i UINT16_MAX){ return MOSQ_ERR_INVAL; } packetlen += 2U+(uint16_t)tlen + 1U; } rc = packet__alloc(&packet, CMD_SUBSCRIBE | 2, packetlen); 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 #ifdef WITH_BROKER metrics__int_inc(mosq_counter_mqtt_subscribe_sent, 1); #endif return packet__queue(mosq, packet); } ================================================ FILE: lib/send_unsubscribe.c ================================================ /* Copyright (c) 2009-2021 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" #endif #include "mosquitto.h" #include "logging_mosq.h" #include "mosquitto/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; } if(mosq->protocol == mosq_p_mqtt5){ packetlen += mosquitto_property_get_remaining_length(properties); } rc = packet__alloc(&packet, CMD_UNSUBSCRIBE | 2, packetlen); if(rc){ 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 metrics__int_inc(mosq_counter_mqtt_unsubscribe_sent, 1); #else for(i=0; iid), local_mid, topic[i]); } #endif return packet__queue(mosq, packet); } ================================================ FILE: lib/socks_mosq.c ================================================ /* Copyright (c) 2014-2021 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__) || defined(_AIX) # include # include #endif #include "mosquitto_internal.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 static inline int socks5__network_error(struct mosquitto *mosq) { WINDOWS_SET_ERRNO_RW(); 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; } } } static inline int socks5__connection_error(struct mosquitto *mosq) { uint8_t v = mosq->in_packet.payload[1]; packet__cleanup(&mosq->in_packet); switch(v){ 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; } 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 = mosquitto_strdup(host); if(!mosq->socks5_host){ return MOSQ_ERR_NOMEM; } mosq->socks5_port = (uint16_t)port; mosquitto_FREE(mosq->socks5_username); mosquitto_FREE(mosq->socks5_password); 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 UNUSED(mosq); UNUSED(host); UNUSED(port); UNUSED(username); UNUSED(password); return MOSQ_ERR_NOT_SUPPORTED; #endif } #ifdef WITH_SOCKS static void socks5__packet_alloc(struct mosquitto__packet **packet, uint32_t packet_length) { *packet = mosquitto_calloc(1, sizeof(struct mosquitto__packet) + packet_length + WS_PACKET_OFFSET); if(!(*packet)){ return; } (*packet)->pos = WS_PACKET_OFFSET; (*packet)->packet_length = packet_length + WS_PACKET_OFFSET; (*packet)->to_process = packet_length; } int socks5__send(struct mosquitto *mosq) { struct mosquitto__packet *packet; size_t slen; uint8_t ulen, plen; uint32_t packet_length; 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){ if(mosq->socks5_username){ packet_length = 4; }else{ packet_length = 3; } socks5__packet_alloc(&packet, packet_length); if(!packet){ return MOSQ_ERR_NOMEM; } packet->payload[0 + WS_PACKET_OFFSET] = 0x05; if(mosq->socks5_username){ packet->payload[1 + WS_PACKET_OFFSET] = 2; packet->payload[2 + WS_PACKET_OFFSET] = SOCKS_AUTH_NONE; packet->payload[3 + WS_PACKET_OFFSET] = SOCKS_AUTH_USERPASS; }else{ packet->payload[1 + WS_PACKET_OFFSET] = 1; packet->payload[2 + WS_PACKET_OFFSET] = 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); return MOSQ_ERR_NOMEM; } return packet__queue(mosq, packet); }else if(state == mosq_cs_socks5_auth_ok){ 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_length = 10; socks5__packet_alloc(&packet, packet_length); if(!packet){ return MOSQ_ERR_NOMEM; } packet->payload[3 + WS_PACKET_OFFSET] = SOCKS_ATYPE_IP_V4; memcpy(&(packet->payload[4 + WS_PACKET_OFFSET]), (const void *)&addr_ipv4, 4); packet->payload[4+4 + WS_PACKET_OFFSET] = MOSQ_MSB(mosq->port); packet->payload[4+4+1 + WS_PACKET_OFFSET] = MOSQ_LSB(mosq->port); }else if(ipv6_pton_result == 1){ packet_length = 22; socks5__packet_alloc(&packet, packet_length); if(!packet){ return MOSQ_ERR_NOMEM; } packet->payload[3 + WS_PACKET_OFFSET] = SOCKS_ATYPE_IP_V6; memcpy(&(packet->payload[4 + WS_PACKET_OFFSET]), (const void *)&addr_ipv6, 16); packet->payload[4+16 + WS_PACKET_OFFSET] = MOSQ_MSB(mosq->port); packet->payload[4+16+1 + WS_PACKET_OFFSET] = MOSQ_LSB(mosq->port); }else{ slen = strlen(mosq->host); if(slen > UCHAR_MAX){ return MOSQ_ERR_NOMEM; } packet_length = 7U + (uint32_t)slen; socks5__packet_alloc(&packet, packet_length); if(!packet){ return MOSQ_ERR_NOMEM; } packet->payload[3 + WS_PACKET_OFFSET] = SOCKS_ATYPE_DOMAINNAME; packet->payload[4 + WS_PACKET_OFFSET] = (uint8_t)slen; memcpy(&(packet->payload[5 + WS_PACKET_OFFSET]), mosq->host, slen); packet->payload[5+slen + WS_PACKET_OFFSET] = MOSQ_MSB(mosq->port); packet->payload[6+slen + WS_PACKET_OFFSET] = MOSQ_LSB(mosq->port); } packet->payload[0 + WS_PACKET_OFFSET] = 0x05; packet->payload[1 + WS_PACKET_OFFSET] = 0x01; packet->payload[2 + WS_PACKET_OFFSET] = 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); return MOSQ_ERR_NOMEM; } return packet__queue(mosq, packet); }else if(state == mosq_cs_socks5_send_userpass){ ulen = (uint8_t)strlen(mosq->socks5_username); plen = (uint8_t)strlen(mosq->socks5_password); packet_length = 3U + ulen + plen; socks5__packet_alloc(&packet, packet_length); if(!packet){ return MOSQ_ERR_NOMEM; } packet->payload[0 + WS_PACKET_OFFSET] = 0x01; packet->payload[1 + WS_PACKET_OFFSET] = ulen; memcpy(&(packet->payload[2 + WS_PACKET_OFFSET]), mosq->socks5_username, ulen); packet->payload[2+ulen + WS_PACKET_OFFSET] = plen; memcpy(&(packet->payload[3+ulen + WS_PACKET_OFFSET]), 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); 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; 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{ return socks5__network_error(mosq); } } 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{ return socks5__network_error(mosq); } } 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{ return socks5__connection_error(mosq); } }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{ return socks5__network_error(mosq); } } 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; } /* We know the value of mosq->in_packet.packet_lenth is within a * bound. At the start of this if statement, it was 5. The next set * of if statements add either (4+2-1)=5 to its value, or * (16+2-1)=17 to its value, or the contents of a uint8_t, which * can be a maximum of 255. So the range is 10 to 260 bytes. * Coverity most likely doesn't realise this because the += * promotes to the size of packet_length. */ /* coverity[tainted_data] */ 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{ mosquitto__set_state(mosq, mosq_cs_socks5_new); return socks5__connection_error(mosq); } }else{ return packet__read(mosq); } return MOSQ_ERR_SUCCESS; } #endif ================================================ FILE: lib/socks_mosq.h ================================================ /* Copyright (c) 2014-2021 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 ================================================ FILE: lib/srv_mosq.c ================================================ /* Copyright (c) 2013-2021 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 "callbacks.h" #include "logging_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; UNUSED(timeouts); 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. */ callback__on_disconnect(mosq, MOSQ_ERR_LOOKUP, NULL); } } #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; } UNUSED(bind_address); 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); } 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 } ================================================ FILE: lib/thread_mosq.c ================================================ /* Copyright (c) 2011-2021 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. */ #if defined(__linux__) # define _GNU_SOURCE /* Exposes pthread_setname_np on Linux */ #endif #include "config.h" #if defined(WITH_THREADING) #if defined(__linux__) # include #elif defined(__NetBSD__) # include #elif defined(__FreeBSD__) || defined(__OpenBSD__) # include #endif #endif #ifndef WIN32 #include #endif #include "mosquitto_internal.h" #include "net_mosq.h" #include "util_mosq.h" void *mosquitto__thread_main(void *obj); int mosquitto_loop_start(struct mosquitto *mosq) { #if defined(WITH_THREADING) if(!mosq || mosq->threaded != mosq_ts_none){ return MOSQ_ERR_INVAL; } if(!COMPAT_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 mosq->threaded = mosq_ts_self; 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; } mosq->run = false; /* 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){ COMPAT_pthread_cancel(mosq->thread_id); } #endif COMPAT_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); } if(mosq->threaded == mosq_ts_self){ mosq->threaded = mosq_ts_none; } 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; } ================================================ FILE: lib/tls_mosq.c ================================================ /* Copyright (c) 2013-2021 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" int mosquitto__server_certificate_verify(int preverify_ok, X509_STORE_CTX *ctx) { UNUSED(ctx); return preverify_ok; } int tls__set_verify_hostname(struct mosquitto *mosq, const char *hostname) { unsigned char ipv6_addr[16]; unsigned char ipv4_addr[4]; int ipv6_ok; int ipv4_ok; int rc; if(mosq->tls_insecure == true || (mosq->tls_cafile == NULL && mosq->tls_capath == NULL && mosq->tls_use_os_certs == false)){ return MOSQ_ERR_SUCCESS; } #ifndef WITH_BROKER if(mosq->port == 0){ /* No hostname verification for unix sockets */ return MOSQ_ERR_SUCCESS; } #endif #ifdef WIN32 ipv6_ok = InetPton(AF_INET6, hostname, &ipv6_addr); ipv4_ok = InetPton(AF_INET, hostname, &ipv4_addr); #else ipv6_ok = inet_pton(AF_INET6, hostname, &ipv6_addr); ipv4_ok = inet_pton(AF_INET, hostname, &ipv4_addr); #endif X509_VERIFY_PARAM *param = SSL_get0_param(mosq->ssl); if(ipv4_ok || ipv6_ok){ rc = X509_VERIFY_PARAM_set1_ip_asc(param, hostname); }else{ rc = X509_VERIFY_PARAM_set1_host(param, hostname, 0); } if(rc == 1){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_TLS; } } #endif ================================================ FILE: lib/tls_mosq.h ================================================ /* Copyright (c) 2013-2021 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 #include "mosquitto.h" int mosquitto__server_certificate_verify(int preverify_ok, X509_STORE_CTX *ctx); int tls__set_verify_hostname(struct mosquitto *mosq, const char *hostname); #endif /* WITH_TLS */ #endif ================================================ FILE: lib/util_mosq.c ================================================ /* Copyright (c) 2009-2021 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 #ifdef WITH_TLS # include #endif #ifdef WITH_BROKER #include "mosquitto_broker_internal.h" #else # include "callbacks.h" #endif #include "mosquitto.h" #include "net_mosq.h" #include "send_mosq.h" #include "tls_mosq.h" #include "util_mosq.h" #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS #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 && net__is_connected(mosq) && now - mosq->next_msg_out - mosq->keepalive >= mosq->bridge->idle_timeout){ log__printf(mosq, MOSQ_LOG_NOTICE, "Bridge connection %s has exceeded idle timeout, disconnecting.", mosq->id); net__socket_close(mosq); return MOSQ_ERR_SUCCESS; } #endif COMPAT_pthread_mutex_lock(&mosq->msgtime_mutex); next_msg_out = mosq->next_msg_out; last_msg_in = mosq->last_msg_in; COMPAT_pthread_mutex_unlock(&mosq->msgtime_mutex); if(mosq->keepalive && net__is_connected(mosq) && (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 */ COMPAT_pthread_mutex_lock(&mosq->msgtime_mutex); mosq->last_msg_in = now; mosq->next_msg_out = now + mosq->keepalive; COMPAT_pthread_mutex_unlock(&mosq->msgtime_mutex); }else{ #ifdef WITH_BROKER # ifdef WITH_BRIDGE if(mosq->bridge){ context__send_will(mosq); } # endif 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; } callback__on_disconnect(mosq, rc, NULL); 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); COMPAT_pthread_mutex_lock(&mosq->mid_mutex); mosq->last_mid++; if(mosq->last_mid == 0){ mosq->last_mid++; } mid = mosq->last_mid; COMPAT_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; size_t i = 0; /* Count the number of leading zero */ for(i=0; i= bin_max_len){ return 0; } /* output leading zero to bin */ bin[leading_zero] = 0; leading_zero++; }else{ break; } } if(BN_hex2bn(&bn, hex) == 0){ if(bn){ BN_free(bn); } return 0; } if(BN_num_bytes(bn) + leading_zero > 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 mosquitto__set_state(struct mosquitto *mosq, enum mosquitto_client_state state) { COMPAT_pthread_mutex_lock(&mosq->state_mutex); #ifdef WITH_BROKER if(mosq->state != mosq_cs_disused) #endif { mosq->state = state; } COMPAT_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; COMPAT_pthread_mutex_lock(&mosq->state_mutex); state = mosq->state; COMPAT_pthread_mutex_unlock(&mosq->state_mutex); return state; } #ifndef WITH_BROKER void mosquitto__set_request_disconnect(struct mosquitto *mosq, bool request_disconnect) { COMPAT_pthread_mutex_lock(&mosq->state_mutex); mosq->request_disconnect = request_disconnect; COMPAT_pthread_mutex_unlock(&mosq->state_mutex); } bool mosquitto__get_request_disconnect(struct mosquitto *mosq) { bool request_disconnect; COMPAT_pthread_mutex_lock(&mosq->state_mutex); request_disconnect = mosq->request_disconnect; COMPAT_pthread_mutex_unlock(&mosq->state_mutex); return request_disconnect; } #endif ================================================ FILE: lib/util_mosq.h ================================================ /* Copyright (c) 2009-2021 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); #ifndef WITH_BROKER void mosquitto__set_request_disconnect(struct mosquitto *mosq, bool request_disconnect); bool mosquitto__get_request_disconnect(struct mosquitto *mosq); #endif #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 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 ================================================ FILE: lib/will_mosq.c ================================================ /* Copyright (c) 2010-2021 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 "mosquitto/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, mosquitto_property_identifier(p)); if(rc){ return rc; } p = mosquitto_property_next(p); } } 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); } return rc; } int will__clear(struct mosquitto *mosq) { if(!mosq->will){ return MOSQ_ERR_SUCCESS; } 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_delay_interval = 0; return MOSQ_ERR_SUCCESS; } ================================================ FILE: lib/will_mosq.h ================================================ /* Copyright (c) 2010-2021 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 ================================================ FILE: libcommon/CMakeLists.txt ================================================ set(C_SRC base64_common.c cjson_common.c file_common.c memory_common.c mqtt_common.c password_common.c property_common.c random_common.c strings_common.c time_common.c topic_common.c utf8_common.c "${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon.h" "${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_base64.h" "${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_cjson.h" "${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_file.h" "${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_memory.h" "${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_properties.h" "${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_random.h" "${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_string.h" "${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_time.h" "${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_topic.h" "${mosquitto_SOURCE_DIR}/include/mosquitto/libcommon_utf8.h" ) if(WIN32) add_library(libmosquitto_common SHARED ${C_SRC} ) else() add_library(libmosquitto_common OBJECT ${C_SRC} ) endif() target_include_directories(libmosquitto_common PUBLIC "${CJSON_INCLUDE_DIRS}" ) target_link_libraries(libmosquitto_common PUBLIC common-options cJSON ) if(ARGON2_FOUND) target_link_libraries(libmosquitto_common PRIVATE argon2) endif() if (WITH_TLS) target_link_libraries(libmosquitto_common PUBLIC OpenSSL::SSL ) elseif(NOT WIN32) include(CheckSymbolExists) check_symbol_exists(getrandom "sys/random.h" GETRANDOM_FOUND) if(GETRANDOM_FOUND) add_definitions("-DHAVE_GETRANDOM") else() message(FATAL_ERROR "C library does not provide getrandom(); enable WITH_TLS instead") endif() endif() if(INC_MEMTRACK) target_compile_definitions(libmosquitto_common PUBLIC "WITH_MEMORY_TRACKING") endif() option(ALLOC_MISMATCH_INVALID_READ "Memory function mismatch detection." OFF) if(ALLOC_MISMATCH_INVALID_READ) target_compile_definitions(libmosquitto_common PRIVATE "ALLOC_MISMATCH_INVALID_READ") endif() option(ALLOC_MISMATCH_ABORT "Memory function mismatch abort." OFF) if(ALLOC_MISMATCH_ABORT) target_compile_definitions(libmosquitto_common PRIVATE "ALLOC_MISMATCH_ABORT") endif() set_target_properties(libmosquitto_common PROPERTIES OUTPUT_NAME mosquitto_common VERSION ${VERSION} SOVERSION 1 POSITION_INDEPENDENT_CODE 1 ) install(TARGETS libmosquitto_common RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" ) ================================================ FILE: libcommon/Makefile ================================================ R=.. include ${R}/config.mk LOCAL_CFLAGS+=-fPIC LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+=-Wl,--version-script=linker.version -Wl,-soname,libmosquitto_common.so.$(SOVERSION) -fPIC LOCAL_LIBADD+=-lcjson ifeq ($(WITH_MEMORY_TRACKING),yes) LOCAL_CPPFLAGS+=-DWITH_MEMORY_TRACKING endif ifeq ($(ALLOC_MISMATCH_INVALID_READ),yes) LOCAL_CPPFLAGS+=-DALLOC_MISMATCH_INVALID_READ endif ifeq ($(ALLOC_MISMATCH_ABORT),yes) LOCAL_CPPFLAGS+=-DALLOC_MISMATCH_ABORT endif ifeq ($(WITH_TLS),yes) LOCAL_LIBADD+=-lcrypto endif # ------------------------------------------ # Targets # ------------------------------------------ .PHONY : really clean install OBJS= \ base64_common.o \ cjson_common.o \ file_common.o \ memory_common.o \ mqtt_common.o \ password_common.o \ property_common.o \ random_common.o \ strings_common.o \ time_common.o \ topic_common.o \ utf8_common.o all : libmosquitto_common.a libmosquitto_common.so.${SOVERSION} install : $(INSTALL) -d "${DESTDIR}${libdir}/" $(INSTALL) ${STRIP_OPTS} libmosquitto_common.so.${SOVERSION} "${DESTDIR}${libdir}/libmosquitto_common.so.${SOVERSION}" ln -sf libmosquitto_common.so.${SOVERSION} "${DESTDIR}${libdir}/libmosquitto_common.so" uninstall : reallyclean : clean clean : -rm -f ${OBJS} libmosquitto_common.so.${SOVERSION} libmosquitto_common.so libmosquitto_common.a *.gcno *.gcda libmosquitto_common.so.${SOVERSION} : ${OBJS} ${CROSS_COMPILE}$(CC) $(LOCAL_LDFLAGS) $^ -o $@ ${LOCAL_LIBADD} -shared libmosquitto_common.a : ${OBJS} ${CROSS_COMPILE}$(AR) cr $@ $^ ${OBJS} : %.o: %.c ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ ================================================ FILE: libcommon/base64_common.c ================================================ /* Copyright (c) 2012-2021 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 # include # include # include #endif #include #include "mosquitto.h" #ifdef WITH_TLS int mosquitto_base64_encode(const unsigned char *in, size_t in_len, char **encoded) { BIO *bmem, *b64; BUF_MEM *bptr = NULL; int rc = 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){ b64 = BIO_push(b64, bmem); BIO_write(b64, in, (int)in_len); if(BIO_flush(b64) == 1){ BIO_get_mem_ptr(b64, &bptr); *encoded = mosquitto_malloc(bptr->length+1); if(*encoded){ memcpy(*encoded, bptr->data, bptr->length); (*encoded)[bptr->length] = '\0'; rc = 0; } } } BIO_free_all(b64); return rc; } int mosquitto_base64_decode(const char *in, unsigned char **decoded, unsigned int *decoded_len) { BIO *bmem, *b64; size_t slen; int len; int rc = 1; slen = strlen(in); *decoded = NULL; *decoded_len = 0; 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){ b64 = BIO_push(b64, bmem); BIO_write(bmem, in, (int)slen); if(BIO_flush(bmem) == 1){ *decoded = mosquitto_calloc(slen, 1); if(*decoded){ len = BIO_read(b64, *decoded, (int)slen); if(len > 0){ *decoded_len = (unsigned int)len; rc = 0; }else{ mosquitto_free(*decoded); *decoded = NULL; } } } } BIO_free_all(b64); return rc; } #endif ================================================ FILE: libcommon/cjson_common.c ================================================ /* Copyright (c) 2009-2021 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 "mosquitto.h" cJSON *mosquitto_properties_to_json(const mosquitto_property *properties) { cJSON *array, *obj; char *name, *value; uint8_t i8; uint16_t len; int propid; if(!properties){ return NULL; } array = cJSON_CreateArray(); if(!array){ return NULL; } do{ propid = mosquitto_property_identifier(properties); obj = cJSON_CreateObject(); if(!obj){ cJSON_Delete(array); return NULL; } cJSON_AddItemToArray(array, obj); /* identifier, (key), value */ if(cJSON_AddStringToObject(obj, "identifier", mosquitto_property_identifier_to_string(propid)) == NULL ){ cJSON_Delete(array); return NULL; } switch(propid){ case MQTT_PROP_PAYLOAD_FORMAT_INDICATOR: /* byte */ mosquitto_property_read_byte(properties, propid, &i8, false); if(cJSON_AddNumberToObject(obj, "value", i8) == NULL){ cJSON_Delete(array); return NULL; } break; case MQTT_PROP_CONTENT_TYPE: case MQTT_PROP_RESPONSE_TOPIC: case MQTT_PROP_REASON_STRING: /* str */ if(mosquitto_property_read_string(properties, propid, &value, false) == NULL){ cJSON_Delete(array); return NULL; } if(cJSON_AddStringToObject(obj, "value", value) == NULL){ free(value); cJSON_Delete(array); return NULL; } free(value); break; case MQTT_PROP_CORRELATION_DATA: { /* bin */ void *binval = NULL; mosquitto_property_read_binary(properties, propid, &binval, &len, false); char *hexval = malloc(2*(size_t)len + 1); if(!hexval){ free(binval); cJSON_Delete(array); return NULL; } for(int 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 contains general purpose utility functions that are not specific to * Mosquitto/MQTT features. */ #include "config.h" #include #include #include #include #include #include #include #include #ifdef WIN32 # include # include # include # include # include # define PATH_MAX MAX_PATH #else # include # include # include # include # include #endif #include "mosquitto.h" void (*libcommon_vprintf)(const char *fmt, va_list va) = NULL; void libcommon_printf(const char *fmt, ...) { va_list va; va_start(va, fmt); if(libcommon_vprintf){ libcommon_vprintf(fmt, va); }else{ vfprintf(stderr, fmt, va); } va_end(va); } FILE *mosquitto_fopen(const char *path, const char *mode, bool restrict_read) { #ifdef WIN32 char buf[4096]; int rc; int flags = 0; 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; DWORD dwShareMode; int fd; FILE *fptr; switch(mode[0]){ case 'a': dwCreationDisposition = OPEN_ALWAYS; dwShareMode = GENERIC_WRITE; flags = _O_APPEND; break; case 'r': dwCreationDisposition = OPEN_EXISTING; dwShareMode = GENERIC_READ; flags = _O_RDONLY; break; case 'w': dwCreationDisposition = CREATE_ALWAYS; dwShareMode = GENERIC_WRITE; break; default: return NULL; } if(mode[1] == '+'){ dwShareMode = GENERIC_READ | GENERIC_WRITE; } 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; } memset(&sec, 0, sizeof(sec)); sec.nLength = sizeof(SECURITY_ATTRIBUTES); sec.bInheritHandle = FALSE; sec.lpSecurityDescriptor = &sd; hfile = CreateFileA(buf, dwShareMode, FILE_SHARE_READ, &sec, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL); LocalFree(pacl); fd = _open_osfhandle((intptr_t)hfile, flags); if(fd < 0){ return NULL; } fptr = _fdopen(fd, mode); if(!fptr){ _close(fd); return NULL; } if(mode[0] == 'a'){ fseek(fptr, 0, SEEK_END); } return fptr; }else{ return fopen(buf, mode); } } #else FILE *fptr; struct stat statbuf; if(restrict_read){ mode_t old_mask; old_mask = umask(0077); int open_flags = 0; if(!getenv("MOSQUITTO_UNSAFE_ALLOW_SYMLINKS")){ open_flags |= O_NOFOLLOW; } for(size_t i = 0; ipw_name, result->pw_name, path); } #if 0 // Future version return NULL; #endif } if(statbuf.st_gid != getgid()){ char buf[4096]; struct group grp, *result; if(getgrgid_r(getgid(), &grp, buf, sizeof(buf), &result) == 0 && result){ libcommon_printf( "Warning: File %s group is not %s. Future versions will refuse to load this file.\n", path, result->gr_name); } #if 0 // Future version return NULL #endif } } if(!S_ISREG(statbuf.st_mode)){ libcommon_printf("Error: %s is not a file.", path); fclose(fptr); return NULL; } return fptr; #endif } char *mosquitto_trimblanks(char *str) { char *endptr; if(str == NULL){ return NULL; } while(isspace((unsigned char)str[0])){ str++; } endptr = &str[strlen(str)-1]; while(endptr > str && isspace((unsigned char)endptr[0])){ endptr[0] = '\0'; endptr--; } return str; } char *mosquitto_fgets(char **buf, int *buflen, FILE *stream) { char *rc; char endchar; int offset = 0; char *newbuf; size_t len; if(stream == NULL || buf == NULL || buflen == NULL || *buflen < 1){ return NULL; } do{ rc = fgets(&((*buf)[offset]), (*buflen)-offset, stream); if(feof(stream) || rc == NULL){ return rc; } len = strlen(*buf); if(len == 0){ return rc; } endchar = (*buf)[len-1]; if(endchar == '\n'){ return rc; } if((int)(len+1) < *buflen){ /* Embedded nulls, invalid string */ return NULL; } /* 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); } #define INVOKE_LOG_FN(format, ...) \ do{ \ if(log_fn){ \ int tmp_err_no = errno; \ char msg[2*PATH_MAX]; \ snprintf(msg, sizeof(msg), (format), __VA_ARGS__); \ msg[sizeof(msg)-1] = '\0'; \ (*log_fn)(msg); \ errno = tmp_err_no; \ } \ }while(0) int mosquitto_write_file(const char *target_path, bool restrict_read, int (*write_fn)(FILE *fptr, void *user_data), void *user_data, void (*log_fn)(const char *msg)) { int rc = 0; FILE *fptr = NULL; char tmp_file_path[PATH_MAX]; if(!target_path || !write_fn){ return MOSQ_ERR_INVAL; } rc = snprintf(tmp_file_path, PATH_MAX, "%s.new", target_path); if(rc < 0 || rc >= PATH_MAX){ return MOSQ_ERR_INVAL; } #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. * */ if(unlink(tmp_file_path) && errno != ENOENT){ INVOKE_LOG_FN("unable to remove stale tmp file %s, error %s", tmp_file_path, strerror(errno)); return MOSQ_ERR_INVAL; } #endif fptr = mosquitto_fopen(tmp_file_path, "wb", restrict_read); if(fptr == NULL){ INVOKE_LOG_FN("unable to open %s for writing, error %s", tmp_file_path, strerror(errno)); return MOSQ_ERR_INVAL; } if((rc = (*write_fn)(fptr, user_data)) != MOSQ_ERR_SUCCESS){ goto error; } rc = MOSQ_ERR_ERRNO; #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. * */ if(fflush(fptr) != 0 && errno != EINTR){ INVOKE_LOG_FN("unable to flush %s, error %s", tmp_file_path, strerror(errno)); goto error; } if(fsync(fileno(fptr)) != 0 && errno != EINTR){ INVOKE_LOG_FN("unable to sync %s to disk, error %s", tmp_file_path, strerror(errno)); goto error; } #endif if(fclose(fptr) != 0){ INVOKE_LOG_FN("unable to close %s on disk, error %s", tmp_file_path, strerror(errno)); fptr = NULL; goto error; } fptr = NULL; #ifdef WIN32 if(remove(target_path) != 0 && errno != ENOENT){ INVOKE_LOG_FN("unable to remove %s on disk, error %s", target_path, strerror(errno)); goto error; } #endif if(rename(tmp_file_path, target_path) != 0){ INVOKE_LOG_FN("unable to replace %s by tmp file %s, error %s", target_path, tmp_file_path, strerror(errno)); goto error; } return MOSQ_ERR_SUCCESS; error: if(fptr){ fclose(fptr); unlink(tmp_file_path); } return MOSQ_ERR_ERRNO; } int mosquitto_read_file(const char *file, bool restrict_read, char **buf, size_t *buflen) { FILE *fptr; long l; size_t buflen_i; *buf = NULL; if(buflen){ *buflen = 0; } fptr = mosquitto_fopen(file, "rt", restrict_read); if(fptr == NULL){ return MOSQ_ERR_ERRNO; } fseek(fptr, 0, SEEK_END); l = ftell(fptr); fseek(fptr, 0, SEEK_SET); if(l < 0){ fclose(fptr); return MOSQ_ERR_ERRNO; }else if(l == 0){ fclose(fptr); return MOSQ_ERR_SUCCESS; } buflen_i = (size_t)l; *buf = mosquitto_calloc(buflen_i+1, sizeof(char)); if((*buf) == NULL){ fclose(fptr); return MOSQ_ERR_NOMEM; } if(fread(*buf, 1, buflen_i, fptr) != buflen_i){ mosquitto_FREE(*buf); fclose(fptr); return MOSQ_ERR_INVAL; } fclose(fptr); if(buflen){ *buflen = buflen_i; } return MOSQ_ERR_SUCCESS; } ================================================ FILE: libcommon/linker.version ================================================ /* Linker version script - currently used here primarily to control which * symbols are exported. */ MOSQ_2.1 { global: libcommon_printf; mosquitto_base64_decode; mosquitto_base64_encode; mosquitto_calloc; mosquitto_connack_string; mosquitto_fgets; mosquitto_fopen; mosquitto_free; mosquitto_free; mosquitto_getrandom; mosquitto_malloc; mosquitto_malloc; mosquitto_max_memory_used; mosquitto_memory_set_limit; mosquitto_memory_used; mosquitto_properties_to_json; mosquitto_property_next; 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_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_binary_value; mosquitto_property_binary_value_length; mosquitto_property_byte_value; mosquitto_property_check_all; mosquitto_property_check_command; mosquitto_property_copy_all; mosquitto_property_free; mosquitto_property_free_all; mosquitto_property_get_length; mosquitto_property_get_length_all; mosquitto_property_get_remaining_length; mosquitto_property_identifier; mosquitto_property_identifier_to_string; mosquitto_property_int16_value; mosquitto_property_int32_value; mosquitto_property_remove; mosquitto_property_string_name; mosquitto_property_string_name_length; mosquitto_property_string_value; mosquitto_property_string_value_length; mosquitto_property_type; mosquitto_property_varint_value; mosquitto_pub_topic_check; mosquitto_pub_topic_check2; mosquitto_pw_cleanup; mosquitto_pw_decode; mosquitto_pw_get_encoded; mosquitto_pw_hash_encoded; mosquitto_pw_is_valid; mosquitto_pw_new; mosquitto_pw_set_param; mosquitto_pw_set_valid; mosquitto_pw_verify; mosquitto_read_file; mosquitto_realloc; mosquitto_realloc; mosquitto_reason_string; mosquitto_strdup; mosquitto_strerror; mosquitto_string_to_command; mosquitto_string_to_property_info; mosquitto_strndup; mosquitto_sub_matches_acl; mosquitto_sub_matches_acl_with_pattern; mosquitto_sub_topic_check; mosquitto_sub_topic_check2; mosquitto_sub_topic_tokenise; mosquitto_sub_topic_tokens_free; mosquitto_time; mosquitto_time_cmp; mosquitto_time_init; mosquitto_time_ns; mosquitto_topic_matches_sub; mosquitto_topic_matches_sub2; mosquitto_topic_matches_sub_with_pattern; mosquitto_trimblanks; mosquitto_validate_utf8; mosquitto_varint_bytes; mosquitto_write_file; local: *; }; ================================================ FILE: libcommon/memory_common.c ================================================ /* Copyright (c) 2009-2021 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" #if defined(WITH_MEMORY_TRACKING) # if defined(__APPLE__) || defined(__FreeBSD__) || defined(__linux__) # define REAL_WITH_MEMORY_TRACKING # endif #endif #ifdef REAL_WITH_MEMORY_TRACKING # if defined(__APPLE__) # include # define malloc_usable_size malloc_size # elif defined(__FreeBSD__) # include # else # include # endif #endif static unsigned long memcount = 0; static unsigned long max_memcount = 0; static size_t mem_limit = 0; void mosquitto_memory_set_limit(size_t lim) { mem_limit = lim; } unsigned long mosquitto_memory_used(void) { return memcount; } unsigned long mosquitto_max_memory_used(void) { return max_memcount; } #ifdef REAL_WITH_MEMORY_TRACKING /* ================================================== * Alloc mismatch tracking * ================================================== */ #if defined(ALLOC_MISMATCH_INVALID_READ) || defined(ALLOC_MISMATCH_ABORT) #define ALLOC_MARKER_SIZE 8 static const char *alloc_marker = "MOSQ_MEM"; static unsigned long dummycounter = 0; unsigned long mosq__get_dummy_counter(void) { return dummycounter; } static void set_alloc_marker(char *mem, size_t size) { memcpy(mem + size - ALLOC_MARKER_SIZE, alloc_marker, ALLOC_MARKER_SIZE); } static bool check_alloc_marker(char *mem, size_t size) { return strncmp(mem + size - ALLOC_MARKER_SIZE, alloc_marker, ALLOC_MARKER_SIZE) == 0; } static void trigger_alloc_mismatch(char *mem, size_t size) { (void)mem; (void)size; #ifdef ALLOC_MISMATCH_INVALID_READ /* Trigger an invalid read on the freed memory and increment dummy counter */ if(strncmp(mem + size - ALLOC_MARKER_SIZE, alloc_marker, ALLOC_MARKER_SIZE) == 0){ ++dummycounter; } #endif #ifdef ALLOC_MISMATCH_ABORT abort(); #endif } #if defined(__linux__) #if !defined(__libc_free) void __libc_free(void *ptr); #endif void free(void *ptr) { if(!ptr){ return; } size_t free_size = malloc_usable_size(ptr); /* If we find the marker the memory was allocated using mosquitto_* allocation function */ bool alloc_mismatch = check_alloc_marker(ptr, free_size); __libc_free(ptr); if(alloc_mismatch){ trigger_alloc_mismatch(ptr, free_size); } } #endif /* defined(__linux__) */ #else /* defined(ALLOC_MISMATCH_INVALID_READ) || defined(ALLOC_MISMATCH_ABORT) */ #define ALLOC_MARKER_SIZE 0 static void set_alloc_marker(char *mem, size_t size) { UNUSED(mem); UNUSED(size); } #endif /* defined(ALLOC_MISMATCH_INVALID_READ) */ /* ================================================== * Alloc functions with tracking * ================================================== */ BROKER_EXPORT void *mosquitto_malloc(size_t size) { void *mem; if(mem_limit && memcount + size > mem_limit){ return NULL; } mem = malloc(size + ALLOC_MARKER_SIZE); if(mem){ size = malloc_usable_size(mem); memcount += size; if(memcount > max_memcount){ max_memcount = memcount; } set_alloc_marker(mem, size); } return mem; } BROKER_EXPORT void *mosquitto_realloc(void *ptr, size_t size) { void *mem; size_t free_size = ptr != NULL ? malloc_usable_size(ptr) : 0UL; #if ALLOC_MARKER_SIZE bool alloc_mismatch = free_size > 0 && !check_alloc_marker(ptr, free_size); #endif /* Avoid counter underflow due to mismatched memory allocation function usage */ if(free_size > memcount){ free_size = memcount; } if(mem_limit && memcount - free_size + size > mem_limit){ return NULL; } mem = realloc(ptr, size + ALLOC_MARKER_SIZE); #if ALLOC_MARKER_SIZE if(alloc_mismatch){ /* This will not trigger if realloc was able to extend the memory in place. */ trigger_alloc_mismatch(ptr, free_size); } #endif if(mem){ size = malloc_usable_size(mem); memcount -= free_size; memcount += size; if(memcount > max_memcount){ max_memcount = memcount; } set_alloc_marker(mem, size); }else if(size == 0){ memcount -= free_size; } return mem; } BROKER_EXPORT void mosquitto_free(void *mem) { if(!mem){ return; } size_t free_size = malloc_usable_size(mem); #if ALLOC_MARKER_SIZE bool alloc_mismatch = !check_alloc_marker(mem, free_size); #ifdef __linux__ __libc_free(mem); #else free(mem); #endif if(alloc_mismatch){ trigger_alloc_mismatch(mem, free_size); } #else /* ALLOC_MARKER_SIZE */ free(mem); #endif /* ALLOC_MARKER_SIZE */ /* Avoid counter underflow due to mismatched memory function allocation usage */ if(free_size > memcount){ free_size = memcount; } memcount -= free_size; } #else /* #ifdef WITH_REAL_MEMORY_TRACKING */ /* ================================================== * Alloc functions without tracking * ================================================== */ BROKER_EXPORT void *mosquitto_malloc(size_t size) { return malloc(size); } BROKER_EXPORT void *mosquitto_realloc(void *ptr, size_t size) { return realloc(ptr, size); } BROKER_EXPORT void mosquitto_free(void *mem) { free(mem); } #endif /* #ifdef WITH_REAL_MEMORY_TRACKING */ /* ================================================== * Alloc functions that use the tracked/untracked versions * ================================================== */ BROKER_EXPORT void *mosquitto_calloc(size_t nmemb, size_t size) { void *mem; const size_t alloc_size = nmemb * size; mem = mosquitto_malloc(alloc_size); if(mem){ memset(mem, 0, alloc_size); } return mem; } BROKER_EXPORT char *mosquitto_strdup(const char *s) { char *str; size_t size = strlen(s) + 1; str = mosquitto_malloc(size); if(str){ memcpy(str, s, size); } return str; } BROKER_EXPORT char *mosquitto_strndup(const char *s, size_t n) { char *str; size_t size = strnlen(s, n); if(size > n){ size = n; } str = mosquitto_malloc(size + 1); if(str){ memcpy(str, s, size); str[size] = 0; } return str; } ================================================ FILE: libcommon/mqtt_common.c ================================================ /* Copyright (c) 2009-2021 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" unsigned int mosquitto_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; } } ================================================ FILE: libcommon/password_common.c ================================================ /* Copyright (c) 2012-2021 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_TLS # include # include # include # define HASH_LEN EVP_MAX_MD_SIZE #endif #include "mosquitto.h" #ifdef WITH_TLS # define HASH_LEN EVP_MAX_MD_SIZE #else /* 64 bytes big enough for SHA512 */ # define HASH_LEN 64 #endif #ifdef WITH_ARGON2 # include # define MOSQ_ARGON2_T 1 # define MOSQ_ARGON2_M 47104 # define MOSQ_ARGON2_P 1 #endif #define PW_DEFAULT_ITERATIONS 1000 static int pw__encode(struct mosquitto_pw *pw); struct mosquitto_pw { union { struct { unsigned char password_hash[HASH_LEN]; /* For SHA512 */ unsigned char salt[HASH_LEN]; size_t salt_len; } sha512; struct { unsigned char password_hash[HASH_LEN]; /* For SHA512 */ unsigned char salt[HASH_LEN]; size_t salt_len; int iterations; } sha512_pbkdf2; struct { unsigned char password_hash[HASH_LEN]; unsigned char salt[HASH_LEN]; size_t salt_len; int iterations; } argon2id; } params; char *encoded_password; enum mosquitto_pwhash_type hashtype; bool valid; }; static int pw__memcmp_const(const void *a, const void *b, size_t len) { #ifdef WITH_TLS return CRYPTO_memcmp(a, b, len); #else int rc = 0; const volatile char *ac = a; const volatile char *bc = b; if(!a || !b){ return 1; } for(size_t i=0; ihashtype = MOSQ_PW_ARGON2ID; pw->params.argon2id.salt_len = HASH_LEN; int rc = mosquitto_getrandom(pw->params.argon2id.salt, (int)pw->params.argon2id.salt_len); if(rc){ return rc; } size_t encoded_len = argon2_encodedlen(MOSQ_ARGON2_T, MOSQ_ARGON2_M, MOSQ_ARGON2_P, (uint32_t)pw->params.argon2id.salt_len, sizeof(pw->params.argon2id.password_hash), Argon2_id); mosquitto_free(pw->encoded_password); pw->encoded_password = mosquitto_calloc(1, encoded_len+1); rc = argon2id_hash_encoded(MOSQ_ARGON2_T, MOSQ_ARGON2_M, MOSQ_ARGON2_P, password, strlen(password), pw->params.argon2id.salt, pw->params.argon2id.salt_len, HASH_LEN, pw->encoded_password, encoded_len+1); if(rc == ARGON2_OK){ pw->valid = true; return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_UNKNOWN; } #else UNUSED(pw); UNUSED(password); return MOSQ_ERR_NOT_SUPPORTED; #endif } static int pw__verify_argon2id(struct mosquitto_pw *pw, const char *password) { #ifdef WITH_ARGON2 int rc = argon2id_verify(pw->encoded_password, password, strlen(password)); if(rc == ARGON2_OK){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } #else UNUSED(pw); UNUSED(password); return MOSQ_ERR_NOT_SUPPORTED; #endif } static int pw__decode_argon2id(struct mosquitto_pw *pw, const char *password) { #ifdef WITH_ARGON2 char *new_password = mosquitto_strdup(password); if(new_password){ mosquitto_free(pw->encoded_password); pw->encoded_password = new_password; pw->valid = true; return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOMEM; } #else UNUSED(pw); UNUSED(password); return MOSQ_ERR_NOT_SUPPORTED; #endif } /* ================================================== * SHA512 PBKDF2 * ================================================== */ #ifdef WITH_TLS static int pw__hash_sha512_pbkdf2(const char *password, struct mosquitto_pw *pw, unsigned char *password_hash, unsigned int hash_len, int iterations) { const EVP_MD *digest; digest = EVP_get_digestbyname("sha512"); if(!digest){ return MOSQ_ERR_UNKNOWN; } PKCS5_PBKDF2_HMAC(password, (int)strlen(password), pw->params.sha512.salt, (int)pw->params.sha512.salt_len, iterations, digest, (int)hash_len, password_hash); return MOSQ_ERR_SUCCESS; } #endif static int pw__create_sha512_pbkdf2(struct mosquitto_pw *pw, const char *password) { #ifdef WITH_TLS pw->hashtype = MOSQ_PW_SHA512_PBKDF2; pw->params.sha512_pbkdf2.salt_len = HASH_LEN; int rc = RAND_bytes(pw->params.sha512_pbkdf2.salt, (int)pw->params.sha512_pbkdf2.salt_len); if(!rc){ return MOSQ_ERR_UNKNOWN; } if(pw->params.sha512_pbkdf2.iterations == 0){ pw->params.sha512_pbkdf2.iterations = PW_DEFAULT_ITERATIONS; } rc = pw__hash_sha512_pbkdf2(password, pw, pw->params.sha512_pbkdf2.password_hash, sizeof(pw->params.sha512_pbkdf2.password_hash), pw->params.sha512_pbkdf2.iterations); pw->valid = (rc == MOSQ_ERR_SUCCESS); return rc; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } static int pw__verify_sha512_pbkdf2(struct mosquitto_pw *pw, const char *password) { #ifdef WITH_TLS int rc; unsigned char password_hash[HASH_LEN]; rc = pw__hash_sha512_pbkdf2(password, pw, password_hash, sizeof(password_hash), pw->params.sha512_pbkdf2.iterations); if(rc != MOSQ_ERR_SUCCESS){ return MOSQ_ERR_AUTH; } if(!pw__memcmp_const(pw->params.sha512_pbkdf2.password_hash, password_hash, HASH_LEN)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } #else return MOSQ_ERR_NOT_SUPPORTED; #endif } static int pw__encode_sha512_pbkdf2(struct mosquitto_pw *pw) { #ifdef WITH_TLS int rc; char *salt64 = NULL, *hash64 = NULL; rc = mosquitto_base64_encode(pw->params.sha512_pbkdf2.salt, pw->params.sha512_pbkdf2.salt_len, &salt64); if(rc){ return MOSQ_ERR_UNKNOWN; } rc = mosquitto_base64_encode(pw->params.sha512_pbkdf2.password_hash, sizeof(pw->params.sha512_pbkdf2.password_hash), &hash64); if(rc){ mosquitto_free(salt64); return MOSQ_ERR_UNKNOWN; } mosquitto_free(pw->encoded_password); size_t len = strlen("$6$$") + strlen("1,000,000,000,000") + strlen(salt64) + strlen(hash64) + 1; pw->encoded_password = mosquitto_calloc(1, len); if(!pw->encoded_password){ return MOSQ_ERR_NOMEM; } snprintf(pw->encoded_password, len, "$%d$%d$%s$%s", pw->hashtype, pw->params.sha512_pbkdf2.iterations, salt64, hash64); mosquitto_free(salt64); mosquitto_free(hash64); return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } static int pw__decode_sha512_pbkdf2(struct mosquitto_pw *pw, const char *salt_password) { #ifdef WITH_TLS char *sp_heap, *saveptr = NULL; char *iterations_s; char *salt_b64, *password_b64; unsigned char *salt, *password; unsigned int salt_len, password_len; int rc; sp_heap = mosquitto_strdup(salt_password); if(!sp_heap){ return MOSQ_ERR_NOMEM; } iterations_s = strtok_r(sp_heap, "$", &saveptr); if(iterations_s == NULL){ mosquitto_free(sp_heap); return MOSQ_ERR_INVAL; } pw->params.sha512_pbkdf2.iterations = atoi(iterations_s); if(pw->params.sha512_pbkdf2.iterations < 1){ mosquitto_free(sp_heap); return MOSQ_ERR_INVAL; } salt_b64 = strtok_r(NULL, "$", &saveptr); if(salt_b64 == NULL){ mosquitto_free(sp_heap); return MOSQ_ERR_INVAL; } rc = mosquitto_base64_decode(salt_b64, &salt, &salt_len); if(rc != MOSQ_ERR_SUCCESS || (salt_len != 12 && salt_len != HASH_LEN)){ mosquitto_free(sp_heap); mosquitto_free(salt); return MOSQ_ERR_INVAL; } memcpy(pw->params.sha512_pbkdf2.salt, salt, salt_len); mosquitto_free(salt); pw->params.sha512_pbkdf2.salt_len = salt_len; password_b64 = strtok_r(NULL, "$", &saveptr); if(password_b64 == NULL){ mosquitto_free(sp_heap); return MOSQ_ERR_INVAL; } rc = mosquitto_base64_decode(password_b64, &password, &password_len); mosquitto_free(sp_heap); if(rc != MOSQ_ERR_SUCCESS || password_len != HASH_LEN){ mosquitto_free(password); return MOSQ_ERR_INVAL; } memcpy(pw->params.sha512_pbkdf2.password_hash, password, password_len); mosquitto_free(password); pw->valid = true; return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } /* ================================================== * SHA512 * ================================================== */ #ifdef WITH_TLS static int pw__hash_sha512(const char *password, struct mosquitto_pw *pw, unsigned char *password_hash, unsigned int hash_len) { 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){ return MOSQ_ERR_UNKNOWN; } #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->params.sha512.salt, pw->params.sha512.salt_len); EVP_DigestFinal_ex(&context, 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->params.sha512.salt, pw->params.sha512.salt_len); EVP_DigestFinal_ex(context, password_hash, &hash_len); EVP_MD_CTX_free(context); #endif return MOSQ_ERR_SUCCESS; } #endif static int pw__create_sha512(struct mosquitto_pw *pw, const char *password) { #ifdef WITH_TLS pw->hashtype = MOSQ_PW_SHA512; pw->params.sha512.salt_len = HASH_LEN; int rc = RAND_bytes(pw->params.sha512.salt, (int)pw->params.sha512.salt_len); if(!rc){ return MOSQ_ERR_UNKNOWN; } rc = pw__hash_sha512(password, pw, pw->params.sha512.password_hash, sizeof(pw->params.sha512.password_hash)); pw->valid = (rc == MOSQ_ERR_SUCCESS); return rc; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } static int pw__verify_sha512(struct mosquitto_pw *pw, const char *password) { #ifdef WITH_TLS int rc; unsigned char password_hash[HASH_LEN]; rc = pw__hash_sha512(password, pw, password_hash, sizeof(password_hash)); if(rc != MOSQ_ERR_SUCCESS){ return MOSQ_ERR_AUTH; } if(!pw__memcmp_const(pw->params.sha512.password_hash, password_hash, HASH_LEN)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } #else return MOSQ_ERR_NOT_SUPPORTED; #endif } static int pw__encode_sha512(struct mosquitto_pw *pw) { #ifdef WITH_TLS int rc; char *salt64 = NULL, *hash64 = NULL; rc = mosquitto_base64_encode(pw->params.sha512.salt, pw->params.sha512.salt_len, &salt64); if(rc){ return MOSQ_ERR_UNKNOWN; } rc = mosquitto_base64_encode(pw->params.sha512.password_hash, sizeof(pw->params.sha512.password_hash), &hash64); if(rc){ return MOSQ_ERR_UNKNOWN; } mosquitto_free(pw->encoded_password); size_t len = strlen("$6$$") + strlen(salt64) + strlen(hash64) + 1; pw->encoded_password = mosquitto_calloc(1, len); if(!pw->encoded_password){ return MOSQ_ERR_NOMEM; } snprintf(pw->encoded_password, len, "$%d$%s$%s", pw->hashtype, salt64, hash64); mosquitto_free(salt64); mosquitto_free(hash64); return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } static int pw__decode_sha512(struct mosquitto_pw *pw, const char *salt_password) { #ifdef WITH_TLS char *sp_heap, *saveptr = NULL; char *salt_b64, *password_b64; unsigned char *salt, *password; unsigned int salt_len, password_len; int rc; sp_heap = mosquitto_strdup(salt_password); if(!sp_heap){ return MOSQ_ERR_NOMEM; } salt_b64 = strtok_r(sp_heap, "$", &saveptr); if(salt_b64 == NULL){ mosquitto_free(sp_heap); return MOSQ_ERR_INVAL; } rc = mosquitto_base64_decode(salt_b64, &salt, &salt_len); if(rc != MOSQ_ERR_SUCCESS || (salt_len != 12 && salt_len != HASH_LEN)){ mosquitto_free(sp_heap); mosquitto_free(salt); return MOSQ_ERR_INVAL; } memcpy(pw->params.sha512.salt, salt, salt_len); mosquitto_free(salt); pw->params.sha512.salt_len = salt_len; password_b64 = strtok_r(NULL, "$", &saveptr); if(password_b64 == NULL){ mosquitto_free(sp_heap); return MOSQ_ERR_INVAL; } rc = mosquitto_base64_decode(password_b64, &password, &password_len); mosquitto_free(sp_heap); if(rc != MOSQ_ERR_SUCCESS || password_len != HASH_LEN){ mosquitto_free(password); return MOSQ_ERR_INVAL; } memcpy(pw->params.sha512.password_hash, password, password_len); mosquitto_free(password); pw->valid = true; return MOSQ_ERR_SUCCESS; #else return MOSQ_ERR_NOT_SUPPORTED; #endif } static int pw__encode(struct mosquitto_pw *pw) { switch(pw->hashtype){ case MOSQ_PW_ARGON2ID: return MOSQ_ERR_SUCCESS; case MOSQ_PW_SHA512_PBKDF2: return pw__encode_sha512_pbkdf2(pw); case MOSQ_PW_SHA512: return pw__encode_sha512(pw); case MOSQ_PW_DEFAULT: break; } return MOSQ_ERR_AUTH; } /* ================================================== * Public * ================================================== */ int mosquitto_pw_new(struct mosquitto_pw **pw, enum mosquitto_pwhash_type hashtype) { *pw = mosquitto_calloc(1, sizeof(struct mosquitto_pw)); if(*pw){ (*pw)->hashtype = hashtype; return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOMEM; } } int mosquitto_pw_hash_encoded(struct mosquitto_pw *pw, const char *password) { int rc = MOSQ_ERR_INVAL; switch(pw->hashtype){ case MOSQ_PW_ARGON2ID: rc = pw__create_argon2id(pw, password); break; case MOSQ_PW_DEFAULT: case MOSQ_PW_SHA512_PBKDF2: rc = pw__create_sha512_pbkdf2(pw, password); break; case MOSQ_PW_SHA512: rc = pw__create_sha512(pw, password); break; default: #ifdef WITH_ARGON2 rc = pw__create_argon2id(pw, password); #else rc = pw__create_sha512_pbkdf2(pw, password); #endif break; } if(rc == MOSQ_ERR_SUCCESS){ return pw__encode(pw); }else{ return rc; } } int mosquitto_pw_verify(struct mosquitto_pw *pw, const char *password) { if(pw && pw->valid){ switch(pw->hashtype){ case MOSQ_PW_ARGON2ID: return pw__verify_argon2id(pw, password); case MOSQ_PW_SHA512_PBKDF2: return pw__verify_sha512_pbkdf2(pw, password); case MOSQ_PW_SHA512: return pw__verify_sha512(pw, password); case MOSQ_PW_DEFAULT: return MOSQ_ERR_AUTH; } } return MOSQ_ERR_AUTH; } void mosquitto_pw_set_valid(struct mosquitto_pw *pw, bool valid) { if(pw){ pw->valid = valid; } } bool mosquitto_pw_is_valid(struct mosquitto_pw *pw) { return pw && pw->valid; } int mosquitto_pw_decode(struct mosquitto_pw *pw, const char *password) { if(!pw){ return MOSQ_ERR_INVAL; } pw->valid = false; if(password[0] != '$'){ return MOSQ_ERR_INVAL; } pw->encoded_password = mosquitto_strdup(password); if(!pw->encoded_password){ return MOSQ_ERR_NOMEM; } if(password[1] == '6' && password[2] == '$'){ pw->hashtype = MOSQ_PW_SHA512; return pw__decode_sha512(pw, &password[3]); }else if(password[1] == '7' && password[2] == '$'){ pw->hashtype = MOSQ_PW_SHA512_PBKDF2; return pw__decode_sha512_pbkdf2(pw, &password[3]); }else if(!strncmp(password, "$argon2id$", strlen("$argon2id$"))){ pw->hashtype = MOSQ_PW_ARGON2ID; return pw__decode_argon2id(pw, password); }else{ mosquitto_FREE(pw->encoded_password); return MOSQ_ERR_INVAL; } } const char *mosquitto_pw_get_encoded(struct mosquitto_pw *pw) { return pw?pw->encoded_password:NULL; } int mosquitto_pw_set_param(struct mosquitto_pw *pw, int param, int value) { if(!pw){ return MOSQ_ERR_INVAL; } switch(param){ case MOSQ_PW_PARAM_ITERATIONS: if(pw->hashtype != MOSQ_PW_SHA512_PBKDF2){ return MOSQ_ERR_INVAL; } pw->params.sha512_pbkdf2.iterations = value; break; } return MOSQ_ERR_SUCCESS; } void mosquitto_pw_cleanup(struct mosquitto_pw *pw) { if(pw){ mosquitto_free(pw->encoded_password); pw->encoded_password = NULL; mosquitto_free(pw); } } ================================================ FILE: libcommon/property_common.c ================================================ /* Copyright (c) 2018-2021 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 "mosquitto.h" #include "property_common.h" void mosquitto_property_free(mosquitto_property **property) { if(!property || !(*property)){ return; } switch((*property)->property_type){ case MQTT_PROP_TYPE_STRING: mosquitto_FREE((*property)->value.s.v); break; case MQTT_PROP_TYPE_BINARY: mosquitto_FREE((*property)->value.bin.v); break; case MQTT_PROP_TYPE_STRING_PAIR: mosquitto_FREE((*property)->name.v); mosquitto_FREE((*property)->value.s.v); break; case MQTT_PROP_TYPE_BYTE: case MQTT_PROP_TYPE_INT16: case MQTT_PROP_TYPE_INT32: case MQTT_PROP_TYPE_VARINT: /* Nothing to free */ break; } mosquitto_FREE(*property); } BROKER_EXPORT void mosquitto_property_free_all(mosquitto_property **property) { mosquitto_property *p, *next; if(!property){ return; } p = *property; while(p){ next = p->next; mosquitto_property_free(&p); p = next; } *property = NULL; } unsigned int mosquitto_property_get_length(const mosquitto_property *property) { if(!property){ return 0; } switch(property->property_type){ case MQTT_PROP_TYPE_BYTE: return 2; /* 1 (identifier) + 1 byte */ case MQTT_PROP_TYPE_INT16: return 3; /* 1 (identifier) + 2 bytes */ case MQTT_PROP_TYPE_INT32: return 5; /* 1 (identifier) + 4 bytes */ case MQTT_PROP_TYPE_VARINT: 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; } case MQTT_PROP_TYPE_BINARY: return 3U + property->value.bin.len; /* 1 + 2 bytes (len) + X bytes (payload) */ case MQTT_PROP_TYPE_STRING: return 3U + property->value.s.len; /* 1 + 2 bytes (len) + X bytes (string) */ case MQTT_PROP_TYPE_STRING_PAIR: return 5U + property->value.s.len + property->name.len; /* 1 + 2*(2 bytes (len) + X bytes (string))*/ default: return 0; } return 0; } unsigned int mosquitto_property_get_length_all(const mosquitto_property *property) { const mosquitto_property *p; unsigned int len = 0; p = property; while(p){ len += mosquitto_property_get_length(p); p = p->next; } return len; } BROKER_EXPORT 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; } BROKER_EXPORT 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; } } BROKER_EXPORT 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; } BROKER_EXPORT 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; prop->property_type = MQTT_PROP_TYPE_BYTE; property__add(proplist, prop); return MOSQ_ERR_SUCCESS; } BROKER_EXPORT 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; prop->property_type = MQTT_PROP_TYPE_INT16; property__add(proplist, prop); return MOSQ_ERR_SUCCESS; } BROKER_EXPORT 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; prop->property_type = MQTT_PROP_TYPE_INT32; property__add(proplist, prop); return MOSQ_ERR_SUCCESS; } BROKER_EXPORT int mosquitto_property_add_varint(mosquitto_property **proplist, int identifier, uint32_t value) { mosquitto_property *prop; if(!proplist || value > MQTT_MAX_PAYLOAD){ 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; prop->property_type = MQTT_PROP_TYPE_VARINT; property__add(proplist, prop); return MOSQ_ERR_SUCCESS; } BROKER_EXPORT 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; prop->property_type = MQTT_PROP_TYPE_BINARY; 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; } BROKER_EXPORT 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; prop->property_type = MQTT_PROP_TYPE_STRING; 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; } BROKER_EXPORT 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; prop->property_type = MQTT_PROP_TYPE_STRING_PAIR; 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; } BROKER_EXPORT 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_PAYLOAD_FORMAT_INDICATOR || 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; } }else if(p->identifier == MQTT_PROP_RESPONSE_TOPIC){ if(mosquitto_pub_topic_check(p->value.s.v) != MOSQ_ERR_SUCCESS){ 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 */ if(p->identifier != MQTT_PROP_USER_PROPERTY){ tail = p->next; while(tail){ if(p->identifier == tail->identifier){ 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; } BROKER_EXPORT int mosquitto_property_identifier(const mosquitto_property *property) { if(property == NULL){ return 0; } return property->identifier; } BROKER_EXPORT int mosquitto_property_type(const mosquitto_property *property) { if(property == NULL){ return 0; } return property->property_type; } BROKER_EXPORT mosquitto_property *mosquitto_property_next(const mosquitto_property *proplist) { if(proplist == NULL){ return NULL; } return proplist->next; } BROKER_EXPORT 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; } BROKER_EXPORT 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; } BROKER_EXPORT 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; } BROKER_EXPORT 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; } BROKER_EXPORT 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; if(p->value.bin.len){ *value = mosquitto_calloc(1, *len + 1U); if(!(*value)){ return NULL; } memcpy(*value, p->value.bin.v, *len); }else{ *value = NULL; } } return p; } BROKER_EXPORT 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){ if(p->value.s.len){ *value = mosquitto_calloc(1, (size_t)p->value.s.len+1); if(!(*value)){ return NULL; } memcpy(*value, p->value.s.v, p->value.s.len); }else{ *value = NULL; } } return p; } BROKER_EXPORT 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){ if(p->name.len){ *name = mosquitto_calloc(1, (size_t)p->name.len+1); if(!(*name)){ return NULL; } memcpy(*name, p->name.v, p->name.len); }else{ *name = NULL; } } if(value){ if(p->value.s.len){ *value = mosquitto_calloc(1, (size_t)p->value.s.len+1); if(!(*value)){ if(name){ mosquitto_FREE(*name); } return NULL; } memcpy(*value, p->value.s.v, p->value.s.len); }else{ *value = NULL; } } return p; } BROKER_EXPORT int mosquitto_property_remove(mosquitto_property **proplist, const mosquitto_property *property) { mosquitto_property *item, *item_prev = NULL; if(proplist == NULL || property == NULL){ return MOSQ_ERR_INVAL; } item = *proplist; while(item){ if(item == property){ if(item_prev == NULL){ *proplist = (*proplist)->next; }else{ item_prev->next = item->next; } item->next = NULL; return MOSQ_ERR_SUCCESS; } item_prev = item; item = item->next; } return MOSQ_ERR_NOT_FOUND; } BROKER_EXPORT 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 = mosquitto_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->client_generated = src->client_generated; pnew->identifier = src->identifier; pnew->property_type = src->property_type; switch(pnew->property_type){ case MQTT_PROP_TYPE_BYTE: pnew->value.i8 = src->value.i8; break; case MQTT_PROP_TYPE_INT16: pnew->value.i16 = src->value.i16; break; case MQTT_PROP_TYPE_INT32: pnew->value.i32 = src->value.i32; break; case MQTT_PROP_TYPE_VARINT: pnew->value.varint = src->value.varint; break; case MQTT_PROP_TYPE_STRING: pnew->value.s.len = src->value.s.len; pnew->value.s.v = src->value.s.v ? mosquitto_strdup(src->value.s.v) : (char *)mosquitto_calloc(1, 1); if(!pnew->value.s.v){ mosquitto_property_free_all(dest); return MOSQ_ERR_NOMEM; } break; case MQTT_PROP_TYPE_BINARY: pnew->value.bin.len = src->value.bin.len; if(src->value.bin.len){ pnew->value.bin.v = mosquitto_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_TYPE_STRING_PAIR: pnew->value.s.len = src->value.s.len; pnew->value.s.v = src->value.s.v ? mosquitto_strdup(src->value.s.v) : (char *)mosquitto_calloc(1, 1); if(!pnew->value.s.v){ mosquitto_property_free_all(dest); return MOSQ_ERR_NOMEM; } pnew->name.len = src->name.len; pnew->name.v = src->name.v ? mosquitto_strdup(src->name.v) : (char *)mosquitto_calloc(1, 1); 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 = mosquitto_property_next(src); } return MOSQ_ERR_SUCCESS; } uint8_t mosquitto_property_byte_value(const mosquitto_property *property) { if(property && property->property_type == MQTT_PROP_TYPE_BYTE){ return property->value.i8; }else{ return 0; } } uint16_t mosquitto_property_int16_value(const mosquitto_property *property) { if(property && property->property_type == MQTT_PROP_TYPE_INT16){ return property->value.i16; }else{ return 0; } } uint32_t mosquitto_property_int32_value(const mosquitto_property *property) { if(property && property->property_type == MQTT_PROP_TYPE_INT32){ return property->value.i32; }else{ return 0; } } uint32_t mosquitto_property_varint_value(const mosquitto_property *property) { if(property && property->property_type == MQTT_PROP_TYPE_VARINT){ return property->value.varint; }else{ return 0; } } const void *mosquitto_property_binary_value(const mosquitto_property *property) { if(property && property->property_type == MQTT_PROP_TYPE_BINARY){ return property->value.bin.v; }else{ return NULL; } } uint16_t mosquitto_property_binary_value_length(const mosquitto_property *property) { if(property && property->property_type == MQTT_PROP_TYPE_BINARY){ return property->value.bin.len; }else{ return 0; } } const char *mosquitto_property_string_value(const mosquitto_property *property) { if(property && (property->property_type == MQTT_PROP_TYPE_STRING || property->property_type == MQTT_PROP_TYPE_STRING_PAIR)){ return property->value.s.v; }else{ return NULL; } } uint16_t mosquitto_property_string_value_length(const mosquitto_property *property) { if(property && (property->property_type == MQTT_PROP_TYPE_STRING || property->property_type == MQTT_PROP_TYPE_STRING_PAIR)){ return property->value.s.len; }else{ return 0; } } const char *mosquitto_property_string_name(const mosquitto_property *property) { if(property && property->property_type == MQTT_PROP_TYPE_STRING_PAIR){ return property->name.v; }else{ return NULL; } } uint16_t mosquitto_property_string_name_length(const mosquitto_property *property) { if(property && property->property_type == MQTT_PROP_TYPE_STRING_PAIR){ return property->name.len; }else{ return 0; } } /* Return the number of bytes we need to add on to the remaining length when * encoding these properties. */ unsigned int mosquitto_property_get_remaining_length(const mosquitto_property *props) { unsigned int proplen, varbytes; proplen = mosquitto_property_get_length_all(props); varbytes = mosquitto_varint_bytes(proplen); return proplen + varbytes; } ================================================ FILE: libcommon/property_common.h ================================================ /* Copyright (c) 2018-2021 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_COMMON_H #define PROPERTY_COMMON_H #include #include #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; uint8_t property_type; bool client_generated; }; #endif ================================================ FILE: libcommon/random_common.c ================================================ /* Copyright (c) 2009-2021 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 /* Keep this here to allow glibc detection */ #ifdef WIN32 # include # include # include # include #endif #ifdef WITH_TLS # include # include #elif defined(HAVE_GETRANDOM) /* From CMakeLists.txt */ # include #elif defined(__linux__) && defined(__GLIBC__) /* For legacy Makefiles */ # if __GLIBC_PREREQ(2, 25) # include # define HAVE_GETRANDOM 1 # endif #endif #include "mosquitto.h" int mosquitto_getrandom(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 /* For legacy Makefiles */ # error "No suitable random function found." #endif return rc; } ================================================ FILE: libcommon/strings_common.c ================================================ /* Copyright (c) 2010-2021 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 #ifndef WIN32 # include #endif #include "mosquitto.h" #include "mosquitto/mqtt_protocol.h" const char *mosquitto_strerror(int mosq_errno) { switch(mosq_errno){ case MOSQ_ERR_QUOTA_EXCEEDED: return "Quota exceeded"; case MOSQ_ERR_AUTH_DELAYED: return "Authentication delayed"; 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 input"; 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_PLUGIN_DEFER: return "Plugin deferring result"; case MOSQ_ERR_MALFORMED_UTF8: return "Malformed UTF-8"; case MOSQ_ERR_KEEPALIVE: return "Keepalive exceeded"; case MOSQ_ERR_LOOKUP: return "DNS Lookup failed"; case MOSQ_ERR_MALFORMED_PACKET: return "Malformed packet"; 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"; case MOSQ_ERR_TIMEOUT: return "Timeout"; case MOSQ_ERR_ALREADY_EXISTS: return "Entry already exists"; case MOSQ_ERR_PLUGIN_IGNORE: return "Ignore plugin"; case MOSQ_ERR_HTTP_BAD_ORIGIN: return "Bad http origin"; case MOSQ_ERR_UNSPECIFIED: return "Unspecified error"; case MOSQ_ERR_IMPLEMENTATION_SPECIFIC: return "Implementaion specific error"; case MOSQ_ERR_CLIENT_IDENTIFIER_NOT_VALID: return "Client identifier not valid"; case MOSQ_ERR_BAD_USERNAME_OR_PASSWORD: return "Bad username or password"; case MOSQ_ERR_SERVER_UNAVAILABLE: return "Server unavailable"; case MOSQ_ERR_SERVER_BUSY: return "Server busy"; case MOSQ_ERR_BANNED: return "Banned"; case MOSQ_ERR_BAD_AUTHENTICATION_METHOD: return "Bad authentication method"; case MOSQ_ERR_SESSION_TAKEN_OVER: return "Session taken over"; case MOSQ_ERR_RECEIVE_MAXIMUM_EXCEEDED: return "Receive maximum exceeded"; case MOSQ_ERR_TOPIC_ALIAS_INVALID: return "Topic alias invalid"; case MOSQ_ERR_ADMINISTRATIVE_ACTION: return "Administrative action"; case MOSQ_ERR_RETAIN_NOT_SUPPORTED: return "Retain not supported"; case MOSQ_ERR_CONNECTION_RATE_EXCEEDED: return "Connection rate exceeded"; default: if(mosq_errno >= 128){ // If mosq_errno is greater than 127, // a mqtt5_return_code error was used return mosquitto_reason_string(mosq_errno); }else{ 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, "suback")){ *cmd = CMD_SUBACK; }else if(!strcasecmp(str, "unsubscribe")){ *cmd = CMD_UNSUBSCRIBE; }else if(!strcasecmp(str, "unsuback")){ *cmd = CMD_UNSUBACK; }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{ *cmd = 0; return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } ================================================ FILE: libcommon/time_common.c ================================================ /* Copyright (c) 2013-2021 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 #if defined(__APPLE__) || defined(__OpenBSD__) # 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" #if _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK) static clockid_t time_clock = CLOCK_MONOTONIC; #endif void mosquitto_time_init(void) { #if _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK) struct timespec tp; #ifdef CLOCK_BOOTTIME if(clock_gettime(CLOCK_BOOTTIME, &tp) == 0){ time_clock = CLOCK_BOOTTIME; }else{ time_clock = CLOCK_MONOTONIC; } #else time_clock = CLOCK_MONOTONIC; #endif #endif } time_t mosquitto_time(void) { #ifdef WIN32 return GetTickCount64()/1000; #elif _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK) struct timespec tp; if(clock_gettime(time_clock, &tp) == 0){ return tp.tv_sec; } return (time_t)-1; #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 } void mosquitto_time_ns(time_t *s, long *ns) { #ifdef WIN32 SYSTEMTIME st; GetLocalTime(&st); *s = time(NULL); *ns = st.wMilliseconds*1000000L; #elif _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK) struct timespec tp; clock_gettime(CLOCK_REALTIME, &tp); *s = tp.tv_sec; *ns = tp.tv_nsec; #else struct timeval tv; gettimeofday(&tv, NULL); *s = tv.tv_sec; *ns = tv.tv_usec * 1000; #endif } long mosquitto_time_cmp(time_t t1_s, long t1_ns, time_t t2_s, long t2_ns) { if(t1_s == t2_s){ return (long)(t1_ns - t2_ns); }else{ return (long)(t1_s - t2_s); } } ================================================ FILE: libcommon/topic_common.c ================================================ /* Copyright (c) 2009-2021 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 WIN32 # include # include # include # include #else # include #endif #include "mosquitto.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. */ BROKER_EXPORT int mosquitto_pub_topic_check(const char *str) { int len = 0; int hier_count = 0; if(str == NULL){ return MOSQ_ERR_INVAL; } while(str && str[0]){ if(str[0] == '+' || str[0] == '#'){ return MOSQ_ERR_INVAL; }else if(str[0] == '/'){ hier_count++; } len++; str = &str[1]; } if(len == 0 || len > 65535){ return MOSQ_ERR_INVAL; } if(hier_count > TOPIC_HIERARCHY_LIMIT){ return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } BROKER_EXPORT int mosquitto_pub_topic_check2(const char *str, size_t len) { size_t i; int hier_count = 0; if(str == NULL || len == 0 || len > 65535){ return MOSQ_ERR_INVAL; } for(i=0; i TOPIC_HIERARCHY_LIMIT){ return MOSQ_ERR_INVAL; } 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. */ BROKER_EXPORT int mosquitto_sub_topic_check(const char *str) { char c = '\0'; int len = 0; int hier_count = 0; 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; } }else if(str[0] == '/'){ hier_count++; } len++; c = str[0]; str = &str[1]; } if(len == 0 || len > 65535){ return MOSQ_ERR_INVAL; } if(hier_count > TOPIC_HIERARCHY_LIMIT){ return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } BROKER_EXPORT int mosquitto_sub_topic_check2(const char *str, size_t len) { char c = '\0'; size_t i; int hier_count = 0; if(str == NULL || len == 0 || len > 65535){ return MOSQ_ERR_INVAL; } for(i=0; i TOPIC_HIERARCHY_LIMIT){ return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static int topic_matches_sub(const char *sub, const char *topic, const char *clientid, const char *username, bool match_patterns, bool *result) { size_t spos; const char *pattern_check; const char *lastchar = NULL; 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(match_patterns && (lastchar == NULL || lastchar[0] == '/') && sub[0] == '%' && (sub[1] == 'c' || sub[1] == 'u') && (sub[2] == '/' || sub[2] == '\0') ){ if(sub[1] == 'c'){ pattern_check = clientid; }else{ pattern_check = username; } if(pattern_check == NULL || pattern_check[0] == '\0'){ return MOSQ_ERR_SUCCESS; } spos += 2; sub += 2; while(pattern_check[0] != 0 && topic[0] != 0 && topic[0] != '/'){ if(pattern_check[0] != topic[0]){ /* Valid input, but no match */ return MOSQ_ERR_SUCCESS; } pattern_check++; topic++; } if(pattern_check[0] != '\0'){ /* substituted pattern part smaller than publish topic part, so fail */ return MOSQ_ERR_SUCCESS; } if((sub[0] == '\0' && topic[0] == '\0') || (sub[0] == '/' && sub[1] == '#' && sub[2] == '\0' && topic[0] == '\0') ){ *result = true; return MOSQ_ERR_SUCCESS; } } 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; } } lastchar = sub-1; } 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; } static int sub_matches_acl(const char *acl, const char *sub, const char *clientid, const char *username, bool match_patterns, bool *result) { size_t apos; const char *pattern_check; const char *lastchar = NULL; *result = false; if(!acl || !sub || acl[0] == 0 || sub[0] == 0){ return MOSQ_ERR_INVAL; } if((acl[0] == '$' && sub[0] != '$') || (sub[0] == '$' && acl[0] != '$')){ return MOSQ_ERR_SUCCESS; } apos = 0; while(acl[0] != 0){ if(match_patterns && (lastchar == NULL || lastchar[0] == '/') && acl[0] == '%' && (acl[1] == 'c' || acl[1] == 'u') && (acl[2] == '/' || acl[2] == '\0') ){ if(acl[1] == 'c'){ pattern_check = clientid; }else{ pattern_check = username; } if(pattern_check == NULL || pattern_check[0] == '\0'){ /* no match */ return MOSQ_ERR_SUCCESS; } if(pattern_check[1] == '\0' && ( pattern_check[0] == '+' || pattern_check[0] == '#' || pattern_check[0] == '/') ){ /* username/client id of just + / # not allowed */ return MOSQ_ERR_SUCCESS; } apos +=2; acl += 2; while(pattern_check[0] != 0 && sub[0] != 0 && sub[0] != '/'){ if(pattern_check[0] != sub[0]){ /* Valid input, but no match */ return MOSQ_ERR_SUCCESS; } pattern_check++; sub++; } if(pattern_check[0] != '\0'){ /* substituted pattern part smaller than publish topic part, so fail */ return MOSQ_ERR_SUCCESS; } if(sub[0] == '\0' && (acl[0] == '\0' || (acl[0] == '/' && acl[1] == '#' && acl[2] == '\0')) ){ *result = true; return MOSQ_ERR_SUCCESS; } } if(acl[0] != sub[0] || sub[0] == 0){ /* Check for wildcard matches */ if(acl[0] == '+'){ if(sub[0] == '#'){ /* + doesn't match # */ return MOSQ_ERR_SUCCESS; } /* Check for bad "+foo" or "a/+foo" subscription */ if(apos > 0 && acl[-1] != '/'){ return MOSQ_ERR_INVAL; } /* Check for bad "foo+" or "foo+/a" subscription */ if(acl[1] != 0 && acl[1] != '/'){ return MOSQ_ERR_INVAL; } apos++; acl++; while(sub[0] != 0 && sub[0] != '/'){ sub++; } if(sub[0] == 0 && acl[0] == 0){ *result = true; return MOSQ_ERR_SUCCESS; } }else if(acl[0] == '#'){ /* Check for bad "foo#" subscription */ if(apos > 0 && acl[-1] != '/'){ return MOSQ_ERR_INVAL; } /* Check for # not the final character of the sub, e.g. "#foo" */ if(acl[1] != 0){ return MOSQ_ERR_INVAL; }else{ *result = true; return MOSQ_ERR_SUCCESS; } }else{ /* Check for e.g. foo/bar matching foo/+/# */ if(sub[0] == 0 && apos > 0 && acl[-1] == '+' && acl[0] == '/' && acl[1] == '#'){ *result = true; return MOSQ_ERR_SUCCESS; } /* There is no match at this point, but is the sub invalid? */ while(acl[0] != 0){ if(acl[0] == '#' && acl[1] != 0){ return MOSQ_ERR_INVAL; } apos++; acl++; } /* Valid input, but no match */ return MOSQ_ERR_SUCCESS; } }else{ /* acl[apos] == sub[spos] */ if(sub[1] == 0){ /* Check for e.g. foo matching foo/# */ if(acl[1] == '/' && acl[2] == '#' && acl[3] == 0){ *result = true; return MOSQ_ERR_SUCCESS; } } apos++; acl++; sub++; if(acl[0] == 0 && sub[0] == 0){ *result = true; return MOSQ_ERR_SUCCESS; }else if(sub[0] == 0 && acl[0] == '+' && acl[1] == 0){ if(apos > 0 && acl[-1] != '/'){ return MOSQ_ERR_INVAL; } apos++; acl++; *result = true; return MOSQ_ERR_SUCCESS; } } lastchar = acl-1; } if((sub[0] != 0 || acl[0] != 0)){ return MOSQ_ERR_SUCCESS; } while(sub[0] != 0){ if(sub[0] == '+' || sub[0] == '#'){ return MOSQ_ERR_SUCCESS; } sub++; } *result = true; return MOSQ_ERR_SUCCESS; } BROKER_EXPORT int mosquitto_sub_matches_acl(const char *acl, const char *sub, bool *result) { return sub_matches_acl(acl, sub, NULL, NULL, false, result); } BROKER_EXPORT int mosquitto_sub_matches_acl_with_pattern(const char *acl, const char *sub, const char *clientid, const char *username, bool *result) { return sub_matches_acl(acl, sub, clientid, username, true, result); } BROKER_EXPORT int mosquitto_topic_matches_sub(const char *sub, const char *topic, bool *result) { return topic_matches_sub(sub, topic, NULL, NULL, false, result); } BROKER_EXPORT int mosquitto_topic_matches_sub_with_pattern(const char *sub, const char *topic, const char *clientid, const char *username, bool *result) { return topic_matches_sub(sub, topic, clientid, username, true, result); } /* Does a topic match a subscription? */ BROKER_EXPORT int mosquitto_topic_matches_sub2(const char *sub, size_t sublen, const char *topic, size_t topiclen, bool *result) { size_t spos, tpos; if(!result){ return MOSQ_ERR_INVAL; } *result = false; if(!sub || !topic || !sublen || !topiclen){ return MOSQ_ERR_INVAL; } if((sub[0] == '$' && topic[0] != '$') || (topic[0] == '$' && sub[0] != '$')){ return MOSQ_ERR_SUCCESS; } spos = 0; tpos = 0; while(spos < sublen){ if(tpos < topiclen && (topic[tpos] == '+' || topic[tpos] == '#')){ return MOSQ_ERR_INVAL; } if(tpos == topiclen || sub[spos] != topic[tpos]){ if(sub[spos] == '+'){ /* Check for bad "+foo" or "a/+foo" subscription */ if(spos > 0 && sub[spos-1] != '/'){ return MOSQ_ERR_INVAL; } /* Check for bad "foo+" or "foo+/a" subscription */ if(spos+1 < sublen && sub[spos+1] != '/'){ return MOSQ_ERR_INVAL; } spos++; while(tpos < topiclen && topic[tpos] != '/'){ if(topic[tpos] == '+' || topic[tpos] == '#'){ return MOSQ_ERR_INVAL; } tpos++; } if(tpos == topiclen && spos == sublen){ *result = true; return MOSQ_ERR_SUCCESS; } }else if(sub[spos] == '#'){ /* Check for bad "foo#" subscription */ if(spos > 0 && sub[spos-1] != '/'){ return MOSQ_ERR_INVAL; } /* Check for # not the final character of the sub, e.g. "#foo" */ if(spos+1 < sublen){ return MOSQ_ERR_INVAL; }else{ while(tpos < topiclen){ if(topic[tpos] == '+' || topic[tpos] == '#'){ return MOSQ_ERR_INVAL; } tpos++; } *result = true; return MOSQ_ERR_SUCCESS; } }else{ /* Check for e.g. foo/bar matching foo/+/# */ if(tpos == topiclen && spos > 0 && sub[spos-1] == '+' && sub[spos] == '/' && spos+1 < sublen && sub[spos+1] == '#'){ *result = true; return MOSQ_ERR_SUCCESS; } /* There is no match at this point, but is the sub invalid? */ while(spos < sublen){ if(sub[spos] == '#' && spos+1 < sublen){ return MOSQ_ERR_INVAL; } spos++; } /* Valid input, but no match */ return MOSQ_ERR_SUCCESS; } }else{ /* sub[spos] == topic[tpos] */ if(tpos+1 == topiclen){ /* Check for e.g. foo matching foo/# */ if(spos+3 == sublen && sub[spos+1] == '/' && sub[spos+2] == '#'){ *result = true; return MOSQ_ERR_SUCCESS; } } spos++; tpos++; if(spos == sublen && tpos == topiclen){ *result = true; return MOSQ_ERR_SUCCESS; }else if(tpos == topiclen && sub[spos] == '+' && spos+1 == sublen){ if(spos > 0 && sub[spos-1] != '/'){ return MOSQ_ERR_INVAL; } spos++; *result = true; return MOSQ_ERR_SUCCESS; } } } if(tpos < topiclen || spos < sublen){ *result = false; } while(tpos < topiclen){ if(topic[tpos] == '+' || topic[tpos] == '#'){ return MOSQ_ERR_INVAL; } tpos++; } return MOSQ_ERR_SUCCESS; } 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. */ #include "config.h" #include #include "mosquitto.h" BROKER_EXPORT 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; } ================================================ FILE: libmosquitto.pc.in ================================================ prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=${prefix} includedir=${prefix}/include libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@ Name: mosquitto Description: mosquitto MQTT library (C bindings) Version: @VERSION@ Cflags: -I${includedir} Libs: -L${libdir} -lmosquitto ================================================ FILE: libmosquittopp.pc.in ================================================ prefix=@CMAKE_INSTALL_PREFIX@ exec_prefix=${prefix} includedir=${prefix}/include libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@ Name: mosquittopp Description: mosquitto MQTT library (C++ bindings) Version: @VERSION@ Cflags: -I${includedir} Libs: -L${libdir} -lmosquittopp ================================================ FILE: make/broker.mk ================================================ ifeq ($(WITH_ADNS),yes) NEED_LIBANL:=$(shell printf 'int main(){return 0;}' | gcc -D_GNU_SOURCE -lanl -o /dev/null -x c - 2>/dev/null || echo yes) ifeq ($(NEED_LIBANL),yes) LOCAL_LDADD+=-lanl endif LOCAL_CPPFLAGS+=-DWITH_ADNS endif ifeq ($(WITH_BRIDGE),yes) LOCAL_CPPFLAGS+=-DWITH_BRIDGE endif ifeq ($(WITH_CONTROL),yes) LOCAL_CPPFLAGS+=-DWITH_CONTROL endif ifeq ($(WITH_EPOLL),yes) ifeq ($(UNAME),Linux) LOCAL_CPPFLAGS+=-DWITH_EPOLL endif endif ifeq ($(WITH_HTTP_API),yes) LOCAL_CPPFLAGS+=-DWITH_HTTP_API LOCAL_LDADD+=-lmicrohttpd endif ifeq ($(WITH_MEMORY_TRACKING),yes) ifneq ($(UNAME),SunOS) LOCAL_CPPFLAGS+=-DWITH_MEMORY_TRACKING endif endif ifeq ($(WITH_OLD_KEEPALIVE),yes) LOCAL_CPPFLAGS+=-DWITH_OLD_KEEPALIVE endif ifeq ($(WITH_PERSISTENCE),yes) LOCAL_CPPFLAGS+=-DWITH_PERSISTENCE endif ifeq ($(WITH_SYS_TREE),yes) LOCAL_CPPFLAGS+=-DWITH_SYS_TREE endif ifeq ($(WITH_SYSTEMD),yes) LOCAL_CPPFLAGS+=-DWITH_SYSTEMD LOCAL_LDADD+=-lsystemd endif ifeq ($(WITH_THREADING),yes) LOCAL_CFLAGS+=-pthread LOCAL_LDFLAGS+=-pthread endif ifeq ($(WITH_TLS),yes) LOCAL_LDADD+=-lssl -lcrypto endif ifeq ($(WITH_WEBSOCKETS),lws) LOCAL_CPPFLAGS+=-DWITH_WEBSOCKETS=WS_IS_LWS LOCAL_LDADD+=-lwebsockets endif ifeq ($(WITH_WRAP),yes) LOCAL_LDADD+=-lwrap LOCAL_CPPFLAGS+=-DWITH_WRAP endif ifeq ($(WITH_XTREPORT),yes) LOCAL_CPPFLAGS+=-DWITH_XTREPORT endif ================================================ FILE: make/unit-test.mk ================================================ ifdef MOSQ_USE_VALGRIND ifeq ($(MOSQ_USE_VALGRIND),callgrind) SANITIZER_COMMAND=valgrind -q --tool=callgrind --log-file=$${t}.vglog endif ifeq ($(MOSQ_USE_VALGRIND),massif) SANITIZER_COMMAND=valgrind -q --tool=massif --log-file=$${t}.vglog endif ifeq ($(MOSQ_USE_VALGRIND),failgrind) SANITIZER_COMMAND=fg-helper endif ifndef SANITIZER_COMMAND SANITIZER_COMMAND=valgrind -q --trace-children=yes --leak-check=full --show-leak-kinds=all --log-file=$${t}.vglog endif else SANITIZER_COMMAND= endif ================================================ FILE: man/CMakeLists.txt ================================================ # 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. find_program(XSLTPROC xsltproc OPTIONAL) if(XSLTPROC AND NOT WIN32) function(compile_manpage page) add_custom_command(OUTPUT ${PROJECT_SOURCE_DIR}/man/${page} COMMAND xsltproc --xinclude --nonet ${PROJECT_SOURCE_DIR}/man/${page}.xml -o ${PROJECT_SOURCE_DIR}/man/ MAIN_DEPENDENCY ${PROJECT_SOURCE_DIR}/man/${page}.xml) add_custom_target(${page} ALL DEPENDS ${PROJECT_SOURCE_DIR}/man/${page}) endfunction() compile_manpage("libmosquitto.3") compile_manpage("mosquitto-tls.7") compile_manpage("mosquitto.7") compile_manpage("mosquitto.8") compile_manpage("mosquitto.conf.5") compile_manpage("mosquitto_ctrl.1") compile_manpage("mosquitto_ctrl_dynsec.1") compile_manpage("mosquitto_ctrl_shell.1") compile_manpage("mosquitto_passwd.1") compile_manpage("mosquitto_pub.1") compile_manpage("mosquitto_rr.1") compile_manpage("mosquitto_signal.1") compile_manpage("mosquitto_sub.1") compile_manpage("mqtt.7") install(FILES mosquitto_ctrl.1 mosquitto_ctrl_dynsec.1 mosquitto_ctrl_shell.1 mosquitto_passwd.1 mosquitto_pub.1 mosquitto_sub.1 mosquitto_rr.1 mosquitto_signal.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 mosquitto.7 mqtt.7 DESTINATION ${CMAKE_INSTALL_MANDIR}/man7 OPTIONAL ) install(FILES mosquitto.8 DESTINATION ${CMAKE_INSTALL_MANDIR}/man8 OPTIONAL) elseif(WIN32) message(WARNING "xsltproc not found: manpages cannot be built") else() message(FATAL_ERROR "xsltproc not found: manpages cannot be built") endif() ================================================ FILE: man/Makefile ================================================ R=.. include ${R}/config.mk .PHONY : all clean install uninstall dist MANPAGES = \ libmosquitto.3 \ mosquitto-tls.7 \ mosquitto.7 \ mosquitto.8 \ mosquitto.conf.5 \ mosquitto_ctrl.1 \ mosquitto_ctrl_dynsec.1 \ mosquitto_ctrl_shell.1 \ mosquitto_passwd.1 \ mosquitto_pub.1 \ mosquitto_rr.1 \ mosquitto_signal.1 \ mosquitto_sub.1 \ mqtt.7 all : ${MANPAGES} clean : reallyclean : clean -rm -f *.orig -rm -f ${MANPAGES} dist : ${MANPAGES} install : $(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_ctrl_shell.1 "${DESTDIR}${mandir}/man1/mosquitto_ctrl_shell.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_rr.1 "${DESTDIR}${mandir}/man1/mosquitto_rr.1" $(INSTALL) -m 644 mosquitto_signal.1 "${DESTDIR}${mandir}/man1/mosquitto_signal.1" $(INSTALL) -m 644 mosquitto_sub.1 "${DESTDIR}${mandir}/man1/mosquitto_sub.1" $(INSTALL) -d "${DESTDIR}$(mandir)/man3" $(INSTALL) -m 644 libmosquitto.3 "${DESTDIR}${mandir}/man3/libmosquitto.3" $(INSTALL) -d "${DESTDIR}$(mandir)/man5" $(INSTALL) -m 644 mosquitto.conf.5 "${DESTDIR}${mandir}/man5/mosquitto.conf.5" $(INSTALL) -d "${DESTDIR}$(mandir)/man7" $(INSTALL) -m 644 mosquitto.7 "${DESTDIR}${mandir}/man7/mosquitto.7" $(INSTALL) -m 644 mosquitto-tls.7 "${DESTDIR}${mandir}/man7/mosquitto-tls.7" $(INSTALL) -m 644 mqtt.7 "${DESTDIR}${mandir}/man7/mqtt.7" $(INSTALL) -d "${DESTDIR}$(mandir)/man8" $(INSTALL) -m 644 mosquitto.8 "${DESTDIR}${mandir}/man8/mosquitto.8" uninstall : -rm -f "${DESTDIR}${mandir}/man1/mosquitto_ctrl.1" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_ctrl_dynsec.1" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_ctrl_shell.1" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_passwd.1" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_pub.1" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_rr.1" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_signal.1" -rm -f "${DESTDIR}${mandir}/man1/mosquitto_sub.1" -rm -f "${DESTDIR}${mandir}/man3/libmosquitto.3" -rm -f "${DESTDIR}${mandir}/man5/mosquitto.conf.5" -rm -f "${DESTDIR}${mandir}/man7/mosquitto-tls.7" -rm -f "${DESTDIR}${mandir}/man7/mosquitto.7" -rm -f "${DESTDIR}${mandir}/man7/mqtt.7" -rm -f "${DESTDIR}${mandir}/man8/mosquitto.8" % : %.xml %.meta manpage.xsl $(XSLTPROC) --xinclude $< 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.7.pot mosquitto.7.xml 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_ctrl/mosquitto_ctrl_shell.1.pot mosquitto_ctrl_shell.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/mosquitto_sub/mosquitto_signal.1.pot mosquitto_signal.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 ================================================ FILE: man/common/env-var-mosquitto-unsafe-allow-symlinks.xml ================================================ MOSQUITTO_UNSAFE_ALLOW_SYMLINKS By default, sensitive file with a path including a symbolic link will be refused to be loaded. Set this environment variable to any value to allow load files through symbolic links. Note that making use of this variable could expose you to symlink attacks and so it should only be used in cases where you are absolutely sure this is not a risk. ================================================ FILE: man/common/option-bind.xml ================================================ Bind the outgoing connection to a local ip address/hostname. Use this argument if you need to restrict network communication to a particular interface. ================================================ FILE: man/common/option-clean-session.xml ================================================ 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 . ================================================ FILE: man/common/option-clientid-prefix.xml ================================================ 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. ================================================ FILE: man/common/option-clientid.xml ================================================ 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. ================================================ FILE: man/common/option-config-file.xml ================================================ ]> config-file &from-version21; Load options from a config file. See the Default Config File and Config File sections at the start of the Options section. ================================================ FILE: man/common/option-debug.xml ================================================ Enable debug messages. ================================================ FILE: man/common/option-format-no-eol.xml ================================================ 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 . ================================================ FILE: man/common/option-format-pretty.xml ================================================ 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. ================================================ FILE: man/common/option-format-verbose.xml ================================================ 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". See also . ================================================ FILE: man/common/option-format.xml ================================================ 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. ================================================ FILE: man/common/option-help.xml ================================================ Display usage information. ================================================ FILE: man/common/option-hide-retain.xml ================================================ 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. See also . ================================================ FILE: man/common/option-host.xml ================================================ Specify the host to connect to. Defaults to localhost. ================================================ FILE: man/common/option-keepalive.xml ================================================ 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. ================================================ FILE: man/common/option-no-tls.xml ================================================ ]> &from-version21; Disable all use of TLS encryption. This is useful if you specify TLS options in a configuration file but want to disable those options. It also stops the automatic use of TLS when connecting to port 8883. ================================================ FILE: man/common/option-nodelay.xml ================================================ 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. ================================================ FILE: man/common/option-password.xml ================================================ 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. ================================================ FILE: man/common/option-payload-file.xml ================================================ Send the contents of a file as the message. ================================================ FILE: man/common/option-payload-message.xml ================================================ Send a single request message from the command line. ================================================ FILE: man/common/option-payload-null.xml ================================================ Send a null (zero length) message. ================================================ FILE: man/common/option-payload-stdin-file.xml ================================================ Send a request message read from stdin, sending the entire content as a single message. ================================================ FILE: man/common/option-port.xml ================================================ Connect to the port specified. If not given, the default of 1883 for plain MQTT or 8883 for MQTT over TLS will be used. ================================================ FILE: man/common/option-property.xml ================================================ Set MQTT v5 properties for with this client. 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, 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. ================================================ FILE: man/common/option-protocol-version.xml ================================================ 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 . ================================================ FILE: man/common/option-proxy.xml ================================================ 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. If the host is given as an IPv6 address, it must be enclosed in square brackets, e.g. . Note that square brackets have special meaning in some shells, so the proxy url may need quoting in double or single quotes. More SOCKS versions may be available in the future, depending on demand, and will use different protocol prefixes as described in curl1 . ================================================ FILE: man/common/option-qos-incoming.xml ================================================ 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 applies to all topics subscribed to in a single instance of this client. ================================================ FILE: man/common/option-quiet.xml ================================================ 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). ================================================ FILE: man/common/option-retain-handling.xml ================================================ ]> always | new | never &from-version21; Use this option to control the retain handling option when making a subscription. This controls under what circumstances an existing retained message is sent to the client when the subscription is made. - always deliver retained messages - deliver retained messages the first time a subscription is made, but not on subsequent subscriptions. This is useful for the case where you have a long running client using a non-clean session. If the connection is dropped briefly, when the client reconnects you will not receive the retained messages again. - never deliver retained messages ================================================ FILE: man/common/option-session-expiry-interval.xml ================================================ Set the session-expiry-interval property on the CONNECT packet. If you use this option, the client will be set to be an MQTT v5 client. 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. ================================================ FILE: man/common/option-srv.xml ================================================ Use SRV lookups to determine which host to connect to. Performs lookups to when used in conjunction with , otherwise uses . ================================================ FILE: man/common/option-timeout.xml ================================================ Provide a timeout as an integer number of seconds. The client 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. ================================================ FILE: man/common/option-tls-alpn.xml ================================================ Provide a protocol to use when connecting to a broker that has multiple protocols available on a single port, e.g. MQTT and WebSockets. ================================================ FILE: man/common/option-tls-cafile.xml ================================================ Define the path to a file containing PEM encoded CA certificates that are trusted. Used to enable SSL communication. See also ================================================ FILE: man/common/option-tls-capath.xml ================================================ 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 ================================================ FILE: man/common/option-tls-cert.xml ================================================ Define the path to a file containing a PEM encoded certificate for this client, if required by the server. See also and the Encrypted Connections section. ================================================ FILE: man/common/option-tls-ciphers.xml ================================================ An openssl compatible list of TLS ciphers to support in the client. See ciphers1 for more information. ================================================ FILE: man/common/option-tls-engine-kpass-sha1.xml ================================================ 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 . ================================================ FILE: man/common/option-tls-engine.xml ================================================ A valid openssl engine id. These can be listed with the openssl engine command. See also . ================================================ FILE: man/common/option-tls-insecure.xml ================================================ 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. ================================================ FILE: man/common/option-tls-key.xml ================================================ Define the path to a file containing a PEM encoded private key for this client, carrying out mutual TLS with the server. See also and the Encrypted Connections section. ================================================ FILE: man/common/option-tls-keyform.xml ================================================ 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 . ================================================ FILE: man/common/option-tls-keylog.xml ================================================ ]> file &from-version21; Log TLS connection information to file. This option allows tools such as tcpdump, wireshark and mqttshark to decrypt TLS traffic and inspect the MQTT traffic. In Wireshark this can be done by setting the option for the protocol. This option should be used for debugging only, it must not be used in production. ================================================ FILE: man/common/option-tls-psk-identity.xml ================================================ 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. ================================================ FILE: man/common/option-tls-psk.xml ================================================ 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. ================================================ FILE: man/common/option-tls-use-os-certs.xml ================================================ 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. ================================================ FILE: man/common/option-tls-version.xml ================================================ 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. ================================================ FILE: man/common/option-unix-socket.xml ================================================ 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.conf5 to configure Mosquitto to listen on a unix socket. ================================================ FILE: man/common/option-url.xml ================================================ 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 or ws(s)://[username[:password]@]host[:port]/path Depending on the scheme, the port will default to different values. mqtt:// - 1883, mqtts:// - 8883, ws:// - 80, wss:// - 443. ================================================ FILE: man/common/option-username.xml ================================================ Provide a username to be used for authenticating with the broker. See also the argument. ================================================ FILE: man/common/option-websockets.xml ================================================ Connect using WebSockets instead of plain TCP. ================================================ FILE: man/common/option-will-payload.xml ================================================ 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 . ================================================ FILE: man/common/option-will-qos.xml ================================================ The QoS to use for the Will. Defaults to 0. This must be used in conjunction with . ================================================ FILE: man/common/option-will-retain.xml ================================================ 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 . ================================================ FILE: man/common/option-will-topic.xml ================================================ The topic on which to send a Will, in the event that the client disconnects unexpectedly. ================================================ FILE: man/common/options-intro.xml ================================================ There are three ways to provide options to &commandname;: the default config file, a specified config file, or options on the command line. Default Config File The default config file is located at or on POSIX systems, or on Windows. The contents of the config file should consist of options, one per line in the format: . If options are also specified on the command line, those options will override the same options set in the config file. 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. . TLS encryption options can be negated with the option. Config file lines that have a as the first character are treated as comments and not processed any further. It is suggested that config files are primarily used for authentication purposes. Use of a config file allows you to authenticate without the need to show the username and password on the command line. Config File &from-version21; A config file can be specified on the command line using . If the option is used, the default config file will not be loaded. The format is the same as for the default config file. ================================================ FILE: man/common/section-bugs.xml ================================================ Bugs mosquitto bug information can be found at ================================================ FILE: man/common/section-encrypted-connections.xml ================================================ Encrypted Connections This client 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 can be provided as an option. Alternatively, if the option is used then the OS provided certificates will be loaded and neither or are needed. To enable TLS connections when using TLS-PSK, you must use the and the options. ================================================ FILE: man/common/section-exit-status.xml ================================================ Exit Status 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 Other codes: Timed out waiting for message ================================================ FILE: man/common/section-output-format.xml ================================================ Output Format There are three ways of formatting the printed output. In all cases a new-line character is appended for each message received unless the argument is given. 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. One extension to strftime is provided 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, %d, %E, %F, %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, %d, %F, %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. If the output length is smaller than this width, the field will be padded to meet this width. This applies to the options %A, %C, %d, %E, %F, %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, for example for a maximum width of 20. 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. Hexadecimal binary field width The %x and %X parameters output the payload as a single hexadecimal string by default. It is also possible to split the hexadecimal payload into fields by a chosen length of nibbles. For example, would split the payload into two nibble or one byte values, separated by spaces and might produce an output of 18 83. The separator character is a space by default, but can be changed to one of by adding that character after the binary field width. For example might produce an output of 18:83. Floating point number printing consideration The output format supports only the IEEE 754 floating point standard as described in Annex F of ISO/IEC 9899:1999. Don't try to use %f or %d if the platform of the publisher uses a different floating point representation standard than IEEE 754 or you will get invalid data. If you are unsure what floating representation your platform is using, then it is most likely IEEE 754. If you get malformed or unexpected values, check if the floating point number in the payload from the publisher is encoded in IEEE 754. If want to print floats, make sure you only subscribe to topics that send only IEEE 754 formatted floats. The processing is very strict about floats and if anything that is not a float is received, an error message will be printed. 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 payload treated as an 8 byte IEEE 754 float (double). the MQTT v5 message-expiry-interval property, if present. the MQTT v5 payload-format-indicator property, if present. the payload treated as an 4 byte IEEE 754 float. 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. 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. ================================================ FILE: man/common/section-properties-connect.xml ================================================ Connect (binary data - note treated as a string) (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) ================================================ FILE: man/common/section-properties-disconnect.xml ================================================ Disconnect (32-bit unsigned integer) (UTF-8 string pair) ================================================ FILE: man/common/section-properties-publish.xml ================================================ Publish (UTF-8 string) (binary data - note treated as a string) (32-bit unsigned integer) (8-bit unsigned integer) (UTF-8 string) (16-bit unsigned integer) (UTF-8 string pair) ================================================ FILE: man/common/section-properties-subscribe.xml ================================================ Subscribe (UTF-8 string pair) ================================================ FILE: man/common/section-properties-unsubscribe.xml ================================================ Unsubscribe (UTF-8 string pair) ================================================ FILE: man/common/section-properties-will.xml ================================================ Will properties (UTF-8 string) (binary data - note treated as a string) (32-bit unsigned integer) (8-bit unsigned integer) (UTF-8 string) (UTF-8 string pair) (32-bit unsigned integer) ================================================ FILE: man/common/section-wills.xml ================================================ Wills The client 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. ================================================ FILE: man/common/synopsis-tls-certificate-options.xml ================================================ tls-certificate-options: file dir file file ciphers protocol file version engine pem engine kpass-sha1 ================================================ FILE: man/common/synopsis-tls-psk-options.xml ================================================ tls-psk-options: hex-key identity ciphers version ================================================ FILE: man/common/synopsis-will.xml ================================================ topic payload qos ================================================ FILE: man/common/version-2.1.xml ================================================ Available from version 2.1. ================================================ FILE: man/html.xsl ================================================ man.css ansi ================================================ FILE: man/libmosquitto.3.meta ================================================ .. title: libmosquitto man page .. slug: libmosquitto-3 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/libmosquitto.3.xml ================================================ libmosquitto 3 Mosquitto Project Library calls libmosquitto MQTT version 5.0/3.1.1 client library Documentation See See Also mosquitto 7 Author Roger Light roger@atchoo.org ================================================ FILE: man/manpage.xsl ================================================ 0 0 https://mosquitto.org/man/ ansi ================================================ FILE: man/mosquitto-tls.7.meta ================================================ .. title: mosquitto-tls man page .. slug: mosquitto-tls-7 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto-tls.7.xml ================================================ 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 -aes256 -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 -aes256 -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 7 mosquitto 8 mosquitto.conf 5 Author Roger Light roger@atchoo.org ================================================ FILE: man/mosquitto.7.meta ================================================ .. title: Mosquitto man page .. slug: mosquitto-7 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto.7.xml ================================================ ]> mosquitto 7 Mosquitto Project Conventions and miscellaneous mosquitto Project overview Description The mosquitto project contains MQTT related programs, and comprises the mosquitto broker and applications, command line clients, and a client library for implementing custom MQTT clients. A brief description of some MQTT features is available at mqtt7. Mosquitto is an Eclipse Foundation project, part of the IoT top level project. The project home page is at mosquitto.org, the github project is at github.com/eclipse-mosquitto/mosquitto, and the project provides a public MQTT test broker available at test.mosquitto.org. Development is driven by Cedalo, who also provide professional support and enterprise features for mosquitto. Mosquitto Broker The mosquitto broker is the core of the project. Details on starting the broker, MQTT support, and feature descriptions can be found in mosquitto8. A full description of the configuration file format can be found in mosquitto.conf5. Mosquitto Broker Applications These command line applications directly support the running of the mosquitto broker. mosquitto_ctrl This can be used to interact with the broker MQTT APIs when the broker is running. It can run in batch mode, where all arguments are provided on the command line, or from version 2.1 onwards, in an interactive shell mode. The batch mode is described in mosquitto_ctrl1, with the Dynamic Security module described in mosquitto_ctrl_dynsec1. The interactive shell mode is described in mosquitto_ctrl_shell1. mosquitto_passwd This tool is used to generate and modify password files that can be used with the plugin or configuration option. It is described in mosquitto_passwd1. mosquitto_signal &from-version21; This tool is used to send signals to the broker. On POSIX systems it performs the same task as the kill command, but with named signals. On Windows it is the only method of sending signals to the broker. It is described in mosquitto_signal1. Mosquitto MQTT Command Line Clients These command line tools act as MQTT clients and can be useful for testing and automation of tasks related to any MQTT broker. mosquitto_pub This client can publish messages to a broker. It supports sending simple messages from the command line, reading from stdin, and sending files. It is described at mosquitto_pub1. mosquitto_rr This client operates in a request/response style by sending a single message to a broker and waiting for a response on another topic. Request/response support is an MQTT v5.0 feature, but it is not required most cases for this client. It is described at mosquitto_rr1. mosquitto_sub This client subscribes to topics on the broker and prints messages that it receives. It has a wide variety of output options. It is described at mosquitto_sub1. Mosquitto Client Library The Mosquitto client library is described at libmosquitto3. Author Roger Light roger@atchoo.org ================================================ FILE: man/mosquitto.8.meta ================================================ .. title: Mosquitto man page .. slug: mosquitto-8 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto.8.xml ================================================ ]> mosquitto 8 Mosquitto Project Mosquitto mosquitto an MQTT broker mosquitto config file port number file Description mosquitto is a broker for the MQTT protocol version 5.0/3.1.1/3.1. It is part of the overall mosquitto project. See mosquitto7 for an overview of all man pages. 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. &from-version21; Disable all logging. This is equivalent to setting to in the configuration file. This overrides any logging options given in the configuration file and also overrides . &from-version21; Load the config file specified with , and verify that it is valid but do not start the broker. The broker exit code will be 0 if the config was valid, or non-zero if no config file was specified or the config file was invalid. Use verbose logging. This is equivalent to setting to in the configuration file. This overrides any 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. Platform limitations 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, this limit is 2048 connections. 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 connected and disconnected client sessions currently 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 total number of socket connections that have been made to the broker, whether or not the MQTT connections were ultimately successful. 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 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 MQTT CONNECT messages received since the broker started. The total number of MQTT CONNACK messages sent since the broker started. The total number of MQTT 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 MQTT PUBLISH messages received since the broker started. The total number of MQTT PUBLISH messages sent since the broker started. The total number of MQTT PUBACK messages received since the broker started. The total number of MQTT PUBACK messages sent since the broker started. The total number of MQTT PUBREC messages received since the broker started. The total number of MQTT PUBREC messages sent since the broker started. The total number of MQTT PUBREL messages received since the broker started. The total number of MQTT PUBREL messages sent since the broker started. The total number of MQTT PUBCOMP messages received since the broker started. The total number of MQTT PUBCOMP messages sent since the broker started. The total number of MQTT SUBSCRIBE messages received since the broker started. The total number of MQTT SUBACK messages sent since the broker started. The total number of MQTT UNSUBSCRIBE messages received since the broker started. The total number of MQTT UNSUBACK messages sent since the broker started. The total number of MQTT PINGREQ messages received since the broker started. The total number of MQTT PINGRESP messages sent since the broker started. The total number of MQTT DISCONNECT messages received since the broker started. The total number of MQTT DISCONNECT messages sent since the broker started. The total number of MQTT AUTH messages received since the broker started. The total number of MQTT AUTH messages sent since the broker started. The current number of packets queued for delivery across all clients. A large and increasing value here may indicate messages are being sent faster than the network can handle. The current number of bytes in packets queued for delivery across all clients. A large and increasing value here may indicate messages are being sent faster than the network can handle. The total number of PUBLISH payload bytes received since the broker started. The total number of PUBLISH payload bytes 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 shared subscriptions active on the broker. 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 On POSIX systems Mosquitto can receive signals and act on them as described below. To send signals, use e.g. kill -HUP <process id of mosquitto> 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. The logs will also be closed and reopened. SIGRTMIN Upon receiving the SIGRTMIN signal, mosquitto will close and reopen the logs to support log rotation. 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. Environment Variables 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. See Also mosquitto 7 mqtt 7 mosquitto-tls 7 mosquitto.conf 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 ================================================ FILE: man/mosquitto.conf.5.meta ================================================ .. title: mosquitto.conf man page .. slug: mosquitto-conf-5 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto.conf.5.xml ================================================ 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. Mosquitto can be instructed to reload the configuration file by sending a SIGHUP signal as described in the Signals section of mosquitto8. Not all configuration options can be reloaded, as detailed in the options below. Sections The rest of this man page is divided into the following sections: a description of the configuration file syntax. a discussion of the authentication options available. the general options for configuring Mosquitto. general options for configuring listeners, which are the ways that MQTT clients can connect to Mosquitto, as well as certificate and pre-shared-key based SSL/TLS options. general options for configuring bridges, which are a way of connecting multiple brokers together, as well as certificate and pre-shared-key based SSL/TLS options. The Files, Bugs, See Also sections. 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 Note: It is suggested that you use the plugin instead of this option. Using plugins for authentication and authorisation allows greater control of what listeners they are applied to, without the need for the deprecated option. 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 substitution 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. Note: In general it is not possible to grant write access to topics in the $SYS topic tree. The exception is $SYS/broker/connection/+/state. 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 ] Global 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 you want to control this setting for each listener individually, use the option. (Note: Deprecated) 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. [ 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 This option is deprecated, please use instead. 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 the built-in 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. Applies to built-in persistence only. 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. [ true | false ] If set to true, the will be enabled. This currently allows interrogating which plugins are enabled, but in the future will allow access to configuring general broker options. If you enable this you should ensure you have authentication and appropriate access control configured, i.e. only allowing access to for a limited set of users. This option applies globally. Reloaded on reload signal. count The maximum number of client sessions to allow across the whole broker. In this context a client session means either a client currently connected via the network, or a client that has clean_session = False (MQTT v3.x) and is disconnected, or has disconnected and still hasn't exceeded its session expiry interval (MQTT v5). See also the setting, which applies to listeners. If you set to 1000 and on a listener to 10, then that means only 10 simultaneous connections will be allowed at once, with an overall maximum of 1000 client sessions. This option applies globally. Defaults to -1 (unlimited) Reloaded on reload signal. count The maximum number of currently connected clients to allow across the whole broker. See also the and settings. This option applies globally. Defaults to -1 (unlimited) Reloaded on reload signal. file path Load an external module to extend broker features. This loads plugins for use across all listeners, regardless of the value of the option. This option functions the same as the option in all other ways. If you set , then define both a and a (which will be attached to a specific listener), then the global plugin will always be processed first. If you set , then behaves identically to . 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. The destination is for Android only, and will output to the logd daemon. 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 is 65535. Set to 0 to allow infinite keepalive. Defaults to 0. Set to 0 to allow clients to set keepalive = 0, which means no keepalive checks are made and the client will never be disconnected by the broker if no messages are received. You should be very sure this is the behaviour that you want. For MQTT v3.1.1 and v3.1 clients, there is no mechanism to tell the client what keepalive value they should use. If an MQTT v3.1.1 or v3.1 client specifies a keepalive time greater than max_keepalive they will be sent a CONNACK message with the "identifier rejected" reason code, and disconnected. 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 2000000 bytes since 2.1. Earlier versions defaulted 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 Note: It is suggested that you use the plugin instead of this option. Using plugins for authentication and authorisation allows greater control of what listeners they are applied to, without the need for the deprecated option. 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, then built-in persistence is enabled. It is recommended that a plugin based persistence is used instead. If enabled, connection, subscription and message data will be written to 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 built-in persistent database. Defaults to mosquitto.db. This option applies globally. Reloaded on reload signal. path The path where plugins should store any persistence data, and the path where the built-in persistence will store its data. If not given, then the current directory is used. This option applies globally. Reloaded on reload signal. duration This option allows the session of persistent clients (those with clean session set to false) that are not currently connected to be removed if they do not reconnect within a certain time frame. This is a non-standard option in MQTT v3.1. MQTT v3.1.1 and v5.0 allow brokers to remove client sessions. Badly designed clients may set clean session to false whilst using a randomly generated client id. This leads to persistent clients that connect once and never reconnect. This option allows these clients to be removed. 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. The expiration period should be an integer followed by one of s h d w m y for second, hour, day, week, month and year respectively. For example: persistent_client_expiration 2m persistent_client_expiration 14d persistent_client_expiration 1y Although it is possible to specify the expiration time in seconds, this is not a suggestion that you should use a short expiration interval. If you have a system where you think the clients should be automatically expired in a short time you should see about fixing the clients instead where possible. 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. value Options to be passed to the most recent defined in the configuration file. See the specific plugin instructions for details of what options are available. Applies to the current plugin/global_plugin being configured. This is also available as the option, but this use is deprecated and will be removed in a future version. file path Specify an external module to use for authentication, access control, and other features. This allows custom username/password and access control functions to be created and other behaviour to be modified. 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 before the built in checks. Not currently reloaded on reload signal. If is set to true, this plugin will be loaded for the current listener only. See also and the option. This is also available as the option, but this use is deprecated and will be removed in a future version. 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. When bridges topics are configured with QoS level 1 or 2 incoming QoS 0 messages for these topics are also queued. 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. minutes The default behaviour of mosquitto is to remove retained messages that have reached their message-expiry-interval property the next time that that message is accessed - either by being replaced by a new message, or on the next subscription that matches the message. If you have a pattern of publishing many retained messages with a message-expiry-interval, but that are not subscribed to, then the expired retained messages will remain in memory. This option configures the broker to periodically check the retained tree for expired messages. Defaults to off. Setting to a value greater than zero means the broker will make a check at an interval of that number of minutes. 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 versions Accepted protocol versions. This sets what versions of the MQTT protocol will be accepted on this listener. Can be any combination of 3, 4, 5 in a comma separated list, e.g. # Allow v5.0 only: listener 1883 accept_protocol_versions 5 # Allow v3.1 and v3.1.1: listener 1884 accept_protocol_versions 3, 4 Defaults to allowing all versions. Reloaded on reload signal. 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 and AIX. Not reloaded on reload signal. [ 2 | 1 ] Enable PROXY protocol support for this listener. Versions 1 and 2 are supported, if you have the choice then version 2 is recommended because it gives you access to TLS information, and support Unix sockets. This option requires the use of a load balancer/proxy such as HAProxy in front of Mosquitto, with the proxy configured to use the PROXY protocol. The PROXY protocol is used to send information about client socket connections from the proxy to the broker. Without this, the connection information and logs in the broker will contain the IP address and port of the proxy itself, rather than the client. Enabling this option should only be done when a trusted proxy is placed in front of Mosquitto, and when no other external access to Mosquitto is possible. Giving external access to a listener with this option enabled is a security risk, particularly if you are using client certificates on the proxy. When using PROXY version 2, this option can be used with TLS termination on the proxy. In this case, TLS information will be passed to the broker as well. Use to reject clients that do not use TLS - this is strongly recommended. Enabling on the listener will result in the broker checking the TLS information provided to ensure that the client has provided a valid certificate. Enabling as well will result in the commonName value from the certificate being used as the client username instead of any provided in the CONNECT packet. In both cases, the listener must not have TLS configured. It is not possible to use the , , or options in conjunction with . Not reloaded on reload signal. directory When a listener is using the http_api 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. This option is also available for websockets listeners if Mosquitto is compiled with websockets support provided by libwebsockets. This is not the default, and will be removed in version 3.0. 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. [ true | false ] Boolean value that determines whether clients that connect without providing a username are allowed to connect to this specific listener. If set, this overrides the value set by If set to false then another means of connection should be created to control authenticated client access. If not explicitly set, the value from will be used. Not reloaded on reload signal. prefix This option allows you to set a string that will be prefixed to the automatically generated client ids (i.e. for when a client connects without providing a client id) to aid visibility in logs. Defaults to . 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 When publishing to MQTT v5 clients, Mosquitto can create topic aliases on a first come first serve basis, i.e. the topics that are published to a client first have aliases created. This option controls the number of aliases per client. It applies per listener. Note that this behaviour is not guaranteed to remain the same. It is possible that future versions introduce mechanisms for controlling which topics receive aliases. This option sets the maximum number topic aliases that Mosquitto will create for an MQTT v5 client, even if the client allows more. For example, if the client sets topic-alias-maximum to 100 and this option is set to 10, the broker will create at most 10 topic aliases. Likewise, if the client sets topic-alias-maximum to 20 and this option is set to 100, then the broker will create at most 20 topic aliases. Defaults to 10. Maximum of 65535. Set to 0 to disable broker to client topic aliases completely. 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 from clients. 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 . : the standard MQTT listener. : MQTT tunnelled over WebSockets. If the legacy websockets support using libwebsockets is used, then only a reduced TLS feature set is available, namely , , , , and . : This starts the listener as a very simple webserver (see the option) that can also serve some HTTP API requests. TLS is supported for this listener, however only the and options are allowed. Authentication is not currently possible - to use this listener it is strongly recommended to bind the listener to the loopback interface and then configure a reverse proxy with the appropriate encryption and authentication. Not reloaded on reload signal. [ true | false ] When a listener is using the PROXY protocol, this option can be used to require that the client connection is using TLS. If set to true, then the PROXY protocol header must contain a TLS indicator. If it does not, the connection will be closed. Defaults to false. 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 . This does not apply globally, but on a per-listener basis. See also . Not reloaded on reload signal. size size Change the size of the buffer used when reading from the network before the size of the MQTT packet is known. Defaults to 4096. Packets received that are smaller than this value in principle only need a single read() call, making reading packets more efficient. This also operates as the option that sets the size of the buffer used by websockets when reading the initial header. If you are passing large header data such as cookies then you may need to increase this value. 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. level If set, this will be compared to the http origin header when a connection attempts to upgrade to WebSockets. Only matching origins will be allowed. Use the exact string provided by the browser in the origin header, e.g. http://example.com:8080. Can be specified multiple times per listener. If not set, connections from any origin will be allowed. Requires libwebsockets 3.1.0 or later. 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. is not supported for websockets. 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 [ true | false ] If set true, will change the certificate verification behaviour to allow client certificates that are expired or are not yet valid, when using . Defaults to file path If equals "pem" this is the path to the PEM encoded server key. This option and must be present to enable certificate based TLS encryption. If is "engine" this represents the engine handle of the private key. 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 and tlsv1.2. If left unset, the default is to allow 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 obtained 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 and tlsv1.2. If left unset, the default is to allow 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. 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". value If the bridge is using MQTT v5, this option sets the maximum number of topic aliases that the bridge will allow the remote broker to configure. Defaults to 10, maximum of 65535. Set to 0 to disable incoming topic aliases completely. [ 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. count If the bridge is using MQTT v5.0 then use to limit the number QoS 1 or 2 messages that can be in-flight at once. Must be 1-65535. Defaults to , which defaults to 20. interval If the bridge is using MQTT v5.0 then use to set the session expiry interval. Set to 0 to have the session expire immediately when the connection drops. Set to 0xFFFFFFFF to have an infinite expiry interval. Otherwise the expiry interval is set to the number of seconds that you specify. Defaults to 0. idle interval counter Set TCP keepalive parameters for this bridge connection. Use this option to allow you to set a long MQTT keepalive value, whilst still being able to detect the connection dropping in a reasonable time. This may be useful when bridging to services that bill for PINGREQ messages. Disabled by default. timeout It specifies the maximum amount of time (in milliseconds) that transmitted data may remain unacknowledged at TCP level. Popular Linux distributions seem to set this time to "up to 20 minutes with system defaults" (from Linux tcp man page). The default time is related to tcp_retries2. Reducing this value helps detecting dropped connections faster. Be aware that when used in combination with TCP Keepalive, it might change the latter's behavior. You can find more details about this setting at: Only available on Linux. [ 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 [stable] 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. The backoff time will be reset to base after a successful connection. When stable is specified, the backoff time will be reset only if the connection remains open for at least stable seconds. Base has a minimum of 1 second and a maximum of 3600 seconds. Cap has a minimum of base, and a maximum of 7200 seconds. 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 60 Same as previous example, but wait for the connection to be stable for at least 30 seconds before resetting the backoff: restart_timeout 10 60 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 pattern may be enclosed in double quotes in case it contains a space. 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. [ lazy | immediate ] If you change bridge options in the configuration file, those configuration changes are applied during a bridge reconnection. The option determines when that reconnection happens, and can be set to either lazy or immediate. lazy is the default, and means that any connected bridge will remain in its current state until a natural reconnection happens, at which point the new configuration will be used. immediate forces a reconnection and so uses the new configuration straight away. 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 At least 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 At least 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. [ true | false ] At least one of , , or must be provided to allow SSL/TLS support. Set to true to enable TLS for this bridge, and to configure it to trust the default certificates provided by openssl. This is typically a large number of certificates. Defaults to false. version Configure the version of the TLS protocol to be used for this bridge. Possible values are tlsv1.3 and tlsv1.2. Defaults to tlsv1.2. The remote broker must support the same version of TLS for the connection to succeed. cipher:list The list of allowed ciphers for this bridge, 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 bridge, for TLS v1.3, each separated with a colon. Files mosquitto.conf See Also mosquitto 7 mosquitto 8 mosquitto_passwd 1 mosquitto-tls 7 mqtt 7 limits.conf 5 Author Roger Light roger@atchoo.org ================================================ FILE: man/mosquitto_ctrl.1.meta ================================================ .. title: mosquitto_ctrl man page .. slug: mosquitto_ctrl-1 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto_ctrl.1.xml ================================================ mosquitto_ctrl 1 Mosquitto Project Commands mosquitto_ctrl a tool for initialising/configuring a Mosquitto broker instance mosquitto_ctrl options | config-file module-name module-command command-options options: auth-options connection-options mqtt-options output-options tls-certificate-options tls-psk-options auth-options: username password connection-options: hostname socket path port-number URL bind-address socks-url mqtt-options: client-id message-QoS protocol-version output-options: mosquitto_ctrl connection-options (interactive shell mode) mosquitto_ctrl Description mosquitto_ctrl is a tool for helping configure a Mosquitto broker instance. It can be run primarily as a straightforward command line tool, as described here, or as an interactive shell as described in mosquitto_ctrl_shell 1 . The interactive shell makes most operations very straightforward and is recommended for ease of use. 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. 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. Specify the quality of service to use for messages, from 0, 1 and 2. Defaults to 1. 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. Properties The / option allows adding properties to different stages of the mosquitto_ctrl run. The properties supported for each command are as follows: Environment Variables See Also mosquitto 7 mqtt 7 mosquitto_ctrl_shell 1 mosquitto_rr 1 mosquitto_pub 1 mosquitto_sub 1 mosquitto 8 libmosquitto 3 mosquitto-tls 7 Author Roger Light roger@atchoo.org ================================================ FILE: man/mosquitto_ctrl_dynsec.1.meta ================================================ .. title: mosquitto_ctrl dynamic security man page .. slug: mosquitto_ctrl_dynsec-1 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto_ctrl_dynsec.1.xml ================================================ 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] See Also mosquitto 7 mqtt 7 mosquitto_rr 1 mosquitto_pub 1 mosquitto_sub 1 mosquitto 8 libmosquitto 3 mosquitto-tls 7 Author Roger Light roger@atchoo.org ================================================ FILE: man/mosquitto_ctrl_shell.1.meta ================================================ .. title: mosquitto_ctrl_shell man page .. slug: mosquitto_ctrl_shell-1 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto_ctrl_shell.1.xml ================================================ mosquitto_ctrl 1 Mosquitto Project Commands mosquitto_ctrl_shell a interactive shell for configuring a Mosquitto broker instance mosquitto_ctrl hostname port-number username password client-id file dir file file Description mosquitto_ctrl is a tool for helping configure a Mosquitto broker instance. This man page describes how to use the interactive shell. For information on the pure command line mode, see mosquitto_ctrl 1 . The interactive shell makes most operations very straightforward and is recommended for ease of use. To run in interactive mode, run mosquitto_ctrl with no module or command, i.e. with at most the set of options described in the synopsis above. The shell will start and you will be presented with a prompt. 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, connect using the or scheme inside the shell, or use either or when starting mosquitto_ctrl on the command line - this also allows custom CA certificates to be used. Client certificates may be used for additional security. To enable this, use the and options. Example shell workflow The typical workflow for using the interactive shell is to configure authentication and connect to a broker, then switch to the mode you are interested in and run its commands. For example, to create a new group in the dynamic-security plugin: $ mosquitto_ctrl mosquitto_ctrl shell v2.1.0 > auth username: admin password: > connect mqtt://localhost mqtt://localhost:1883> dynsec mqtt://localhost:1883|dynsec> createGroup newgroup OK Shell Behaviour The interactive shell operates in a set of different modes which have different commands available. The shell has tab completion for the commands and their arguments, where possible. It should usually be possible to press the tab key twice to be able to be shown a list of the currently available commmands or arguments. The shell has a history of commands that can be accessed by pressing the up and down arrow keys. The history is not saved to disk. Help can be obtained for any command by typing help followed by the command name. For example: help createGroup. The different modes are: Pre-connection In this mode it is possible to set the authentication details, connect to a broker, read help and exit. Post-connection In this mode, mosquitto_ctrl is connected to a broker and you can switch between different control modules, view help or exit. dynsec Allows you to create, delete, and modify users, groups, roles, and ACLs. broker Allows you to view listener and plugin information. Authentication mosquitto_ctrl supports authentication via username and password, or via x509 client certificates. If you are using username and password authentication, then you must set the username and password before connecting. This can be done in one of two ways. The first is by using the and options on the command line. The second is by using the auth command in the shell. Authentication in the shell can done in one of two ways. The first is by using the auth command, which will then prompt for a username and password. The second is by using the auth username command, which will then prompt for a password. Connection To connect to a broker, use the connect command. Connect to the broker at localhost on port 1883. > connect Connect to a specific broker using the default port 1883. > connect mqtt://test.mosquitto.org Connect to a specific broker using the specific port 1884. > connect mqtt://test.mosquitto.org:1884 Connect to a specific broker using TLS. > connect mqtts://test.mosquitto.org Connect to a specific broker using websockets. > connect ws://test.mosquitto.org Connect to a specific broker using websockets over TLS. > connect wss://test.mosquitto.org If the option is used on the command line, the shell will immediately attempt to connect to the host specified. Dynamic-security mode Once connected, you can use the command dynsec to switch to the dynamic-security mode. This will only work if the broker has the dynamic-security plugin loaded, and you have permission to use it. The dynamic-security mode has commands to create, delete, and modify users, groups, roles, and ACLs. The commands can be discovered by pressing the tab key twice. Usernames, group names, and role names can be auto-completed for the appropriate commands by pressing the tab key. Help is available for each command by using help followed by the command name. To leave the dynamic-security mode, use the return command, or use the exit command to exit the shell. Broker mode Use the command broker to switch to the broker mode. This will only work if the broker has the option set to true. The broker mode has the commands listListeners, to show currently configured listener configuration, and listPlugins, to show currently loaded plugins. To leave the broker mode, use the return command, or use the exit command to exit the shell. Connection Options The options below may be given on the command line Exit Status mosquitto_ctrl returns zero on success, or non-zero on error. See Also mosquitto 7 mqtt 7 mosquitto_ctrl 1 mosquitto_rr 1 mosquitto_pub 1 mosquitto_sub 1 mosquitto 8 libmosquitto 3 mosquitto-tls 7 Author Roger Light roger@atchoo.org ================================================ FILE: man/mosquitto_passwd.1.meta ================================================ .. title: mosquitto_passwd man page .. slug: mosquitto_passwd-1 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto_passwd.1.xml ================================================ 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. If the filename is specified as a dash then the output will be to stdout. This only really makes sense with . Delete the specified user from the password file. Choose the hash to use. Can be one of argon2id, sha512-pbkdf2, or sha512. Defaults to argon2id. 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_passwd returns zero on success or non-zero on error. Examples Add a user to a new password file: mosquitto_passwd -c /etc/mosquitto/passwd ral Add a user to an existing password file: mosquitto_passwd /etc/mosquitto/passwd ral Add a user to an existing password file, passing the password on the command line: mosquitto_passwd -b /etc/mosquitto/passwd ral z2Dr0BsvtZ Update the password for a user in an existing password file: mosquitto_passwd /etc/mosquitto/passwd ral Add a user to an existing password file using the sha512 hash for Mosquitto 1.6 compatibility: mosquitto_passwd -H sha512 /etc/mosquitto/passwd ral Delete a user from a password file mosquitto_passwd -D /etc/mosquitto/passwd ral Environment Variables See Also mosquitto 7 mosquitto 8 mosquitto.conf 5 mqtt 7 Author Roger Light roger@atchoo.org ================================================ FILE: man/mosquitto_pub.1.meta ================================================ .. title: mosquitto_pub man page .. slug: mosquitto_pub-1 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto_pub.1.xml ================================================ ]> mosquitto_pub 1 Mosquitto Project Commands mosquitto_pub an MQTT version 5/3.1.1/3.1 client for publishing simple messages mosquitto_pub options topic payload-options options: auth-options connection-options misc-options mqtt-options output-options publish-options tls-certificate-options tls-psk-options auth-options: username password connection-options hostname socket path port-number URL bind-address socks-url misc-options: config-file mqtt-options: command identifier value client-id client-id-prefix keepalive-time session-expiry-interval protocol-version output-options: payload-options: file message publish-options: message-QoS count seconds 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. Options &options-intro; The options Send messages read from stdin, splitting separate lines into separate messages. Specify the quality of service to use for the message, from 0, 1 and 2. Defaults to 0. 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. The MQTT topic on which to publish the message. See mqtt7 for more information on MQTT topics. Properties The / option allows adding properties to different stages of the mosquitto_pub run. The properties supported for each command are as follows: 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 Power on an appliance using zigbee2mqtt and an appropriately configured power socket: mosquitto_pub -t zigbee2mqtt/power-microwave/set -m '{"state":"ON"}' Files $XDG_CONFIG_HOME/mosquitto_pub $HOME/.config/mosquitto_pub $HOME/snap/mosquitto/current/.config/mosquitto_pub (for snap installs) Configuration file for default options. See Also mosquitto 7 mqtt 7 mosquitto_rr 1 mosquitto_sub 1 mosquitto 8 libmosquitto 3 mosquitto-tls 7 Author Roger Light roger@atchoo.org ================================================ FILE: man/mosquitto_rr.1.meta ================================================ .. title: mosquitto_rr man page .. slug: mosquitto_rr-1 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto_rr.1.xml ================================================ ]> mosquitto_rr 1 Mosquitto Project Commands mosquitto_rr an MQTT version 5/3.1.1 client for request/response messaging mosquitto_rr options response-topic message-topic payload-options options: auth-options connection-options misc-options mqtt-options output-options tls-certificate-options tls-psk-options auth-options: username password connection-options: hostname socket path port-number URL bind-address socks-url misc-options: config-file message-processing-timeout mqtt-options: command identifier value client-id client-id-prefix keepalive-time message-QoS always | new | never protocol-version session-expiry-interval output-options: payload-options: file message 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 Options &options-intro; The options Response topic. The client will subscribe to this topic to wait for a response. &from-version21; If this option is specified, mosquitto_rr will print out the latency between it starting to publish a request and the response arriving. This number includes both the broker and client processing times, as well as any inherent network latency. This can be used to measure message delivery latency very simply by specifying an identical request and response topic. The option will be automatically used when is in use. The MQTT topic where the request message will be sent. Properties The / option allows adding properties to different stages of the mosquitto_rr run. The properties supported for each command are as follows: Files $XDG_CONFIG_HOME/mosquitto_rr $HOME/.config/mosquitto_rr $HOME/snap/mosquitto/current/.config/mosquitto_rr (for snap installs) Configuration file for default options. See Also mosquitto 7 mqtt 7 mosquitto_pub 1 mosquitto_sub 1 mosquitto 8 libmosquitto 3 mosquitto-tls 7 Author Roger Light roger@atchoo.org ================================================ FILE: man/mosquitto_signal.1.meta ================================================ .. title: mosquitto_signal man page .. slug: mosquitto_signal-1 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto_signal.1.xml ================================================ mosquitto_signal 1 Mosquitto Project Commands mosquitto_signal a utility for sending signal events to Mosquitto brokers running on the local computer. mosquitto_signal pid signal mosquitto_signal Description mosquitto_signal is a utility that can send named signals to one or all instances of a Mosquitto broker running on the local computer. On POSIX like systems, it is a convenient replacement for the kill1 command, with the added enhancement of being able to use named signals rather than generic system signals like SIGUSR1, and with the ability to signal multiple brokers at once. On Windows, it is the only means of sending signals to a broker. Options Send the given signal to all processes matching the name mosquitto. As with all signal sending, only those processes you have permission to send the signal to will receive the signal. pid Send the signal to a specific process id. mosquitto_signal will always attempt to send the corresponding signal to the given process and will not check whether it appears to be a mosquitto process. Signals The following named signals are available for use. Trigger the broker to reload its configuration file, if in use. On POSIX like systems this can also be triggered using the signal. Note that is used by other named signals. If the broker is using , then this will trigger the broker to close and reopen the log file. On POSIX like systems this can also be triggered using the signal. Note that is used by other named signals. Trigger the broker to quit. On POSIX like systems this can also be triggered using the signal. Trigger the broker to print a representation of the subscription and retain trees to stdout. This is intended for debugging purposes only. On POSIX like systems this can also be triggered using the signal. Note that is used by other named signals. Trigger the broker to write some internal state information to on POSIX systems or on Windows systems. This is intended for debugging purposes only. This signal is only used by the broker when appropriate support is compiled in, which is not the case by default. On POSIX like systems this can also be triggered using the signal. See Also mosquitto 7 mosquitto 8 Author Roger Light roger@atchoo.org ================================================ FILE: man/mosquitto_sub.1.meta ================================================ .. title: mosquitto_sub man page .. slug: mosquitto_sub-1 .. category: man .. type: man .. pretty_url: False ================================================ FILE: man/mosquitto_sub.1.xml ================================================ ]> mosquitto_sub 1 Mosquitto Project Commands mosquitto_sub an MQTT version 5/3.1.1/3.1 client for subscribing to topics mosquitto_sub options message-topic unsubscribe-topic options: auth-options connection-options misc-options mqtt-options output-options tls-certificate-options tls-psk-options auth-options: username password connection-options: hostname socket path port-number URL bind-address socks-url misc-options: config-file message-processing-timeout mqtt-options: command identifier value client-id client-id-prefix keepalive-time message-QoS always | new | never protocol-version session-expiry-interval output-options: msg-count chance filter-out 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. Options &options-intro; The options 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 or 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. 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. &from-version21; Instead of printing the messages received, print a count of the messages received at one second intervals. Other options related to output formatting are not valid when this option is active. 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, then 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. 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. 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. &from-version21; Messages will be printed on a fixed line number based on the topic and order in which topics are received. Useful for monitoring multiple topics that have single line payloads. Unexpected behaviour will occur if there are more topics than lines in the terminal, or if the payload occupies more than a single line. This can be used in conjuction with other output options e.g. . Requires ANSI escape code support in the terminal. Properties The / option allows adding properties to different stages of the mosquitto_sub run. The properties supported for each command are as follows: Examples Note that these really are examples - the subscriptions will work if you run them as shown, but there must be something publishing messages on those topics for you to receive anything. Subscribe to temperature information on localhost with QoS 1: mosquitto_sub -t sensors/temperature -q 1 Subscribe to hard drive temperature updates on multiple machines/hard drives. This expects each machine to be publishing its hard drive temperature to sensors/machines/HOSTNAME/temperature/HD_NAME. mosquitto_sub -t sensors/machines/+/temperature/+ Subscribe to all broker status messages: mosquitto_sub -v -t \$SYS/# Specify the output format as "ISO-8601 date : topic : payload in hex" mosquitto_sub -F '@Y-@m-@dT@H:@M:@S@z : %t : %x' -t '#' Specify the output format as "seconds since epoch.nanoseconds : retained flag : qos : mid : payload length" mosquitto_sub -F '%@s.@N : %r : %q : %m : %l' -q 2 -t '#' Topic and payload output, but with colour where supported. mosquitto_sub -F '\e[92m%t \e[96m%p\e[0m' -q 2 -t '#' Files $XDG_CONFIG_HOME/mosquitto_sub $HOME/.config/mosquitto_sub $HOME/snap/mosquitto/current/.config/mosquitto_sub (for snap installs) Configuration file for default options. See Also mosquitto 7 mqtt 7 mosquitto_pub 1 mosquitto_rr 1 mosquitto 8 libmosquitto 3 mosquitto-tls 7 Author Roger Light roger@atchoo.org ================================================ FILE: man/mqtt.7.meta ================================================ .. title: MQTT man page .. slug: mqtt-7 .. category: man .. type: man .. pretty_url: False .. hide_title: True ================================================ FILE: man/mqtt.7.xml ================================================ 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 https://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, 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 7 mosquitto 8 mosquitto_pub 1 mosquitto_sub 1 Author Roger Light roger@atchoo.org ================================================ FILE: misc/currentcost/cc128_log_mysql.pl ================================================ #!/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(); ================================================ FILE: misc/currentcost/cc128_parse.pl ================================================ #!/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"; } } ================================================ FILE: misc/currentcost/cc128_read.pl ================================================ #!/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); ================================================ FILE: misc/currentcost/cc128_read.py ================================================ #!/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() ================================================ FILE: misc/currentcost/gnome-panel/CurrentCostMQTT.py ================================================ #!/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) ================================================ FILE: misc/currentcost/gnome-panel/CurrentCostMQTT.server ================================================ ================================================ FILE: misc/letsencrypt/mosquitto-copy.sh ================================================ #!/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. # Set which domain this script will be run for MY_DOMAIN=example.com # Set the directory that the certificates will be copied to. CERTIFICATE_DIR=/etc/mosquitto/certs for D in ${RENEWED_DOMAINS}; do if [ "${D}" = "${MY_DOMAIN}" ]; then # Copy new certificate to Mosquitto directory cp ${RENEWED_LINEAGE}/fullchain.pem ${CERTIFICATE_DIR}/server.pem cp ${RENEWED_LINEAGE}/privkey.pem ${CERTIFICATE_DIR}/server.key # Set ownership to Mosquitto chown mosquitto: ${CERTIFICATE_DIR}/server.pem ${CERTIFICATE_DIR}/server.key # Ensure permissions are restrictive chmod 0600 ${CERTIFICATE_DIR}/server.pem ${CERTIFICATE_DIR}/server.key # Tell Mosquitto to reload certificates and configuration pkill -HUP -x mosquitto fi done ================================================ FILE: mosquitto.conf ================================================ # 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: # # acl_file # allow_anonymous - use listener_allow_anonymous instead # allow_zero_length_clientid # auto_id_prefix - use listener_auto_id_prefix instead # password_file # plugin - use plugin_load and plugin_use instead # plugin_opt_* # psk_file # # 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 # The maximum number of client sessions to allow across the whole broker. In # this context a client session means either a client currently connected via # the network, or a client that has clean_session = False (MQTT v3.x) and is # disconnected, or has disconnected and still hasn't exceeded its session # expiry interval (MQTT v5). # # See also the global_max_connections setting, and the max_connections setting, # which applies to listeners. If you set global_max_clients to 1000 and # max_connections on a listener to 10, then that means only 10 simultaneous # connections will be allowed at once, with an overall maximum of 1000 client # sessions. # #global_max_clients -1 # The maximum number of currently connected clients to allow across the whole # broker. # See also the global_max_clients and max_connections settings. #global_max_connections -1 # 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 is # 65535. Set to 0 to allow infinite keepalive. Defaults to 0. # # Set to 0 to allow clients to set keepalive = 0, which means no keepalive # checks are made and the client will never be disconnected by the broker if no # messages are received. You should be very sure this is the behaviour that you # want. # # For MQTT v3.1.1 and v3.1 clients, there is no mechanism to tell the client # what keepalive value they should use. If an MQTT v3.1.1 or v3.1 client # specifies a keepalive time greater than max_keepalive they will be sent a # CONNACK message with the "identifier rejected" reason code, and disconnected. # #max_keepalive 0 # 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 the session of persistent clients (those with clean # session set to false) that are not currently connected to be removed if they # do not reconnect within a certain time frame. This is a non-standard option # in MQTT v3.1. MQTT v3.1.1 and v5.0 allow brokers to remove client sessions. # # Badly designed clients may set clean session to false whilst using a randomly # generated client id. This leads to persistent clients that connect once and # never reconnect. This option allows these clients to be removed. 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. # # 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. Use global_max_clients if you wish to enforce a # client limit across the whole broker. # Default is -1, which means unlimited connections, unless otherwise limited by # global_max_clients. # 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, websockets, or http_api. # # mqtt: A standard MQTT based listener # websockets: MQTT tunnelled over WebSockets. If the legacy websockets support # using libwebsockets is used, then only a reduced TLS feature set # is available. # http_api: This starts the listener as a very simple webserver that can also # serve some HTTP API requests. TLS is supported for this listener, # however only the certfile and keyfile options are allowed. # Authentication is not currently possible - to use this listener it # is strongly recommended to bind the listener to the loopback # interface and then configure a reverse proxy with the appropriate # encryption and authentication. #protocol mqtt # Accepted protocol versions. This sets what versions of the MQTT protocol will # be accepted on this listener. Can be any combination of 3, 4, 5 in a comma # separated list, e.g. # # # Allow v5.0 only: # listener 1883 # accept_protocol_versions 5 # # # Allow v3.1 and v3.1.1: # listener 1884 # accept_protocol_versions 3, 4 # # Defaults to allowing all versions. #accept_protocol_versions 3,4,5 # If you wish to allow unauthenticated connections for a specific listener, use # the listener_allow_anonymous option set to true. If not set, the value # determined by the global allow_anonymous option will be used. If # listener_allow_anonymous is set at the same time as allow_anonymous, the # value set by listener_allow_anonymous will always take priority. #listener_allow_anonymous # This option allows you to set a prefix to automatically generated client ids # (i.e. for when a client connects without providing a client id) to aid # visibility in logs. # Defaults to 'auto-' #listener_auto_id_prefix auto- # 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. # This does not apply globally, but on a per-listener basis. #use_username_as_clientid # Change the size of the buffer used when reading from the network before the # size of the MQTT packet is known. Defaults to 4096. Packets received that are # smaller than this value in principle only need a single read() call, making # reading packets more efficient. # # This also operates as the option that sets the size of the buffer used by # websockets when reading the initial header. If you are passing large # header data such as cookies then you may need to increase this value. #packet_buffer_size # Enforce origin checking for websockets connections. This should be set to the # string of the host that you wish to allow connections from, as set as the # Origin header in the http request. # For example: https://example.com:8080 # If left unset will allow connections from any origin. # May be set multiple times. #websockets_origin # ----------------------------------------------------------------- # 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 # Configure the minimum version of the TLS protocol to be used for this listener. # Possible values are tlsv1.3 and tlsv1.2. #tls_version tlsv1.2 # If you wish to control which encryption ciphers are used, use the ciphers # option. The list of available ciphers can be obtained using the "openssl # ciphers" command and should be provided in the same format as the output of # that command. 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 # If set true, disable_client_cert_date_checks will change the certificate # verification behaviour to allow client certificates that are expired or are # not yet valid, when using `require_certificate true`. #disable_client_cert_date_checks 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. # capath is not supported for websockets. #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 obtained # using the "openssl ciphers" command and should be provided in the same format # as the output of that command. #ciphers # Set use_identity_as_username to have the psk identity sent by the client used # as its username. Authentication will be carried out using the PSK rather than # the MQTT username/password and so password_file will not be used for this # listener. #use_identity_as_username false # ================================================================= # 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. # # Can also be defined by setting the MOSQUITTO_PERSISTENCE_LOCATION environment # variable prior to running the broker. If both the config file option and the # environment variable are set, the environment variable takes precedent. # # This can also be used by plugins using the mosquitto_persistence_location() function. #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. # # The android destination is for logging into the Android logd logging daemon. # This options is only available when building for the Android target. # # 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 a plugin is used as well as # password_file, the 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 plugin is used as well, the 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 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 # 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 substitution 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 plugin is used as well as acl_file, the 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 # plugin option. This is a path to a loadable plugin. See also the # plugin_opt_* options described below. # # The 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 plugin option is specified alongside either of # password_file or acl_file then the plugin checks will be made first. # # If the per_listener_settings option is false, the plugin will be apply to all # listeners. If per_listener_settings is true, then the plugin will apply to # the current listener being defined only. # # This option is also available as `auth_plugin`, but this use is deprecated # and will be removed in the future. # #plugin # If the 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 plugin_opt_* will be passed to the plugin, for example: # # This option is also available as `auth_opt_*`, but this use is deprecated # and will be removed in the future. # # plugin_opt_db_host # plugin_opt_db_port # plugin_opt_db_username # plugin_opt_db_password # The `plugin` option is affected by the `per_listener_settings` option. If you # want to set `per_listener_settings true` but still want to use a plugin work # across all listeners, then use the `global_plugin` option. This option # functions the same as the `plugin` option in all other ways. # # If you set `per_listener_settings true`, then define both a `global_plugin` # and a `plugin` (which will be attached to a specific listener), then the # global plugin will always be processed first. # # If you set `per_listener_settings false`, then `global_plugin` behaves # identically to `plugin`. # #global_plugin # ================================================================= # 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 # If the bridge is using MQTT v5.0 then use bridge_receive_maximum to # limit the number QoS 1 or 2 messages that can be in-flight at once. # Must be 1-65535. Defaults to the same value as max_inflight_messages, # which defaults to 20. #bridge_receive_maximum 20 # 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 # If the bridge is using MQTT v5.0 then use bridge_session_expiry_interval to # set the session expiry interval. Set to 0 to have the session expire # immediately when the connection drops. Set to 0xFFFFFFFF to have an infinite # expiry interval. Otherwise the expiry interval is set to the number of # seconds that you specify. # Defaults to 0. #bridge_session_expiry_interval 0 # 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 MQTT keepalive interval (PING) for this bridge connection, in # seconds. #keepalive_interval 60 # Set TCP keepalive parameters for this bridge connection. # Disabled by default. #bridge_tcp_keepalive # Change the maximum amount of time (in milliseconds) that transmitted data # may remain unacknowledged at TCP level. # Popular Linux distributions seem to set this time to "up to 20 minutes with # system defaults" (from Linux tcp man page). Reducing this value helps # detecting dropped connections faster. # When used together with TCP Keepalive, it might change it's behavior. # More details at: https://blog.cloudflare.com/when-tcp-sockets-refuse-to-die/ # Only available on Linux. #bridge_tcp_user_timeout # 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 # If set to true, only publish notification messages to the local broker giving # information about the state of the bridge connection. Defaults to false. #notifications_local_only false # 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. # Minimum of 1, maximum of 3600 # # 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 60 # # Same as previous example, but wait for the connection to be stable for # at least 30 seconds before resetting the backoff: # restart_timeout 10 60 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 # If the bridge is using MQTT v5, this option sets the maximum number of topic # aliases that the bridge will allow the remote broker to configure. Defaults # to 10, maximum of 65535. Set to 0 to disable incoming topic aliases # completely. #bridge_max_topic_alias 10 # If you change bridge options in the configuration file, those configuration # changes are applied during a bridge reconnection. The bridge_reload_type # option determines when that reconnection happens, and can be set to either # lazy or immediate. # # lazy is the default, and means that any connected bridge will remain in its # current state until a natural reconnection happens, at which point the new # configuration is used. # # immediate forces a reconnection and so uses the new configuration straight # away. #bridge_reload_type lazy # When publishing to MQTT v5 clients, Mosquitto can create topic aliases on a # first come first serve basis, i.e. the topics that are published to a client # first have aliases created. The max_topic_alias_broker option controls the # number of aliases per client. It applies per listener. # # Note that this behaviour is not guaranteed to remain the same. It is possible # that future versions introduce mechanisms for controlling which topics # receive aliases. # # This option sets the maximum number topic aliases that Mosquitto will create # for an MQTT v5 client, even if the client allows more. # # For example, if the client sets topic-alias-maximum to 100 and this option is # set to 10, the broker will create at most 10 topic aliases. Likewise, if the # client sets topic-alias-maximum to 20 and this option is set to 100, then the # broker will create at most 20 topic aliases. # # Defaults to 10. Maximum of 65535. Set to 0 to disable broker to client topic # aliases completely. #max_topic_alias_broker 10 # The max_topic_alias 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 from clients. The maximum value # possible is 65535. #max_topic_alias 10 # ----------------------------------------------------------------- # Certificate based SSL/TLS support # ----------------------------------------------------------------- # To enable TLS support, the bridge must be configured to trust some # certificate authority certificates. This can be done in three ways, by # defining at least one of bridge_cafile, bridge_capath, or # bridge_tls_use_os_certs. # Use bridge_cafile or bridge_capath to explicitly choose which certificates to # trust 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 # Set bridge_tls_use_os_certs to true (default is false) to configure this # bridge to use the default certificates as configured in openssl. #bridge_tls_use_os_certs false # 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 # Require the use of Online Certificate Status Protocol (OCSP) for this bridge #bridge_require_ocsp false # 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 # Configure the version of the TLS protocol to be used for this bridge. # Possible values are tlsv1.3 and tlsv1.2. Defaults to tlsv1.2. # The remote broker must support the same version of TLS for the connection to succeed. #bridge_tls_version # 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 # bridge_ciphers_tls1.3 for TLS v1.3. #bridge_ciphers # Choose which TLS v1.3 ciphersuites are used for this bridge. # Defaults to "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256" #bridge_ciphers_tls1.3 # ----------------------------------------------------------------- # 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 # ================================================================= # Broker control # ================================================================= # Enable the $CONTROL/broker/# topic API #enable_control_api false # ================================================================= # 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 ================================================ FILE: plugins/CMakeLists.txt ================================================ function(add_mosquitto_plugin_no_install PLUGIN_NAME SRCLIST INCLIST LINKLIST) add_library(${PLUGIN_NAME} MODULE ${SRCLIST}) target_include_directories(${PLUGIN_NAME} PRIVATE ${INCLIST} "${mosquitto_SOURCE_DIR}/" "${mosquitto_SOURCE_DIR}/common" "${mosquitto_SOURCE_DIR}/include" ) set_target_properties(${PLUGIN_NAME} PROPERTIES PREFIX "" POSITION_INDEPENDENT_CODE 1 ) target_link_libraries(${PLUGIN_NAME} PRIVATE ${LINKLIST} common-options mosquitto ) endfunction() function(add_mosquitto_plugin PLUGIN_NAME SRCLIST INCLIST LINKLIST) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${SRCLIST}" "${INCLIST}" "${LINKLIST}") if(WIN32) install(TARGETS ${PLUGIN_NAME} DESTINATION "${CMAKE_INSTALL_BINDIR}") else() install(TARGETS ${PLUGIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" ) endif() endfunction() option(WITH_PLUGIN_ACL_FILE "Build acl-file plugin?" ON) option(WITH_PLUGIN_DYNAMIC_SECURITY "Build dynamic-security plugin?" ON) option(WITH_PLUGIN_EXAMPLES "Build example plugins?" ON) option(WITH_PLUGIN_PERSIST_SQLITE "Build persist-sqlite plugin?" ON) option(WITH_PLUGIN_PASSWORD_FILE "Build password-file plugin?" ON) option(WITH_PLUGIN_SPARKPLUG_AWARE "Build sparkplug-aware plugin?" ON) if(WITH_PLUGIN_ACL_FILE) add_subdirectory(acl-file) endif() if(WITH_PLUGIN_DYNAMIC_SECURITY) add_subdirectory(dynamic-security) endif() if (WITH_PLUGIN_EXAMPLES) add_subdirectory(examples) endif() if(WITH_PLUGIN_PASSWORD_FILE) add_subdirectory(password-file) endif() if (WITH_PLUGIN_PERSIST_SQLITE) find_package(SQLite3 REQUIRED) add_subdirectory(persist-sqlite) endif() if(WITH_PLUGIN_SPARKPLUG_AWARE) add_subdirectory(sparkplug-aware) endif() ================================================ FILE: plugins/Makefile ================================================ R=.. include ${R}/config.mk DIRS= \ acl-file \ dynamic-security \ examples \ password-file \ sparkplug-aware ifeq ($(WITH_SQLITE),yes) DIRS+=persist-sqlite endif .PHONY : all binary check clean reallyclean test test-compile 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 test-compile : 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 ================================================ FILE: plugins/README.md ================================================ # Plugins This directory contains plugins for use with Mosquitto. ## Dynamic security This is a fully functioning plugin that implements authentication and access control, with configuration via a $CONTROL topic. See the readme in dynamic-security for more information. ## Examples / Add properties This is an **example** plugin that demonstrates adding MQTT v5 properties to messages, and how to get client information. ## Examples / Authenticate by IP address This is an **example** plugin that demonstrates a basic authentication callback that allows clients based on their IP address. Password based authentication is preferred over this very simple type of access control. ## Examples / Client lifetime stats This is an **example** plugin that collects counts of how long client sessions last, in different time buckets of 0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1k, 2k, 5k, 10k, 20k, 50k, 100k, 200k, 500k, 1M, 2M, 5M, 10M, 20M, 50M, 100M, 200M, 500M seconds. It periodically publishes the counts at `$SYS/broker/client/lifetimes/`. ## Examples / Client properties This is an **example** plugin that demonstrates some of the functions for retrieving client information such as client id and username. ## Examples / Connection state This is an **example** plugin to demonstrate the use of the connect and disconnect events. It publishes messages to $SYS/broker/connection/client//state for every client that connects to the broker, to indicate the connection state of that client. ## Examples / Deferred authentication This is an **example** plugin to demonstrate how a plugin can carry out delayed basic authentication. This method should be used where the plugin sends an authentication request to an external server so that if there is a delay in getting a response it does not block the broker. The plugin may spawn extra threads to handle the authentication requests, but the call to `mosquitto_complete_basic_auth()` must happen in the main Mosquitto thread. ## Examples / Message timestamp This is an **example** plugin to demonstrate how it is possible to attach MQTT v5 properties to messages after they have been received, and before they are sent on to subscribers. This plugin attaches a user-property property to each message which contains the ISO-8601 timestamp of the time the message was received by the broker. This means it is possible for MQTT v5 clients to see how old a retained message is, for example. ## Examples / Payload modification This is an **example** plugin to demonstrate how it is possible to modify the payload of messages after they have been received, and before they are sent on to subscribers. If you are considering using this feature, you should be very certain you have verified the payload is the correct format before modifying it. This plugin adds the text string "hello " to the beginning of each payload, so with anything other than simple plain text messages it will corrupt the payload contents. ## Examples / Payload size stats This is an **example** plugin that collects counts of payload message sizes, in time buckets of 0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1k, 2k, 5k, 10k, 20k, 50k, 100k, 200k, 500k, 1M, 2M, 5M, 10M, 20M, 50M, 100M, 200M, 500M bytes. It periodically publishes the counts at `$SYS/broker/publish/sizes/`. ## Examples / Print IP on publish This is an **example** plugin that prints out client ID and IP address of any client that publishes on a particular topic. ## Examples / Topic modification This is an **example** plugin to demonstrate how it is possible to modify the topic of messages after they have been received, and before they are sent on to subscribers. This plugin removes the `/uplink` end part of topics that match the pattern `device/+/data/uplink`, so devices publishing to `device/0001/data/uplink` will effectively be publishing to `device/0001/data`. ## Examples / Wildcard temp This is an **example** plugin that denies access to the `#` subscription topic only. This prevents clients from discovering which topics are active and reduces outgoing bandwidth. If clients connect with username `wildcard` and subscribes to `#` they will be allowed 20 seconds of access, after which the subscription will be silently removed. ================================================ FILE: plugins/acl-file/CMakeLists.txt ================================================ set(PLUGIN_NAME mosquitto_acl_file) set(SRCLIST acl_check.c acl_parse.c plugin.c ) set(INCLIST ${mosquitto_SOURCE_DIR}/src) set(LINKLIST libmosquitto_common) add_mosquitto_plugin("${PLUGIN_NAME}" "${SRCLIST}" "${INCLIST}" "${LINKLIST}") ================================================ FILE: plugins/acl-file/Makefile ================================================ R=../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_acl_file LOCAL_CFLAGS+= LOCAL_CPPFLAGS+=-I${R}/src LOCAL_LDFLAGS+= LOCAL_LIBADD+=${LIBMOSQ_COMMON} # Objects for this plugin only, built from source in this directory OBJS = \ acl_check.o \ acl_parse.o \ plugin.o # Objects from e.g. the common directory that are not in this directory OBJS_EXTERNAL = all : binary include ${R}/plugins/plugin.mk ================================================ FILE: plugins/acl-file/acl_check.c ================================================ /* Copyright (c) 2011-2021 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 "acl_file.h" #include "mosquitto.h" int acl_file__check(int event, void *event_data, void *userdata) { struct mosquitto_evt_acl_check *ed = event_data; struct acl__user *acl_user; struct acl__entry *acl_root; bool result; struct acl_file_data *data = userdata; const char *clientid; const char *username; UNUSED(event); // FIXME 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. */ } clientid = mosquitto_client_id(ed->client); username = mosquitto_client_username(ed->client); if(!data->acl_file && !data->acl_users && !data->acl_patterns){ return MOSQ_ERR_PLUGIN_IGNORE; } if(username){ HASH_FIND(hh, data->acl_users, username, strlen(username), acl_user); }else{ acl_user = &data->acl_anon; } if(!acl_user && !data->acl_patterns){ return MOSQ_ERR_ACL_DENIED; } if(acl_user){ acl_root = acl_user->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 = data->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(username && strpbrk(username, "+#")){ mosquitto_log_printf(MOSQ_LOG_NOTICE, "ACL denying access to client with dangerous username \"%s\"", username); return MOSQ_ERR_ACL_DENIED; } if(clientid && strpbrk(clientid, "+#")){ mosquitto_log_printf(MOSQ_LOG_NOTICE, "ACL denying access to client with dangerous client id \"%s\"", clientid); return MOSQ_ERR_ACL_DENIED; } } /* Loop through all pattern ACLs. ACL denial patterns are iterated over first. */ if(!clientid){ return MOSQ_ERR_ACL_DENIED; } while(acl_root){ if(acl_root->ucount && !username){ acl_root = acl_root->next; continue; } if(mosquitto_topic_matches_sub_with_pattern(acl_root->topic, ed->topic, clientid, username, &result)){ return MOSQ_ERR_ACL_DENIED; } 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; } ================================================ FILE: plugins/acl-file/acl_parse.c ================================================ /* Copyright (c) 2011-2021 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 "mosquitto.h" #include "acl_file.h" static int acl__add_to_user(struct acl__user *acl_user, const char *topic, int access) { struct acl__entry *acl; acl = mosquitto_calloc(1, sizeof(struct acl__entry)); if(!acl){ return MOSQ_ERR_NOMEM; } acl->access = access; acl->topic = mosquitto_strdup(topic); if(!acl->topic){ return MOSQ_ERR_NOMEM; } /* Add acl to user acl list */ if(access == MOSQ_ACL_NONE){ /* Put "deny" acls at front of the list */ DL_PREPEND(acl_user->acl, acl); }else{ DL_APPEND(acl_user->acl, acl); } return MOSQ_ERR_SUCCESS; } static struct acl__user *acl__find_or_create_user(struct acl_file_data *data, const char *user, unsigned user_hashv) { if(user == NULL){ return &data->acl_anon; }else{ struct acl__user *acl_user=NULL; HASH_FIND_BYHASHVALUE(hh, data->acl_users, user, strlen(user), user_hashv, acl_user); if(!acl_user){ acl_user = mosquitto_calloc(1, sizeof(struct acl__user)); if(!acl_user){ return NULL; } if(user){ acl_user->username = mosquitto_strdup(user); if(!acl_user->username){ mosquitto_FREE(acl_user); return NULL; } } HASH_ADD_KEYPTR(hh, data->acl_users, acl_user->username, strlen(acl_user->username), acl_user); } return acl_user; } } static int acl__add(struct acl_file_data *data, const char *user, unsigned user_hashv, const char *topic, int access) { struct acl__user *acl_user=NULL; if(!data || !topic){ return MOSQ_ERR_INVAL; } acl_user = acl__find_or_create_user(data, user, user_hashv); if(!acl_user){ return MOSQ_ERR_NOMEM; } return acl__add_to_user(acl_user, topic, access); } static int acl__add_pattern(struct acl_file_data *data, const char *topic, int access) { struct acl__entry *acl, *acl_tail; char *local_topic; char *s; if(!data| !topic){ return MOSQ_ERR_INVAL; } local_topic = mosquitto_strdup(topic); if(!local_topic){ return MOSQ_ERR_NOMEM; } acl = mosquitto_malloc(sizeof(struct acl__entry)); 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){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Warning: ACL pattern '%s' does not contain '%%c' or '%%u'.", topic); } if(data->acl_patterns){ acl_tail = data->acl_patterns; if(access == MOSQ_ACL_NONE){ /* Put "deny" acls at front of the list */ acl->next = acl_tail; data->acl_patterns = acl; }else{ while(acl_tail->next){ acl_tail = acl_tail->next; } acl_tail->next = acl; } }else{ data->acl_patterns = acl; } return MOSQ_ERR_SUCCESS; } int acl_file__parse(struct acl_file_data *data) { 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; unsigned user_hashv = 0; if(!data){ return MOSQ_ERR_INVAL; } if(!data->acl_file){ return MOSQ_ERR_SUCCESS; } buf = mosquitto_calloc((size_t)buflen, 1); if(buf == NULL){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } aclfptr = mosquitto_fopen(data->acl_file, "rt", true); if(!aclfptr){ mosquitto_FREE(buf); mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Unable to open acl_file \"%s\".", data->acl_file); return MOSQ_ERR_UNKNOWN; } /* topic [read|write] * user */ while(mosquitto_fgets(&buf, &buflen, aclfptr)){ slen = strlen(buf); while(slen > 0 && isspace((unsigned char)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){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Empty topic in acl_file \"%s\".", data->acl_file); rc = MOSQ_ERR_INVAL; break; } token = strtok_r(NULL, "", &saveptr); if(token){ topic = mosquitto_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{ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Invalid topic access type \"%s\" in acl_file \"%s\".", access_s, data->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){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Invalid ACL topic \"%s\" in acl_file \"%s\".", topic, data->acl_file); rc = MOSQ_ERR_INVAL; break; } if(topic_pattern == 0){ rc = acl__add(data, user, user_hashv, topic, access); }else{ rc = acl__add_pattern(data, topic, access); } if(rc){ break; } }else if(!strcmp(token, "user")){ token = strtok_r(NULL, "", &saveptr); if(token){ token = mosquitto_trimblanks(token); if(slen == 0){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Missing username in acl_file \"%s\".", data->acl_file); rc = MOSQ_ERR_INVAL; break; } mosquitto_FREE(user); user = mosquitto_strdup(token); if(!user){ rc = MOSQ_ERR_NOMEM; break; } HASH_VALUE(user, strlen(user), user_hashv); }else{ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Missing username in acl_file \"%s\".", data->acl_file); rc = MOSQ_ERR_INVAL; break; } }else{ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Invalid line in acl_file \"%s\": %s.", data->acl_file, buf); rc = MOSQ_ERR_INVAL; break; } } } mosquitto_FREE(buf); mosquitto_FREE(user); fclose(aclfptr); return rc; } static void acl__free_entries(struct acl__entry *entry) { while(entry){ struct acl__entry *next = entry->next; mosquitto_FREE(entry->topic); mosquitto_FREE(entry); entry = next; } } void acl_file__cleanup(struct acl_file_data *data) { struct acl__user *user, *user_tmp; HASH_ITER(hh, data->acl_users, user, user_tmp){ HASH_DELETE(hh, data->acl_users, user); mosquitto_FREE(user->username); acl__free_entries(user->acl); mosquitto_FREE(user); } acl__free_entries(data->acl_anon.acl); data->acl_anon.acl = NULL; acl__free_entries(data->acl_patterns); data->acl_patterns = NULL; } int acl_file__reload(int event, void *event_data, void *userdata) { struct acl_file_data *data = userdata; UNUSED(event); UNUSED(event_data); acl_file__cleanup(data); return acl_file__parse(data); } ================================================ FILE: plugins/acl-file/plugin.c ================================================ /* Copyright (c) 2023 Cedalo Gmbh */ #include "config.h" #include #include #include "mosquitto.h" #include "acl_file.h" #define PLUGIN_NAME "acl-file" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static int handle_options(struct acl_file_data *data, struct mosquitto_opt *options, int option_count) { for(int i=0; iacl_file); data->acl_file = mosquitto_strdup(options[i].value); if(!data->acl_file){ return MOSQ_ERR_NOMEM; } }else{ mosquitto_log_printf(MOSQ_LOG_ERR, PLUGIN_NAME ": Error: Unknown option '%s'.", options[i].key); return MOSQ_ERR_INVAL; } } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *options, int option_count) { struct acl_file_data *data; int rc; UNUSED(options); UNUSED(option_count); data = mosquitto_calloc(1, sizeof(struct acl_file_data)); if(!data){ return MOSQ_ERR_NOMEM; } *user_data = data; mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, NULL); rc = handle_options(data, options, option_count); if(rc){ return rc; } rc = acl_file__parse(data); if(rc){ return rc; } rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_ACL_CHECK, acl_file__check, NULL, data); if(rc){ return rc; } rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_RELOAD, acl_file__reload, NULL, data); if(rc){ return rc; } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *options, int option_count) { struct acl_file_data *data = user_data; UNUSED(options); UNUSED(option_count); mosquitto_callback_unregister(mosq_pid, MOSQ_EVT_ACL_CHECK, acl_file__check, NULL); mosquitto_callback_unregister(mosq_pid, MOSQ_EVT_RELOAD, acl_file__reload, NULL); acl_file__cleanup(data); mosquitto_FREE(data->acl_file); mosquitto_FREE(data); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/acl-file/test.conf ================================================ listener 1883 allow_anonymous true plugin ./mosquitto_acl_file.so plugin_opt_acl_file ./acl_file ================================================ FILE: plugins/acl-file/test.sh ================================================ VG="valgrind --log-file=vglog" ${VG} ../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/dynamic-security/CMakeLists.txt ================================================ if(WITH_TLS) set(PLUGIN_NAME mosquitto_dynamic_security) set(SRCLIST acl.c auth.c clients.c clientlist.c config.c config_init.c control.c default_acl.c details.c dynamic_security.h groups.c grouplist.c ../../common/json_help.c ../../common/json_help.h kicklist.c plugin.c roles.c rolelist.c tick.c ) set(INCLIST "${CJSON_INCLUDE_DIRS}" "${mosquitto_SOURCE_DIR}/lib" "${mosquitto_SOURCE_DIR}/src" ) set(LINKLIST libmosquitto_common cJSON OpenSSL::SSL ) if(ARGON2_FOUND) set(LINKLIST "${LINKLIST}" argon2 ) endif() add_mosquitto_plugin("${PLUGIN_NAME}" "${SRCLIST}" "${INCLIST}" "${LINKLIST}") endif() ================================================ FILE: plugins/dynamic-security/Makefile ================================================ R=../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_dynamic_security LOCAL_CFLAGS+= LOCAL_CPPFLAGS+=-I${R}/lib/ -I${R}/src/ -I${R}/plugins/common LOCAL_LIBADD+=-lcjson -lm $(LIBMOSQ_COMMON) LOCAL_LDFLAGS+= WITH_PW_CACHE:=yes ifeq ($(WITH_PW_CACHE),yes) LOCAL_CPPFLAGS+=-DWITH_PW_CACHE endif OBJS = \ acl.o \ auth.o \ clients.o \ clientlist.o \ config.o \ config_init.o \ control.o \ default_acl.o \ details.o \ groups.o \ grouplist.o \ kicklist.o \ plugin.o \ roles.o \ rolelist.o \ tick.o OBJS_EXTERNAL = \ json_help.o EXTRA_DEPS:=dynamic_security.h ifeq ($(WITH_TLS),yes) ALL_DEPS:= binary else ALL_DEPS:= endif all : ${ALL_DEPS} json_help.o : ${R}/common/json_help.c ${R}/common/json_help.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ include ${R}/plugins/plugin.mk ================================================ FILE: plugins/dynamic-security/README.md ================================================ # 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 setClientId username clientId ``` ## 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/# ``` ================================================ FILE: plugins/dynamic-security/acl.c ================================================ /* Copyright (c) 2020-2021 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 "dynamic_security.h" typedef int (*MOSQ_FUNC_acl_check)(struct dynsec__data *data, struct mosquitto_evt_acl_check *, struct dynsec__rolelist *); /* FIXME - CACHE! */ /* ################################################################ * # * # ACL check - publish broker to client * # * ################################################################ */ static int acl_check_publish_c_recv(struct dynsec__data *data, 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; const char *clientid, *username; UNUSED(data); clientid = mosquitto_client_id(ed->client); username = mosquitto_client_username(ed->client); HASH_ITER(hh, base_rolelist, rolelist, rolelist_tmp){ HASH_ITER(hh, rolelist->role->acls.publish_c_recv, acl, acl_tmp){ if(mosquitto_topic_matches_sub_with_pattern(acl->topic, ed->topic, clientid, username, &result)){ return MOSQ_ERR_ACL_DENIED; } 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 dynsec__data *data, 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; const char *clientid, *username; UNUSED(data); clientid = mosquitto_client_id(ed->client); username = mosquitto_client_username(ed->client); HASH_ITER(hh, base_rolelist, rolelist, rolelist_tmp){ HASH_ITER(hh, rolelist->role->acls.publish_c_send, acl, acl_tmp){ if(mosquitto_topic_matches_sub_with_pattern(acl->topic, ed->topic, clientid, username, &result)){ return MOSQ_ERR_ACL_DENIED; } 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 dynsec__data *data, 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; bool result; const char *clientid, *username; bool has_wildcard; UNUSED(data); len = strlen(ed->topic); has_wildcard = (strpbrk(ed->topic, "+#") != NULL); clientid = mosquitto_client_id(ed->client); username = mosquitto_client_username(ed->client); HASH_ITER(hh, base_rolelist, rolelist, rolelist_tmp){ if(rolelist->role->allow_wildcard_subs == false && has_wildcard == true){ return MOSQ_ERR_ACL_DENIED; } 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(mosquitto_sub_matches_acl_with_pattern(acl->topic, ed->topic, clientid, username, &result)){ /* Invalid input, so deny */ return MOSQ_ERR_ACL_DENIED; } if(result){ 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 dynsec__data *data, 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; bool result; const char *clientid, *username; UNUSED(data); len = strlen(ed->topic); clientid = mosquitto_client_id(ed->client); username = mosquitto_client_username(ed->client); 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(mosquitto_sub_matches_acl_with_pattern(acl->topic, ed->topic, clientid, username, &result)){ /* Invalid input, so deny */ return MOSQ_ERR_ACL_DENIED; } if(result){ 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 dynsec__data *data, 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(data, username); if(client == NULL){ return MOSQ_ERR_PLUGIN_DEFER; } /* Client roles */ rc = check(data, ed, client->rolelist); if(rc != MOSQ_ERR_NOT_FOUND){ return rc; } HASH_ITER(hh, client->grouplist, grouplist, grouplist_tmp){ rc = check(data, ed, grouplist->group->rolelist); if(rc != MOSQ_ERR_NOT_FOUND){ return rc; } } }else if(data->anonymous_group){ /* If we have a group for anonymous users, use that for checking. */ rc = check(data, ed, data->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; struct dynsec__data *data = userdata; 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(data, event_data, acl_check_subscribe, data->default_access.subscribe); break; case MOSQ_ACL_UNSUBSCRIBE: return acl_check(data, event_data, acl_check_unsubscribe, data->default_access.unsubscribe); break; case MOSQ_ACL_WRITE: /* Client to broker */ return acl_check(data, event_data, acl_check_publish_c_send, data->default_access.publish_c_send); break; case MOSQ_ACL_READ: return acl_check(data, event_data, acl_check_publish_c_recv, data->default_access.publish_c_recv); break; default: return MOSQ_ERR_PLUGIN_DEFER; } return MOSQ_ERR_PLUGIN_DEFER; } ================================================ FILE: plugins/dynamic-security/auth.c ================================================ /* Copyright (c) 2020-2021 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" /* ################################################################ * # * # Username/password check * # * ################################################################ */ int dynsec_auth__basic_auth_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_basic_auth *ed = event_data; struct dynsec__data *data = userdata; struct dynsec__client *client; const char *clientid; UNUSED(event); UNUSED(userdata); if(ed->username == NULL || ed->password == NULL){ return MOSQ_ERR_PLUGIN_DEFER; } client = dynsec_clients__find(data, 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(mosquitto_pw_verify(client->pw, ed->password) == MOSQ_ERR_SUCCESS){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } }else{ return MOSQ_ERR_PLUGIN_DEFER; } } ================================================ FILE: plugins/dynamic-security/clientlist.c ================================================ /* Copyright (c) 2020-2021 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 "dynamic_security.h" #include "json_help.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__data *data, struct dynsec__clientlist *base_clientlist) { struct dynsec__clientlist *clientlist, *clientlist_tmp; HASH_ITER(hh, base_clientlist, clientlist, clientlist_tmp){ dynsec_kicklist__add(data, clientlist->client->username); } } 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); } } ================================================ FILE: plugins/dynamic-security/clients.c ================================================ /* Copyright (c) 2020-2021 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 "dynamic_security.h" #include "json_help.h" struct connection_array_context { const char *username; cJSON *j_connections; }; /* ################################################################ * # * # Function declarations * # * ################################################################ */ static int dynsec__remove_client_from_all_groups(struct dynsec__data *data, const char *username); static void client__remove_all_roles(struct dynsec__client *client); /* ################################################################ * # * # Local variables * # * ################################################################ */ /* ################################################################ * # * # 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(struct dynsec__data *data, const char *username) { struct dynsec__client *client = NULL; if(username){ HASH_FIND(hh, data->clients, username, strlen(username), client); } return client; } static void client__free_item(struct dynsec__data *data, struct dynsec__client *client) { struct dynsec__client *client_found; if(client == NULL){ return; } client_found = dynsec_clients__find(data, client->username); if(client_found){ HASH_DEL(data->clients, client_found); } dynsec_rolelist__cleanup(&client->rolelist); dynsec__remove_client_from_all_groups(data, client->username); mosquitto_pw_cleanup(client->pw); mosquitto_free(client->text_name); mosquitto_free(client->text_description); mosquitto_free(client->clientid); mosquitto_free(client); } void dynsec_clients__cleanup(struct dynsec__data *data) { struct dynsec__client *client, *client_tmp; HASH_ITER(hh, data->clients, client, client_tmp){ client__free_item(data, client); } } /* ################################################################ * # * # Config file load and save * # * ################################################################ */ int dynsec_clients__config_load(struct dynsec__data *data, cJSON *tree) { cJSON *j_clients, *j_client = NULL, *j_roles, *j_role; struct dynsec__client *client; struct dynsec__role *role; int priority; 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){ /* Username */ const char *username; if(json_get_string(j_client, "username", &username, false) != MOSQ_ERR_SUCCESS){ continue; } size_t username_len = strlen(username); if(username_len == 0){ continue; } if(dynsec_clients__find(data, username)){ continue; } client = mosquitto_calloc(1, sizeof(struct dynsec__client) + username_len + 1); if(client == NULL){ return MOSQ_ERR_NOMEM; } strncpy(client->username, username, username_len); bool disabled; if(json_get_bool(j_client, "disabled", &disabled, false, false) == MOSQ_ERR_SUCCESS){ client->disabled = disabled; } const char *password; if(json_get_string(j_client, "encoded_password", &password, false) == MOSQ_ERR_SUCCESS){ if(!client->pw && mosquitto_pw_new(&client->pw, MOSQ_PW_DEFAULT)){ return MOSQ_ERR_NOMEM; } if(mosquitto_pw_decode(client->pw, password) == MOSQ_ERR_NOMEM){ return MOSQ_ERR_NOMEM; } }else{ /* sha512-pbkdf2 only */ int iterations; const char *salt; json_get_int(j_client, "iterations", &iterations, true, 0); if(json_get_string(j_client, "salt", &salt, false) == MOSQ_ERR_SUCCESS && json_get_string(j_client, "password", &password, false) == MOSQ_ERR_SUCCESS && iterations > 0){ char buf[1024]; if(!client->pw && mosquitto_pw_new(&client->pw, MOSQ_PW_SHA512_PBKDF2)){ return MOSQ_ERR_NOMEM; } snprintf(buf, sizeof(buf), "$7$%d$%s$%s", iterations, salt, password); mosquitto_pw_decode(client->pw, buf); }else{ mosquitto_pw_set_valid(client->pw, false); } } /* Client id */ const char *clientid; if(json_get_string(j_client, "clientid", &clientid, false) == MOSQ_ERR_SUCCESS){ client->clientid = mosquitto_strdup(clientid); if(client->clientid == NULL){ mosquitto_free(client); continue; } } /* Text name */ const char *textname; if(json_get_string(j_client, "textname", &textname, false) == MOSQ_ERR_SUCCESS){ client->text_name = mosquitto_strdup(textname); if(client->text_name == NULL){ mosquitto_free(client->clientid); mosquitto_free(client); continue; } } /* Text description */ const char *textdescription; if(json_get_string(j_client, "textdescription", &textdescription, false) == MOSQ_ERR_SUCCESS){ client->text_description = mosquitto_strdup(textdescription); if(client->text_description == NULL){ mosquitto_free(client->text_name); mosquitto_free(client->clientid); 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)){ const char *rolename; if(json_get_string(j_role, "rolename", &rolename, false) == MOSQ_ERR_SUCCESS){ json_get_int(j_role, "priority", &priority, true, -1); if(priority > PRIORITY_MAX){ priority = PRIORITY_MAX; } if(priority < -PRIORITY_MAX){ priority = -PRIORITY_MAX; } role = dynsec_roles__find(data, rolename); dynsec_rolelist__client_add(client, role, priority); } } } } HASH_ADD(hh, data->clients, username, username_len, client); } } HASH_SORT(data->clients, client_cmp); return 0; } static int dynsec__config_add_clients(struct dynsec__data *data, cJSON *j_clients) { struct dynsec__client *client, *client_tmp; cJSON *j_client, *j_roles; HASH_ITER(hh, data->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(mosquitto_pw_is_valid(client->pw)){ if(cJSON_AddStringToObject(j_client, "encoded_password", mosquitto_pw_get_encoded(client->pw)) == NULL){ return 1; } } } return 0; } int dynsec_clients__config_save(struct dynsec__data *data, cJSON *tree) { cJSON *j_clients; if((j_clients = cJSON_AddArrayToObject(tree, "clients")) == NULL){ return 1; } if(dynsec__config_add_clients(data, j_clients)){ return 1; } return 0; } int dynsec_clients__process_create(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username, *password, *clientid = NULL; const char *text_name, *text_description; struct dynsec__client *client; int rc; cJSON *j_groups, *j_group; int priority; const char *admin_clientid, *admin_username; size_t username_len; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } username_len = strlen(username); if(username_len == 0){ mosquitto_control_command_reply(cmd, "Empty username"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)username_len) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Username not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "password", &password, true) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing password"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "clientid", &clientid, true) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing client id"); return MOSQ_ERR_INVAL; } if(clientid && mosquitto_validate_utf8(clientid, (int)strlen(clientid)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Client ID not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "textname", &text_name, true) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing textname"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "textdescription", &text_description, true) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing textdescription"); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(data, username); if(client){ mosquitto_control_command_reply(cmd, "Client already exists"); return MOSQ_ERR_SUCCESS; } client = mosquitto_calloc(1, sizeof(struct dynsec__client) + username_len + 1); if(client == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } strncpy(client->username, username, username_len); if(text_name){ client->text_name = mosquitto_strdup(text_name); if(client->text_name == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); client__free_item(data, client); return MOSQ_ERR_NOMEM; } } if(text_description){ client->text_description = mosquitto_strdup(text_description); if(client->text_description == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); client__free_item(data, client); return MOSQ_ERR_NOMEM; } } if(password){ if(mosquitto_pw_new(&client->pw, MOSQ_PW_DEFAULT) || mosquitto_pw_hash_encoded(client->pw, password) ){ mosquitto_control_command_reply(cmd, "Internal error"); client__free_item(data, client); return MOSQ_ERR_NOMEM; } } if(clientid && strlen(clientid) > 0){ client->clientid = mosquitto_strdup(clientid); if(client->clientid == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); client__free_item(data, client); return MOSQ_ERR_NOMEM; } } rc = dynsec_rolelist__load_from_json(data, cmd->j_command, &client->rolelist); if(rc == MOSQ_ERR_SUCCESS || rc == ERR_LIST_NOT_FOUND){ }else if(rc == MOSQ_ERR_NOT_FOUND){ mosquitto_control_command_reply(cmd, "Role not found"); client__free_item(data, client); return MOSQ_ERR_INVAL; }else{ if(rc == MOSQ_ERR_INVAL){ mosquitto_control_command_reply(cmd, "'roles' not an array or missing/invalid rolename"); }else{ mosquitto_control_command_reply(cmd, "Internal error"); } client__free_item(data, client); return MOSQ_ERR_INVAL; } /* Must add user before groups, otherwise adding groups will fail */ HASH_ADD_INORDER(hh, data->clients, username, username_len, client, client_cmp); j_groups = cJSON_GetObjectItem(cmd->j_command, "groups"); if(j_groups && cJSON_IsArray(j_groups)){ cJSON_ArrayForEach(j_group, j_groups){ if(cJSON_IsObject(j_group)){ const char *groupname; if(json_get_string(j_group, "groupname", &groupname, false) == MOSQ_ERR_SUCCESS){ json_get_int(j_group, "priority", &priority, true, -1); if(priority > PRIORITY_MAX){ priority = PRIORITY_MAX; } rc = dynsec_groups__add_client(data, username, groupname, priority, false); if(rc == ERR_GROUP_NOT_FOUND){ mosquitto_control_command_reply(cmd, "Group not found"); client__free_item(data, client); return MOSQ_ERR_INVAL; }else if(rc != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Internal error"); client__free_item(data, client); return MOSQ_ERR_INVAL; } } } } } dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username; struct dynsec__client *client; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(data, username); if(client){ dynsec__remove_client_from_all_groups(data, username); client__remove_all_roles(client); client__free_item(data, client); dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); /* Enforce any changes */ dynsec_kicklist__add(data, username); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | deleteClient | username=%s", admin_clientid, admin_username, username); return MOSQ_ERR_SUCCESS; }else{ mosquitto_control_command_reply(cmd, "Client not found"); return MOSQ_ERR_SUCCESS; } } int dynsec_clients__process_disable(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username; struct dynsec__client *client; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Username not valid UTF-8"); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(data, username); if(client == NULL){ mosquitto_control_command_reply(cmd, "Client not found"); return MOSQ_ERR_SUCCESS; } client->disabled = true; dynsec_kicklist__add(data, username); dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username; struct dynsec__client *client; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Username not valid UTF-8"); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(data, username); if(client == NULL){ mosquitto_control_command_reply(cmd, "Client not found"); return MOSQ_ERR_SUCCESS; } client->disabled = false; dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username, *clientid; char *clientid_heap = NULL; struct dynsec__client *client; size_t slen; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Username not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "clientid", &clientid, true) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing client ID"); return MOSQ_ERR_INVAL; } if(clientid){ slen = strlen(clientid); if(mosquitto_validate_utf8(clientid, (int)slen) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Client ID not valid UTF-8"); return MOSQ_ERR_INVAL; } if(slen > 0){ clientid_heap = mosquitto_strdup(clientid); if(clientid_heap == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } }else{ clientid_heap = NULL; } } client = dynsec_clients__find(data, username); if(client == NULL){ mosquitto_free(clientid_heap); mosquitto_control_command_reply(cmd, "Client not found"); return MOSQ_ERR_SUCCESS; } mosquitto_free(client->clientid); client->clientid = clientid_heap; dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); /* Enforce any changes */ dynsec_kicklist__add(data, username); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(!client->pw){ if(mosquitto_pw_new(&client->pw, MOSQ_PW_DEFAULT)){ return MOSQ_ERR_NOMEM; } } return mosquitto_pw_hash_encoded(client->pw, password); } int dynsec_clients__process_set_password(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username, *password; struct dynsec__client *client; int rc; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Username not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "password", &password, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing password"); return MOSQ_ERR_INVAL; } if(strlen(password) == 0){ mosquitto_control_command_reply(cmd, "Empty password is not allowed"); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(data, username); if(client == NULL){ mosquitto_control_command_reply(cmd, "Client not found"); return MOSQ_ERR_SUCCESS; } rc = client__set_password(client, password); if(rc == MOSQ_ERR_SUCCESS){ dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); /* Enforce any changes */ dynsec_kicklist__add(data, username); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | setClientPassword | username=%s | password=******", admin_clientid, admin_username, username); }else{ mosquitto_control_command_reply(cmd, "Internal error"); } 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username; char *clientid = NULL; const char *password = NULL; char *text_name = NULL, *text_description = NULL; bool have_clientid = false, have_text_name = false, have_text_description = false, have_rolelist = false, have_password = false; struct dynsec__client *client; struct dynsec__group *group; struct dynsec__rolelist *rolelist = NULL; const char *str; int rc; int priority; cJSON *j_group, *j_groups; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Username not valid UTF-8"); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(data, username); if(client == NULL){ mosquitto_control_command_reply(cmd, "Client not found"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "clientid", &str, false) == MOSQ_ERR_SUCCESS){ have_clientid = true; if(str && strlen(str) > 0){ clientid = mosquitto_strdup(str); if(clientid == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); rc = MOSQ_ERR_NOMEM; goto error; } }else{ clientid = NULL; } } if(json_get_string(cmd->j_command, "password", &password, false) == MOSQ_ERR_SUCCESS){ if(strlen(password) > 0){ have_password = true; } } if(json_get_string(cmd->j_command, "textname", &str, false) == MOSQ_ERR_SUCCESS){ have_text_name = true; text_name = mosquitto_strdup(str); if(text_name == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); rc = MOSQ_ERR_NOMEM; goto error; } } if(json_get_string(cmd->j_command, "textdescription", &str, false) == MOSQ_ERR_SUCCESS){ have_text_description = true; text_description = mosquitto_strdup(str); if(text_description == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); rc = MOSQ_ERR_NOMEM; goto error; } } rc = dynsec_rolelist__load_from_json(data, cmd->j_command, &rolelist); if(rc == MOSQ_ERR_SUCCESS){ have_rolelist = true; }else if(rc == ERR_LIST_NOT_FOUND){ /* There was no list in the JSON, so no modification */ }else if(rc == MOSQ_ERR_NOT_FOUND){ mosquitto_control_command_reply(cmd, "Role not found"); rc = MOSQ_ERR_INVAL; goto error; }else{ if(rc == MOSQ_ERR_INVAL){ mosquitto_control_command_reply(cmd, "'roles' not an array or missing/invalid rolename"); }else{ mosquitto_control_command_reply(cmd, "Internal error"); } rc = MOSQ_ERR_INVAL; goto error; } j_groups = cJSON_GetObjectItem(cmd->j_command, "groups"); if(j_groups && cJSON_IsArray(j_groups)){ /* Iterate through list to check all groups are valid */ cJSON_ArrayForEach(j_group, j_groups){ if(cJSON_IsObject(j_group)){ const char *groupname; if(json_get_string(j_group, "groupname", &groupname, false) == MOSQ_ERR_SUCCESS){ group = dynsec_groups__find(data, groupname); if(group == NULL){ mosquitto_control_command_reply(cmd, "'groups' contains an object with a 'groupname' that does not exist"); rc = MOSQ_ERR_INVAL; goto error; } }else{ mosquitto_control_command_reply(cmd, "'groups' contains an object with an invalid 'groupname'"); rc = MOSQ_ERR_INVAL; goto error; } } } dynsec__remove_client_from_all_groups(data, username); cJSON_ArrayForEach(j_group, j_groups){ if(cJSON_IsObject(j_group)){ const char *groupname; if(json_get_string(j_group, "groupname", &groupname, false) == MOSQ_ERR_SUCCESS){ json_get_int(j_group, "priority", &priority, true, -1); if(priority > PRIORITY_MAX){ priority = PRIORITY_MAX; } dynsec_groups__add_client(data, username, groupname, priority, false); } } } } if(have_password){ /* FIXME - This is the one call that will result in modification on internal error - note that groups have already been modified */ rc = client__set_password(client, password); if(rc != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Internal error"); mosquitto_kick_client_by_username(username, false); /* If this fails we have the situation that the password is set as * invalid, but the config isn't saved, so restarting the broker * *now* will mean the client can log in again. This might be * "good", but is inconsistent, so save the config to be * consistent. */ dynsec__config_batch_save(data); rc = MOSQ_ERR_NOMEM; goto error; } } if(have_clientid){ mosquitto_free(client->clientid); client->clientid = clientid; } if(have_text_name){ mosquitto_free(client->text_name); client->text_name = text_name; } if(have_text_description){ mosquitto_free(client->text_description); client->text_description = text_description; } if(have_rolelist){ client__remove_all_roles(client); client__add_new_roles(client, rolelist); dynsec_rolelist__cleanup(&rolelist); } dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); /* Enforce any changes */ dynsec_kicklist__add(data, username); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | modifyClient | username=%s", admin_clientid, admin_username, username); return MOSQ_ERR_SUCCESS; error: mosquitto_free(clientid); mosquitto_free(text_name); mosquitto_free(text_description); dynsec_rolelist__cleanup(&rolelist); return rc; } static int dynsec__remove_client_from_all_groups(struct dynsec__data *data, const char *username) { struct dynsec__grouplist *grouplist, *grouplist_tmp; struct dynsec__client *client; client = dynsec_clients__find(data, username); if(client){ HASH_ITER(hh, client->grouplist, grouplist, grouplist_tmp){ dynsec_groups__remove_client(data, username, grouplist->group->groupname, false); } } return MOSQ_ERR_SUCCESS; } static int dynsec__add_client_address(const struct mosquitto *client, void *context_ptr) { struct connection_array_context *functor_context = (struct connection_array_context *)context_ptr; const char *username = mosquitto_client_username(client); if((username == NULL && functor_context->username == NULL) || (username && functor_context->username && !strcmp(functor_context->username, username))){ cJSON *j_connection = cJSON_CreateObject(); const char *address; if(!j_connection){ return MOSQ_ERR_NOMEM; } if((address = mosquitto_client_address(client)) && !cJSON_AddStringToObject(j_connection, "address", address)){ cJSON_Delete(j_connection); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(functor_context->j_connections, j_connection); } return MOSQ_ERR_SUCCESS; } static cJSON *dynsec_connections__all_to_json(const char *username, const char *clientid) { struct connection_array_context functor_context = { username, cJSON_CreateArray()}; if(functor_context.j_connections == NULL){ return NULL; } if(clientid){ const struct mosquitto *client = mosquitto_client(clientid); if(client && dynsec__add_client_address(client, &functor_context) != MOSQ_ERR_SUCCESS){ cJSON_Delete(functor_context.j_connections); return NULL; } }else{ if(mosquitto_apply_on_all_clients(&dynsec__add_client_address, &functor_context) != MOSQ_ERR_SUCCESS){ cJSON_Delete(functor_context.j_connections); return NULL; } } return functor_context.j_connections; } static cJSON *add_client_to_json(struct dynsec__client *client, bool verbose) { cJSON *j_client = NULL; if(verbose){ cJSON *j_groups, *j_roles, *j_connections; 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); j_connections = dynsec_connections__all_to_json(client->username, client->clientid); if(j_connections == NULL){ cJSON_Delete(j_client); return NULL; } cJSON_AddItemToObject(j_client, "connections", j_connections); }else{ j_client = cJSON_CreateString(client->username); if(j_client == NULL){ return NULL; } } return j_client; } int dynsec_clients__process_get(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username; struct dynsec__client *client; cJSON *tree, *j_client, *j_data; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Username not valid UTF-8"); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(data, username); if(client == NULL){ mosquitto_control_command_reply(cmd, "Client not found"); return MOSQ_ERR_SUCCESS; } tree = cJSON_CreateObject(); if(tree == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } if(cJSON_AddStringToObject(tree, "command", "getClient") == NULL || (j_data = cJSON_AddObjectToObject(tree, "data")) == NULL || (cmd->correlation_data && cJSON_AddStringToObject(tree, "correlationData", cmd->correlation_data) == NULL) ){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } j_client = add_client_to_json(client, true); if(j_client == NULL){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(j_data, "client", j_client); cJSON_AddItemToArray(cmd->j_responses, tree); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { 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(cmd->j_command, "verbose", &verbose, true, false); json_get_int(cmd->j_command, "count", &count, true, -1); json_get_int(cmd->j_command, "offset", &offset, true, 0); tree = cJSON_CreateObject(); if(tree == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); 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, data->clients)) == NULL || (j_clients = cJSON_AddArrayToObject(j_data, "clients")) == NULL || (cmd->correlation_data && cJSON_AddStringToObject(tree, "correlationData", cmd->correlation_data) == NULL) ){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } i = 0; HASH_ITER(hh, data->clients, client, client_tmp){ if(i>=offset){ j_client = add_client_to_json(client, verbose); if(j_client == NULL){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_clients, j_client); if(count >= 0){ count--; if(count <= 0){ break; } } } i++; } cJSON_AddItemToArray(cmd->j_responses, tree); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username, *rolename; struct dynsec__client *client; struct dynsec__role *role; int priority; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Username not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing rolename"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Role name not valid UTF-8"); return MOSQ_ERR_INVAL; } json_get_int(cmd->j_command, "priority", &priority, true, -1); if(priority > PRIORITY_MAX){ priority = PRIORITY_MAX; } client = dynsec_clients__find(data, username); if(client == NULL){ mosquitto_control_command_reply(cmd, "Client not found"); return MOSQ_ERR_SUCCESS; } role = dynsec_roles__find(data, rolename); if(role == NULL){ mosquitto_control_command_reply(cmd, "Role not found"); return MOSQ_ERR_SUCCESS; } if(dynsec_rolelist__client_add(client, role, priority) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_UNKNOWN; } dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); /* Enforce any changes */ dynsec_kicklist__add(data, username); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username, *rolename; struct dynsec__client *client; struct dynsec__role *role; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Username not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing rolename"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Role name not valid UTF-8"); return MOSQ_ERR_INVAL; } client = dynsec_clients__find(data, username); if(client == NULL){ mosquitto_control_command_reply(cmd, "Client not found"); return MOSQ_ERR_SUCCESS; } role = dynsec_roles__find(data, rolename); if(role == NULL){ mosquitto_control_command_reply(cmd, "Role not found"); return MOSQ_ERR_SUCCESS; } dynsec_rolelist__client_remove(client, role); dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); /* Enforce any changes */ dynsec_kicklist__add(data, username); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | removeClientRole | username=%s | rolename=%s", admin_clientid, admin_username, username, rolename); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/dynamic-security/config.c ================================================ /* Copyright (c) 2020-2021 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 "dynamic_security.h" #include "json_help.h" static int dynsec__general_config_load(struct dynsec__data *data, cJSON *tree) { cJSON *j_default_access; json_get_int64(tree, "changeIndex", &data->changeindex, true, 0); j_default_access = cJSON_GetObjectItem(tree, "defaultACLAccess"); if(j_default_access && cJSON_IsObject(j_default_access)){ json_get_bool(j_default_access, ACL_TYPE_PUB_C_SEND, &data->default_access.publish_c_send, true, false); json_get_bool(j_default_access, ACL_TYPE_PUB_C_RECV, &data->default_access.publish_c_recv, true, false); json_get_bool(j_default_access, ACL_TYPE_SUB_GENERIC, &data->default_access.subscribe, true, false); json_get_bool(j_default_access, ACL_TYPE_UNSUB_GENERIC, &data->default_access.unsubscribe, true, false); } return MOSQ_ERR_SUCCESS; } static int dynsec__general_config_save(struct dynsec__data *data, cJSON *tree) { cJSON *j_default_access; cJSON_AddIntToObject(tree, "changeIndex", data->changeindex); j_default_access = cJSON_CreateObject(); if(j_default_access == NULL){ return 1; } cJSON_AddItemToObject(tree, "defaultACLAccess", j_default_access); if(cJSON_AddBoolToObject(j_default_access, ACL_TYPE_PUB_C_SEND, data->default_access.publish_c_send) == NULL || cJSON_AddBoolToObject(j_default_access, ACL_TYPE_PUB_C_RECV, data->default_access.publish_c_recv) == NULL || cJSON_AddBoolToObject(j_default_access, ACL_TYPE_SUB_GENERIC, data->default_access.subscribe) == NULL || cJSON_AddBoolToObject(j_default_access, ACL_TYPE_UNSUB_GENERIC, data->default_access.unsubscribe) == NULL ){ return 1; } return MOSQ_ERR_SUCCESS; } int dynsec__config_from_json(struct dynsec__data *data, const char *json_str) { cJSON *tree; tree = cJSON_Parse(json_str); if(tree == NULL){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error loading Dynamic security plugin config: File is not valid JSON."); return 1; } if(dynsec__general_config_load(data, tree) || dynsec_roles__config_load(data, tree) || dynsec_clients__config_load(data, tree) || dynsec_groups__config_load(data, tree) ){ cJSON_Delete(tree); return 1; } cJSON_Delete(tree); return 0; } int dynsec__config_load(struct dynsec__data *data) { FILE *fptr; long flen_l; size_t flen; char *json_str; int rc; /* Load from file */ fptr = fopen(data->config_file, "rb"); if(fptr == NULL){ /* Attempt to initialise a new config file */ if(dynsec__config_init(data) == MOSQ_ERR_SUCCESS){ /* If it works, try to open the file again */ fptr = fopen(data->config_file, "rb"); } if(fptr == NULL){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error loading Dynamic security plugin config: File is not readable - check permissions."); return MOSQ_ERR_UNKNOWN; } } fseek(fptr, 0, SEEK_END); flen_l = ftell(fptr); if(flen_l < 0){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error loading Dynamic security plugin config: %s", strerror(errno)); fclose(fptr); return 1; }else if(flen_l == 0){ fclose(fptr); return 0; } flen = (size_t)flen_l; fseek(fptr, 0, SEEK_SET); json_str = mosquitto_calloc(flen+1, sizeof(char)); if(json_str == NULL){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Out of memory."); fclose(fptr); return 1; } if(fread(json_str, 1, flen, fptr) != flen){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Error loading Dynamic security plugin config: Unable to read file contents.\n"); mosquitto_free(json_str); fclose(fptr); return 1; } fclose(fptr); rc = dynsec__config_from_json(data, json_str); free(json_str); return rc; } char *dynsec__config_to_json(struct dynsec__data *data) { cJSON *tree; char *json_str; tree = cJSON_CreateObject(); if(tree == NULL){ return NULL; } if(dynsec__general_config_save(data, tree) || dynsec_clients__config_save(data, tree) || dynsec_groups__config_save(data, tree) || dynsec_roles__config_save(data, tree)){ cJSON_Delete(tree); return NULL; } /* Print json to string */ json_str = cJSON_Print(tree); cJSON_Delete(tree); return json_str; } void dynsec__log_write_error(const char *msg) { mosquitto_log_printf(MOSQ_LOG_ERR, "Error saving Dynamic security plugin config: %s", msg); } int dynsec__write_json_config(FILE *fptr, void *user_data) { struct dynsec__data *data = (struct dynsec__data *)user_data; char *json_str; size_t json_str_len; int rc = MOSQ_ERR_SUCCESS; json_str = dynsec__config_to_json(data); if(json_str == NULL){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error saving Dynamic security plugin config: Out of memory.\n"); return MOSQ_ERR_NOMEM; } json_str_len = strlen(json_str); if(fwrite(json_str, 1, json_str_len, fptr) != json_str_len){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error saving Dynamic security plugin config: Cannot write whole config (%ld) bytes to file %s", json_str_len, data->config_file); rc = MOSQ_ERR_UNKNOWN; } mosquitto_free(json_str); return rc; } void dynsec__config_batch_save(struct dynsec__data *data) { data->changeindex++; data->need_save = true; } void dynsec__config_save(struct dynsec__data *data) { data->need_save = false; mosquitto_write_file(data->config_file, true, &dynsec__write_json_config, data, &dynsec__log_write_error); } ================================================ FILE: plugins/dynamic-security/config_init.c ================================================ /* Copyright (c) 2021 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 "dynamic_security.h" #include "json_help.h" const char pw_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=_+[]{}@#~,./<>?"; static int add_default_access(cJSON *j_tree) { cJSON *j_default_access; j_default_access = cJSON_AddObjectToObject(j_tree, "defaultACLAccess"); if(j_default_access == NULL){ return MOSQ_ERR_NOMEM; } /* 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 ){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } static int get_password_from_init_file(struct dynsec__data *data, char **pw) { FILE *fptr; char buf[1024]; int pos; if(data->password_init_file == NULL){ *pw = NULL; return MOSQ_ERR_SUCCESS; } fptr = mosquitto_fopen(data->password_init_file, "rt", true); if(!fptr){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Unable to get initial password from '%s', file not accessible.", data->password_init_file); return MOSQ_ERR_INVAL; } if(!fgets(buf, sizeof(buf), fptr)){ fclose(fptr); mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Unable to get initial password from '%s', file empty.", data->password_init_file); return MOSQ_ERR_INVAL; } fclose(fptr); pos = (int)strlen(buf)-1; while(pos >= 0 && isspace((unsigned char)buf[pos])){ buf[pos] = '\0'; pos--; } if(strlen(buf) == 0){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Unable to get initial password from '%s', password is empty.", data->password_init_file); return MOSQ_ERR_INVAL; } *pw = strdup(buf); if(!*pw){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Unable to get initial password from '%s', out of memory.", data->password_init_file); return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } /* Generate a password for the admin user * * Uses passwords from, in order: * * * The password defined in the plugin_opt_password_init_file file * * The contents of the MOSQUITTO_DYNSEC_PASSWORD environment variable * * Randomly generated passwords for "admin", "user", stored in plain text at '.pw' */ static int generate_password(struct dynsec__data *data, cJSON *j_client, char **password) { struct mosquitto_pw *pw; char *pwenv; if(data->init_mode == dpwim_file){ if(get_password_from_init_file(data, password)){ return MOSQ_ERR_INVAL; } }else if(data->init_mode == dpwim_env){ pwenv = getenv("MOSQUITTO_DYNSEC_PASSWORD"); if(pwenv == NULL || strlen(pwenv) < 12){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Not generating dynsec config, MOSQUITTO_DYNSEC_PASSWORD must be at least 12 characters."); return MOSQ_ERR_INVAL; } *password = strdup(pwenv); if(*password == NULL){ return MOSQ_ERR_NOMEM; } }else{ unsigned char vb; unsigned long v; size_t len; const size_t pwlen = 20; *password = malloc(pwlen+1); if(*password == NULL){ return MOSQ_ERR_NOMEM; } len = sizeof(pw_chars)-1; for(size_t i=0; i= (RAND_MAX - (RAND_MAX % len))); (*password)[i] = pw_chars[v%len]; } (*password)[pwlen] = '\0'; } if(mosquitto_pw_new(&pw, MOSQ_PW_DEFAULT) != MOSQ_ERR_SUCCESS || mosquitto_pw_hash_encoded(pw, *password) != MOSQ_ERR_SUCCESS || cJSON_AddStringToObject(j_client, "encoded_password", mosquitto_pw_get_encoded(pw)) == NULL){ mosquitto_pw_cleanup(pw); free(*password); *password = NULL; return MOSQ_ERR_UNKNOWN; } mosquitto_pw_cleanup(pw); return MOSQ_ERR_SUCCESS; } static int client_role_add(cJSON *j_roles, const char *rolename) { cJSON *j_role; j_role = cJSON_CreateObject(); if(j_role == NULL){ return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_roles, j_role); if(cJSON_AddStringToObject(j_role, "rolename", rolename) == NULL){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } static int client_add_admin(struct dynsec__data *data, FILE *pwfile, cJSON *j_clients) { cJSON *j_client, *j_roles; char *password = NULL; j_client = cJSON_CreateObject(); if(j_client == NULL){ return MOSQ_ERR_NOMEM; } if(generate_password(data, j_client, &password)){ cJSON_Delete(j_client); return MOSQ_ERR_UNKNOWN; } cJSON_AddItemToArray(j_clients, j_client); if(cJSON_AddStringToObject(j_client, "username", "admin") == NULL || cJSON_AddStringToObject(j_client, "textname", "Admin user") == NULL || (j_roles = cJSON_AddArrayToObject(j_client, "roles")) == NULL ){ cJSON_Delete(j_client); free(password); return MOSQ_ERR_NOMEM; } if(client_role_add(j_roles, "super-admin") || client_role_add(j_roles, "sys-observe") || client_role_add(j_roles, "topic-observe")){ free(password); return MOSQ_ERR_NOMEM; } if(data->init_mode == dpwim_random){ fprintf(pwfile, "admin %s\n", password); } free(password); return MOSQ_ERR_SUCCESS; } static int client_add_user(struct dynsec__data *data, FILE *pwfile, cJSON *j_clients) { cJSON *j_client, *j_roles; char *password = NULL; if(data->init_mode != dpwim_random){ return MOSQ_ERR_SUCCESS; } j_client = cJSON_CreateObject(); if(j_client == NULL){ return MOSQ_ERR_NOMEM; } if(generate_password(data, j_client, &password)){ cJSON_Delete(j_client); return MOSQ_ERR_UNKNOWN; } if(cJSON_AddStringToObject(j_client, "username", "democlient") == NULL || cJSON_AddStringToObject(j_client, "textname", "Demonstration client with full read/write access to the '#' topic hierarchy.") == NULL || (j_roles = cJSON_AddArrayToObject(j_client, "roles")) == NULL ){ free(password); cJSON_Delete(j_client); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_clients, j_client); if(client_role_add(j_roles, "client")){ free(password); return MOSQ_ERR_NOMEM; } fprintf(pwfile, "democlient %s\n", password); free(password); return MOSQ_ERR_SUCCESS; } static int add_clients(struct dynsec__data *data, cJSON *j_tree) { cJSON *j_clients; char *pwfile; size_t len; FILE *fptr = NULL; if(data->init_mode == dpwim_random){ len = strlen(data->config_file) + 5; pwfile = malloc(len); if(pwfile == NULL){ return MOSQ_ERR_NOMEM; } snprintf(pwfile, len, "%s.pw", data->config_file); fptr = mosquitto_fopen(pwfile, "wb", true); free(pwfile); if(fptr == NULL){ return MOSQ_ERR_UNKNOWN; } } j_clients = cJSON_AddArrayToObject(j_tree, "clients"); if(j_clients == NULL){ if(fptr){ fclose(fptr); } return MOSQ_ERR_NOMEM; } if(client_add_admin(data, fptr, j_clients) || client_add_user(data, fptr, j_clients) ){ if(fptr){ fclose(fptr); } return MOSQ_ERR_NOMEM; } if(fptr){ fclose(fptr); } return MOSQ_ERR_SUCCESS; } static int group_add_anon(cJSON *j_groups) { cJSON *j_group; j_group = cJSON_CreateObject(); if(j_group == NULL){ return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_groups, j_group); if(cJSON_AddStringToObject(j_group, "groupname", "unauthenticated") == NULL || cJSON_AddStringToObject(j_group, "textname", "Unauthenticated group") == NULL || cJSON_AddStringToObject(j_group, "textdescription", "If unauthenticated access is allowed, this group can be used to define roles for clients that connect without a password.") == NULL || cJSON_AddArrayToObject(j_group, "roles") == NULL ){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } static int add_groups(cJSON *j_tree) { cJSON *j_groups; j_groups = cJSON_AddArrayToObject(j_tree, "groups"); if(j_groups == NULL){ return MOSQ_ERR_NOMEM; } return group_add_anon(j_groups); } static int acl_add(cJSON *j_acls, const char *acltype, const char *topic, int priority, bool allow) { cJSON *j_acl; j_acl = cJSON_CreateObject(); cJSON_AddItemToArray(j_acls, j_acl); if(cJSON_AddStringToObject(j_acl, "acltype", acltype) == NULL || cJSON_AddStringToObject(j_acl, "topic", topic) == NULL || cJSON_AddNumberToObject(j_acl, "priority", priority) == NULL || cJSON_AddBoolToObject(j_acl, "allow", allow) == NULL ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } static int add_role_with_full_permission(cJSON *j_roles, const char *role_name, const char *text_description, const char *topic_pattern) { cJSON *j_role, *j_acls; j_role = cJSON_CreateObject(); if(j_role == NULL){ return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_roles, j_role); if(cJSON_AddStringToObject(j_role, "rolename", role_name) == NULL || cJSON_AddStringToObject(j_role, "textdescription", text_description) == NULL || (j_acls = cJSON_AddArrayToObject(j_role, "acls")) == NULL){ return MOSQ_ERR_NOMEM; } if(acl_add(j_acls, "publishClientSend", topic_pattern, 0, true) || acl_add(j_acls, "publishClientReceive", topic_pattern, 0, true) || acl_add(j_acls, "subscribePattern", topic_pattern, 0, true) || acl_add(j_acls, "unsubscribePattern", topic_pattern, 0, true)){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } static int role_add_sys_notify(cJSON *j_roles) { cJSON *j_role, *j_acls; j_role = cJSON_CreateObject(); if(j_role == NULL){ return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_roles, j_role); if(cJSON_AddStringToObject(j_role, "rolename", "sys-notify") == NULL || cJSON_AddStringToObject(j_role, "textdescription", "Allow bridges to publish connection state messages.") == NULL || (j_acls = cJSON_AddArrayToObject(j_role, "acls")) == NULL ){ return MOSQ_ERR_NOMEM; } if(acl_add(j_acls, "publishClientSend", "$SYS/broker/connection/%c/state", 0, true) ){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } static int role_add_sys_observe(cJSON *j_roles) { cJSON *j_role, *j_acls; j_role = cJSON_CreateObject(); if(j_role == NULL){ return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_roles, j_role); if(cJSON_AddStringToObject(j_role, "rolename", "sys-observe") == NULL || cJSON_AddStringToObject(j_role, "textdescription", "Observe the $SYS topic hierarchy.") == NULL || (j_acls = cJSON_AddArrayToObject(j_role, "acls")) == NULL ){ return MOSQ_ERR_NOMEM; } if(acl_add(j_acls, "publishClientReceive", "$SYS/#", 0, true) || acl_add(j_acls, "subscribePattern", "$SYS/#", 0, true) ){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } static int role_add_topic_observe(cJSON *j_roles) { cJSON *j_role, *j_acls; j_role = cJSON_CreateObject(); if(j_role == NULL){ return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_roles, j_role); if(cJSON_AddStringToObject(j_role, "rolename", "topic-observe") == NULL || cJSON_AddStringToObject(j_role, "textdescription", "Read only access to the full application topic hierarchy.") == NULL || (j_acls = cJSON_AddArrayToObject(j_role, "acls")) == NULL ){ return MOSQ_ERR_NOMEM; } if(acl_add(j_acls, "publishClientReceive", "#", 0, true) || acl_add(j_acls, "subscribePattern", "#", 0, true) || acl_add(j_acls, "unsubscribePattern", "#", 0, true) ){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } static int add_roles(cJSON *j_tree) { cJSON *j_roles; j_roles = cJSON_AddArrayToObject(j_tree, "roles"); if(j_roles == NULL){ return MOSQ_ERR_NOMEM; } if(add_role_with_full_permission(j_roles, "client", "Read/write access to the full application topic hierarchy.", "#") || add_role_with_full_permission(j_roles, "broker-admin", "Grants access to administer general broker configuration.", "$CONTROL/broker/#") || add_role_with_full_permission(j_roles, "dynsec-admin", "Grants access to administer clients/groups/roles.", "$CONTROL/dynamic-security/#") || add_role_with_full_permission(j_roles, "super-admin", "Grants access to administer all kind of broker controls", "$CONTROL/#") || role_add_sys_notify(j_roles) || role_add_sys_observe(j_roles) || role_add_topic_observe(j_roles)){ return MOSQ_ERR_NOMEM; } return MOSQ_ERR_SUCCESS; } int dynsec__config_init(struct dynsec__data *data) { FILE *fptr; cJSON *j_tree; char *json_str; mosquitto_log_printf(MOSQ_LOG_INFO, "Dynamic security plugin config not found, generating a default config."); if(data->password_init_file){ mosquitto_log_printf(MOSQ_LOG_INFO, " Using admin password from file '%s'", data->password_init_file); data->init_mode = dpwim_file; }else if(getenv("MOSQUITTO_DYNSEC_PASSWORD")){ mosquitto_log_printf(MOSQ_LOG_INFO, " Using admin password from MOSQUITTO_DYNSEC_PASSWORD environment variable"); data->init_mode = dpwim_env; }else{ mosquitto_log_printf(MOSQ_LOG_INFO, " Generated passwords are at %s.pw", data->config_file); data->init_mode = dpwim_random; } j_tree = cJSON_CreateObject(); if(j_tree == NULL){ return MOSQ_ERR_NOMEM; } if(add_default_access(j_tree) != MOSQ_ERR_SUCCESS || add_clients(data, j_tree) != MOSQ_ERR_SUCCESS || add_groups(j_tree) != MOSQ_ERR_SUCCESS || add_roles(j_tree) != MOSQ_ERR_SUCCESS || cJSON_AddStringToObject(j_tree, "anonymousGroup", "unauthenticated") == NULL ){ cJSON_Delete(j_tree); return MOSQ_ERR_NOMEM; } json_str = cJSON_Print(j_tree); cJSON_Delete(j_tree); if(json_str == NULL){ return MOSQ_ERR_NOMEM; } fptr = mosquitto_fopen(data->config_file, "wb", true); if(fptr == NULL){ return MOSQ_ERR_UNKNOWN; } fprintf(fptr, "%s", json_str); free(json_str); fclose(fptr); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/dynamic-security/control.c ================================================ /* Copyright (c) 2020-2021 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 "dynamic_security.h" #include "json_help.h" #define RESPONSE_TOPIC "$CONTROL/dynamic-security/v1/response" static int dynsec__handle_command(struct mosquitto_control_cmd *cmd, void *userdata) { struct dynsec__data *data = userdata; int rc = MOSQ_ERR_SUCCESS; /* Plugin */ if(!strcasecmp(cmd->command_name, "setDefaultACLAccess")){ rc = dynsec__process_set_default_acl_access(data, cmd); }else if(!strcasecmp(cmd->command_name, "getDefaultACLAccess")){ rc = dynsec__process_get_default_acl_access(data, cmd); }else if(!strcasecmp(cmd->command_name, "getDetails")){ rc = dynsec_details__process_get(data, cmd); /* Clients */ }else if(!strcasecmp(cmd->command_name, "createClient")){ rc = dynsec_clients__process_create(data, cmd); }else if(!strcasecmp(cmd->command_name, "deleteClient")){ rc = dynsec_clients__process_delete(data, cmd); }else if(!strcasecmp(cmd->command_name, "getClient")){ rc = dynsec_clients__process_get(data, cmd); }else if(!strcasecmp(cmd->command_name, "listClients")){ rc = dynsec_clients__process_list(data, cmd); }else if(!strcasecmp(cmd->command_name, "modifyClient")){ rc = dynsec_clients__process_modify(data, cmd); }else if(!strcasecmp(cmd->command_name, "setClientPassword")){ rc = dynsec_clients__process_set_password(data, cmd); }else if(!strcasecmp(cmd->command_name, "setClientId")){ rc = dynsec_clients__process_set_id(data, cmd); }else if(!strcasecmp(cmd->command_name, "addClientRole")){ rc = dynsec_clients__process_add_role(data, cmd); }else if(!strcasecmp(cmd->command_name, "removeClientRole")){ rc = dynsec_clients__process_remove_role(data, cmd); }else if(!strcasecmp(cmd->command_name, "enableClient")){ rc = dynsec_clients__process_enable(data, cmd); }else if(!strcasecmp(cmd->command_name, "disableClient")){ rc = dynsec_clients__process_disable(data, cmd); /* Groups */ }else if(!strcasecmp(cmd->command_name, "addGroupClient")){ rc = dynsec_groups__process_add_client(data, cmd); }else if(!strcasecmp(cmd->command_name, "createGroup")){ rc = dynsec_groups__process_create(data, cmd); }else if(!strcasecmp(cmd->command_name, "deleteGroup")){ rc = dynsec_groups__process_delete(data, cmd); }else if(!strcasecmp(cmd->command_name, "getGroup")){ rc = dynsec_groups__process_get(data, cmd); }else if(!strcasecmp(cmd->command_name, "listGroups")){ rc = dynsec_groups__process_list(data, cmd); }else if(!strcasecmp(cmd->command_name, "modifyGroup")){ rc = dynsec_groups__process_modify(data, cmd); }else if(!strcasecmp(cmd->command_name, "removeGroupClient")){ rc = dynsec_groups__process_remove_client(data, cmd); }else if(!strcasecmp(cmd->command_name, "addGroupRole")){ rc = dynsec_groups__process_add_role(data, cmd); }else if(!strcasecmp(cmd->command_name, "removeGroupRole")){ rc = dynsec_groups__process_remove_role(data, cmd); }else if(!strcasecmp(cmd->command_name, "setAnonymousGroup")){ rc = dynsec_groups__process_set_anonymous_group(data, cmd); }else if(!strcasecmp(cmd->command_name, "getAnonymousGroup")){ rc = dynsec_groups__process_get_anonymous_group(data, cmd); /* Roles */ }else if(!strcasecmp(cmd->command_name, "createRole")){ rc = dynsec_roles__process_create(data, cmd); }else if(!strcasecmp(cmd->command_name, "getRole")){ rc = dynsec_roles__process_get(data, cmd); }else if(!strcasecmp(cmd->command_name, "listRoles")){ rc = dynsec_roles__process_list(data, cmd); }else if(!strcasecmp(cmd->command_name, "modifyRole")){ rc = dynsec_roles__process_modify(data, cmd); }else if(!strcasecmp(cmd->command_name, "deleteRole")){ rc = dynsec_roles__process_delete(data, cmd); }else if(!strcasecmp(cmd->command_name, "addRoleACL")){ rc = dynsec_roles__process_add_acl(data, cmd); }else if(!strcasecmp(cmd->command_name, "removeRoleACL")){ rc = dynsec_roles__process_remove_acl(data, cmd); /* Unknown */ }else{ mosquitto_control_command_reply(cmd, "Unknown command"); rc = MOSQ_ERR_INVAL; } return rc; } int dynsec_control_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_control *ed = event_data; struct dynsec__data *data = userdata; int rc; UNUSED(event); data->need_save = false; rc = mosquitto_control_generic_callback(ed, RESPONSE_TOPIC, userdata, dynsec__handle_command); if(rc == MOSQ_ERR_SUCCESS && data->need_save){ dynsec__config_save(data); } return rc; } ================================================ FILE: plugins/dynamic-security/default_acl.c ================================================ /* Copyright (c) 2020-2021 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 "dynamic_security.h" #include "json_help.h" int dynsec__process_set_default_acl_access(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { cJSON *j_actions, *j_action; bool allow; const char *admin_clientid, *admin_username; const char *acltype; j_actions = cJSON_GetObjectItem(cmd->j_command, "acls"); if(j_actions == NULL || !cJSON_IsArray(j_actions)){ mosquitto_control_command_reply(cmd, "Missing/invalid actions array"); return MOSQ_ERR_INVAL; } admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); cJSON_ArrayForEach(j_action, j_actions){ if(json_get_string(j_action, "acltype", &acltype, false) == MOSQ_ERR_SUCCESS && json_get_bool(j_action, "allow", &allow, false, false) == MOSQ_ERR_SUCCESS){ if(!strcasecmp(acltype, ACL_TYPE_PUB_C_SEND)){ data->default_access.publish_c_send = allow; }else if(!strcasecmp(acltype, ACL_TYPE_PUB_C_RECV)){ data->default_access.publish_c_recv = allow; }else if(!strcasecmp(acltype, ACL_TYPE_SUB_GENERIC)){ data->default_access.subscribe = allow; }else if(!strcasecmp(acltype, ACL_TYPE_UNSUB_GENERIC)){ data->default_access.unsubscribe = allow; } mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | setDefaultACLAccess | acltype=%s | allow=%s", admin_clientid, admin_username, acltype, allow?"true":"false"); } } dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); return MOSQ_ERR_SUCCESS; } int dynsec__process_get_default_acl_access(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { cJSON *tree, *jtmp, *j_data, *j_acls, *j_acl; const char *admin_clientid, *admin_username; tree = cJSON_CreateObject(); if(tree == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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", data->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", data->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", data->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", data->default_access.unsubscribe) == NULL ){ goto internal_error; } cJSON_AddItemToArray(cmd->j_responses, tree); if(cmd->correlation_data){ jtmp = cJSON_AddStringToObject(tree, "correlationData", cmd->correlation_data); if(jtmp == NULL){ goto internal_error; } } return MOSQ_ERR_SUCCESS; internal_error: cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } ================================================ FILE: plugins/dynamic-security/details.c ================================================ /* Copyright (c) 2025 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 "dynamic_security.h" #include "json_help.h" int dynsec_details__process_get(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { cJSON *tree, *j_data; const char *admin_clientid, *admin_username; tree = cJSON_CreateObject(); if(tree == NULL || cJSON_AddStringToObject(tree, "command", "getDetails") == NULL || (j_data = cJSON_AddObjectToObject(tree, "data")) == NULL || (cmd->correlation_data && cJSON_AddStringToObject(tree, "correlationData", cmd->correlation_data) == NULL) || cJSON_AddIntToObject(j_data, "clientCount", (int)HASH_CNT(hh, data->clients)) == NULL || cJSON_AddIntToObject(j_data, "groupCount", (int)HASH_CNT(hh, data->groups)) == NULL || cJSON_AddIntToObject(j_data, "roleCount", (int)HASH_CNT(hh, data->roles)) == NULL || cJSON_AddIntToObject(j_data, "changeIndex", data->changeindex) == NULL ){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(cmd->j_responses, tree); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | getDetails", admin_clientid, admin_username); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/dynamic-security/dynamic_security.h ================================================ #ifndef DYNAMIC_SECURITY_H #define DYNAMIC_SECURITY_H /* Copyright (c) 2020-2021 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" #define PRIORITY_MAX 100000 /* ################################################################ * # * # 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; struct dynsec__role *role; int priority; char rolename[]; }; struct dynsec__kicklist { struct dynsec__kicklist *next, *prev; char username[]; }; struct dynsec__client { UT_hash_handle hh; struct mosquitto_pw *pw; struct dynsec__rolelist *rolelist; struct dynsec__grouplist *grouplist; char *clientid; char *text_name; char *text_description; bool disabled; char username[]; }; struct dynsec__group { UT_hash_handle hh; struct dynsec__rolelist *rolelist; struct dynsec__clientlist *clientlist; char *text_name; char *text_description; char groupname[]; }; struct dynsec__acl { UT_hash_handle hh; int priority; bool allow; char topic[]; }; 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 *text_name; char *text_description; bool allow_wildcard_subs; char rolename[]; }; struct dynsec__acl_default_access { bool publish_c_send; bool publish_c_recv; bool subscribe; bool unsubscribe; }; enum dynsec_pw_init_mode { dpwim_file = 1, dpwim_env = 2, dpwim_random = 3, }; struct dynsec__data { char *config_file; char *password_init_file; struct dynsec__client *clients; struct dynsec__group *groups; struct dynsec__role *roles; struct dynsec__group *anonymous_group; struct dynsec__kicklist *kicklist; struct dynsec__acl_default_access default_access; int64_t changeindex; int init_mode; bool need_save; }; /* ################################################################ * # * # Plugin Functions * # * ################################################################ */ int dynsec__config_init(struct dynsec__data *data); void dynsec__config_save(struct dynsec__data *data); void dynsec__config_batch_save(struct dynsec__data *data); int dynsec__config_load(struct dynsec__data *data); char *dynsec__config_to_json(struct dynsec__data *data); int dynsec__config_from_json(struct dynsec__data *data, const char *json_str); void dynsec__command_reply(cJSON *j_responses, struct mosquitto *context, const char *command, const char *error, const char *correlation_data); int dynsec_control_callback(int event, void *event_data, void *userdata); /* ################################################################ * # * # ACL Functions * # * ################################################################ */ int dynsec__acl_check_callback(int event, void *event_data, void *userdata); int dynsec__process_set_default_acl_access(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec__process_get_default_acl_access(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); /* ################################################################ * # * # Auth Functions * # * ################################################################ */ 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(struct dynsec__data *data); int dynsec_clients__config_load(struct dynsec__data *data, cJSON *tree); int dynsec_clients__config_save(struct dynsec__data *data, cJSON *tree); int dynsec_clients__process_add_role(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_clients__process_create(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_clients__process_delete(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_clients__process_disable(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_clients__process_enable(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_clients__process_get(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_clients__process_list(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_clients__process_modify(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_clients__process_remove_role(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_clients__process_set_id(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_clients__process_set_password(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); struct dynsec__client *dynsec_clients__find(struct dynsec__data *data, 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__data *data, struct dynsec__clientlist *base_clientlist); /* ################################################################ * # * # Group Functions * # * ################################################################ */ void dynsec_groups__cleanup(struct dynsec__data *data); int dynsec_groups__config_load(struct dynsec__data *data, cJSON *tree); int dynsec_groups__add_client(struct dynsec__data *data, const char *username, const char *groupname, int priority, bool update_config); int dynsec_groups__config_save(struct dynsec__data *data, cJSON *tree); int dynsec_groups__process_add_client(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_groups__process_add_role(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_groups__process_create(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_groups__process_delete(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_groups__process_get(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_groups__process_list(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_groups__process_modify(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_groups__process_remove_client(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_groups__process_remove_role(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_groups__process_get_anonymous_group(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_groups__process_set_anonymous_group(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_groups__remove_client(struct dynsec__data *data, const char *username, const char *groupname, bool update_config); struct dynsec__group *dynsec_groups__find(struct dynsec__data *data, 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(struct dynsec__data *data); int dynsec_roles__config_load(struct dynsec__data *data, cJSON *tree); int dynsec_roles__config_save(struct dynsec__data *data, cJSON *tree); int dynsec_roles__process_add_acl(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_roles__process_create(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_roles__process_delete(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_roles__process_get(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_roles__process_list(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_roles__process_modify(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); int dynsec_roles__process_remove_acl(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); struct dynsec__role *dynsec_roles__find(struct dynsec__data *data, 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(struct dynsec__data *data, 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); /* ################################################################ * # * # Kick List Functions * # * ################################################################ */ int dynsec_kicklist__add(struct dynsec__data *data, const char *username); void dynsec_kicklist__kick(struct dynsec__data *data); int dynsec__tick_callback(int event, void *event_data, void *userdata); void dynsec_kicklist__cleanup(struct dynsec__data *data); /* ################################################################ * # * # Change Index Functions * # * ################################################################ */ int dynsec_details__process_get(struct dynsec__data *data, struct mosquitto_control_cmd *cmd); #endif ================================================ FILE: plugins/dynamic-security/grouplist.c ================================================ /* Copyright (c) 2020-2021 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 "dynamic_security.h" #include "json_help.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); } } ================================================ FILE: plugins/dynamic-security/groups.c ================================================ /* Copyright (c) 2020-2021 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 "dynamic_security.h" #include "json_help.h" /* ################################################################ * # * # Plugin global variables * # * ################################################################ */ /* ################################################################ * # * # 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 * # * ################################################################ */ /* ################################################################ * # * # Utility functions * # * ################################################################ */ static void group__kick_all(struct dynsec__data *data, struct dynsec__group *group) { if(group == data->anonymous_group){ dynsec_kicklist__add(data, NULL); } dynsec_clientlist__kick_all(data, 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(struct dynsec__data *data, const char *groupname) { struct dynsec__group *group = NULL; if(groupname){ HASH_FIND(hh, data->groups, groupname, strlen(groupname), group); } return group; } static void group__free_item(struct dynsec__data *data, struct dynsec__group *group) { struct dynsec__group *found_group = NULL; if(group == NULL){ return; } found_group = dynsec_groups__find(data, group->groupname); if(found_group){ HASH_DEL(data->groups, found_group); } dynsec__remove_all_clients_from_group(group); mosquitto_free(group->text_name); mosquitto_free(group->text_description); dynsec_rolelist__cleanup(&group->rolelist); mosquitto_free(group); } int dynsec_groups__process_add_role(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const 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(cmd->j_command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing groupname"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Group name not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing rolename"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Role name not valid UTF-8"); return MOSQ_ERR_INVAL; } json_get_int(cmd->j_command, "priority", &priority, true, -1); if(priority > PRIORITY_MAX){ priority = PRIORITY_MAX; } if(priority < -PRIORITY_MAX){ priority = -PRIORITY_MAX; } group = dynsec_groups__find(data, groupname); if(group == NULL){ mosquitto_control_command_reply(cmd, "Group not found"); return MOSQ_ERR_SUCCESS; } role = dynsec_roles__find(data, rolename); if(role == NULL){ mosquitto_control_command_reply(cmd, "Role not found"); return MOSQ_ERR_SUCCESS; } admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); rc = dynsec_rolelist__group_add(group, role, priority); if(rc == MOSQ_ERR_SUCCESS){ /* Continue */ }else if(rc == MOSQ_ERR_ALREADY_EXISTS){ mosquitto_control_command_reply(cmd, "Group is already in this role"); return MOSQ_ERR_ALREADY_EXISTS; }else{ mosquitto_control_command_reply(cmd, "Internal error"); 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_batch_save(data); mosquitto_control_command_reply(cmd, NULL); /* Enforce any changes */ group__kick_all(data, group); return MOSQ_ERR_SUCCESS; } void dynsec_groups__cleanup(struct dynsec__data *data) { struct dynsec__group *group, *group_tmp = NULL; HASH_ITER(hh, data->groups, group, group_tmp){ group__free_item(data, group); } data->anonymous_group = NULL; } /* ################################################################ * # * # Config file load * # * ################################################################ */ int dynsec_groups__config_load(struct dynsec__data *data, cJSON *tree) { cJSON *j_groups, *j_group; cJSON *j_clientlist; cJSON *j_roles; const char *groupname; struct dynsec__group *group; struct dynsec__role *role; 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 name */ size_t groupname_len; if(json_get_string(j_group, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ continue; } groupname_len = strlen(groupname); if(groupname_len == 0){ continue; } if(dynsec_groups__find(data, groupname)){ continue; } group = mosquitto_calloc(1, sizeof(struct dynsec__group) + groupname_len + 1); if(group == NULL){ return MOSQ_ERR_NOMEM; } strncpy(group->groupname, groupname, groupname_len+1); /* Text name */ const char *textname; if(json_get_string(j_group, "textname", &textname, false) == MOSQ_ERR_SUCCESS){ if(textname){ group->text_name = mosquitto_strdup(textname); if(group->text_name == NULL){ mosquitto_free(group); continue; } } } /* Text description */ const char *textdescription; if(json_get_string(j_group, "textdescription", &textdescription, false) == MOSQ_ERR_SUCCESS){ if(textdescription){ group->text_description = mosquitto_strdup(textdescription); if(group->text_description == NULL){ mosquitto_free(group->text_name); mosquitto_free(group); continue; } } } /* Roles */ j_roles = cJSON_GetObjectItem(j_group, "roles"); if(j_roles && cJSON_IsArray(j_roles)){ cJSON *j_role; cJSON_ArrayForEach(j_role, j_roles){ if(cJSON_IsObject(j_role)){ const char *rolename; if(json_get_string(j_role, "rolename", &rolename, false) == MOSQ_ERR_SUCCESS){ json_get_int(j_role, "priority", &priority, true, -1); if(priority > PRIORITY_MAX){ priority = PRIORITY_MAX; } if(priority < -PRIORITY_MAX){ priority = -PRIORITY_MAX; } role = dynsec_roles__find(data, rolename); dynsec_rolelist__group_add(group, role, priority); } } } } /* This must go before clients are loaded, otherwise the group won't be found */ HASH_ADD(hh, data->groups, groupname, groupname_len, group); /* Clients */ j_clientlist = cJSON_GetObjectItem(j_group, "clients"); if(j_clientlist && cJSON_IsArray(j_clientlist)){ cJSON *j_client; cJSON_ArrayForEach(j_client, j_clientlist){ if(cJSON_IsObject(j_client)){ const char *username; if(json_get_string(j_client, "username", &username, false) == MOSQ_ERR_SUCCESS){ json_get_int(j_client, "priority", &priority, true, -1); if(priority > PRIORITY_MAX){ priority = PRIORITY_MAX; } if(priority < -PRIORITY_MAX){ priority = -PRIORITY_MAX; } dynsec_groups__add_client(data, username, group->groupname, priority, false); } } } } } } HASH_SORT(data->groups, group_cmp); if(json_get_string(tree, "anonymousGroup", &groupname, false) == MOSQ_ERR_SUCCESS){ data->anonymous_group = dynsec_groups__find(data, groupname); } return 0; } /* ################################################################ * # * # Config load and save * # * ################################################################ */ static int dynsec__config_add_groups(struct dynsec__data *data, cJSON *j_groups) { struct dynsec__group *group, *group_tmp = NULL; cJSON *j_group, *j_clients, *j_roles; HASH_ITER(hh, data->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(struct dynsec__data *data, 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(data, j_groups)){ return 1; } if(data->anonymous_group && cJSON_AddStringToObject(tree, "anonymousGroup", data->anonymous_group->groupname) == NULL){ return 1; } return 0; } int dynsec_groups__process_create(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *groupname, *text_name, *text_description; struct dynsec__group *group = NULL; int rc = MOSQ_ERR_SUCCESS; const char *admin_clientid, *admin_username; size_t groupname_len; if(json_get_string(cmd->j_command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing groupname"); return MOSQ_ERR_INVAL; } groupname_len = strlen(groupname); if(groupname_len == 0){ mosquitto_control_command_reply(cmd, "Empty groupname"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)groupname_len) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Group name not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "textname", &text_name, true) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing textname"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "textdescription", &text_description, true) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing textdescription"); return MOSQ_ERR_INVAL; } group = dynsec_groups__find(data, groupname); if(group){ mosquitto_control_command_reply(cmd, "Group already exists"); return MOSQ_ERR_SUCCESS; } group = mosquitto_calloc(1, sizeof(struct dynsec__group) + groupname_len + 1); if(group == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } strncpy(group->groupname, groupname, groupname_len+1); if(text_name){ group->text_name = mosquitto_strdup(text_name); if(group->text_name == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); group__free_item(data, group); return MOSQ_ERR_NOMEM; } } if(text_description){ group->text_description = mosquitto_strdup(text_description); if(group->text_description == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); group__free_item(data, group); return MOSQ_ERR_NOMEM; } } rc = dynsec_rolelist__load_from_json(data, cmd->j_command, &group->rolelist); if(rc == MOSQ_ERR_SUCCESS || rc == ERR_LIST_NOT_FOUND){ }else if(rc == MOSQ_ERR_NOT_FOUND){ mosquitto_control_command_reply(cmd, "Role not found"); group__free_item(data, group); return MOSQ_ERR_INVAL; }else{ mosquitto_control_command_reply(cmd, "Internal error"); group__free_item(data, group); return MOSQ_ERR_INVAL; } HASH_ADD_INORDER(hh, data->groups, groupname, groupname_len, group, group_cmp); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | createGroup | groupname=%s", admin_clientid, admin_username, groupname); dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); return MOSQ_ERR_SUCCESS; } int dynsec_groups__process_delete(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *groupname; struct dynsec__group *group; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing groupname"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Group name not valid UTF-8"); return MOSQ_ERR_INVAL; } group = dynsec_groups__find(data, groupname); if(group){ if(group == data->anonymous_group){ mosquitto_control_command_reply(cmd, "Deleting the anonymous group is forbidden"); return MOSQ_ERR_INVAL; } /* Enforce any changes */ group__kick_all(data, group); dynsec__remove_all_roles_from_group(group); group__free_item(data, group); dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | deleteGroup | groupname=%s", admin_clientid, admin_username, groupname); return MOSQ_ERR_SUCCESS; }else{ mosquitto_control_command_reply(cmd, "Group not found"); return MOSQ_ERR_SUCCESS; } } int dynsec_groups__add_client(struct dynsec__data *data, 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(data, username); if(client == NULL){ return ERR_USER_NOT_FOUND; } group = dynsec_groups__find(data, 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_batch_save(data); } return MOSQ_ERR_SUCCESS; } int dynsec_groups__process_add_client(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username, *groupname; int rc; int priority; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Username not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing groupname"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Group name not valid UTF-8"); return MOSQ_ERR_INVAL; } json_get_int(cmd->j_command, "priority", &priority, true, -1); if(priority > PRIORITY_MAX){ priority = PRIORITY_MAX; } if(priority < -PRIORITY_MAX){ priority = -PRIORITY_MAX; } rc = dynsec_groups__add_client(data, username, groupname, priority, true); if(rc == MOSQ_ERR_SUCCESS){ admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | addGroupClient | groupname=%s | username=%s | priority=%d", admin_clientid, admin_username, groupname, username, priority); mosquitto_control_command_reply(cmd, NULL); }else if(rc == ERR_USER_NOT_FOUND){ mosquitto_control_command_reply(cmd, "Client not found"); }else if(rc == ERR_GROUP_NOT_FOUND){ mosquitto_control_command_reply(cmd, "Group not found"); }else if(rc == MOSQ_ERR_ALREADY_EXISTS){ mosquitto_control_command_reply(cmd, "Client is already in this group"); }else{ mosquitto_control_command_reply(cmd, "Internal error"); } /* Enforce any changes */ dynsec_kicklist__add(data, username); 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(struct dynsec__data *data, const char *username, const char *groupname, bool update_config) { struct dynsec__client *client; struct dynsec__group *group; client = dynsec_clients__find(data, username); if(client == NULL){ return ERR_USER_NOT_FOUND; } group = dynsec_groups__find(data, 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_batch_save(data); } return MOSQ_ERR_SUCCESS; } int dynsec_groups__process_remove_client(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *username, *groupname; int rc; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "username", &username, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing username"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(username, (int)strlen(username)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Username not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing groupname"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Group name not valid UTF-8"); return MOSQ_ERR_INVAL; } rc = dynsec_groups__remove_client(data, username, groupname, true); if(rc == MOSQ_ERR_SUCCESS){ admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | removeGroupClient | groupname=%s | username=%s", admin_clientid, admin_username, groupname, username); mosquitto_control_command_reply(cmd, NULL); }else if(rc == ERR_USER_NOT_FOUND){ mosquitto_control_command_reply(cmd, "Client not found"); }else if(rc == ERR_GROUP_NOT_FOUND){ mosquitto_control_command_reply(cmd, "Group not found"); }else{ mosquitto_control_command_reply(cmd, "Internal error"); } /* Enforce any changes */ dynsec_kicklist__add(data, username); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { 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(cmd->j_command, "verbose", &verbose, true, false); json_get_int(cmd->j_command, "count", &count, true, -1); json_get_int(cmd->j_command, "offset", &offset, true, 0); tree = cJSON_CreateObject(); if(tree == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); 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, data->groups)) == NULL || (j_groups = cJSON_AddArrayToObject(j_data, "groups")) == NULL || (cmd->correlation_data && cJSON_AddStringToObject(tree, "correlationData", cmd->correlation_data) == NULL) ){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } i = 0; HASH_ITER(hh, data->groups, group, group_tmp){ if(i>=offset){ if(verbose){ j_group = add_group_to_json(group); if(j_group == NULL){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); 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); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } } if(count >= 0){ count--; if(count <= 0){ break; } } } i++; } cJSON_AddItemToArray(cmd->j_responses, tree); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *groupname; cJSON *tree, *j_group, *j_data; struct dynsec__group *group; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing groupname"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Group name not valid UTF-8"); return MOSQ_ERR_INVAL; } tree = cJSON_CreateObject(); if(tree == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } if(cJSON_AddStringToObject(tree, "command", "getGroup") == NULL || (j_data = cJSON_AddObjectToObject(tree, "data")) == NULL || (cmd->correlation_data && cJSON_AddStringToObject(tree, "correlationData", cmd->correlation_data) == NULL) ){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } group = dynsec_groups__find(data, groupname); if(group){ j_group = add_group_to_json(group); if(j_group == NULL){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(j_data, "group", j_group); }else{ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Group not found"); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(cmd->j_responses, tree); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *groupname, *rolename; struct dynsec__group *group; struct dynsec__role *role; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing groupname"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Group name not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing rolename"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Role name not valid UTF-8"); return MOSQ_ERR_INVAL; } group = dynsec_groups__find(data, groupname); if(group == NULL){ mosquitto_control_command_reply(cmd, "Group not found"); return MOSQ_ERR_SUCCESS; } role = dynsec_roles__find(data, rolename); if(role == NULL){ mosquitto_control_command_reply(cmd, "Role not found"); return MOSQ_ERR_SUCCESS; } dynsec_rolelist__group_remove(group, role); dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); /* Enforce any changes */ group__kick_all(data, group); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *groupname = NULL; char *text_name = NULL, *text_description = NULL; struct dynsec__client *client = NULL; struct dynsec__group *group = NULL; struct dynsec__rolelist *rolelist = NULL; bool have_text_name = false, have_text_description = false, have_rolelist = false; const char *str; int rc; int priority; cJSON *j_client, *j_clients; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing groupname"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Group name not valid UTF-8"); return MOSQ_ERR_INVAL; } group = dynsec_groups__find(data, groupname); if(group == NULL){ mosquitto_control_command_reply(cmd, "Group not found"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "textname", &str, false) == MOSQ_ERR_SUCCESS){ have_text_name = true; text_name = mosquitto_strdup(str); if(text_name == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); rc = MOSQ_ERR_NOMEM; goto error; } } if(json_get_string(cmd->j_command, "textdescription", &str, false) == MOSQ_ERR_SUCCESS){ have_text_description = true; text_description = mosquitto_strdup(str); if(text_description == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); rc = MOSQ_ERR_NOMEM; goto error; } } rc = dynsec_rolelist__load_from_json(data, cmd->j_command, &rolelist); if(rc == MOSQ_ERR_SUCCESS){ /* Apply changes below */ have_rolelist = true; }else if(rc == ERR_LIST_NOT_FOUND){ /* There was no list in the JSON, so no modification */ rolelist = NULL; }else if(rc == MOSQ_ERR_NOT_FOUND){ mosquitto_control_command_reply(cmd, "Role not found"); rc = MOSQ_ERR_INVAL; goto error; }else{ if(rc == MOSQ_ERR_INVAL){ mosquitto_control_command_reply(cmd, "'roles' not an array or missing/invalid rolename"); }else{ mosquitto_control_command_reply(cmd, "Internal error"); } rc = MOSQ_ERR_INVAL; goto error; } j_clients = cJSON_GetObjectItem(cmd->j_command, "clients"); if(j_clients && cJSON_IsArray(j_clients)){ /* Iterate over array to check clients are valid before proceeding */ cJSON_ArrayForEach(j_client, j_clients){ if(cJSON_IsObject(j_client)){ const char *username; if(json_get_string(j_client, "username", &username, false) == MOSQ_ERR_SUCCESS){ client = dynsec_clients__find(data, username); if(client == NULL){ mosquitto_control_command_reply(cmd, "'clients' contains an object with a 'username' that does not exist"); rc = MOSQ_ERR_INVAL; goto error; } }else{ mosquitto_control_command_reply(cmd, "'clients' contains an object with an invalid 'username'"); rc = MOSQ_ERR_INVAL; goto error; } } } /* Kick all clients in the *current* group */ group__kick_all(data, group); dynsec__remove_all_clients_from_group(group); /* Now we can add the new clients to the group */ cJSON_ArrayForEach(j_client, j_clients){ if(cJSON_IsObject(j_client)){ const char *username; if(json_get_string(j_client, "username", &username, false) == MOSQ_ERR_SUCCESS){ json_get_int(j_client, "priority", &priority, true, -1); if(priority > PRIORITY_MAX){ priority = PRIORITY_MAX; } if(priority < -PRIORITY_MAX){ priority = -PRIORITY_MAX; } dynsec_groups__add_client(data, username, groupname, priority, false); } } } } /* Apply remaining changes to group, note that user changes are already applied */ if(have_text_name){ mosquitto_free(group->text_name); group->text_name = text_name; } if(have_text_description){ mosquitto_free(group->text_description); group->text_description = text_description; } if(have_rolelist){ dynsec_rolelist__cleanup(&group->rolelist); group->rolelist = rolelist; } /* And save */ dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); /* Enforce any changes - kick any clients in the *new* group */ group__kick_all(data, group); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | modifyGroup | groupname=%s", admin_clientid, admin_username, groupname); return MOSQ_ERR_SUCCESS; error: mosquitto_free(text_name); mosquitto_free(text_description); dynsec_rolelist__cleanup(&rolelist); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | modifyGroup | groupname=%s", admin_clientid, admin_username, groupname); return rc; } int dynsec_groups__process_set_anonymous_group(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *groupname; struct dynsec__group *group = NULL; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "groupname", &groupname, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing groupname"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(groupname, (int)strlen(groupname)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Group name not valid UTF-8"); return MOSQ_ERR_INVAL; } group = dynsec_groups__find(data, groupname); if(group == NULL){ mosquitto_control_command_reply(cmd, "Group not found"); return MOSQ_ERR_SUCCESS; } data->anonymous_group = group; dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); /* Enforce any changes */ dynsec_kicklist__add(data, NULL); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { cJSON *tree, *j_data, *j_group; const char *groupname; const char *admin_clientid, *admin_username; tree = cJSON_CreateObject(); if(tree == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } if(data->anonymous_group){ groupname = data->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 || (cmd->correlation_data && cJSON_AddStringToObject(tree, "correlationData", cmd->correlation_data) == NULL) ){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(cmd->j_responses, tree); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | getAnonymousGroup", admin_clientid, admin_username); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/dynamic-security/kicklist.c ================================================ /* Copyright (c) 2020-2021 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 "dynamic_security.h" int dynsec_kicklist__add(struct dynsec__data *data, const char *username) { struct dynsec__kicklist *kick; size_t slen; if(username){ slen = strlen(username); }else{ slen = 0; } kick = malloc(sizeof(struct dynsec__kicklist)+slen+1); if(!kick){ return MOSQ_ERR_NOMEM; } if(username){ strcpy(kick->username, username); }else{ kick->username[0] = '\0'; } DL_APPEND(data->kicklist, kick); return MOSQ_ERR_SUCCESS; } void dynsec_kicklist__kick(struct dynsec__data *data) { struct dynsec__kicklist *kick, *tmp; DL_FOREACH_SAFE(data->kicklist, kick, tmp){ DL_DELETE(data->kicklist, kick); if(strlen(kick->username)){ mosquitto_kick_client_by_username(kick->username, false); }else{ mosquitto_kick_client_by_username(NULL, false); } free(kick); } } void dynsec_kicklist__cleanup(struct dynsec__data *data) { struct dynsec__kicklist *kick, *tmp; DL_FOREACH_SAFE(data->kicklist, kick, tmp){ DL_DELETE(data->kicklist, kick); free(kick); } } ================================================ FILE: plugins/dynamic-security/migrate_to_dynsec.py ================================================ #!/usr/bin/env python3 """ Migration script to migrate from acl_file and password_file to the Dynamic Security Plugin. """ import json import argparse from pathlib import Path # use Path to be able to handle Windows as well from dataclasses import dataclass, asdict, field from typing import Optional, Self # # Dynamic Security Plugin # @dataclass class DynsecAclDefaultAccess: publishClientSend: bool = False publishClientReceive: bool = True subscribe: bool = False unsubscribe: bool = True @dataclass class DynSecAcl: acltype: str priority: int allow: bool topic: str @dataclass class DynSecRole: rolename: str = "" textname: str = "" textdescription: str = "" allowwildcardsubs: bool = True acls: list[DynSecAcl] = field(default_factory=list) @staticmethod def create_role_with_permissions( role_name: str, text_description: str, topic_pattern: str, permissions: list[str], ) -> Self: return DynSecRole( rolename=role_name, textdescription=text_description, acls=[ DynSecAcl(permission, 0, True, topic_pattern) for permission in permissions ], allowwildcardsubs=True, ) @staticmethod def create_role_with_full_permissions( role_name: str, text_description: str, topic_pattern: str ) -> Self: return DynSecRole.create_role_with_permissions( role_name=role_name, text_description=text_description, topic_pattern=topic_pattern, permissions=[ "publishClientSend", "publishClientReceive", "subscribePattern", "unsubscribePattern", ], ) DYNSEC_DEFAULT_ROLES: list[DynSecRole] = [ DynSecRole.create_role_with_full_permissions( role_name="client", text_description="Read/write access to the full application topic hierarchy.", topic_pattern="#", ), DynSecRole.create_role_with_full_permissions( role_name="broker-admin", text_description="Grants access to administer general broker configuration.", topic_pattern="$CONTROL/broker/#", ), DynSecRole.create_role_with_full_permissions( role_name="dynsec-admin", text_description="Grants access to administer clients/groups/roles.", topic_pattern="$CONTROL/dynamic-security/#", ), DynSecRole.create_role_with_full_permissions( role_name="inspect-admin", text_description="Grants access to administer inspect data.", topic_pattern="$CONTROL/cedalo/inspect/#", ), DynSecRole.create_role_with_full_permissions( role_name="super-admin", text_description="Grants access to administer all kind of broker controls", topic_pattern="$CONTROL/#", ), DynSecRole.create_role_with_permissions( role_name="sys-notify", text_description="Allow bridges to publish connection state messages.", topic_pattern=r"$SYS/broker/connection/%c/state", permissions=["publishClientSend"], ), DynSecRole.create_role_with_permissions( role_name="sys-observe", text_description="Observe the $SYS topic hierarchy.", topic_pattern="$SYS/#", permissions=["publishClientReceive", "subscribePattern"], ), DynSecRole.create_role_with_permissions( role_name="topic-observe", text_description="Read only access to the full application topic hierarchy.", topic_pattern="#", permissions=[ "publishClientReceive", "subscribePattern", "unsubscribePattern", ], ), ] @dataclass class DynSecClient: username: str rolelist: list[dict[str, str]] password: Optional[str] = None salt: Optional[str] = None hash_algorithm_id: int = 7 iterations: int = 1000 encoded_password: Optional[int] = None textname: str = "" textdescription: str = "" # clientid omitted as it cannot be set for the user in the ACL file disabled: bool = False def asdict(self) -> dict: dynsec_client_as_dict = { "username": self.username, "roles": self.rolelist, "disabled": self.disabled, } if self.encoded_password is not None: dynsec_client_as_dict.update({"encoded_password": self.encoded_password}) else: dynsec_client_as_dict.update( { "password": self.password, "salt": self.salt, "iterations": self.iterations, } ) if self.textname is not None: dynsec_client_as_dict.update({"textname": self.textname}) if self.textdescription is not None: dynsec_client_as_dict.update({"textdescription": self.textdescription}) return dynsec_client_as_dict @dataclass class DynSecGroup: groupname: str textname: str textdescription: str roles: list[DynSecRole] DYNSEC_DEFAULT_ANON_GROUP = DynSecGroup( groupname="unauthenticated", textname="Unauthenticated group", textdescription="If unauthenticated access is allowed, this group can be used to define roles for clients that connect without a password.", roles=[], ) @dataclass class DynSecConfig: defaultACLAccess: DynsecAclDefaultAccess = field( default_factory=DynsecAclDefaultAccess ) clients: list[DynSecClient] = field(default_factory=list) groups: list[DynSecGroup] = field( default_factory=lambda: [DYNSEC_DEFAULT_ANON_GROUP] ) roles: list[DynSecRole] = field(default_factory=lambda: DYNSEC_DEFAULT_ROLES) anonymousGroup: str = "unauthenticated" def asdict(self) -> dict: return { "defaultACLAccess": asdict(self.defaultACLAccess), "clients": [client.asdict() for client in self.clients], "groups": [asdict(group) for group in self.groups], "roles": [asdict(role) for role in self.roles], "anonymousGroup": self.anonymousGroup, } # # ACL file # ACL_FILE_DYNSEC_MAP = { "read": [ "subscribePattern", ], "write": ["publishClientSend"], "readwrite": [ "subscribePattern", "publishClientSend", ], "deny": [ "subscribePattern", "publishClientSend", ], } def is_parent_topic(parent_topic: str, topic: str, user: str = None) -> bool: if len(parent_topic) == 0 or len(topic) == 0: return False if (parent_topic.startswith("$") and not topic.startswith("$")) or ( not parent_topic.startswith("$") and topic.startswith("$") ): return False tokens_sub_topic = parent_topic.split("/") tokens_topic = topic.split("/") if not "#" in parent_topic and len(tokens_sub_topic) != len(tokens_topic): return False for token_parent_topic, token_topic in zip(tokens_sub_topic, tokens_topic): if token_parent_topic in ("#", "+"): continue if token_parent_topic in (r"%c", r"%u"): if token_parent_topic == r"%u" and user is not None: token_parent_topic.replace(r"%u", user) else: continue if token_parent_topic != token_topic: return False return True @dataclass class AclFileConfig: global_acls: list[DynSecAcl] = field(default_factory=list) user_acls: dict[str, list[DynSecAcl]] = field(default_factory=dict) @staticmethod def topic_or_pattern_sanity_check(acl_file_line: str, tokens: list[str]) -> None: # At least topic/pattern keyword and the topic string must be provided if len(tokens) < 2: raise ValueError( f'Invalid topic/pattern definition: "{acl_file_line}" (Too few arguments)' ) # Topic is missing if len(tokens) == 2 and tokens[1] in ACL_FILE_DYNSEC_MAP: raise ValueError( f'Invalid topic/pattern definition: "{acl_file_line}" (Topic missing)' ) # Topic string contains at least one whitespace => access type is mandatory if len(tokens) > 3 and tokens[1] not in ACL_FILE_DYNSEC_MAP: raise ValueError( f'Invalid topic/pattern definition: "{acl_file_line}" (Access type missing)' ) @staticmethod def parse_topic_or_pattern_acl(acl_file_line: str) -> list[DynSecAcl]: tokens = acl_file_line.strip().split(" ") # Raises in case of an invalid definition AclFileConfig.topic_or_pattern_sanity_check(acl_file_line, tokens) return [ DynSecAcl( acltype=permission, priority=0 if len(tokens) == 2 or tokens[1] != "deny" else 1, allow=True if len(tokens) == 2 else tokens[1] != "deny", topic=tokens[1] if len(tokens) == 2 else " ".join(tokens[2:]), ) for permission in ( ACL_FILE_DYNSEC_MAP["readwrite"] if len(tokens) == 2 else ACL_FILE_DYNSEC_MAP[tokens[1]] ) ] @staticmethod def parse_acl_file(acl_file_path: Path) -> Self: acl_file_lines = acl_file_path.read_text(encoding="utf-8").splitlines() acl_file_config = AclFileConfig() current_user: str = None for line in acl_file_lines: if line.startswith("#"): continue if line.startswith("user"): current_user = line.replace("user ", "") if current_user not in acl_file_config.user_acls: acl_file_config.user_acls[current_user] = [] continue current_acls: list[DynSecAcl] = None if line.startswith("pattern") or line.startswith("topic"): current_acls = AclFileConfig.parse_topic_or_pattern_acl(line) if current_acls is not None: if not line.startswith("pattern") and current_user is not None: acl_file_config.user_acls[current_user].extend(current_acls) else: acl_file_config.global_acls.extend(current_acls) return acl_file_config # # Password file # @dataclass class PasswordFile: username_password_map: dict[str, Optional[str]] = field(default_factory=dict) def __getitem__(self, username: str): return self.username_password_map[username] def __setitem__(self, username: str, pw_data: str): self.username_password_map[username] = pw_data @staticmethod def parse_password_file(pw_file_path: Path) -> Self: pw_file_lines = pw_file_path.read_text(encoding="utf-8").splitlines() pw_file = PasswordFile() for line in pw_file_lines: [username, password] = line.strip().split(":") pw_file[username] = password return pw_file # # Migration # def filter_used_deny_acls(acls: list[DynSecAcl], user: str = None) -> AclFileConfig: deny_acls = list(filter(lambda dynsec_acl: not dynsec_acl.allow, acls)) allow_acls = list(filter(lambda dynsec_acl: dynsec_acl not in deny_acls, acls)) final_acls = [] for deny_acl in deny_acls: for allow_acl in allow_acls: if is_parent_topic(allow_acl.topic, deny_acl.topic, user): final_acls.append(deny_acl) break if deny_acl not in final_acls: print(f"WARNING: Removing unused 'deny' ACL: {deny_acl}") final_acls.extend(allow_acls) return final_acls def migrate_to_dynsec( acl_file_config: AclFileConfig, pw_file: PasswordFile ) -> DynSecConfig: dynsec_config = DynSecConfig() for user in pw_file.username_password_map.keys(): user_rolename = f"client-role-{user}" # ACL file user_acls = acl_file_config.user_acls.get(user) if user_acls is not None: user_acls_filtered = filter_used_deny_acls( acl_file_config.user_acls[user], user ) dynsec_config.roles.append( DynSecRole(rolename=user_rolename, acls=user_acls_filtered) ) new_client = DynSecClient( username=user, rolelist=[{"rolename": user_rolename}] if user_acls is not None else [], ) # Password file user_password_details = pw_file[user] if user_password_details.startswith("$argon2id"): new_client.encoded_password = user_password_details else: # leading "$" creates an empty string on split and hash algo ID is unused # -> omit first two elements from split [iterations_string, new_client.salt, new_client.password] = ( user_password_details.split("$")[2:] ) new_client.iterations = int(iterations_string) dynsec_config.clients.append(new_client) return dynsec_config def migrate_mosquitto_conf( mosquitto_conf: str, dynsec_lib_path: Path, dynsec_config_path: Path ) -> str: migrated_mosquitto_conf: list[str] = [] for line in mosquitto_conf.splitlines(): if line.startswith("acl_file"): continue if line.startswith("password_file"): dynsec_plugin_configuration = [ f"plugin {str(dynsec_lib_path)}", f"plugin_opt_config_file {str(dynsec_config_path)}", ] migrated_mosquitto_conf.extend(dynsec_plugin_configuration) continue migrated_mosquitto_conf.append(line) return "\n".join(migrated_mosquitto_conf) def main(): parser = argparse.ArgumentParser() parser.add_argument("--acl-file", required=True, type=str, help="Path to ACL file") parser.add_argument( "--pw-file", required=True, type=str, help="Path to password file" ) parser.add_argument( "--conf", required=False, type=str, help="Path to mosquitto.conf file" ) parser.add_argument( "--dynsec-lib", required=False, type=str, help="Path to mosquitto_dynamic_security.so/.dll", ) args = parser.parse_args() acl_file_path = Path(args.acl_file) pw_file_path = Path(args.pw_file) dynsec_config_file_path = Path(__file__).parent.resolve() / "dynamic-security.json" if args.conf is not None: if args.dynsec_lib is None: print( "Error: Cannot migrate mosquitto.conf file. Reason: --dynsec-lib argument is missing" ) return mosquitto_conf_path = Path(args.conf) mosquitto_conf = mosquitto_conf_path.read_text(encoding="utf-8") # Migrate mosquitto.conf migrated_mosquitto_conf = migrate_mosquitto_conf( mosquitto_conf, Path(args.dynsec_lib), dynsec_config_file_path, ) # Backup old mosquitto.conf and afterwards write migrated mosquitto.conf file mosquitto_conf_path.with_suffix(".conf.old.dynsec").write_text( mosquitto_conf, encoding="utf-8" ) mosquitto_conf_path.write_text(migrated_mosquitto_conf, encoding="utf-8") parsed_acl_file: AclFileConfig = AclFileConfig.parse_acl_file(acl_file_path) # Add global ACLs to users for _, user_acls in parsed_acl_file.user_acls.items(): user_acls.extend(parsed_acl_file.global_acls) parsed_pw_file: PasswordFile = PasswordFile.parse_password_file(pw_file_path) # Migrate config and write to file dynsec_config = migrate_to_dynsec(parsed_acl_file, parsed_pw_file) dynsec_config_file_path.write_text( data=json.dumps(dynsec_config.asdict(), indent=4), encoding="utf-8" ) if __name__ == "__main__": main() ================================================ FILE: plugins/dynamic-security/plugin.c ================================================ /* Copyright (c) 2020-2021 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 #endif #include "mosquitto.h" #include "dynamic_security.h" #include "json_help.h" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static struct dynsec__data dynsec_data; static mosquitto_plugin_id_t *plg_id = NULL; #ifdef WIN32 # include # include # include # include # include # define PATH_MAX MAX_PATH #else # include # include # include # include #endif int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *options, int option_count) { int i; int rc; UNUSED(user_data); memset(&dynsec_data, 0, sizeof(struct dynsec__data)); 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 #include #include "dynamic_security.h" #include "json_help.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); } 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; size_t rolename_len; if(role == NULL){ return MOSQ_ERR_INVAL; } rolename_len = strlen(role->rolename); if(rolename_len == 0){ return MOSQ_ERR_INVAL; } HASH_FIND(hh, *base_rolelist, role->rolename, rolename_len, rolelist); if(rolelist){ return MOSQ_ERR_ALREADY_EXISTS; }else{ rolelist = mosquitto_calloc(1, sizeof(struct dynsec__rolelist) + rolename_len + 1); if(rolelist == NULL){ return MOSQ_ERR_NOMEM; } rolelist->role = role; rolelist->priority = priority; strncpy(rolelist->rolename, role->rolename, rolename_len+1); HASH_ADD_INORDER(hh, *base_rolelist, rolename, rolename_len, 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; } rc = dynsec_clientlist__add(&role->clientlist, client, priority); if(rc){ dynsec_rolelist__remove_role(&client->rolelist, role); } return rc; } 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; } rc = dynsec_grouplist__add(&role->grouplist, group, priority); if(rc){ dynsec_rolelist__remove_role(&group->rolelist, role); } return rc; } int dynsec_rolelist__load_from_json(struct dynsec__data *data, cJSON *command, struct dynsec__rolelist **rolelist) { cJSON *j_roles, *j_role; int priority; struct dynsec__role *role; const char *rolename; j_roles = cJSON_GetObjectItem(command, "roles"); if(j_roles){ if(cJSON_IsArray(j_roles)){ cJSON_ArrayForEach(j_role, j_roles){ if(json_get_string(j_role, "rolename", &rolename, false) == MOSQ_ERR_SUCCESS){ json_get_int(j_role, "priority", &priority, true, -1); if(priority > PRIORITY_MAX){ priority = PRIORITY_MAX; } role = dynsec_roles__find(data, rolename); 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; } ================================================ FILE: plugins/dynamic-security/roles.c ================================================ /* Copyright (c) 2020-2021 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 #endif #include "dynamic_security.h" #include "json_help.h" static cJSON *add_role_to_json(struct dynsec__role *role, bool verbose); static void role__remove_all_clients(struct dynsec__data *data, struct dynsec__role *role); /* ################################################################ * # * # 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); } 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__data *data, struct dynsec__role *role, bool remove_from_hash) { if(remove_from_hash){ HASH_DEL(data->roles, role); } dynsec_clientlist__cleanup(&role->clientlist); dynsec_grouplist__cleanup(&role->grouplist); mosquitto_free(role->text_name); mosquitto_free(role->text_description); 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(struct dynsec__data *data, const char *rolename) { struct dynsec__role *role = NULL; if(rolename){ HASH_FIND(hh, data->roles, rolename, strlen(rolename), role); } return role; } void dynsec_roles__cleanup(struct dynsec__data *data) { struct dynsec__role *role, *role_tmp = NULL; HASH_ITER(hh, data->roles, role, role_tmp){ role__free_item(data, role, true); } } static void role__kick_all(struct dynsec__data *data, struct dynsec__role *role) { struct dynsec__grouplist *grouplist, *grouplist_tmp = NULL; dynsec_clientlist__kick_all(data, role->clientlist); HASH_ITER(hh, role->grouplist, grouplist, grouplist_tmp){ if(grouplist->group == data->anonymous_group){ dynsec_kicklist__add(data, NULL); } dynsec_clientlist__kick_all(data, 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(struct dynsec__data *data, 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, data->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; struct dynsec__acl *acl; cJSON_ArrayForEach(j_acl, j_acls){ const char *acltype; const char *topic; size_t topic_len; if(json_get_string(j_acl, "acltype", &acltype, false) != MOSQ_ERR_SUCCESS){ continue; } if(strcasecmp(acltype, key) != 0){ continue; } if(json_get_string(j_acl, "topic", &topic, false) != MOSQ_ERR_SUCCESS){ continue; } topic_len = strlen(topic); if(topic_len == 0){ continue; } HASH_FIND(hh, *acllist, topic, strlen(topic), acl); if(acl){ continue; } acl = mosquitto_calloc(1, sizeof(struct dynsec__acl) + topic_len + 1); if(acl == NULL){ return 1; } strncpy(acl->topic, topic, topic_len+1); json_get_int(j_acl, "priority", &acl->priority, true, 0); if(acl->priority > PRIORITY_MAX){ acl->priority = PRIORITY_MAX; } if(acl->priority < -PRIORITY_MAX){ acl->priority = -PRIORITY_MAX; } json_get_bool(j_acl, "allow", &acl->allow, true, false); bool allow; if(json_get_bool(j_acl, "allow", &allow, false, false) == MOSQ_ERR_SUCCESS){ acl->allow = allow; } HASH_ADD_INORDER(hh, *acllist, topic, topic_len, acl, insert_acl_cmp); } return 0; } int dynsec_roles__config_load(struct dynsec__data *data, cJSON *tree) { cJSON *j_roles, *j_role, *j_acls; struct dynsec__role *role; size_t rolename_len; 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 name */ const char *rolename; if(json_get_string(j_role, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ continue; } rolename_len = strlen(rolename); if(rolename_len == 0){ continue; } if(dynsec_roles__find(data, rolename)){ continue; } role = mosquitto_calloc(1, sizeof(struct dynsec__role) + rolename_len + 1); if(role == NULL){ return MOSQ_ERR_NOMEM; } strncpy(role->rolename, rolename, rolename_len+1); /* Text name */ const char *textname; if(json_get_string(j_role, "textname", &textname, false) == MOSQ_ERR_SUCCESS){ role->text_name = mosquitto_strdup(textname); if(role->text_name == NULL){ mosquitto_free(role); continue; } } /* Text description */ const char *textdescription; if(json_get_string(j_role, "textdescription", &textdescription, false) == MOSQ_ERR_SUCCESS){ role->text_description = mosquitto_strdup(textdescription); if(role->text_description == NULL){ mosquitto_free(role->text_name); mosquitto_free(role); continue; } } /* Allow wildcard subs */ json_get_bool(j_role, "allowwildcardsubs", &role->allow_wildcard_subs, true, true); /* 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->text_name); mosquitto_free(role->text_description); mosquitto_free(role); continue; } } HASH_ADD(hh, data->roles, rolename, rolename_len, role); } } HASH_SORT(data->roles, role_cmp); return 0; } int dynsec_roles__process_create(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *rolename; const char *text_name, *text_description; bool allow_wildcard_subs; struct dynsec__role *role; int rc = MOSQ_ERR_SUCCESS; cJSON *j_acls; const char *admin_clientid, *admin_username; size_t rolename_len; if(json_get_string(cmd->j_command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing rolename"); return MOSQ_ERR_INVAL; } rolename_len = strlen(rolename); if(rolename_len == 0){ mosquitto_control_command_reply(cmd, "Empty rolename"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)rolename_len) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Role name not valid UTF-8"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "textname", &text_name, true) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing textname"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "textdescription", &text_description, true) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing textdescription"); return MOSQ_ERR_INVAL; } if(json_get_bool(cmd->j_command, "allowwildcardsubs", &allow_wildcard_subs, true, true) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid allowwildcardsubs"); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(data, rolename); if(role){ mosquitto_control_command_reply(cmd, "Role already exists"); return MOSQ_ERR_SUCCESS; } role = mosquitto_calloc(1, sizeof(struct dynsec__role) + rolename_len + 1); if(role == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } strncpy(role->rolename, rolename, rolename_len+1); if(text_name){ role->text_name = mosquitto_strdup(text_name); if(role->text_name == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); rc = MOSQ_ERR_NOMEM; goto error; } } if(text_description){ role->text_description = mosquitto_strdup(text_description); if(role->text_description == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); rc = MOSQ_ERR_NOMEM; goto error; } } role->allow_wildcard_subs = allow_wildcard_subs; /* ACLs */ j_acls = cJSON_GetObjectItem(cmd->j_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 ){ mosquitto_control_command_reply(cmd, "Internal error"); rc = MOSQ_ERR_NOMEM; goto error; } } HASH_ADD_INORDER(hh, data->roles, rolename, rolename_len, role, role_cmp); dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(data, role, false); } return rc; } static void role__remove_all_clients(struct dynsec__data *data, struct dynsec__role *role) { struct dynsec__clientlist *clientlist, *clientlist_tmp = NULL; HASH_ITER(hh, role->clientlist, clientlist, clientlist_tmp){ dynsec_kicklist__add(data, clientlist->client->username); dynsec_rolelist__client_remove(clientlist->client, role); } } static void role__remove_all_groups(struct dynsec__data *data, struct dynsec__role *role) { struct dynsec__grouplist *grouplist, *grouplist_tmp = NULL; HASH_ITER(hh, role->grouplist, grouplist, grouplist_tmp){ if(grouplist->group == data->anonymous_group){ dynsec_kicklist__add(data, NULL); } dynsec_clientlist__kick_all(data, grouplist->group->clientlist); dynsec_rolelist__group_remove(grouplist->group, role); } } int dynsec_roles__process_delete(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *rolename; struct dynsec__role *role; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing rolename"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Role name not valid UTF-8"); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(data, rolename); if(role){ role__remove_all_clients(data, role); role__remove_all_groups(data, role); role__free_item(data, role, true); dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | deleteRole | rolename=%s", admin_clientid, admin_username, rolename); return MOSQ_ERR_SUCCESS; }else{ mosquitto_control_command_reply(cmd, "Role not found"); 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_AddBoolToObject(j_role, "allowwildcardsubs", role->allow_wildcard_subs) == 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { 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(cmd->j_command, "verbose", &verbose, true, false); json_get_int(cmd->j_command, "count", &count, true, -1); json_get_int(cmd->j_command, "offset", &offset, true, 0); tree = cJSON_CreateObject(); if(tree == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); 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, data->roles)) == NULL || (j_roles = cJSON_AddArrayToObject(j_data, "roles")) == NULL || (cmd->correlation_data && cJSON_AddStringToObject(tree, "correlationData", cmd->correlation_data) == NULL) ){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } i = 0; HASH_ITER(hh, data->roles, role, role_tmp){ if(i>=offset){ j_role = add_role_to_json(role, verbose); if(j_role == NULL){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_roles, j_role); if(count >= 0){ count--; if(count <= 0){ break; } } } i++; } cJSON_AddItemToArray(cmd->j_responses, tree); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *rolename; struct dynsec__role *role; struct dynsec__acl **acllist, *acl; int rc; const char *admin_clientid, *admin_username; const char *topic; size_t topic_len; const char *acltype; if(json_get_string(cmd->j_command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing rolename"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Role name not valid UTF-8"); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(data, rolename); if(role == NULL){ mosquitto_control_command_reply(cmd, "Role not found"); return MOSQ_ERR_SUCCESS; } if(json_get_string(cmd->j_command, "acltype", &acltype, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing acltype"); return MOSQ_ERR_SUCCESS; } if(!strcasecmp(acltype, ACL_TYPE_PUB_C_SEND)){ acllist = &role->acls.publish_c_send; }else if(!strcasecmp(acltype, ACL_TYPE_PUB_C_RECV)){ acllist = &role->acls.publish_c_recv; }else if(!strcasecmp(acltype, ACL_TYPE_SUB_LITERAL)){ acllist = &role->acls.subscribe_literal; }else if(!strcasecmp(acltype, ACL_TYPE_SUB_PATTERN)){ acllist = &role->acls.subscribe_pattern; }else if(!strcasecmp(acltype, ACL_TYPE_UNSUB_LITERAL)){ acllist = &role->acls.unsubscribe_literal; }else if(!strcasecmp(acltype, ACL_TYPE_UNSUB_PATTERN)){ acllist = &role->acls.unsubscribe_pattern; }else{ mosquitto_control_command_reply(cmd, "Unknown acltype"); return MOSQ_ERR_SUCCESS; } if(json_get_string(cmd->j_command, "topic", &topic, false) == MOSQ_ERR_SUCCESS){ topic_len = strlen(topic); if(mosquitto_validate_utf8(topic, (int)topic_len) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Topic not valid UTF-8"); return MOSQ_ERR_INVAL; } rc = mosquitto_sub_topic_check(topic); if(rc != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid ACL topic"); return MOSQ_ERR_INVAL; } }else{ mosquitto_control_command_reply(cmd, "Invalid/missing topic"); return MOSQ_ERR_SUCCESS; } HASH_FIND(hh, *acllist, topic, topic_len, acl); if(acl){ mosquitto_control_command_reply(cmd, "ACL with this topic already exists"); return MOSQ_ERR_SUCCESS; } acl = mosquitto_calloc(1, sizeof(struct dynsec__acl) + topic_len + 1); if(acl == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_SUCCESS; } strncpy(acl->topic, topic, topic_len+1); json_get_int(cmd->j_command, "priority", &acl->priority, true, 0); if(acl->priority > PRIORITY_MAX){ acl->priority = PRIORITY_MAX; } if(acl->priority < -PRIORITY_MAX){ acl->priority = -PRIORITY_MAX; } json_get_bool(cmd->j_command, "allow", &acl->allow, true, false); HASH_ADD_INORDER(hh, *acllist, topic, topic_len, acl, insert_acl_cmp); dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); role__kick_all(data, role); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); 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, acltype, topic, acl->priority, acl->allow?"true":"false"); return MOSQ_ERR_SUCCESS; } int dynsec_roles__process_remove_acl(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *rolename; struct dynsec__role *role; struct dynsec__acl **acllist, *acl; const char *topic; int rc; const char *admin_clientid, *admin_username; const char *acltype; if(json_get_string(cmd->j_command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing rolename"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Role name not valid UTF-8"); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(data, rolename); if(role == NULL){ mosquitto_control_command_reply(cmd, "Role not found"); return MOSQ_ERR_SUCCESS; } if(json_get_string(cmd->j_command, "acltype", &acltype, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing acltype"); return MOSQ_ERR_SUCCESS; } if(!strcasecmp(acltype, ACL_TYPE_PUB_C_SEND)){ acllist = &role->acls.publish_c_send; }else if(!strcasecmp(acltype, ACL_TYPE_PUB_C_RECV)){ acllist = &role->acls.publish_c_recv; }else if(!strcasecmp(acltype, ACL_TYPE_SUB_LITERAL)){ acllist = &role->acls.subscribe_literal; }else if(!strcasecmp(acltype, ACL_TYPE_SUB_PATTERN)){ acllist = &role->acls.subscribe_pattern; }else if(!strcasecmp(acltype, ACL_TYPE_UNSUB_LITERAL)){ acllist = &role->acls.unsubscribe_literal; }else if(!strcasecmp(acltype, ACL_TYPE_UNSUB_PATTERN)){ acllist = &role->acls.unsubscribe_pattern; }else{ mosquitto_control_command_reply(cmd, "Unknown acltype"); return MOSQ_ERR_SUCCESS; } if(json_get_string(cmd->j_command, "topic", &topic, false)){ mosquitto_control_command_reply(cmd, "Invalid/missing topic"); return MOSQ_ERR_SUCCESS; } if(mosquitto_validate_utf8(topic, (int)strlen(topic)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Topic not valid UTF-8"); return MOSQ_ERR_INVAL; } rc = mosquitto_sub_topic_check(topic); if(rc != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid ACL topic"); return MOSQ_ERR_INVAL; } HASH_FIND(hh, *acllist, topic, strlen(topic), acl); if(acl){ role__free_acl(acllist, acl); dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); role__kick_all(data, role); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | removeRoleACL | rolename=%s | acltype=%s | topic=%s", admin_clientid, admin_username, rolename, acltype, topic); }else{ mosquitto_control_command_reply(cmd, "ACL not found"); } return MOSQ_ERR_SUCCESS; } int dynsec_roles__process_get(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *rolename; struct dynsec__role *role; cJSON *tree, *j_role, *j_data; const char *admin_clientid, *admin_username; if(json_get_string(cmd->j_command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing rolename"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Role name not valid UTF-8"); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(data, rolename); if(role == NULL){ mosquitto_control_command_reply(cmd, "Role not found"); return MOSQ_ERR_SUCCESS; } tree = cJSON_CreateObject(); if(tree == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } if(cJSON_AddStringToObject(tree, "command", "getRole") == NULL || (j_data = cJSON_AddObjectToObject(tree, "data")) == NULL || (cmd->correlation_data && cJSON_AddStringToObject(tree, "correlationData", cmd->correlation_data) == NULL) ){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } j_role = add_role_to_json(role, true); if(j_role == NULL){ cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } cJSON_AddItemToObject(j_data, "role", j_role); cJSON_AddItemToArray(cmd->j_responses, tree); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | getRole | rolename=%s", admin_clientid, admin_username, rolename); return MOSQ_ERR_SUCCESS; } int dynsec_roles__process_modify(struct dynsec__data *data, struct mosquitto_control_cmd *cmd) { const char *rolename; const char *text_name, *text_description; struct dynsec__role *role; cJSON *j_acls; bool allow_wildcard_subs; bool do_kick = false; 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(cmd->j_command, "rolename", &rolename, false) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Invalid/missing rolename"); return MOSQ_ERR_INVAL; } if(mosquitto_validate_utf8(rolename, (int)strlen(rolename)) != MOSQ_ERR_SUCCESS){ mosquitto_control_command_reply(cmd, "Role name not valid UTF-8"); return MOSQ_ERR_INVAL; } role = dynsec_roles__find(data, rolename); if(role == NULL){ mosquitto_control_command_reply(cmd, "Role does not exist"); return MOSQ_ERR_INVAL; } if(json_get_string(cmd->j_command, "textname", &text_name, false) == MOSQ_ERR_SUCCESS){ char *str = mosquitto_strdup(text_name); if(str == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } mosquitto_free(role->text_name); role->text_name = str; } if(json_get_string(cmd->j_command, "textdescription", &text_description, false) == MOSQ_ERR_SUCCESS){ char *str = mosquitto_strdup(text_description); if(str == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } mosquitto_free(role->text_description); role->text_description = str; } if(json_get_bool(cmd->j_command, "allowwildcardsubs", &allow_wildcard_subs, false, true) == MOSQ_ERR_SUCCESS){ if(role->allow_wildcard_subs != allow_wildcard_subs){ role->allow_wildcard_subs = allow_wildcard_subs; do_kick = true; } } j_acls = cJSON_GetObjectItem(cmd->j_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); mosquitto_control_command_reply(cmd, "Internal error"); 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; do_kick = true; } if(do_kick){ role__kick_all(data, role); } dynsec__config_batch_save(data); mosquitto_control_command_reply(cmd, NULL); admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "dynsec: %s/%s | modifyRole | rolename=%s", admin_clientid, admin_username, rolename); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/dynamic-security/test.conf ================================================ listener 1883 plugin ./mosquitto_dynamic_security.so plugin_opt_config_file test.json enable_control_api true ================================================ FILE: plugins/dynamic-security/test.sh ================================================ rm test.json export MOSQUITTO_DYNSEC_PASSWORD=passwordpass export VG="valgrind --log-file=vglog" ${VG} ../../src/mosquitto -c test.conf ================================================ FILE: plugins/dynamic-security/tick.c ================================================ /* Copyright (c) 2020-2021 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" int dynsec__tick_callback(int event, void *event_data, void *userdata) { UNUSED(event); UNUSED(event_data); dynsec_kicklist__kick(userdata); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/CMakeLists.txt ================================================ if(NOT WIN32) add_subdirectory(add-properties) add_subdirectory(client-lifetime-stats) add_subdirectory(message-timestamp) endif() add_subdirectory(auth-by-env) add_subdirectory(auth-by-ip) add_subdirectory(client-properties) add_subdirectory(connection-state) add_subdirectory(delayed-auth) add_subdirectory(deny-protocol-version) add_subdirectory(force-retain) add_subdirectory(limit-subscription-qos) add_subdirectory(payload-ban) add_subdirectory(payload-modification) add_subdirectory(payload-size-stats) add_subdirectory(plugin-event-stats) add_subdirectory(print-ip-on-publish) add_subdirectory(tick-interval) add_subdirectory(topic-hierarchy-flatten) add_subdirectory(topic-modification) add_subdirectory(topic-jail) add_subdirectory(wildcard-temp) ================================================ FILE: plugins/examples/Makefile ================================================ DIRS= \ add-properties \ auth-by-env \ auth-by-ip \ client-lifetime-stats \ client-properties \ connection-state \ delayed-auth \ deny-protocol-version \ force-retain \ limit-subscription-qos \ message-timestamp \ payload-ban \ payload-modification \ payload-size-stats \ plugin-event-stats \ print-ip-on-publish \ tick-interval \ topic-modification \ topic-jail \ wildcard-temp .PHONY : all binary check clean reallyclean test test-compile 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 test-compile: check : test test: test-compile 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 ================================================ FILE: plugins/examples/add-properties/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_add_properties) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/add-properties/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_add_properties LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/add-properties/mosquitto_add_properties.c ================================================ /* Copyright (c) 2020-2021 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. Simon Christmann - use timestamp in unix epoch milliseconds; add client properties */ /* * Adds MQTT v5 user-properties to incoming messages: * - $timestamp: unix epoch in milliseconds * - $clientid: client id of the publishing client * - $client_username: username that the publishing client used to authenticate * * Compile with: * gcc -I -fPIC -shared add_properties.c -o add_properties.so * * Use in config with: * * plugin /path/to/add_properties.so * * Note that this only works on Mosquitto 2.0 or later. */ #include "config.h" #include #include #include "mosquitto.h" #define TS_BUF_LEN (14+1) // 14 characters in unix epoch (ms) is ≈16 Nov 5138 #define PLUGIN_NAME "add-properties" #define PLUGIN_VERSION "1.0" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static int callback_message_in(int event, void *event_data, void *userdata) { struct mosquitto_evt_message *ed = event_data; int result; struct timespec ts; char ts_buf[TS_BUF_LEN]; UNUSED(event); UNUSED(userdata); // Add timestamp in unix epoch (ms) clock_gettime(CLOCK_REALTIME, &ts); snprintf(ts_buf, TS_BUF_LEN, "%li%03lu", ts.tv_sec, ts.tv_nsec / 1000 / 1000); result = mosquitto_property_add_string_pair( &ed->properties, MQTT_PROP_USER_PROPERTY, "$timestamp", ts_buf); if(result != MOSQ_ERR_SUCCESS){ return result; } // Add client id result = mosquitto_property_add_string_pair( &ed->properties, MQTT_PROP_USER_PROPERTY, "$clientid", mosquitto_client_id(ed->client)); if(result != MOSQ_ERR_SUCCESS){ return result; } // Add client username result = mosquitto_property_add_string_pair( &ed->properties, MQTT_PROP_USER_PROPERTY, "$client_username", mosquitto_client_username(ed->client)); if(result != MOSQ_ERR_SUCCESS){ return result; } // If no return occurred up to this point, we were successful return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); return mosquitto_callback_register(mosq_pid, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL, NULL); } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/add-properties/test.conf ================================================ plugin ./mosquitto_add_properties.so ================================================ FILE: plugins/examples/add-properties/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/auth-by-env/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_auth_by_env) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "libmosquitto_common") ================================================ FILE: plugins/examples/auth-by-env/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_auth_by_env LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/auth-by-env/mosquitto_auth_by_env.c ================================================ /* Copyright (c) 2021 Frank Villaro-Dixon This plugin is under the WTFPL. Do what you want with it. SPDX-License-Identifier: WTFPL Contributors: Frank Villaro-Dixon - initial implementation and documentation. */ /* * This plugin allows users to authenticate with any username, as long as * the provided password matches the MOSQUITTO_PASSWORD environment variable. * If the MOSQUITTO_PASSWORD env variable is empty, then authentication is rejected. * * Compile with: * gcc -I -fPIC -shared mosquitto_auth_by_env.c -o mosquitto_auth_by_env.so * * Use in config with: * * plugin /path/to/mosquitto_auth_by_env.so * * Note that this only works on Mosquitto 2.0 or later. */ #include "config.h" #include #include #include #include "mosquitto.h" #define ENV_MOSQUITTO_PASSWORD "MOSQUITTO_PASSWORD" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static char *environment_password = NULL; static int basic_auth_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_basic_auth *ed = event_data; UNUSED(event); UNUSED(userdata); if(!environment_password || !ed->password){ return MOSQ_ERR_PLUGIN_DEFER; } if(!strcmp(ed->password, environment_password)){ /* Password matched MOSQUITTO_PASSWORD */ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_PLUGIN_DEFER; } } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); char *env_var_content; mosq_pid = identifier; env_var_content = getenv(ENV_MOSQUITTO_PASSWORD); if(env_var_content && strlen(env_var_content) > 0){ environment_password = mosquitto_strdup(env_var_content); if(!environment_password){ mosquitto_log_printf(MOSQ_LOG_ERR, "Out of memory."); return MOSQ_ERR_NOMEM; } return mosquitto_callback_register(mosq_pid, MOSQ_EVT_BASIC_AUTH, basic_auth_callback, NULL, NULL); } mosquitto_log_printf(MOSQ_LOG_ERR, "auth-by-env plugin called, but " ENV_MOSQUITTO_PASSWORD " environment variable is empty"); return MOSQ_ERR_INVAL; } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/auth-by-ip/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_auth_by_ip) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "libmosquitto_common") ================================================ FILE: plugins/examples/auth-by-ip/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_auth_by_ip LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/auth-by-ip/mosquitto_auth_by_ip.c ================================================ /* Copyright (c) 2021 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 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.h" #define PLUGIN_NAME "auth-by-ip" #define PLUGIN_VERSION "1.0" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); 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_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); return mosquitto_callback_register(mosq_pid, MOSQ_EVT_BASIC_AUTH, basic_auth_callback, NULL, NULL); } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/auth-by-ip/test.conf ================================================ listener 1883 plugin ./mosquitto_auth_by_ip.so ================================================ FILE: plugins/examples/auth-by-ip/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/client-lifetime-stats/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_client_lifetime_stats) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/client-lifetime-stats/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_client_lifetime_stats LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/client-lifetime-stats/mosquitto_client_lifetime_stats.c ================================================ /* Copyright (c) 2021 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. */ /* * Publish statistics on client session lifetimes. * * Compile with: * gcc -I -fPIC -shared mosquitto_client_lifetime_stats.c -o mosquitto_client_lifetime_stats.so * * Use in config with: * * plugin /path/to/mosquitto_client_lifetime_stats.so * * Note that this only works on Mosquitto 2.0 or later. */ #include "config.h" #include #include #include #include #include #include "mosquitto.h" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; struct lifetime_s { UT_hash_handle hh; char *id; time_t connect; }; struct lifetime_s *local_lifetimes = NULL; #define LIFETIME_COUNT 28 static const char *lifetime_strs[LIFETIME_COUNT] = { "0", "1", "2", "5", "10", "20", "50", "100", "200", "500", "1k", "2k", "5k", "10k", "20k", "50k", "100k", "200k", "500k", "1M", "2M", "5M", "10M", "20M", "50M", "100M", "200M", "500M" }; static uint32_t lifetime_values[LIFETIME_COUNT] = { 0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, 2000000, 5000000, 10000000, 20000000, 50000000, 100000000, 200000000, 500000000 }; static long lifetime_counts[LIFETIME_COUNT]; static long last_lifetime_counts[LIFETIME_COUNT]; static time_t last_report = 0; static int callback_tick(int event, void *event_data, void *userdata) { struct timespec ts; char topic[40]; char payload[40]; int slen; int i; UNUSED(event); UNUSED(event_data); UNUSED(userdata); clock_gettime(CLOCK_REALTIME, &ts); if(last_report + 10 < ts.tv_sec){ last_report = ts.tv_sec; for(i=0; iclient); if(id){ HASH_FIND(hh, local_lifetimes, id, strlen(id), client); if(!client){ client = malloc(sizeof(struct lifetime_s)); if(client == NULL){ return MOSQ_ERR_SUCCESS; } client->id = strdup(id); if(client->id == NULL){ free(client); return MOSQ_ERR_SUCCESS; } client->connect = time(NULL); HASH_ADD_KEYPTR(hh, local_lifetimes, client->id, strlen(client->id), client); } } return MOSQ_ERR_SUCCESS; } static int callback_disconnect(int event, void *event_data, void *userdata) { struct mosquitto_evt_disconnect *ed = event_data; int i; const char *id; struct lifetime_s *client; time_t lifetime; UNUSED(event); UNUSED(userdata); id = mosquitto_client_id(ed->client); if(id){ HASH_FIND(hh, local_lifetimes, id, strlen(id), client); if(client){ HASH_DELETE(hh, local_lifetimes, client); lifetime = time(NULL) - client->connect; free(client->id); free(client); for(i=0; i -fPIC -shared printf_example.c -o printf_example.so * * Use in config with: * * plugin /path/to/printf_example.so * * Note that this only works on Mosquitto 2.0 or later. */ #include #include #include "mosquitto.h" #define PLUGIN_NAME "client-properties" #define PLUGIN_VERSION "1.0" #define UNUSED(A) (void)(A) MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static int callback_message_in(int event, void *event_data, void *userdata) { struct mosquitto_evt_message *ed = event_data; UNUSED(event); UNUSED(userdata); printf("printf-example - client address: %s\n", mosquitto_client_address(ed->client)); printf("printf-example - client id: %s\n", mosquitto_client_id(ed->client)); printf("printf-example - client username: %s\n", mosquitto_client_username(ed->client)); printf("printf-example - payload: '%.*s'\n", ed->payloadlen, (char *)ed->payload); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); return mosquitto_callback_register(mosq_pid, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL, NULL); } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/client-properties/test.conf ================================================ plugin ./mosquitto_client_properties.so ================================================ FILE: plugins/examples/client-properties/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/connection-state/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_connection_state) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/connection-state/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_connection_state LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/connection-state/mosquitto_connection_state.c ================================================ /* Copyright (c) 2021 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ /* * This is an example plugin showing how you could publish online/offline * state for all clients. * * Compile with: * gcc -I -fPIC -shared mosquitto_connection_state.c -o mosquitto_connection_state.so * * Use in config with: * * plugin /path/to/mosquitto_connection_state.so * * Note that this only works on Mosquitto 2.0 or later. */ #include #include #include #include "mosquitto.h" #define PLUGIN_NAME "connection-state" #define PLUGIN_VERSION "1.0" #define UNUSED(A) (void)(A) MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static int connect_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_connect *ed = event_data; const char *clientid; char topic[1024]; int len; UNUSED(event); UNUSED(userdata); clientid = mosquitto_client_id(ed->client); len = snprintf(topic, sizeof(topic), "$SYS/broker/connection/client/%s/state", clientid); if(len < (int)sizeof(topic)){ mosquitto_broker_publish_copy(NULL, topic, 1, "1", 0, true, NULL); }else{ /* client id too large */ } return MOSQ_ERR_SUCCESS; } static int disconnect_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_disconnect *ed = event_data; const char *clientid; char topic[1024]; int len; mosquitto_property *proplist = NULL; int rc; UNUSED(event); UNUSED(userdata); clientid = mosquitto_client_id(ed->client); len = snprintf(topic, sizeof(topic), "$SYS/broker/connection/client/%s/state", clientid); if(len < (int)sizeof(topic)){ /* Expire our "disconnected" message after a day. */ rc = mosquitto_property_add_int32(&proplist, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, 86400); if(rc){ return rc; } rc = mosquitto_broker_publish_copy(NULL, topic, 1, "0", 0, true, proplist); if(rc){ mosquitto_property_free_all(&proplist); } }else{ /* client id too large */ } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { int rc; UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_CONNECT, connect_callback, NULL, NULL); if(rc){ return rc; } rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_DISCONNECT, disconnect_callback, NULL, NULL); return rc; } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/connection-state/test.conf ================================================ plugin ./mosquitto_connection_state.so ================================================ FILE: plugins/examples/connection-state/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/delayed-auth/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_delayed_auth) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "libmosquitto_common") ================================================ FILE: plugins/examples/delayed-auth/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_delayed_auth LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/delayed-auth/mosquitto_delayed_auth.c ================================================ /* Copyright (c) 2021 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ /* * This is an example plugin showing how to carry out delayed authentication. * The "authentication" in this example makes no checks whatsoever, but delays * the response by 5 seconds, and randomly chooses whether it should succeed. * * Compile with: * gcc -I -fPIC -shared mosquitto_delayed_auth.c -o mosquitto_delayed_auth.so * * Use in config with: * * plugin /path/to/mosquitto_delayed_auth.so * * Note that this only works on Mosquitto 2.0 or later. */ #include #include #include #include #include #include #include "mosquitto.h" #define PLUGIN_NAME "delayed-auth" #define PLUGIN_VERSION "1.0" #ifndef UNUSED # define UNUSED(A) (void)(A) #endif MOSQUITTO_PLUGIN_DECLARE_VERSION(5); struct client_list { UT_hash_handle hh; char *id; time_t request_time; }; static mosquitto_plugin_id_t *mosq_pid = NULL; static struct client_list *clients = NULL; static time_t last_check = 0; static bool authentication_check(struct client_list *client, time_t now) { time_t secs; secs = now - client->request_time; return secs > 5 ? true : false; } static int basic_auth_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_basic_auth *ed = event_data; static struct client_list *client; const char *id; UNUSED(event); UNUSED(userdata); id = mosquitto_client_id(ed->client); HASH_FIND(hh, clients, id, strlen(id), client); if(client){ client->request_time = time(NULL); }else{ client = mosquitto_malloc(sizeof(struct client_list)); if(client == NULL){ return MOSQ_ERR_NOMEM; } client->id = mosquitto_strdup(id); if(client->id == NULL){ mosquitto_free(client); return MOSQ_ERR_NOMEM; } client->request_time = time(NULL); HASH_ADD_KEYPTR(hh, clients, client->id, strlen(client->id), client); mosquitto_log_printf(MOSQ_LOG_DEBUG, "Starting auth for %s at %ld", client->id, time(NULL)); } return MOSQ_ERR_AUTH_DELAYED; } static int tick_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_tick *ed = event_data; struct client_list *client, *client_tmp; time_t now; long r; UNUSED(event); UNUSED(userdata); now = time(NULL); if(now >= last_check){ HASH_ITER(hh, clients, client, client_tmp){ if(authentication_check(client, now)){ /* Deny access 1/4 of the time, yes it's biased number generation. */ #ifdef WIN32 r = rand() % 1000; #else /* coverity[dont_call] - we don't care about random() not being cryptographically secure here */ r = random() % 1000; #endif if(r > 740){ mosquitto_complete_basic_auth(client->id, MOSQ_ERR_AUTH); }else{ mosquitto_complete_basic_auth(client->id, MOSQ_ERR_SUCCESS); } mosquitto_log_printf(MOSQ_LOG_DEBUG, "Completing auth for %s at %ld", client->id, now); HASH_DELETE(hh, clients, client); mosquitto_free(client->id); mosquitto_free(client); } } last_check = now; } /* Declare that we want another call in 1 second at the earliest */ ed->next_s = 1; return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { int rc; UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_BASIC_AUTH, basic_auth_callback, NULL, NULL); if(rc){ return rc; } rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_TICK, tick_callback, NULL, NULL); return rc; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { struct client_list *client, *client_tmp; UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); HASH_ITER(hh, clients, client, client_tmp){ HASH_DELETE(hh, clients, client); mosquitto_free(client->id); mosquitto_free(client); } return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/delayed-auth/test.conf ================================================ listener 1883 plugin ./mosquitto_delayed_auth.so sys_interval 1 log_timestamp_format %Y-%m-%dT%H:%M:%S ================================================ FILE: plugins/examples/delayed-auth/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/deny-protocol-version/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_deny_protocol_version) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/deny-protocol-version/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_deny_protocol_version LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/deny-protocol-version/mosquitto_deny_protocol_version.c ================================================ /* Copyright (c) 2022 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ /* * This is an example plugin showing how to deny access based on the version of * the protocol spec a client connects with. It does no other authentication * checks. * * It could be used with other authentication plugins by specifying it in the * config file before another plugin, for example: * * plugin /usr/lib/mosquitto_deny_protocol_version.so * plugin /usr/lib/mosquitto_dynamic_security.so * * or: * * plugin /usr/lib/mosquitto_deny_protocol_version.so * password_file pwfile * * It will *not* work on its own. * * In Mosquitto 2.1, this can be achieved with the `accept_protocol_version` * option instead. * * * To compile: * * gcc -I -fPIC -shared mosquitto_deny_protocol_version.c -o mosquitto_deny_protocol_version.so * * Note that this only works on Mosquitto 2.0 or later. */ #include "config.h" #include #include #include "mosquitto.h" static mosquitto_plugin_id_t *mosq_pid = NULL; int mosquitto_plugin_version(int supported_version_count, const int *supported_versions) { int i; for(i=0; iclient); if(protocol_version == 5 || protocol_version == 4){ /* Allow access to MQTT v5.0 and v3.1.1 - this passes on responsibility * for the actual auth checks to the next plugin/password file in the * config list. If no other plugins/password file is defined, then * access will be denied. */ return MOSQ_ERR_PLUGIN_DEFER; }else{ /* Deny access to all others */ return MOSQ_ERR_AUTH; } } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; return mosquitto_callback_register(mosq_pid, MOSQ_EVT_BASIC_AUTH, basic_auth_callback, NULL, NULL); } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return mosquitto_callback_unregister(mosq_pid, MOSQ_EVT_BASIC_AUTH, basic_auth_callback, NULL); } ================================================ FILE: plugins/examples/deny-protocol-version/test.conf ================================================ listener 1883 plugin ./mosquitto_deny_protocol_version.so password_file pwfile ================================================ FILE: plugins/examples/deny-protocol-version/test.sh ================================================ #!/bin/sh ../../apps/mosquitto_passwd/mosquitto_passwd -c -b pwfile username password ../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/force-retain/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_force_retain) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/force-retain/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_force_retain LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/force-retain/mosquitto_force_retain.c ================================================ /* Copyright (c) 2021 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 an *example* plugin which forces all messages processed by the * broker to be treated as though they had the retained bit set. * * Compile with: * gcc -I -fPIC -shared mosquitto_force_retain.c -o mosquitto_force_retain.so * * Use in config with: * * plugin /path/to/mosquitto_force_retain.so * * Note that this only works on Mosquitto 2.0 or later. */ #include #include #include "mosquitto.h" #define PLUGIN_NAME "force-retain" #define PLUGIN_VERSION "1.0" #define UNUSED(A) (void)(A) MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static int callback_message_in(int event, void *event_data, void *userdata) { struct mosquitto_evt_message *ed = event_data; UNUSED(event); UNUSED(userdata); ed->retain = true; return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); return mosquitto_callback_register(mosq_pid, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL, NULL); } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/force-retain/test.conf ================================================ plugin ./mosquitto_force_retain.so ================================================ FILE: plugins/examples/force-retain/test.sh ================================================ ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/limit-subscription-qos/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_limit_subscription_qos) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/limit-subscription-qos/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_limit_subscription_qos LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/limit-subscription-qos/mosquitto_limit_subscription_qos.c ================================================ /* Copyright (c) 2021 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: Abilio Marques - initial implementation and documentation. */ /* * This is an *example* plugin which limits all the subscriptions' QoS to 1. * * Compile with: * gcc -I -fPIC -shared mosquitto_limit_subscription.c -o mosquitto_limit_subscription_qos.so * * Use in config with: * * plugin /path/to/mosquitto_limit_subscription_qos.so * * Note that this only works on Mosquitto 2.0 or later. */ #include #include #include "mosquitto.h" #define PLUGIN_NAME "limit-subscription-qos" #define PLUGIN_VERSION "1.0" #define UNUSED(A) (void)(A) MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static int callback_subscribe(int event, void *event_data, void *userdata) { struct mosquitto_evt_subscribe *ed = event_data; UNUSED(event); UNUSED(userdata); if(MQTT_SUB_OPT_GET_QOS(ed->data.options) > 1){ MQTT_SUB_OPT_SET_QOS(ed->data.options, 1); } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); return mosquitto_callback_register(mosq_pid, MOSQ_EVT_SUBSCRIBE, callback_subscribe, NULL, NULL); } ================================================ FILE: plugins/examples/limit-subscription-qos/test.conf ================================================ plugin ./mosquitto_limit_subscription_qos.so ================================================ FILE: plugins/examples/limit-subscription-qos/test.sh ================================================ ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/message-timestamp/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_message_timestamp) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/message-timestamp/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_message_timestamp LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/message-timestamp/mosquitto_message_timestamp.c ================================================ /* Copyright (c) 2020-2021 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.h" #define PLUGIN_NAME "message-timestamp" #define PLUGIN_VERSION "1.0" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static int callback_message_in(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_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); return mosquitto_callback_register(mosq_pid, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL, NULL); } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/message-timestamp/test.conf ================================================ plugin ./mosquitto_message_timestamp.so ================================================ FILE: plugins/examples/message-timestamp/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/payload-ban/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_payload_ban) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/payload-ban/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_payload_ban LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/payload-ban/mosquitto_payload_ban.c ================================================ /* Copyright (c) 2022 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ /* * This is an example plugin that inspects payloads before they are published. * On matching payload, the publish is denied, the IP address of the client * added to a log file that can be used with fail2ban or similar to ban the * client connection, and the client kicked. * * This was developed in response to an obnoxious campaign by an MQTT client * that was republishing spam advertising messages to every retained message on * test.mosquitto.org * * Compile with: * gcc -I -fPIC -shared mosquitto_payload_ban.c -o mosquitto_payload_ban.so * * Use in config with: * * plugin /path/to/mosquitto_payload_ban.so * * Note that this only works on Mosquitto 2.0 or later. */ #include "config.h" #include #include #include #include "mosquitto.h" #define PLUGIN_NAME "payload-ban" #define PLUGIN_VERSION "1.0" struct banlist { UT_hash_handle hh_by_address; UT_hash_handle hh_by_id; char ip_address[50]; char clientid[]; }; MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static struct banlist *banlist_by_address = NULL; static struct banlist *banlist_by_id = NULL; static int basic_auth_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_basic_auth *ed = event_data; struct banlist *entry; const char *ip_address; const char *clientid; UNUSED(event); UNUSED(userdata); ip_address = mosquitto_client_address(ed->client); if(ip_address){ HASH_FIND(hh_by_address, banlist_by_address, ip_address, strlen(ip_address), entry); if(entry){ return MOSQ_ERR_AUTH; } } clientid = mosquitto_client_id(ed->client); if(clientid){ HASH_FIND(hh_by_id, banlist_by_id, clientid, strlen(clientid), entry); if(entry){ return MOSQ_ERR_AUTH; } } return MOSQ_ERR_SUCCESS; } static int acl_check_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_acl_check *ed = event_data; struct banlist *new_entry = NULL, *entry; const char *clientid, *ip_address; FILE *fptr; UNUSED(event); UNUSED(userdata); if(ed->payload && ed->payloadlen > sizeof("Tired of using an old outdated MQTT client")){ if(!strncmp(ed->payload, "Tired of using an old outdated MQTT client", strlen("Tired of using an old outdated MQTT client"))){ ip_address = mosquitto_client_address(ed->client); clientid = mosquitto_client_id(ed->client); HASH_FIND(hh_by_address, banlist_by_address, ip_address, strlen(ip_address), entry); if(entry){ mosquitto_kick_client_by_clientid(clientid, false); return MOSQ_ERR_ACL_DENIED; } new_entry = calloc(1, sizeof(struct banlist)+strlen(clientid) + 1); if(!new_entry){ return MOSQ_ERR_ACL_DENIED; } strcpy(new_entry->clientid, clientid); strncpy(new_entry->ip_address, ip_address, sizeof(new_entry->ip_address)-1); HASH_ADD(hh_by_id, banlist_by_id, clientid, strlen(clientid), new_entry); HASH_ADD(hh_by_address, banlist_by_address, ip_address, strlen(ip_address), new_entry); mosquitto_kick_client_by_clientid(clientid, false); fptr = fopen("/tmp/payload-banlist", "at"); if(fptr){ fprintf(fptr, "%s || %s\n", ip_address, clientid); fclose(fptr); } return MOSQ_ERR_ACL_DENIED; } } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); mosquitto_callback_register(mosq_pid, MOSQ_EVT_BASIC_AUTH, basic_auth_callback, NULL, NULL); mosquitto_callback_register(mosq_pid, MOSQ_EVT_ACL_CHECK, acl_check_callback, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { struct banlist *entry, *entry_tmp; UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); HASH_ITER(hh_by_address, banlist_by_address, entry, entry_tmp){ HASH_DELETE(hh_by_address, banlist_by_address, entry); HASH_DELETE(hh_by_id, banlist_by_id, entry); free(entry); } return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/payload-ban/test.conf ================================================ listener 1883 plugin ./mosquitto_payload_ban.so ================================================ FILE: plugins/examples/payload-ban/test.sh ================================================ #!/bin/sh valgrind ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/payload-modification/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_payload_modification) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/payload-modification/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_payload_modification LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/payload-modification/mosquitto_payload_modification.c ================================================ /* Copyright (c) 2020-2021 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 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.h" #define PLUGIN_NAME "payload-modification" #define PLUGIN_VERSION "1.0" #define UNUSED(A) (void)(A) MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static int callback_message_in(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_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); return mosquitto_callback_register(mosq_pid, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL, NULL); } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/payload-modification/test.conf ================================================ plugin ./mosquitto_payload_modification.so ================================================ FILE: plugins/examples/payload-modification/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/payload-size-stats/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_payload_size_stats) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/payload-size-stats/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_payload_size_stats LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/payload-size-stats/mosquitto_payload_size_stats.c ================================================ /* Copyright (c) 2021 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. */ /* * Publish statistics on message payload size. * * Compile with: * gcc -I -fPIC -shared mosquitto_payload_size_stats.c -o mosquitto_payload_size_stats.so * * Use in config with: * * plugin /path/to/mosquitto_payload_size_stats.so * * Note that this only works on Mosquitto 2.0 or later. */ #include "config.h" #include #include #include #include "mosquitto.h" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; #define SIZE_COUNT 28 static const char *size_strs[SIZE_COUNT] = { "0", "1", "2", "5", "10", "20", "50", "100", "200", "500", "1k", "2k", "5k", "10k", "20k", "50k", "100k", "200k", "500k", "1M", "2M", "5M", "10M", "20M", "50M", "100M", "200M", "500M" }; static uint32_t size_values[SIZE_COUNT] = { 0, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, 2000000, 5000000, 10000000, 20000000, 50000000, 100000000, 200000000, 500000000 }; static long size_counts[SIZE_COUNT]; static long last_size_counts[SIZE_COUNT]; static time_t last_report = 0; static int callback_tick(int event, void *event_data, void *userdata) { time_t now_sec; char topic[40]; char payload[40]; int slen; int i; UNUSED(event); UNUSED(event_data); UNUSED(userdata); now_sec = time(NULL); if(last_report + 10 < now_sec){ last_report = now_sec; for(i=0; ipayloadlen <= size_values[i]){ size_counts[i]++; break; } } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); memset(size_counts, 0, sizeof(size_counts)); memset(last_size_counts, 0, sizeof(last_size_counts)); mosq_pid = identifier; mosquitto_callback_register(mosq_pid, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL, NULL); mosquitto_callback_register(mosq_pid, MOSQ_EVT_TICK, callback_tick, NULL, NULL); return MOSQ_ERR_SUCCESS; } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/payload-size-stats/test.conf ================================================ plugin ./mosquitto_payload_size_stats.so ================================================ FILE: plugins/examples/payload-size-stats/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/plugin-event-stats/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_plugin_event_stats) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/plugin-event-stats/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_plugin_event_stats LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/plugin-event-stats/mosquitto_plugin_event_stats.c ================================================ /* Copyright (c) 2022 Cedalo Gmbh 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. */ /* * Publish statistics on plugin event counts * * Compile with: * gcc -I -fPIC -shared mosquitto_plugin_event_stats.c -o mosquitto_plugin_event_stats.so * * Use in config with: * * plugin /path/to/mosquitto_plugin_event_stats.so * * Note that this only works on Mosquitto 2.1 or later. */ #include #include "config.h" #include #include #include "mosquitto.h" #define PLUGIN_NAME "plugin-event-stats" #define PLUGIN_VERSION "1.0" #define MAX_EVT MOSQ_EVT_MESSAGE_OUT MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static uint64_t evt_counts[MAX_EVT+1]; static uint64_t last_evt_counts[MAX_EVT+1]; static time_t last_report = 0; #define TOPIC_BASE "$SYS/broker/plugin/events/" const char evt_topics[][60] = { "", /* No event */ TOPIC_BASE "reload", /* MOSQ_EVT_RELOAD */ TOPIC_BASE "acl_check", /* MOSQ_EVT_ACL_CHECK */ TOPIC_BASE "auth/basic", /* MOSQ_EVT_BASIC_AUTH */ TOPIC_BASE "auth/ext/start", /* MOSQ_EVT_EXT_AUTH_START */ TOPIC_BASE "auth/ext/continue", /* MOSQ_EVT_EXT_AUTH_CONTINUE */ TOPIC_BASE "control", /* MOSQ_EVT_CONTROL */ TOPIC_BASE "message/in", /* MOSQ_EVT_MESSAGE_IN */ TOPIC_BASE "psk_key", /* MOSQ_EVT_PSK_KEY */ TOPIC_BASE "tick", /* MOSQ_EVT_TICK */ TOPIC_BASE "disconnect", /* MOSQ_EVT_DISCONNECT */ TOPIC_BASE "connect", /* MOSQ_EVT_CONNECT */ TOPIC_BASE "subscribe", /* MOSQ_EVT_SUBSCRIBE */ TOPIC_BASE "unsubscribe", /* MOSQ_EVT_UNSUBSCRIBE */ TOPIC_BASE "persist/restore", /* MOSQ_EVT_PERSIST_RESTORE */ TOPIC_BASE "persist/message/base/add", /* MOSQ_EVT_PERSIST_MSG_ADD */ TOPIC_BASE "persist/message/base/delete", /* MOSQ_EVT_PERSIST_MSG_DELETE */ TOPIC_BASE "persist/message/retain/set", /* MOSQ_EVT_PERSIST_RETAIN_SET */ TOPIC_BASE "persist/message/retain/delete", /* MOSQ_EVT_PERSIST_RETAIN_DELETE */ TOPIC_BASE "persist/client/add", /* MOSQ_EVT_PERSIST_CLIENT_ADD */ TOPIC_BASE "persist/client/delete", /* MOSQ_EVT_PERSIST_CLIENT_DELETE */ TOPIC_BASE "persist/client/update", /* MOSQ_EVT_PERSIST_CLIENT_UPDATE */ TOPIC_BASE "persist/subscription/add", /* MOSQ_EVT_PERSIST_SUBSCRIPTION_ADD */ TOPIC_BASE "persist/subscription/delete", /* MOSQ_EVT_PERSIST_SUBSCRIPTION_DELETE */ TOPIC_BASE "persist/message/client/add", /* MOSQ_EVT_PERSIST_CLIENT_MSG_ADD */ TOPIC_BASE "persist/message/client/delete", /* MOSQ_EVT_PERSIST_CLIENT_MSG_DELETE */ TOPIC_BASE "persist/message/client/update", /* MOSQ_EVT_PERSIST_CLIENT_MSG_UPDATE */ TOPIC_BASE "message/out", /* MOSQ_EVT_MESSAGE_OUT */ }; static int callback_tick(int event, void *event_data, void *userdata) { struct mosquitto_evt_tick *ed = event_data; char payload[40]; int slen; UNUSED(event); UNUSED(userdata); if(last_report + 10 < ed->now_s){ last_report = ed->now_s; for(int i=1; i MAX_EVT){ return MOSQ_ERR_SUCCESS; }else{ evt_counts[event]++; } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); memset(evt_counts, 0, sizeof(evt_counts)); memset(last_evt_counts, 0, sizeof(last_evt_counts)); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); mosquitto_callback_register(mosq_pid, MOSQ_EVT_TICK, callback_tick, NULL, NULL); for(int i=1; i #include #include "mosquitto.h" #define PLUGIN_NAME "print-ip-on-publish" #define PLUGIN_VERSION "1.0" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static char my_topic[] = "troublesome/topic"; static int callback_message_in(int event, void *event_data, void *userdata) { struct mosquitto_evt_message *ed = event_data; UNUSED(event); UNUSED(userdata); if(!strcmp(ed->topic, my_topic)){ printf("PUBLISH FROM %s on IP %s\n", mosquitto_client_id(ed->client), mosquitto_client_address(ed->client)); } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); return mosquitto_callback_register(mosq_pid, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL, NULL); } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/print-ip-on-publish/test.conf ================================================ plugin ./mosquitto_print_ip_on_publish.so ================================================ FILE: plugins/examples/print-ip-on-publish/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/tick-interval/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_tick_interval) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "libmosquitto_common") ================================================ FILE: plugins/examples/tick-interval/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_tick_interval LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/tick-interval/mosquitto_tick_interval.c ================================================ /* Copyright (c) 2025 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ /* * This is an example plugin showing how a plugin can choose how frequently it * receives a tick event. Note that this request is not a guarantee that the * tick will be called that frequently, only that it will not be called more * frequently. * * Setting to 0 means that a tick event will always be triggered for this * plugin when the broker is ready to do so. * * Compile with: * gcc -I -fPIC -shared mosquitto_tick.c -o mosquitto_tick.so * * Use in config with the below, where the interval is in seconds: * * plugin /path/to/mosquitto_tick.so * plugin_opt_interval 1 * * Note that this only works on Mosquitto 2.0 or later. */ #include #include #include #include #include #include #include "mosquitto.h" #define PLUGIN_NAME "tick-interval" #define PLUGIN_VERSION NULL #ifndef UNUSED # define UNUSED(A) (void)(A) #endif MOSQUITTO_PLUGIN_DECLARE_VERSION(5); struct plugin_data { mosquitto_plugin_id_t *pid; int interval; }; static int tick_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_tick *ed = event_data; struct plugin_data *data = userdata; UNUSED(event); mosquitto_log_printf(MOSQ_LOG_INFO, "Tick event for plugin with interval %d.", data->interval); ed->next_s = data->interval; /* We want the next tick to occur at the earliest in "interval" seconds */ ed->next_ms = 0; /* And 0 milliseconds */ return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **userdata, struct mosquitto_opt *opts, int opt_count) { struct plugin_data *data; data = mosquitto_calloc(1, sizeof(struct plugin_data)); if(!data){ return MOSQ_ERR_NOMEM; } *userdata = data; data->interval = -1; data->pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); for(int i=0; iinterval = atoi(opts[i].value); }else{ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Unknown option '%s'.", opts[i].key); return MOSQ_ERR_INVAL; } } if(data->interval < 0){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: interval must be >= 0."); return MOSQ_ERR_INVAL; } return mosquitto_callback_register(data->pid, MOSQ_EVT_TICK, tick_callback, NULL, data); } int mosquitto_plugin_cleanup(void *userdata, struct mosquitto_opt *opts, int opt_count) { struct plugin_data *data = userdata; UNUSED(opts); UNUSED(opt_count); mosquitto_FREE(data); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/tick-interval/test.conf ================================================ listener 1883 plugin ./mosquitto_tick_interval.so plugin_opt_interval 1 plugin ./mosquitto_tick_interval.so plugin_opt_interval 4 ================================================ FILE: plugins/examples/tick-interval/test.sh ================================================ #!/bin/sh valgrind --log-file=vglog ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/topic-hierarchy-flatten/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_topic_hierarchy_flatten) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/topic-hierarchy-flatten/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_topic_hierarchy_flatten LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/topic-hierarchy-flatten/mosquitto_topic_hierarchy_flatten.c ================================================ /* Copyright (c) 2020-2025 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 an *example* plugin which looks at messages coming in and if their * topic matches a topic filter, makes the payload available on another topic, * flattening the hierarchy if the topic filter includes a wildcard. * * The input topic filter and output topic can be configured in the plugin * config. The "plugin_opt_republish" option can be set to true/false. If set * to true, then the original incoming messages are unaffected and a new * message is published for each matching message. If set to false, the * original message has its topic replaced with the output topic. * * Compile with: * gcc -I -fPIC -shared mosquitto_topic_hierarchy_flatten.c -o mosquitto_topic_hierarchy_flatten.so * * Use in config with: * * plugin /path/to/mosquitto_topic_hierarchy_flatten.so * plugin_opt_input_topic_filter my/+/topics * plugin_opt_output_topic the/single/output/topic * plugin_opt_republish true * * Note that this only works on Mosquitto 2.1 or later. */ #include #include #include "mosquitto.h" #define PLUGIN_NAME "topic-hierarchy-flatten" #define UNUSED(A) (void)(A) MOSQUITTO_PLUGIN_DECLARE_VERSION(5); struct plugin_data { mosquitto_plugin_id_t *pid; char *input_topic_filter; char *output_topic; bool republish; }; static int callback_message_in(int event, void *event_data, void *userdata) { struct mosquitto_evt_message *ed = event_data; struct plugin_data *data = userdata; bool result; int rc; UNUSED(event); mosquitto_topic_matches_sub(data->input_topic_filter, ed->topic, &result); if(result){ if(data->republish){ mosquitto_property *props = NULL; if(ed->properties){ rc = mosquitto_property_copy_all(&props, ed->properties); if(rc){ return rc; } } rc = mosquitto_broker_publish_copy(NULL, data->output_topic, (int)ed->payloadlen, ed->payload, ed->qos, ed->retain, props); if(rc){ mosquitto_property_free_all(&props); return rc; } }else{ ed->topic = mosquitto_strdup(data->output_topic); if(!ed->topic){ return MOSQ_ERR_NOMEM; } } } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **userdata, struct mosquitto_opt *opts, int opt_count) { struct plugin_data *data = mosquitto_calloc(1, sizeof(struct plugin_data)); if(!data){ return MOSQ_ERR_NOMEM; } *userdata = data; data->republish = true; for(int i=0; iinput_topic_filter = mosquitto_strdup(opts[i].value); if(!data->input_topic_filter){ return MOSQ_ERR_NOMEM; } }else if(!strcmp(opts[i].key, "output_topic")){ data->output_topic = mosquitto_strdup(opts[i].value); if(!data->output_topic){ return MOSQ_ERR_NOMEM; } }else if(!strcmp(opts[i].key, "republish")){ data->republish = !strcmp(opts[i].value, "true"); } } if(!data->input_topic_filter){ data->input_topic_filter = mosquitto_strdup("input/#"); if(!data->input_topic_filter){ return MOSQ_ERR_NOMEM; } } if(!data->output_topic){ data->output_topic = mosquitto_strdup("output"); if(!data->output_topic){ return MOSQ_ERR_NOMEM; } } mosquitto_log_printf(MOSQ_LOG_INFO, PLUGIN_NAME ": Input topic filter is '%s'", data->input_topic_filter); mosquitto_log_printf(MOSQ_LOG_INFO, PLUGIN_NAME ": Output topic is '%s'", data->output_topic); mosquitto_log_printf(MOSQ_LOG_INFO, PLUGIN_NAME ": Republish is %s", data->republish?"true":"false"); data->pid = identifier; return mosquitto_callback_register(data->pid, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL, data); } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *userdata, struct mosquitto_opt *opts, int opt_count) { struct plugin_data *data = userdata; UNUSED(opts); UNUSED(opt_count); if(data){ mosquitto_callback_unregister(data->pid, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL); mosquitto_FREE(data->input_topic_filter); mosquitto_FREE(data->output_topic); mosquitto_FREE(data); } return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/topic-hierarchy-flatten/test.conf ================================================ plugin ./mosquitto_topic_hierarchy_flatten.so plugin_opt_republish true ================================================ FILE: plugins/examples/topic-hierarchy-flatten/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/topic-jail/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_topic_jail) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/topic-jail/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_topic_jail LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/topic-jail/mosquitto_topic_jail.c ================================================ /* Copyright (c) 2020-2021 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: Abilio Marques - initial implementation and documentation. */ /* * This is an *example* plugin which demonstrates how to jail a client. * It mounts such client topics in a subtree starting with the client id. * It modifies it's subscriptions and the topics of the messages destined to * that client. It also modifies the topics of the messages published * by the client. * * client | event | destination | original topic | modified topic * -------|-------|-------------|----------------------|-------------------- * jailed | sub | --- | topic | ${jailed_id}/topic * normal | pub | jailed | ${jailed_id}/topic | topic * jailed | pub | normal | topic | ${jailed_id}/topic * * For simplicity of this example, all clients with id starting with "jailed" * will be jailed. All other clients will work as normal. * * Two jailed clients cannot interact with each other. Normal clients can interact * with any jailed client by publishing or subscribing to the mounted topic. * * You should be very sure of what you are doing before making use of this feature. * * Compile with: * gcc -I -fPIC -shared mosquitto_topic_jail.c -o mosquitto_topic_jail.so * * Use in config with: * * plugin /path/to/mosquitto_topic_jail.so * * Note that this only works on Mosquitto 2.0 or later. */ #include #include #include "mosquitto.h" #define PLUGIN_NAME "topic-jail" #define PLUGIN_VERSION "1.0" #define UNUSED(A) (void)(A) MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static bool is_jailed(const char *str) { return strncmp("jailed", str, 6) == 0; } static int callback_message_in(int event, void *event_data, void *userdata) { struct mosquitto_evt_message *ed = event_data; char *new_topic; size_t new_topic_len; UNUSED(event); UNUSED(userdata); const char *clientid = mosquitto_client_id(ed->client); if(!is_jailed(clientid)){ /* will only modify the topic of jailed clients */ return MOSQ_ERR_SUCCESS; } /* put the clientid on front of the topic */ /* calculate the length of the new payload */ new_topic_len = strlen(clientid) + sizeof('/') + strlen(ed->topic) + 1; /* Allocate some memory - use * mosquitto_calloc/mosquitto_malloc/mosquitto_strdup when allocating, to * allow the broker to track memory usage */ new_topic = mosquitto_calloc(1, new_topic_len); if(new_topic == NULL){ return MOSQ_ERR_NOMEM; } /* prepend the clientid to the topic */ snprintf(new_topic, new_topic_len, "%s/%s", clientid, ed->topic); /* Assign the new topic to the event data structure. You * must *not* free the original topic, it will be handled by the * broker. */ ed->topic = new_topic; return MOSQ_ERR_SUCCESS; } static int callback_message_out(int event, void *event_data, void *userdata) { struct mosquitto_evt_message *ed = event_data; size_t clientid_len; UNUSED(event); UNUSED(userdata); const char *clientid = mosquitto_client_id(ed->client); if(!is_jailed(clientid)){ /* will only modify the topic of jailed clients */ return MOSQ_ERR_SUCCESS; } /* remove the clientid from the front of the topic */ clientid_len = strlen(clientid); if(strlen(ed->topic) <= clientid_len + 1){ /* the topic is not long enough to contain the * clientid + '/' */ return MOSQ_ERR_SUCCESS; } if(!strncmp(clientid, ed->topic, clientid_len) && ed->topic[clientid_len] == '/'){ /* Allocate some memory - use * mosquitto_calloc/mosquitto_malloc/mosquitto_strdup when allocating, to * allow the broker to track memory usage */ /* skip the clientid + '/' */ char *new_topic = mosquitto_strdup(ed->topic + clientid_len + 1); if(new_topic == NULL){ return MOSQ_ERR_NOMEM; } /* Assign the new topic to the event data structure. You * must *not* free the original topic, it will be handled by the * broker. */ ed->topic = new_topic; } return MOSQ_ERR_SUCCESS; } static int callback_subscribe(int event, void *event_data, void *userdata) { struct mosquitto_evt_subscribe *ed = event_data; char *new_sub; size_t new_sub_len; UNUSED(event); UNUSED(userdata); const char *clientid = mosquitto_client_id(ed->client); if(!is_jailed(clientid)){ /* will only modify the topic of jailed clients */ return MOSQ_ERR_SUCCESS; } /* put the clientid on front of the topic */ /* calculate the length of the new payload */ new_sub_len = strlen(clientid) + sizeof('/') + strlen(ed->data.topic_filter) + 1; /* Allocate some memory - use * mosquitto_calloc/mosquitto_malloc/mosquitto_strdup when allocating, to * allow the broker to track memory usage */ new_sub = mosquitto_calloc(1, new_sub_len); if(new_sub == NULL){ return MOSQ_ERR_NOMEM; } /* prepend the clientid to the subscription */ snprintf(new_sub, new_sub_len, "%s/%s", clientid, ed->data.topic_filter); /* Assign the new topic to the event data structure. You * must *not* free the original topic, it will be handled by the * broker. */ ed->data.topic_filter = new_sub; return MOSQ_ERR_SUCCESS; } static int callback_unsubscribe(int event, void *event_data, void *userdata) { struct mosquitto_evt_unsubscribe *ed = event_data; char *new_sub; size_t new_sub_len; UNUSED(event); UNUSED(userdata); const char *clientid = mosquitto_client_id(ed->client); if(!is_jailed(clientid)){ /* will only modify the topic of jailed clients */ return MOSQ_ERR_SUCCESS; } /* put the clientid on front of the topic */ /* calculate the length of the new payload */ new_sub_len = strlen(clientid) + sizeof('/') + strlen(ed->data.topic_filter) + 1; /* Allocate some memory - use * mosquitto_calloc/mosquitto_malloc/mosquitto_strdup when allocating, to * allow the broker to track memory usage */ new_sub = mosquitto_calloc(1, new_sub_len); if(new_sub == NULL){ return MOSQ_ERR_NOMEM; } /* prepend the clientid to the subscription */ snprintf(new_sub, new_sub_len, "%s/%s", clientid, ed->data.topic_filter); /* Assign the new topic to the event data structure. You * must *not* free the original topic, it will be handled by the * broker. */ ed->data.topic_filter = new_sub; return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); int rc; rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL, NULL); if(rc){ return rc; } rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_MESSAGE_OUT, callback_message_out, NULL, NULL); if(rc){ return rc; } rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_SUBSCRIBE, callback_subscribe, NULL, NULL); if(rc){ return rc; } rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_UNSUBSCRIBE, callback_unsubscribe, NULL, NULL); return rc; } ================================================ FILE: plugins/examples/topic-jail/test.conf ================================================ plugin ./mosquitto_topic_jail.so ================================================ FILE: plugins/examples/topic-jail/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/topic-modification/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_topic_modification) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/topic-modification/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_topic_modification LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/topic-modification/mosquitto_topic_modification.c ================================================ /* Copyright (c) 2020-2021 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 an *example* plugin which demonstrates how to modify the topic 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_topic_modification.c -o mosquitto_topic_modification.so * * Use in config with: * * plugin /path/to/mosquitto_topic_modification.so * * Note that this only works on Mosquitto 2.0 or later. */ #include #include #include "mosquitto.h" #define PLUGIN_NAME "topic-modification" #define PLUGIN_VERSION "1.0" #define UNUSED(A) (void)(A) MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static int callback_message_in(int event, void *event_data, void *userdata) { struct mosquitto_evt_message *ed = event_data; bool result; UNUSED(event); UNUSED(userdata); /* This simply removes "/uplink" from the end of every matching topic. You * can of course do much more complicated message processing if needed. */ mosquitto_topic_matches_sub("device/+/data/uplink", ed->topic, &result); if(result){ ed->topic[strlen(ed->topic) - strlen("/uplink")] = '\0'; } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; return mosquitto_callback_register(mosq_pid, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL, NULL); } /* mosquitto_plugin_cleanup() is optional in 2.1 and later. Use it only if you have your own cleanup to do */ int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/topic-modification/test.conf ================================================ plugin ./mosquitto_topic_modification.so ================================================ FILE: plugins/examples/topic-modification/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/examples/wildcard-temp/CMakeLists.txt ================================================ set (PLUGIN_NAME mosquitto_wildcard_temp) add_mosquitto_plugin_no_install("${PLUGIN_NAME}" "${PLUGIN_NAME}.c" "" "") ================================================ FILE: plugins/examples/wildcard-temp/Makefile ================================================ R=../../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_wildcard_temp LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LIBADD+= all : binary OBJS:=${PLUGIN_NAME}.o PLUGIN_NOINST:=1 include ${R}/plugins/plugin.mk ================================================ FILE: plugins/examples/wildcard-temp/mosquitto_wildcard_temp.c ================================================ /* Copyright (c) 2021 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ /* * This is an example plugin that denies subscriptions to the '#' topic filter, * but with special behaviour for clients that connect with the username * `wildcard`. * * The first time per session that clients with this username attempt to * subscribe to the '#' topic filter, it will succeed. They will then have 20 * seconds of access to that subscription, subject to any other access controls * that are in place, after which the subscription will be automatically * removed. * * The intention is to allow temporary access to the '#' topic filter so that * topic discovery can be done on public servers such as test.mosquitto.org, * but also to limit bandwidth use. * * Compile with: * gcc -I -fPIC -shared mosquitto_wildcard_temp.c -o mosquitto_wildcard_temp.so * * Use in config with: * * plugin /path/to/mosquitto_wildcard_temp.so * * Note that this only works on Mosquitto 2.1 or later. */ #include #include #include #include #include #include #include #include "mosquitto.h" #define PLUGIN_NAME "wildcard-temp" #define PLUGIN_VERSION "1.0" /* How long the client has '#' access for, in seconds */ #define ACCESS_PERIOD 20 #ifndef UNUSED # define UNUSED(A) (void)(A) #endif MOSQUITTO_PLUGIN_DECLARE_VERSION(5); struct client_list { UT_hash_handle hh; struct client_list *next, *prev; time_t sub_end; uint8_t sub_status; char id[]; }; static mosquitto_plugin_id_t *mosq_pid = NULL; static struct client_list *clients = NULL; static struct client_list *active_subs = NULL; static int connect_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_basic_auth *ed = event_data; static struct client_list *client; const char *id, *username; size_t idlen; UNUSED(event); UNUSED(userdata); username = mosquitto_client_username(ed->client); if(!username || strcmp(username, "wildcard")){ return MOSQ_ERR_SUCCESS; } id = mosquitto_client_id(ed->client); idlen = strlen(id); HASH_FIND(hh, clients, id, idlen, client); if(client){ return MOSQ_ERR_SUCCESS; }else{ client = mosquitto_calloc(1, sizeof(struct client_list) + idlen+1); if(client == NULL){ return MOSQ_ERR_NOMEM; } memcpy(client->id, id, idlen); HASH_ADD_KEYPTR(hh, clients, client->id, idlen, client); } return MOSQ_ERR_SUCCESS; } static int disconnect_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_basic_auth *ed = event_data; static struct client_list *client; const char *id; size_t idlen; UNUSED(event); UNUSED(userdata); id = mosquitto_client_id(ed->client); idlen = strlen(id); HASH_FIND(hh, clients, id, idlen, client); if(client){ HASH_DELETE(hh, clients, client); if(active_subs){ DL_DELETE(active_subs, client); } mosquitto_free(client); } return MOSQ_ERR_SUCCESS; } static int acl_check_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_acl_check *ed = event_data; static struct client_list *client; const char *id; UNUSED(event); UNUSED(userdata); if(ed->access == MOSQ_ACL_SUBSCRIBE && !strcmp(ed->topic, "#")){ id = mosquitto_client_id(ed->client); HASH_FIND(hh, clients, id, strlen(id), client); if(client && client->sub_status == 0){ client->sub_status = 1; client->sub_end = time(NULL) + ACCESS_PERIOD; DL_APPEND(active_subs, client); return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } } return MOSQ_ERR_PLUGIN_IGNORE; } static int tick_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_tick *ed = event_data; struct client_list *client, *client_tmp; time_t now; UNUSED(event); UNUSED(userdata); now = time(NULL); DL_FOREACH_SAFE(active_subs, client, client_tmp){ if(client->sub_end < now){ mosquitto_subscription_delete(client->id, "#"); DL_DELETE(active_subs, client); }else{ break; } } /* Declare that we want another call in 1 second at the earliest */ ed->next_s = 1; return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { int rc; UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_CONNECT, connect_callback, NULL, NULL); rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_DISCONNECT, disconnect_callback, NULL, NULL); rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_ACL_CHECK, acl_check_callback, NULL, NULL); if(rc){ return rc; } rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_TICK, tick_callback, NULL, NULL); return rc; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { struct client_list *client, *client_tmp; UNUSED(user_data); UNUSED(opts); UNUSED(opt_count); HASH_ITER(hh, clients, client, client_tmp){ HASH_DELETE(hh, clients, client); mosquitto_free(client); } return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/examples/wildcard-temp/test.conf ================================================ listener 1883 plugin ./mosquitto_wildcard_temp.so allow_anonymous true sys_interval 1 log_timestamp_format %Y-%m-%dT%H:%M:%S ================================================ FILE: plugins/examples/wildcard-temp/test.sh ================================================ #!/bin/sh ../../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/password-file/CMakeLists.txt ================================================ set(PLUGIN_NAME mosquitto_password_file) set(SRCLIST password_check.c password_parse.c plugin.c ) set(INCLIST ${mosquitto_SOURCE_DIR}/src) set(LINKLIST libmosquitto_common) add_mosquitto_plugin("${PLUGIN_NAME}" "${SRCLIST}" "${INCLIST}" "${LINKLIST}") ================================================ FILE: plugins/password-file/Makefile ================================================ R=../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_password_file LOCAL_CFLAGS+= LOCAL_CPPFLAGS+=-I${R}/src LOCAL_LDFLAGS+= LOCAL_LIBADD+=${LIBMOSQ_COMMON} # Objects for this plugin only, built from source in this directory OBJS = \ password_check.o \ password_parse.o \ plugin.o # Objects from e.g. the common directory that are not in this directory OBJS_EXTERNAL = all : binary include ${R}/plugins/plugin.mk ================================================ FILE: plugins/password-file/password_check.c ================================================ /* Copyright (c) 2011-2021 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 "password_file.h" int password_file__check(int event, void *event_data, void *userdata) { struct mosquitto_evt_basic_auth *ed = event_data; struct password_file_data *data = userdata; struct mosquitto__unpwd *u; UNUSED(event); if(ed->username == NULL){ return MOSQ_ERR_PLUGIN_IGNORE; } // FIXME if(ed->client->bridge) return MOSQ_ERR_SUCCESS; HASH_FIND(hh, data->unpwd, ed->username, strlen(ed->username), u); if(u){ if(u->pw){ if(ed->password){ return mosquitto_pw_verify(u->pw, ed->password); }else{ return MOSQ_ERR_AUTH; } }else{ return MOSQ_ERR_SUCCESS; } } return MOSQ_ERR_AUTH; } ================================================ FILE: plugins/password-file/password_parse.c ================================================ /* Copyright (c) 2011-2021 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 "password_file.h" int password_file__parse(struct password_file_data *data) { FILE *pwfile; struct mosquitto__unpwd *unpwd = NULL; char *username, *password; char *saveptr = NULL; char *buf; int buflen = 256; int rc = MOSQ_ERR_INVAL; buf = mosquitto_malloc((size_t)buflen); if(buf == NULL){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } pwfile = mosquitto_fopen(data->password_file, "rt", true); if(!pwfile){ mosquitto_log_printf(MOSQ_LOG_ERR, "password-file: Error: Unable to open pwfile \"%s\".", data->password_file); mosquitto_FREE(buf); return MOSQ_ERR_UNKNOWN; } while(!feof(pwfile)){ if(mosquitto_fgets(&buf, &buflen, pwfile)){ unpwd = NULL; if(buf[0] == '#'){ continue; } if(!strchr(buf, ':')){ continue; } username = strtok_r(buf, ":", &saveptr); if(username){ username = mosquitto_trimblanks(username); if(strlen(username) > 65535){ mosquitto_log_printf(MOSQ_LOG_ERR, "password-file: Error: Invalid line in password file '%s', username too long.", data->password_file); goto error; } if(strlen(username) <= 0){ mosquitto_log_printf(MOSQ_LOG_ERR, "password-file: Error: Empty username in password file '%s'.", data->password_file); goto error; } HASH_FIND(hh, data->unpwd, username, strlen(username), unpwd); if(unpwd){ unpwd = NULL; mosquitto_log_printf(MOSQ_LOG_ERR, "password-file: Error: Duplicate user '%s' in password file '%s'.", username, data->password_file); goto error; } unpwd = mosquitto_calloc(1, sizeof(struct mosquitto__unpwd)); if(!unpwd){ goto error; } unpwd->username = mosquitto_strdup(username); if(!unpwd->username){ rc = MOSQ_ERR_NOMEM; goto error; } password = strtok_r(NULL, ":", &saveptr); if(password){ password = mosquitto_trimblanks(password); if(strlen(password) > 65535){ mosquitto_log_printf(MOSQ_LOG_ERR, "password-file: Error: Invalid line in password file '%s', password too long.", data->password_file); goto error; } if(mosquitto_pw_new(&unpwd->pw, MOSQ_PW_DEFAULT) || mosquitto_pw_decode(unpwd->pw, password)){ mosquitto_log_printf(MOSQ_LOG_ERR, "password-file: Error: Unable to decode line in password file '%s'.", data->password_file); goto error; } HASH_ADD_KEYPTR(hh, data->unpwd, unpwd->username, strlen(unpwd->username), unpwd); }else{ mosquitto_log_printf(MOSQ_LOG_ERR, "password-file: Error: Invalid line in password file '%s': %s", data->password_file, buf); goto error; } } } } fclose(pwfile); mosquitto_FREE(buf); return MOSQ_ERR_SUCCESS; error: if(unpwd){ mosquitto_pw_cleanup(unpwd->pw); mosquitto_FREE(unpwd->username); mosquitto_FREE(unpwd); } mosquitto_FREE(buf); fclose(pwfile); return rc; } void password_file__cleanup(struct password_file_data *data) { struct mosquitto__unpwd *u, *tmp = NULL; if(!data){ return; } HASH_ITER(hh, data->unpwd, u, tmp){ HASH_DEL(data->unpwd, u); mosquitto_pw_cleanup(u->pw); mosquitto_FREE(u->username); mosquitto_FREE(u); } } int password_file__reload(int event, void *event_data, void *userdata) { struct password_file_data *data = userdata; UNUSED(event); UNUSED(event_data); password_file__cleanup(data); return password_file__parse(data); } ================================================ FILE: plugins/password-file/plugin.c ================================================ /* Copyright (c) 2025 Cedalo Gmbh */ #include "config.h" #include #include #include "mosquitto.h" #include "password_file.h" #define PLUGIN_NAME "password-file" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; static int handle_options(struct password_file_data *data, struct mosquitto_opt *options, int option_count) { for(int i=0; ipassword_file); data->password_file = mosquitto_strdup(options[i].value); if(!data->password_file){ return MOSQ_ERR_NOMEM; } }else{ mosquitto_log_printf(MOSQ_LOG_ERR, PLUGIN_NAME ": Error: Unknown option '%s'.", options[i].key); return MOSQ_ERR_INVAL; } } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *options, int option_count) { struct password_file_data *data; int rc; UNUSED(options); UNUSED(option_count); data = mosquitto_calloc(1, sizeof(struct password_file_data)); if(!data){ return MOSQ_ERR_NOMEM; } *user_data = data; mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, NULL); rc = handle_options(data, options, option_count); if(rc){ return rc; } rc = password_file__parse(data); if(rc){ return rc; } rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_BASIC_AUTH, password_file__check, NULL, data); if(rc){ return rc; } rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_RELOAD, password_file__reload, NULL, data); if(rc){ return rc; } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *options, int option_count) { struct password_file_data *data = user_data; UNUSED(options); UNUSED(option_count); mosquitto_callback_unregister(mosq_pid, MOSQ_EVT_BASIC_AUTH, password_file__check, NULL); mosquitto_callback_unregister(mosq_pid, MOSQ_EVT_RELOAD, password_file__reload, NULL); password_file__cleanup(data); mosquitto_FREE(data->password_file); mosquitto_FREE(data); return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/password-file/test.conf ================================================ listener 1883 allow_anonymous true plugin ./mosquitto_password_file.so plugin_opt_password_file ./test.pwfile ================================================ FILE: plugins/password-file/test.pwfile ================================================ user:$7$1000$h0tqVxBwkB9rKAXukTtffzdbBQtNy1q5FBTDwSW4hucfjpqunBbxW10NVnRk7Cfh0lQndnOv2+k4wJavgz1JNw==$02ujkUXlKkJGFzlQHNjUgXwG3XRB1mr3vs8NX5teGCJGbN4hdgSpHNHuj47j8r5SHXsO7GeHpmkpPNhLraVVcQ== ================================================ FILE: plugins/password-file/test.sh ================================================ VG="valgrind --log-file=vglog" ${VG} ../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/persist-sqlite/CMakeLists.txt ================================================ if(SQLITE3_FOUND) set(PLUGIN_NAME "mosquitto_persist_sqlite") set(SRCLIST persist_sqlite.h util.h ../../common/json_help.h base_msgs.c clients.c client_msgs.c common.c init.c ../../common/json_help.c plugin.c restore.c retain_msgs.c subscriptions.c tick.c will.c ) set(INCLIST "${CJSON_INCLUDE_DIRS}" ) set(LINKLIST libmosquitto_common cJSON SQLite::SQLite3 ) add_mosquitto_plugin("${PLUGIN_NAME}" "${SRCLIST}" "${INCLIST}" "${LINKLIST}") endif() ================================================ FILE: plugins/persist-sqlite/Makefile ================================================ R=../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_persist_sqlite LOCAL_CFLAGS+= LOCAL_CPPFLAGS+=-I${R}/src/ -I${R}/plugins/common LOCAL_LIBADD+=-lsqlite3 ${LIBMOSQ_COMMON} LOCAL_LDFLAGS+= OBJS = \ base_msgs.o \ clients.o \ client_msgs.o \ common.o \ init.o \ plugin.o \ restore.o \ retain_msgs.o \ subscriptions.o \ tick.o \ will.o OBJS_EXTERNAL = \ json_help.o ALL_DEPS:= binary all : ${ALL_DEPS} json_help.o : ${R}/common/json_help.c ${R}/common/json_help.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ EXTRA_DEPS:=persist_sqlite.h include ${R}/plugins/plugin.mk ================================================ FILE: plugins/persist-sqlite/base_msgs.c ================================================ /* Copyright (c) 2021 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 "mosquitto.h" #include "persist_sqlite.h" #include "util.h" int persist_sqlite__base_msg_add_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_base_msg *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = MOSQ_ERR_UNKNOWN; char *str = NULL; UNUSED(event); rc = 0; rc += sqlite3_bind_int64(ms->base_msg_add_stmt, 1, (int64_t)ed->data.store_id); rc += sqlite3_bind_int64(ms->base_msg_add_stmt, 2, ed->data.expiry_time); rc += sqlite3_bind_text(ms->base_msg_add_stmt, 3, ed->data.topic, (int)strlen(ed->data.topic), SQLITE_STATIC); if(ed->data.payload){ rc += sqlite3_bind_blob(ms->base_msg_add_stmt, 4, ed->data.payload, (int)ed->data.payloadlen, SQLITE_STATIC); }else{ rc += sqlite3_bind_null(ms->base_msg_add_stmt, 4); } if(ed->data.source_id){ rc += sqlite3_bind_text(ms->base_msg_add_stmt, 5, ed->data.source_id, (int)strlen(ed->data.source_id), SQLITE_STATIC); }else{ rc += sqlite3_bind_null(ms->base_msg_add_stmt, 5); } if(ed->data.source_username){ rc += sqlite3_bind_text(ms->base_msg_add_stmt, 6, ed->data.source_username, (int)strlen(ed->data.source_username), SQLITE_STATIC); }else{ rc += sqlite3_bind_null(ms->base_msg_add_stmt, 6); } rc += sqlite3_bind_int(ms->base_msg_add_stmt, 7, (int)ed->data.payloadlen); rc += sqlite3_bind_int(ms->base_msg_add_stmt, 8, ed->data.source_mid); rc += sqlite3_bind_int(ms->base_msg_add_stmt, 9, ed->data.source_port); rc += sqlite3_bind_int(ms->base_msg_add_stmt, 10, ed->data.qos); rc += sqlite3_bind_int(ms->base_msg_add_stmt, 11, ed->data.retain); if(ed->data.properties){ str = properties_to_json_str(ed->data.properties); } if(str){ rc += sqlite3_bind_text(ms->base_msg_add_stmt, 12, str, (int)strlen(str), SQLITE_STATIC); }else{ rc += sqlite3_bind_null(ms->base_msg_add_stmt, 12); } rc = sqlite3_single_step_stmt(rc, ms, ms->base_msg_add_stmt); sqlite3_reset(ms->base_msg_add_stmt); free(str); return rc; } int persist_sqlite__base_msg_remove_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_base_msg *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = 1; UNUSED(event); if(sqlite3_bind_int64(ms->base_msg_remove_stmt, 1, (int64_t)ed->data.store_id) == SQLITE_OK){ rc = sqlite3_single_step_stmt(0, ms, ms->base_msg_remove_stmt); } sqlite3_reset(ms->base_msg_remove_stmt); return rc; } int persist_sqlite__base_msg_clear(struct mosquitto_sqlite *ms, const char *clientid) { int rc = MOSQ_ERR_UNKNOWN; if(sqlite3_bind_text(ms->base_msg_remove_for_clientid_stmt, 1, clientid, (int)strlen(clientid), SQLITE_STATIC) == SQLITE_OK){ rc = sqlite3_single_step_stmt(0, ms, ms->base_msg_remove_for_clientid_stmt); } sqlite3_reset(ms->base_msg_remove_for_clientid_stmt); return rc; } ================================================ FILE: plugins/persist-sqlite/client_msgs.c ================================================ /* Copyright (c) 2021 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 "mosquitto/broker.h" #include "persist_sqlite.h" int persist_sqlite__client_msg_add_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_client_msg *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = MOSQ_ERR_UNKNOWN; UNUSED(event); if(sqlite3_bind_text(ms->client_msg_add_stmt, 1, ed->data.clientid, (int)strlen(ed->data.clientid), SQLITE_STATIC) == SQLITE_OK && sqlite3_bind_int64(ms->client_msg_add_stmt, 2, (int64_t)ed->data.cmsg_id) == SQLITE_OK && sqlite3_bind_int64(ms->client_msg_add_stmt, 3, (int64_t)ed->data.store_id) == SQLITE_OK && sqlite3_bind_int(ms->client_msg_add_stmt, 4, ed->data.dup) == SQLITE_OK && sqlite3_bind_int(ms->client_msg_add_stmt, 5, ed->data.direction) == SQLITE_OK && sqlite3_bind_int(ms->client_msg_add_stmt, 6, ed->data.mid) == SQLITE_OK && sqlite3_bind_int(ms->client_msg_add_stmt, 7, ed->data.qos) == SQLITE_OK && sqlite3_bind_int(ms->client_msg_add_stmt, 8, ed->data.retain) == SQLITE_OK && sqlite3_bind_int(ms->client_msg_add_stmt, 9, ed->data.state) == SQLITE_OK && sqlite3_bind_int(ms->client_msg_add_stmt, 10, (int)ed->data.subscription_identifier) == SQLITE_OK ){ ms->event_count++; rc = sqlite3_step(ms->client_msg_add_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } sqlite3_reset(ms->client_msg_add_stmt); return rc; } int persist_sqlite__client_msg_remove_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_client_msg *ed = event_data; struct mosquitto_sqlite *ms = userdata; UNUSED(event); ms->event_count++; return persist_sqlite__client_msg_remove(ms, ed->data.clientid, (int64_t)ed->data.store_id, ed->data.direction); } int persist_sqlite__client_msg_update_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_client_msg *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = MOSQ_ERR_UNKNOWN; UNUSED(event); if(sqlite3_bind_int(ms->client_msg_update_stmt, 1, ed->data.state) == SQLITE_OK && sqlite3_bind_int(ms->client_msg_update_stmt, 2, ed->data.dup) == SQLITE_OK && sqlite3_bind_text(ms->client_msg_update_stmt, 3, ed->data.clientid, (int)strlen(ed->data.clientid), SQLITE_STATIC) == SQLITE_OK && sqlite3_bind_int64(ms->client_msg_update_stmt, 4, (int64_t)ed->data.store_id) == SQLITE_OK ){ ms->event_count++; rc = sqlite3_step(ms->client_msg_update_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } sqlite3_reset(ms->client_msg_update_stmt); return rc; } int persist_sqlite__client_msg_clear(struct mosquitto_sqlite *ms, const char *clientid) { int rc = MOSQ_ERR_UNKNOWN; if(sqlite3_bind_text(ms->client_msg_clear_all_stmt, 1, clientid, (int)strlen(clientid), SQLITE_STATIC) == SQLITE_OK){ ms->event_count++; rc = sqlite3_step(ms->client_msg_clear_all_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } sqlite3_reset(ms->client_msg_clear_all_stmt); return rc; } ================================================ FILE: plugins/persist-sqlite/clients.c ================================================ /* Copyright (c) 2021 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 "mosquitto/broker.h" #include "persist_sqlite.h" #include "util.h" int persist_sqlite__client_add_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_client *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = MOSQ_ERR_UNKNOWN; time_t now; UNUSED(event); if(sqlite3_bind_text(ms->client_add_stmt, 1, ed->data.clientid, (int)strlen(ed->data.clientid), SQLITE_STATIC) == SQLITE_OK){ if(ed->data.username){ sqlite3_bind_text(ms->client_add_stmt, 2, ed->data.username, (int)strlen(ed->data.username), SQLITE_STATIC); }else{ sqlite3_bind_null(ms->client_add_stmt, 2); } now = time(NULL); if(sqlite3_bind_int64(ms->client_add_stmt, 3, now) == SQLITE_OK && sqlite3_bind_int64(ms->client_add_stmt, 4, ed->data.will_delay_time) == SQLITE_OK && sqlite3_bind_int64(ms->client_add_stmt, 5, ed->data.session_expiry_time) == SQLITE_OK && sqlite3_bind_int(ms->client_add_stmt, 6, ed->data.listener_port) == SQLITE_OK && sqlite3_bind_int(ms->client_add_stmt, 7, (int)ed->data.max_packet_size) == SQLITE_OK && sqlite3_bind_int(ms->client_add_stmt, 8, ed->data.max_qos) == SQLITE_OK && sqlite3_bind_int(ms->client_add_stmt, 9, ed->data.retain_available) == SQLITE_OK && sqlite3_bind_int(ms->client_add_stmt, 10, (int)ed->data.session_expiry_interval) == SQLITE_OK && sqlite3_bind_int(ms->client_add_stmt, 11, (int)ed->data.will_delay_interval) == SQLITE_OK ){ ms->event_count++; rc = sqlite3_step(ms->client_add_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } } sqlite3_reset(ms->client_add_stmt); return rc; } int persist_sqlite__client_remove_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_client *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = 1; UNUSED(event); if(sqlite3_bind_text(ms->subscription_clear_stmt, 1, ed->data.clientid, (int)strlen(ed->data.clientid), SQLITE_STATIC) == SQLITE_OK){ ms->event_count++; rc = sqlite3_step(ms->subscription_clear_stmt); sqlite3_reset(ms->subscription_clear_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } /* Delete base msgs before deletion of client_msgs as the query will iterate over the client_msgs table */ persist_sqlite__base_msg_clear(ms, ed->data.clientid); persist_sqlite__client_msg_clear(ms, ed->data.clientid); if(sqlite3_bind_text(ms->client_remove_stmt, 1, ed->data.clientid, (int)strlen(ed->data.clientid), SQLITE_STATIC) == SQLITE_OK){ ms->event_count++; rc = sqlite3_step(ms->client_remove_stmt); sqlite3_reset(ms->client_remove_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } return rc; } int persist_sqlite__client_update_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_client *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = 1; UNUSED(event); if(sqlite3_bind_int64(ms->client_update_stmt, 1, ed->data.session_expiry_time) == SQLITE_OK && sqlite3_bind_int64(ms->client_update_stmt, 2, ed->data.will_delay_time) == SQLITE_OK && sqlite3_bind_text(ms->client_update_stmt, 3, ed->data.clientid, (int)strlen(ed->data.clientid), SQLITE_STATIC) == SQLITE_OK ){ ms->event_count++; rc = sqlite3_step(ms->client_update_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } sqlite3_reset(ms->client_update_stmt); return rc; } ================================================ FILE: plugins/persist-sqlite/common.c ================================================ /* Copyright (c) 2021 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 "persist_sqlite.h" int persist_sqlite__client_msg_remove(struct mosquitto_sqlite *ms, const char *clientid, int64_t store_id, int direction) { int rc = 1; mosquitto_log_printf(MOSQ_LOG_DEBUG, "Drop message clientid %s store_id %ld direction %d", clientid, store_id, direction); if(sqlite3_bind_text(ms->client_msg_remove_stmt, 1, clientid, (int)strlen(clientid), SQLITE_STATIC) == SQLITE_OK && sqlite3_bind_int64(ms->client_msg_remove_stmt, 2, store_id) == SQLITE_OK && sqlite3_bind_int(ms->client_msg_remove_stmt, 3, direction) == SQLITE_OK ){ rc = sqlite3_step(ms->client_msg_remove_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } sqlite3_reset(ms->client_msg_remove_stmt); return rc; } ================================================ FILE: plugins/persist-sqlite/init.c ================================================ /* Copyright (c) 2021 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 "persist_sqlite.h" #include "mosquitto.h" #include "mosquitto/broker.h" static int extract_version_numbers(void *data_ptr, int num_columns, char **values, char **column_names) { unsigned int found = 0; int *version_array = (int *)data_ptr; for(int i = 0; i < num_columns; ++i){ if(!sqlite3_stricmp(column_names[i], "MAJOR")){ version_array[0] = values[i] ? atoi(values[i]) : 0; found |= 0x4; }else if(!sqlite3_stricmp(column_names[i], "MINOR")){ version_array[1] = values[i] ? atoi(values[i]) : 0; found |= 0x2; }else if(!sqlite3_stricmp(column_names[i], "PATCH")){ version_array[2] = values[i] ? atoi(values[i]) : 0; found |= 0x1; } } if(found != 0x7){ return SQLITE_MISMATCH; } return SQLITE_OK; } static int create_tables_1_1(struct mosquitto_sqlite *ms) { int rc; rc = sqlite3_exec(ms->db, "CREATE TABLE IF NOT EXISTS wills " "(" "client_id TEXT PRIMARY KEY," "payload BLOB," "topic STRING NOT NULL," "payloadlen INTEGER," "qos INTEGER," "retain INTEGER," "properties STRING" ");", NULL, NULL, NULL); if(rc){ return rc; } rc = sqlite3_exec((*ms).db, "UPDATE version_info" " SET major = 1, minor = 1, patch = 0" " WHERE component = 'database_schema';", NULL, NULL, NULL); if(rc){ return rc; } return 0; } static int create_tables(struct mosquitto_sqlite *ms) { int rc; int db_schema_version[3] = { 0, 0, 0 }; rc = sqlite3_exec(ms->db, "CREATE TABLE IF NOT EXISTS base_msgs " "(" "store_id INT64 PRIMARY KEY," "expiry_time INT64," "topic STRING NOT NULL," "payload BLOB," "source_id STRING," "source_username STRING," "payloadlen INTEGER," "source_mid INTEGER," "source_port INTEGER," "qos INTEGER," "retain INTEGER," "properties STRING" ");", NULL, NULL, NULL); if(rc){ goto fail; } rc = sqlite3_exec(ms->db, "CREATE TABLE IF NOT EXISTS retains " "(" "topic STRING PRIMARY KEY," "store_id INT64" //"FOREIGN KEY (store_id) REFERENCES msg_store(store_id) " //"ON DELETE CASCADE" ");", NULL, NULL, NULL); if(rc){ goto fail; } rc = sqlite3_exec(ms->db, "CREATE TABLE IF NOT EXISTS clients " "(" "client_id TEXT PRIMARY KEY," "username TEXT," "connection_time INT64," "will_delay_time INT64," "session_expiry_time INT64," "listener_port INT," "max_packet_size INT," "max_qos INT," "retain_available INT," "session_expiry_interval INT," "will_delay_interval INT" ");", NULL, NULL, NULL); if(rc){ goto fail; } rc = sqlite3_exec(ms->db, "CREATE TABLE IF NOT EXISTS subscriptions " "(" "client_id TEXT NOT NULL," "topic TEXT NOT NULL," "subscription_options INTEGER," "subscription_identifier INTEGER," "PRIMARY KEY (client_id, topic) " ");", NULL, NULL, NULL); if(rc){ goto fail; } rc = sqlite3_exec(ms->db, "CREATE TABLE IF NOT EXISTS client_msgs " "(" "client_id TEXT NOT NULL," "cmsg_id INT64," "store_id INT64," "dup INTEGER," "direction INTEGER," "mid INTEGER," "qos INTEGER," "retain INTEGER," "state INTEGER," "subscription_identifier INTEGER" //"state INTEGER," //"FOREIGN KEY (client_id) REFERENCES clients(client_id) " //"ON DELETE CASCADE," //"FOREIGN KEY (store_id) REFERENCES msg_store(store_id) " //"ON DELETE CASCADE" ");", NULL, NULL, NULL); if(rc){ goto fail; } rc = sqlite3_exec(ms->db, "CREATE INDEX IF NOT EXISTS client_msgs_client_id ON client_msgs(client_id);", NULL, NULL, NULL); if(rc){ goto fail; } rc = sqlite3_exec(ms->db, "DROP INDEX IF EXISTS client_msgs_store_id;", NULL, NULL, NULL); if(rc){ goto fail; } rc = sqlite3_exec(ms->db, "CREATE INDEX IF NOT EXISTS client_msgs_store_id ON client_msgs(store_id,client_id);", NULL, NULL, NULL); if(rc){ goto fail; } rc = sqlite3_exec(ms->db, "CREATE INDEX IF NOT EXISTS retains_storeid ON retains(store_id);", NULL, NULL, NULL); if(rc){ goto fail; } sqlite3_exec(ms->db, "ALTER TABLE client_msgs ADD COLUMN cmsg_id INT64", NULL, NULL, NULL); sqlite3_exec(ms->db, "ALTER TABLE client_msgs ADD COLUMN subscription_identifier INT", NULL, NULL, NULL); rc = sqlite3_exec(ms->db, "CREATE TABLE IF NOT EXISTS version_info " "(" "component TEXT NOT NULL," "major INTEGER NOT NULL," "minor INTEGER NOT NULL," "patch INTEGER NOT NULL" ");", NULL, NULL, NULL); if(rc){ goto fail; } rc = sqlite3_exec(ms->db, "SELECT major,minor,patch" " FROM version_info " " WHERE component = 'database_schema';", &extract_version_numbers, db_schema_version, NULL); if(rc){ goto fail; } if(db_schema_version[0] == 0){ rc = sqlite3_exec((*ms).db, "INSERT INTO version_info(component,major,minor,patch) " "VALUES ('database_schema','1','0','0');", NULL, NULL, NULL); if(rc){ goto fail; } db_schema_version[0] = 1; db_schema_version[1] = 0; db_schema_version[2] = 0; } if(db_schema_version[0] == 1){ /* 1.0.x needs to be upgraded to 1.1 */ if(db_schema_version[1] == 0){ rc = create_tables_1_1(ms); if(rc){ goto fail; } db_schema_version[0] = 1; db_schema_version[1] = 1; db_schema_version[2] = 0; } /* 1.1.x is the current DB-Schema version */ if(db_schema_version[1] == 1){ return 0; } } mosquitto_log_printf(MOSQ_LOG_ERR, "Sqlite persistence: Unknown database_schema version %d.%d.%d", db_schema_version[0], db_schema_version[1], db_schema_version[2]); rc = MOSQ_ERR_INVAL; goto close_db; fail: mosquitto_log_printf(MOSQ_LOG_ERR, "Sqlite persistence: Error creating tables: %s %s", sqlite3_errstr(rc), ms->db ? sqlite3_errmsg(ms->db) : ""); close_db: sqlite3_close(ms->db); ms->db = NULL; return rc; } static int prepare_statements(struct mosquitto_sqlite *ms) { int rc; /* Subscriptions */ rc = sqlite3_prepare_v3(ms->db, "INSERT OR REPLACE INTO subscriptions " "(client_id, topic, subscription_options, subscription_identifier) " "VALUES (?,?,?,?)", -1, SQLITE_PREPARE_PERSISTENT, &ms->subscription_add_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "DELETE FROM subscriptions WHERE client_id=? and topic=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->subscription_remove_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "DELETE FROM subscriptions WHERE client_id=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->subscription_clear_stmt, NULL); if(rc){ goto fail; } /* Clients */ rc = sqlite3_prepare_v3(ms->db, "INSERT OR REPLACE INTO clients " "(client_id, username, connection_time, will_delay_time, session_expiry_time, " "listener_port, max_packet_size, max_qos, retain_available, " "session_expiry_interval, will_delay_interval) " "VALUES(?,?,?,?,?,?,?,?,?,?,?)", -1, SQLITE_PREPARE_PERSISTENT, &ms->client_add_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "DELETE FROM clients WHERE client_id=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->client_remove_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "UPDATE clients SET session_expiry_time=?, will_delay_time=? " "WHERE client_id=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->client_update_stmt, NULL); if(rc){ goto fail; } /* Client messages */ rc = sqlite3_prepare_v3(ms->db, "INSERT INTO client_msgs " "(client_id,cmsg_id,store_id,dup,direction,mid,qos,retain,state,subscription_identifier) " "VALUES(?,?,?,?,?,?,?,?,?,?)", -1, SQLITE_PREPARE_PERSISTENT, &ms->client_msg_add_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "DELETE FROM client_msgs WHERE client_id=? AND store_id=? AND direction=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->client_msg_remove_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "UPDATE client_msgs SET state=?,dup=? WHERE client_id=? AND store_id=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->client_msg_update_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "DELETE FROM client_msgs WHERE client_id=? AND direction=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->client_msg_clear_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "DELETE FROM client_msgs WHERE client_id=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->client_msg_clear_all_stmt, NULL); if(rc){ goto fail; } /* Message store */ rc = sqlite3_prepare_v3(ms->db, "INSERT INTO base_msgs " "(store_id, expiry_time, topic, payload, source_id, source_username, " "payloadlen, source_mid, source_port, qos, retain, properties) " "VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", -1, SQLITE_PREPARE_PERSISTENT, &ms->base_msg_add_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "DELETE FROM base_msgs WHERE store_id=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->base_msg_remove_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "DELETE FROM base_msgs AS bm " "WHERE bm.store_id IN " "( SELECT cm.store_id FROM client_msgs AS cm" " LEFT OUTER JOIN client_msgs AS oc ON oc.store_id = cm.store_id AND oc.client_id != cm.client_id" " LEFT OUTER JOIN retains AS rm ON rm.store_id = cm.store_id" " WHERE cm.client_id = ? AND oc.store_id IS NULL AND rm.store_id IS NULL)", -1, SQLITE_PREPARE_PERSISTENT, &ms->base_msg_remove_for_clientid_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "SELECT store_id, expiry_time, topic, payload, source_id, source_username, " "payloadlen, source_mid, source_port, qos, retain, properties " "FROM base_msgs WHERE store_id=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->base_msg_load_stmt, NULL); if(rc){ goto fail; } /* Retains */ rc = sqlite3_prepare_v3(ms->db, "INSERT OR REPLACE INTO retains " "(topic, store_id)" "VALUES(?,?)", -1, SQLITE_PREPARE_PERSISTENT, &ms->retain_msg_set_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "DELETE FROM retains WHERE topic=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->retain_msg_remove_stmt, NULL); if(rc){ goto fail; } /* Will messages */ rc = sqlite3_prepare_v3(ms->db, "INSERT OR REPLACE INTO wills " "(client_id, payload, topic, payloadlen, qos, retain, properties)" "VALUES(?,?,?,?,?,?,?)", -1, SQLITE_PREPARE_PERSISTENT, &ms->will_add_stmt, NULL); if(rc){ goto fail; } rc = sqlite3_prepare_v3(ms->db, "DELETE FROM wills WHERE client_id=?", -1, SQLITE_PREPARE_PERSISTENT, &ms->will_remove_stmt, NULL); if(rc){ goto fail; } return 0; fail: mosquitto_log_printf(MOSQ_LOG_ERR, "Sqlite persistence: Error preparing statements: %s", sqlite3_errstr(rc)); sqlite3_close(ms->db); ms->db = NULL; return 1; } int persist_sqlite__init(struct mosquitto_sqlite *ms) { int rc; char buf[50]; rc = sqlite3_open_v2(ms->db_file, &ms->db, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, NULL); if(rc != SQLITE_OK){ mosquitto_log_printf(MOSQ_LOG_ERR, "Sqlite persistence: Error opening %s: %s", ms->db_file, sqlite3_errstr(rc)); return MOSQ_ERR_UNKNOWN; } snprintf(buf, sizeof(buf), "PRAGMA page_size=%u;", ms->page_size); rc = sqlite3_exec(ms->db, buf, NULL, NULL, NULL); if(rc){ goto fail; } rc = sqlite3_exec(ms->db, "PRAGMA journal_mode=WAL;", NULL, NULL, NULL); if(rc){ goto fail; } rc = sqlite3_exec(ms->db, "PRAGMA foreign_keys = ON;", NULL, NULL, NULL); if(rc){ goto fail; } snprintf(buf, sizeof(buf), "PRAGMA synchronous=%d;", ms->synchronous); rc = sqlite3_exec(ms->db, buf, NULL, NULL, NULL); if(rc){ goto fail; } rc = create_tables(ms); if(rc){ return rc; } rc = prepare_statements(ms); if(rc){ return rc; } sqlite3_exec(ms->db, "BEGIN;", NULL, NULL, NULL); return MOSQ_ERR_SUCCESS; fail: mosquitto_log_printf(MOSQ_LOG_ERR, "Sqlite persistence: Error opening database: %s", sqlite3_errstr(rc)); return MOSQ_ERR_UNKNOWN; } void persist_sqlite__cleanup(struct mosquitto_sqlite *ms) { if(ms->db){ int rc = sqlite3_exec(ms->db, "END;", NULL, NULL, NULL); if(rc != SQLITE_OK){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Sqlite persistence: Closing final transaction %s", sqlite3_errstr(rc)); } } sqlite3_finalize(ms->client_add_stmt); sqlite3_finalize(ms->client_remove_stmt); sqlite3_finalize(ms->client_update_stmt); sqlite3_finalize(ms->subscription_add_stmt); sqlite3_finalize(ms->subscription_remove_stmt); sqlite3_finalize(ms->subscription_clear_stmt); sqlite3_finalize(ms->client_msg_add_stmt); sqlite3_finalize(ms->client_msg_remove_stmt); sqlite3_finalize(ms->client_msg_update_stmt); sqlite3_finalize(ms->client_msg_clear_stmt); sqlite3_finalize(ms->client_msg_clear_all_stmt); sqlite3_finalize(ms->base_msg_add_stmt); sqlite3_finalize(ms->base_msg_remove_stmt); sqlite3_finalize(ms->base_msg_remove_for_clientid_stmt); sqlite3_finalize(ms->base_msg_load_stmt); sqlite3_finalize(ms->retain_msg_set_stmt); sqlite3_finalize(ms->retain_msg_remove_stmt); sqlite3_finalize(ms->will_add_stmt); sqlite3_finalize(ms->will_remove_stmt); if(ms->db){ int rc = sqlite3_wal_checkpoint_v2(ms->db, NULL, SQLITE_CHECKPOINT_TRUNCATE, NULL, NULL); if(rc != SQLITE_OK){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Warning: Sqlite persistence: Final wal_checkpoint %s", sqlite3_errstr(rc)); } rc = sqlite3_close(ms->db); if(rc != SQLITE_OK){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Warning: Sqlite persistence: Error closing database: %s", sqlite3_errstr(rc)); } ms->db = NULL; } mosquitto_log_printf(MOSQ_LOG_INFO, "Sqlite persistence: Closed DB"); } ================================================ FILE: plugins/persist-sqlite/migrate_to_persist_sqlite.py ================================================ #!/usr/bin/env python3 """ Migration script to migrate from Snapshot persistence to Persist SQLite Plugin. """ import argparse import base64 import json import shutil import sqlite3 import subprocess import sys from pathlib import Path # use Path to be able to handle Windows as well from typing import Self # Snapshot persistence class SnapshotPersistence: def __init__(self, json_dump: str): j_snapshot_persistence = json.loads(json_dump) self.base_messages: list[dict] = j_snapshot_persistence["base-messages"] self.clients: list[dict] = j_snapshot_persistence["clients"] self.client_messages: list[dict] = j_snapshot_persistence["client-messages"] self.retained_messages: list[dict] = j_snapshot_persistence["retained-messages"] self.subscriptions: list[dict] = j_snapshot_persistence["subscriptions"] # SQlite3 DB class SQLite3Persistence: def __init__(self): self.__store_id_topic_map: dict[int, str] = {} self.__db_path: Path = Path(__file__).parent.resolve() / "mosquitto.sqlite3" self.__conn: sqlite3.Connection = None self.__cursor: sqlite3.Cursor = None self.__init_db() def __del__(self): self.__close_db() def __close_db(self): if self.__cursor is not None: self.__cursor.close() if self.__conn is not None: self.__conn.commit() self.__conn.close() def __on_error(self): self.__close_db() self.__db_path.unlink(missing_ok=True) sys.exit(1) def __init_db(self): try: self.__conn = sqlite3.connect(self.__db_path) self.__cursor = self.__conn.cursor() self.__create_tables() self.__create_indices() except sqlite3.Error as err: print(f"Error during SQLite3 DB initialization. Reason: {str(err)}") self.__on_error() def __create_clients_table(self): self.__cursor.execute( "CREATE TABLE IF NOT EXISTS clients " "(" "client_id TEXT PRIMARY KEY," "username TEXT," "connection_time INT64," "will_delay_time INT64," "session_expiry_time INT64," "listener_port INT," "max_packet_size INT," "max_qos INT," "retain_available INT," "session_expiry_interval INT," "will_delay_interval INT" ");", ) def __create_client_msgs_table(self): self.__cursor.execute( "CREATE TABLE IF NOT EXISTS client_msgs " "(" "client_id TEXT NOT NULL," "cmsg_id INT64," "store_id INT64," "dup INTEGER," "direction INTEGER," "mid INTEGER," "qos INTEGER," "retain INTEGER," "state INTEGER," "subscription_identifier INT" # "state INTEGER," # "FOREIGN KEY (client_id) REFERENCES clients(client_id) " # "ON DELETE CASCADE," # "FOREIGN KEY (store_id) REFERENCES msg_store(store_id) " # "ON DELETE CASCADE" ");" ) def __create_base_msgs_table(self): self.__cursor.execute( "CREATE TABLE IF NOT EXISTS base_msgs " "(" "store_id INT64 PRIMARY KEY," "expiry_time INT64," "topic STRING NOT NULL," "payload BLOB," "source_id STRING," "source_username STRING," "payloadlen INTEGER," "source_mid INTEGER," "source_port INTEGER," "qos INTEGER," "retain INTEGER," "properties STRING" ");" ) def __create_retains_table(self): self.__cursor.execute( "CREATE TABLE IF NOT EXISTS retains " "(" "topic STRING PRIMARY KEY," "store_id INT64" # "FOREIGN KEY (store_id) REFERENCES msg_store(store_id) " # "ON DELETE CASCADE" ");" ) def __create_subscriptions_table(self): self.__cursor.execute( "CREATE TABLE IF NOT EXISTS subscriptions " "(" "client_id TEXT NOT NULL," "topic TEXT NOT NULL," "subscription_options INTEGER," "subscription_identifier INTEGER," "PRIMARY KEY (client_id, topic)" ");", ) def __create_version_info_table(self): self.__cursor.execute( "CREATE TABLE IF NOT EXISTS version_info " "(" "component TEXT NOT NULL," "major INTEGER NOT NULL," "minor INTEGER NOT NULL," "patch INTEGER NOT NULL" ");" ) def __create_tables(self): self.__create_clients_table() self.__create_client_msgs_table() self.__create_base_msgs_table() self.__create_retains_table() self.__create_subscriptions_table() self.__create_version_info_table() def __create_indices(self): self.__cursor.execute( "CREATE INDEX IF NOT EXISTS client_msgs_client_id ON client_msgs(client_id);" ) self.__cursor.execute("DROP INDEX IF EXISTS client_msgs_store_id;") self.__cursor.execute( "CREATE INDEX IF NOT EXISTS client_msgs_store_id ON client_msgs(store_id,client_id);" ) self.__cursor.execute( "CREATE INDEX IF NOT EXISTS retains_storeid ON retains(store_id);" ) def __add_clients(self, clients: list[dict]): self.__cursor.executemany( "INSERT OR REPLACE INTO clients " "(client_id, username, connection_time, will_delay_time, session_expiry_time, " "listener_port, max_packet_size, max_qos, retain_available, " "session_expiry_interval, will_delay_interval) " "VALUES(?,?,?,?,?,?,?,?,?,?,?)", [ ( client["clientid"], client["username"], 0, # connection_time 0, # will_delay_time client["session-expiry-time"], client["listener-port"], 0, # max_packet_size 2, # max_qos True, # retain_available client["session-expiry-interval"], 0, # will_delay_interval ) for client in clients ], ) def __add_client_msgs(self, client_msgs: list[dict]): for cmsg_counter, client_msg in enumerate(client_msgs, start=1): self.__cursor.execute( "INSERT INTO client_msgs " "(client_id,cmsg_id,store_id,dup,direction,mid,qos," "retain,state,subscription_identifier) " "VALUES(?,?,?,?,?,?,?,?,?,?)", ( client_msg["clientid"], cmsg_counter, # cmsg_id client_msg["storeid"], 0, # dup client_msg["direction"], client_msg["mid"], client_msg["qos"], False, # retain client_msg["state"], client_msg["subscription-identifier"], ), ) def __add_base_msgs(self, base_msgs: list[dict]): for base_msg in base_msgs: self.__store_id_topic_map.update({base_msg["storeid"]: base_msg["topic"]}) payload = base64.b64decode(base_msg["payload"]) if "payload" in base_msg else None self.__cursor.execute( "INSERT INTO base_msgs " "(store_id, expiry_time, topic, payload, source_id, source_username, " "payloadlen, source_mid, source_port, qos, retain, properties) " "VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", ( base_msg["storeid"], base_msg["expiry-time"], base_msg["topic"], payload if "payload" in base_msg else None, base_msg["clientid"] if "clientid" in base_msg else None, base_msg["username"] if "username" in base_msg else None, len(payload) if "username" in base_msg else 0, base_msg["source-mid"], base_msg["source-port"], base_msg["qos"], base_msg["retain"], base_msg["properties"] if "properties" in base_msg else None, ), ) def __add_subscriptions(self, subscriptions: list[dict]): self.__cursor.executemany( "INSERT OR REPLACE INTO subscriptions " "(client_id, topic, subscription_options, subscription_identifier) " "VALUES (?,?,?,?)", [ ( subscription["clientid"], subscription["topic"], subscription["options"], subscription["identifier"], ) for subscription in subscriptions ], ) def __add_retained_messages(self, retained_messages: list[dict]): self.__cursor.executemany( "INSERT OR REPLACE INTO retains (topic, store_id) VALUES(?,?)", [ ( self.__store_id_topic_map[retained_message["storeid"]], retained_message["storeid"], ) for retained_message in retained_messages ], ) def migrate_to_persist_sqlite( self, snapshot_persistence: SnapshotPersistence ) -> Self: try: # self.__add_base_msgs must be executed before self.__add_retained_messages gets invoked self.__add_base_msgs(snapshot_persistence.base_messages) self.__add_retained_messages(snapshot_persistence.retained_messages) self.__add_subscriptions(snapshot_persistence.subscriptions) self.__add_clients(snapshot_persistence.clients) self.__add_client_msgs(snapshot_persistence.client_messages) except (sqlite3.Error, TypeError) as err: print(f"Error during SQLite3 DB creation. Reason: {str(err)}") self.__on_error() # Migration def find_mosquitto_db_dump() -> str: mosquitto_db_dump = shutil.which("mosquitto_db_dump") if mosquitto_db_dump is None: raise RuntimeError( 'Could not find mosquitto_db_dump. Provide the path via the "--dump-tool" argument ' "or make sure the executable is contained in your system's path." ) return mosquitto_db_dump def dump_mosquitto_db_to_json( mosquitto_db_dump: str, persistence_db_path: Path ) -> str: return subprocess.check_output( [ mosquitto_db_dump, "--json", str(persistence_db_path), ] ).decode(encoding="utf-8") def migrate_mosquitto_conf(mosquitto_conf: str, persist_sqlite_lib_path: Path) -> str: migrated_mosquitto_conf: list[str] = [] for line in mosquitto_conf.splitlines(): if line.startswith("persistence true"): migrated_mosquitto_conf.append(f"plugin {str(persist_sqlite_lib_path)}") continue migrated_mosquitto_conf.append(line) return "\n".join(migrated_mosquitto_conf) def main(): parser = argparse.ArgumentParser() parser.add_argument( "--persistence-db", required=True, type=str, help="Path to mosquitto.db file" ) parser.add_argument( "--conf", required=False, type=str, help="Path to mosquitto.conf file" ) parser.add_argument( "--persist-sqlite-lib", required=False, type=str, help="Path to mosquitto_persist_sqlite.so/.dll", ) parser.add_argument( "--dump-tool", required=False, type=str, help="Path to mosquitto_db_dump executable", ) # support local builds args = parser.parse_args() persistence_db_path = Path(args.persistence_db) mosquitto_db_dump = ( args.dump_tool if args.dump_tool else find_mosquitto_db_dump() ) if args.conf is not None: if args.persist_sqlite_lib is None: print( "Error: Cannot migrate mosquitto.conf file. Reason: --persist-sqlite-lib argument is missing" ) sys.exit(1) # Migrate mosquitto.conf mosquitto_conf_path = Path(args.conf) mosquitto_conf = mosquitto_conf_path.read_text(encoding="utf-8") migrated_mosquitto_conf = migrate_mosquitto_conf( mosquitto_conf, Path(args.persist_sqlite_lib) ) # Backup old mosquitto.conf and afterwards write migrated mosquitto.conf file mosquitto_conf_path.with_suffix(".conf.old.persistence").write_text( mosquitto_conf, encoding="utf-8" ) mosquitto_conf_path.write_text(migrated_mosquitto_conf, encoding="utf-8") # Dump Snapshot persistence and parse JSON snapshot_persistence = SnapshotPersistence( dump_mosquitto_db_to_json(mosquitto_db_dump, persistence_db_path) ) # Migrate Snapshot persistence and write SQLite3 file SQLite3Persistence().migrate_to_persist_sqlite(snapshot_persistence) if __name__ == "__main__": main() ================================================ FILE: plugins/persist-sqlite/persist_sqlite.h ================================================ /* Copyright (c) 2021,2022 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_SQLITE_H #define PERSIST_SQLITE_H #include #include #include #ifndef UNUSED # define UNUSED(A) (void)(A) #endif struct mosquitto_sqlite { char *db_file; sqlite3 *db; sqlite3_stmt *client_add_stmt; sqlite3_stmt *client_remove_stmt; sqlite3_stmt *client_update_stmt; sqlite3_stmt *subscription_add_stmt; sqlite3_stmt *subscription_remove_stmt; sqlite3_stmt *subscription_clear_stmt; sqlite3_stmt *client_msg_add_stmt; sqlite3_stmt *client_msg_remove_stmt; sqlite3_stmt *client_msg_update_stmt; sqlite3_stmt *client_msg_clear_stmt; sqlite3_stmt *client_msg_clear_all_stmt; sqlite3_stmt *base_msg_add_stmt; sqlite3_stmt *base_msg_remove_stmt; sqlite3_stmt *base_msg_remove_for_clientid_stmt; sqlite3_stmt *base_msg_load_stmt; sqlite3_stmt *retain_msg_set_stmt; sqlite3_stmt *retain_msg_remove_stmt; sqlite3_stmt *will_add_stmt; sqlite3_stmt *will_remove_stmt; int synchronous; unsigned int event_count; unsigned int flush_period; unsigned int page_size; }; int persist_sqlite__init(struct mosquitto_sqlite *ms); void persist_sqlite__cleanup(struct mosquitto_sqlite *ms); int persist_sqlite__restore_cb(int event, void *event_data, void *userdata); int persist_sqlite__client_msg_remove(struct mosquitto_sqlite *ms, const char *clientid, int64_t store_id, int direction); int persist_sqlite__client_add_cb(int event, void *event_data, void *userdata); int persist_sqlite__client_update_cb(int event, void *event_data, void *userdata); int persist_sqlite__client_remove_cb(int event, void *event_data, void *userdata); int persist_sqlite__client_msg_add_cb(int event, void *event_data, void *userdata); int persist_sqlite__client_msg_clear(struct mosquitto_sqlite *ms, const char *clientid); int persist_sqlite__client_msg_remove_cb(int event, void *event_data, void *userdata); int persist_sqlite__client_msg_update_cb(int event, void *event_data, void *userdata); int persist_sqlite__base_msg_add_cb(int event, void *event_data, void *userdata); int persist_sqlite__base_msg_load_cb(int event, void *event_data, void *userdata); int persist_sqlite__base_msg_remove_cb(int event, void *event_data, void *userdata); int persist_sqlite__base_msg_clear(struct mosquitto_sqlite *ms, const char *clientid); int persist_sqlite__retain_msg_set_cb(int event, void *event_data, void *userdata); int persist_sqlite__retain_msg_remove_cb(int event, void *event_data, void *userdata); int persist_sqlite__subscription_add_cb(int event, void *event_data, void *userdata); int persist_sqlite__subscription_remove_cb(int event, void *event_data, void *userdata); int persist_sqlite__will_add_cb(int event, void *event_data, void *userdata); int persist_sqlite__will_remove_cb(int event, void *event_data, void *userdata); int persist_sqlite__tick_cb(int event, void *event_data, void *userdata); #endif ================================================ FILE: plugins/persist-sqlite/plugin.c ================================================ /* Copyright (c) 2021 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 # include #else # include #endif #include "mosquitto.h" #include "mosquitto/broker.h" #include "mosquitto/broker_plugin.h" #include "mosquitto/mqtt_protocol.h" #include "persist_sqlite.h" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *plg_id = NULL; static struct mosquitto_sqlite plg_data; static int conf_parse_uint(const char *in, const char *name, unsigned int *value, int min_value) { int v = atoi(in); if(v < min_value){ mosquitto_log_printf(MOSQ_LOG_ERR, "Error: Invalid '%s' value %d in configuration.", name, v); return MOSQ_ERR_INVAL; } *value = (unsigned int)v; return MOSQ_ERR_SUCCESS; } static void set_defaults(void) { /* "normal" synchronous mode. */ plg_data.synchronous = 1; /* 5 seconds */ plg_data.flush_period = 5; plg_data.page_size = 4 * 1024; } static int get_db_file(struct mosquitto_opt *options, int option_count) { const char *persistence_location; int i; persistence_location = mosquitto_persistence_location(); if(persistence_location){ #ifdef WIN32 (void)mkdir(persistence_location); #else (void)mkdir(persistence_location, 0770); #endif plg_data.db_file = malloc(strlen(persistence_location) + 1 + strlen("/mosquitto.sqlite3")); if(!plg_data.db_file){ mosquitto_log_printf(MOSQ_LOG_INFO, "Sqlite persistence: Out of memory."); return MOSQ_ERR_NOMEM; } sprintf(plg_data.db_file, "%s/mosquitto.sqlite3", persistence_location); }else{ 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 #include #include #include #include "json_help.h" #include "mosquitto.h" #include "mosquitto/broker.h" #include "mosquitto/mqtt_protocol.h" #include "persist_sqlite.h" static uint8_t hex2nibble(char c) { switch(c){ case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'A': return 10; case 'a': return 10; case 'B': return 11; case 'b': return 11; case 'C': return 12; case 'c': return 12; case 'D': return 13; case 'd': return 13; case 'E': return 14; case 'e': return 14; case 'F': return 15; case 'f': return 15; default: return 0; } } static mosquitto_property *json_to_properties(const char *json) { mosquitto_property *properties = NULL; cJSON *array, *obj, *j_value; int propid, proptype; size_t slen; if(!json){ return NULL; } array = cJSON_Parse(json); if(!array){ return NULL; } if(!cJSON_IsArray(array)){ cJSON_Delete(array); return NULL; } cJSON_ArrayForEach(obj, array){ const char *identifier; j_value = cJSON_GetObjectItem(obj, "value"); if(json_get_string(obj, "identifier", &identifier, false) != MOSQ_ERR_SUCCESS || !j_value){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Ignoring property whilst restoring, invalid identifier / value"); continue; } if(mosquitto_string_to_property_info(identifier, &propid, &proptype)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Ignoring property whilst restoring, unknown identifier"); continue; } switch(proptype){ case MQTT_PROP_TYPE_BYTE: if(!cJSON_IsNumber(j_value)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Ignoring %s property whilst restoring, value is incorrect type", "byte"); continue; } if(mosquitto_property_add_byte(&properties, propid, (uint8_t)j_value->valueint)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Out of memory whilst restoring %s property", "byte"); continue; } break; case MQTT_PROP_TYPE_INT16: if(!cJSON_IsNumber(j_value)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Ignoring %s property whilst restoring, value is incorrect type", "int16"); continue; } if(mosquitto_property_add_int16(&properties, propid, (uint16_t)j_value->valueint)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Out of memory whilst restoring %s property", "int16"); continue; } break; case MQTT_PROP_TYPE_INT32: if(!cJSON_IsNumber(j_value)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Ignoring %s property whilst restoring, value is incorrect type", "int32"); continue; } if(mosquitto_property_add_int32(&properties, propid, (uint32_t)j_value->valueint)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Out of memory whilst restoring %s property", "int32"); continue; } break; case MQTT_PROP_TYPE_VARINT: if(!cJSON_IsNumber(j_value)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Ignoring %s property whilst restoring, value is incorrect type", "varint"); continue; } if(mosquitto_property_add_varint(&properties, propid, (uint32_t)j_value->valueint)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Out of memory whilst restoring %s property", "varint"); continue; } break; case MQTT_PROP_TYPE_BINARY: if(!cJSON_IsString(j_value)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Ignoring %s property whilst restoring, value is incorrect type", "binary"); continue; } uint8_t *binstr = NULL; uint16_t len = 0; if(j_value->valuestring){ slen = strlen(j_value->valuestring); if(slen/2 > UINT16_MAX){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Ignoring %s property whilst restoring, value is too large", "binary"); continue; } for(size_t i=0; ivaluestring)[i/2] = (uint8_t)(hex2nibble(j_value->valuestring[i])<<4) + hex2nibble(j_value->valuestring[i+1]); } binstr = (uint8_t *)j_value->valuestring; len = (uint16_t)slen/2; } if(mosquitto_property_add_binary(&properties, propid, binstr, len)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Out of memory whilst restoring %s property", "binary"); continue; } break; case MQTT_PROP_TYPE_STRING: if(!cJSON_IsString(j_value)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Ignoring %s property whilst restoring, value is incorrect type", "string"); continue; } if(mosquitto_property_add_string(&properties, propid, j_value->valuestring)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Out of memory whilst restoring %s property", "string"); continue; } break; case MQTT_PROP_TYPE_STRING_PAIR: { const char *prop_name; if(!cJSON_IsString(j_value)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Ignoring %s property whilst restoring, value is incorrect type", "string pair"); continue; } if(json_get_string(obj, "name", &prop_name, false) != MOSQ_ERR_SUCCESS){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Ignoring string pair property whilst restoring, name is missing or incorrect type"); continue; } if(mosquitto_property_add_string_pair(&properties, propid, prop_name, j_value->valuestring)){ mosquitto_log_printf(MOSQ_LOG_WARNING, "Sqlite persistence: Out of memory whilst restoring %s property", "string pair"); continue; } } break; } } cJSON_Delete(array); return properties; } static int client_restore(struct mosquitto_sqlite *ms) { sqlite3_stmt *stmt; int rc; struct mosquitto_client client; long count = 0, failed = 0; const char *str; memset(&client, 0, sizeof(client)); rc = sqlite3_prepare_v2(ms->db, "SELECT client_id,username,will_delay_time,session_expiry_time," "listener_port,max_packet_size,max_qos," "retain_available,session_expiry_interval,will_delay_interval " "FROM clients", -1, &stmt, NULL); if(rc != SQLITE_OK){ mosquitto_log_printf(MOSQ_LOG_ERR, "sqlite: Error restoring clients: %s", sqlite3_errstr(rc)); return MOSQ_ERR_UNKNOWN; } while(sqlite3_step(stmt) == SQLITE_ROW){ str = (const char *)sqlite3_column_text(stmt, 0); if(str){ client.clientid = mosquitto_strdup(str); } str = (const char *)sqlite3_column_text(stmt, 1); if(str){ client.username = mosquitto_strdup(str); } client.will_delay_time = (time_t)sqlite3_column_int64(stmt, 2); client.session_expiry_time = (time_t)sqlite3_column_int64(stmt, 3); client.listener_port = (uint16_t)sqlite3_column_int(stmt, 4); client.max_packet_size = (uint32_t)sqlite3_column_int(stmt, 5); client.max_qos = (uint8_t)sqlite3_column_int(stmt, 6); client.retain_available = (bool)sqlite3_column_int(stmt, 7); client.session_expiry_interval = (uint32_t)sqlite3_column_int(stmt, 8); client.will_delay_interval = (uint32_t)sqlite3_column_int(stmt, 9); rc = mosquitto_persist_client_add(&client); if(rc == MOSQ_ERR_SUCCESS){ count++; }else{ failed++; } } sqlite3_finalize(stmt); mosquitto_log_printf(MOSQ_LOG_INFO, "sqlite: Restored %ld clients (%ld failed)", count, failed); return rc; } static int subscription_restore(struct mosquitto_sqlite *ms) { sqlite3_stmt *stmt; struct mosquitto_subscription sub; int rc; long count = 0, failed = 0; rc = sqlite3_prepare_v2(ms->db, "SELECT client_id,topic,subscription_options,subscription_identifier " "FROM subscriptions", -1, &stmt, NULL); if(rc != SQLITE_OK){ mosquitto_log_printf(MOSQ_LOG_ERR, "sqlite: Error restoring subscriptions: %s", sqlite3_errstr(rc)); return MOSQ_ERR_UNKNOWN; } while(sqlite3_step(stmt) == SQLITE_ROW){ memset(&sub, 0, sizeof(sub)); sub.clientid = (char *)sqlite3_column_text(stmt, 0); sub.topic_filter = (char *)sqlite3_column_text(stmt, 1); sub.options = (uint8_t)sqlite3_column_int(stmt, 2); sub.identifier = (uint32_t)sqlite3_column_int(stmt, 3); rc = mosquitto_subscription_add(&sub); if(rc == MOSQ_ERR_SUCCESS){ count++; }else{ failed++; } } sqlite3_finalize(stmt); mosquitto_log_printf(MOSQ_LOG_INFO, "sqlite: Restored %ld subscriptions (%ld failed)", count, failed); return MOSQ_ERR_SUCCESS; } static int base_msg_restore(struct mosquitto_sqlite *ms) { sqlite3_stmt *stmt; struct mosquitto_base_msg base_msg; int rc; long count = 0, failed = 0; const char *str; const void *payload; rc = sqlite3_prepare_v2(ms->db, "SELECT store_id, expiry_time, topic, payload, source_id, source_username, payloadlen, source_mid, source_port, qos, retain, properties " "FROM base_msgs", -1, &stmt, NULL); if(rc != SQLITE_OK){ mosquitto_log_printf(MOSQ_LOG_ERR, "sqlite: Error restoring messages: %s", sqlite3_errstr(rc)); return MOSQ_ERR_UNKNOWN; } while(sqlite3_step(stmt) == SQLITE_ROW){ memset(&base_msg, 0, sizeof(base_msg)); base_msg.store_id = (uint64_t)sqlite3_column_int64(stmt, 0); base_msg.expiry_time = (time_t)sqlite3_column_int64(stmt, 1); str = (const char *)sqlite3_column_text(stmt, 2); if(str){ base_msg.topic = mosquitto_strdup(str); if(!base_msg.topic){ failed++; continue; } } base_msg.source_id = (char *)sqlite3_column_text(stmt, 4); base_msg.source_username = (char *)sqlite3_column_text(stmt, 5); payload = (const void *)sqlite3_column_blob(stmt, 3); base_msg.payloadlen = (uint32_t)sqlite3_column_int(stmt, 6); if(payload && base_msg.payloadlen){ base_msg.payload = mosquitto_malloc(base_msg.payloadlen+1); if(!base_msg.payload){ mosquitto_free(base_msg.topic); failed++; continue; } memcpy(base_msg.payload, payload, base_msg.payloadlen); ((uint8_t *)base_msg.payload)[base_msg.payloadlen] = 0; } base_msg.source_mid = (uint16_t)sqlite3_column_int(stmt, 7); base_msg.source_port = (uint16_t)sqlite3_column_int(stmt, 8); base_msg.qos = (uint8_t)sqlite3_column_int(stmt, 9); base_msg.retain = sqlite3_column_int(stmt, 10); base_msg.properties = json_to_properties((const char *)sqlite3_column_text(stmt, 11)); rc = mosquitto_persist_base_msg_add(&base_msg); if(rc == MOSQ_ERR_SUCCESS){ count++; }else{ failed++; } } sqlite3_finalize(stmt); mosquitto_log_printf(MOSQ_LOG_INFO, "sqlite: Restored %ld base messages (%ld failed)", count, failed); return MOSQ_ERR_SUCCESS; } static int client_msg_restore(struct mosquitto_sqlite *ms) { sqlite3_stmt *stmt; struct mosquitto_client_msg client_msg; int rc; long count = 0, failed = 0; rc = sqlite3_prepare_v2(ms->db, "SELECT client_id, cmsg_id, store_id, dup, direction, mid, qos, retain, state, subscription_identifier " "FROM client_msgs ORDER BY rowid", -1, &stmt, NULL); if(rc != SQLITE_OK){ mosquitto_log_printf(MOSQ_LOG_ERR, "sqlite: Error restoring client messages: %s", sqlite3_errstr(rc)); return MOSQ_ERR_UNKNOWN; } memset(&client_msg, 0, sizeof(client_msg)); while(sqlite3_step(stmt) == SQLITE_ROW){ client_msg.clientid = (const char *)sqlite3_column_text(stmt, 0); client_msg.cmsg_id = (uint64_t)sqlite3_column_int64(stmt, 1); client_msg.store_id = (uint64_t)sqlite3_column_int64(stmt, 2); client_msg.dup = (uint8_t)sqlite3_column_int(stmt, 3); client_msg.direction = (uint8_t)sqlite3_column_int(stmt, 4); client_msg.mid = (uint16_t)sqlite3_column_int(stmt, 5); client_msg.qos = (uint8_t)sqlite3_column_int(stmt, 6); client_msg.retain = sqlite3_column_int(stmt, 7); client_msg.state = (uint8_t)sqlite3_column_int(stmt, 8); client_msg.subscription_identifier = (uint32_t)sqlite3_column_int(stmt, 9); rc = mosquitto_persist_client_msg_add(&client_msg); if(rc == MOSQ_ERR_SUCCESS){ count++; }else{ failed++; } } sqlite3_finalize(stmt); mosquitto_log_printf(MOSQ_LOG_INFO, "sqlite: Restored %ld client messages (%ld failed)", count, failed); return MOSQ_ERR_SUCCESS; } static int retain_restore(struct mosquitto_sqlite *ms) { sqlite3_stmt *stmt; int rc; long count = 0, failed = 0; const char *topic; uint64_t store_id; rc = sqlite3_prepare_v2(ms->db, "SELECT topic, store_id " "FROM retains ORDER BY topic", -1, &stmt, NULL); if(rc != SQLITE_OK){ mosquitto_log_printf(MOSQ_LOG_ERR, "sqlite: Error restoring retained messages: %s", sqlite3_errstr(rc)); return MOSQ_ERR_UNKNOWN; } while(sqlite3_step(stmt) == SQLITE_ROW){ topic = (const char *)sqlite3_column_text(stmt, 0); if(!topic){ failed++; continue; } store_id = (uint64_t)sqlite3_column_int64(stmt, 1); rc = mosquitto_persist_retain_msg_set(topic, store_id); if(rc == MOSQ_ERR_SUCCESS){ count++; }else{ failed++; } } sqlite3_finalize(stmt); mosquitto_log_printf(MOSQ_LOG_INFO, "sqlite: Restored %ld retained messages (%ld failed)", count, failed); return MOSQ_ERR_SUCCESS; } static int publish_will_msg(const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties) { void *payload_mosq = NULL; int rc; if(payloadlen){ payload_mosq = mosquitto_malloc((size_t)payloadlen); if(!payload_mosq){ return MOSQ_ERR_NOMEM; } memcpy(payload_mosq, payload, (size_t)payloadlen); } rc = mosquitto_broker_publish(NULL, topic, payloadlen, payload_mosq, qos, retain, properties); if(rc != MOSQ_ERR_SUCCESS){ mosquitto_free(payload_mosq); } return rc; } static int will_restore(struct mosquitto_sqlite *ms) { sqlite3_stmt *stmt; int rc; long count = 0, failed = 0; const char *clientid, *topic; const void *payload; mosquitto_property *properties; int payloadlen, qos, retain; rc = sqlite3_prepare_v2(ms->db, "SELECT w.client_id,w.topic,w.payload,w.payloadlen,w.qos,w.retain,w.properties," " c.session_expiry_time,c.will_delay_interval" " FROM wills w" " LEFT OUTER JOIN clients c ON c.client_id = w.client_id", -1, &stmt, NULL); if(rc != SQLITE_OK){ mosquitto_log_printf(MOSQ_LOG_ERR, "sqlite: Error restoring will messages: %s", sqlite3_errstr(rc)); return MOSQ_ERR_UNKNOWN; } while(sqlite3_step(stmt) == SQLITE_ROW){ clientid = (const char *)sqlite3_column_text(stmt, 0); topic = (const char *)sqlite3_column_text(stmt, 1); payload = (const void *)sqlite3_column_blob(stmt, 2); payloadlen = (int)sqlite3_column_int64(stmt, 3); qos = sqlite3_column_int(stmt, 4); retain = (bool)sqlite3_column_int(stmt, 5); properties = json_to_properties((const char *)sqlite3_column_text(stmt, 6)); rc = mosquitto_client_will_set(clientid, topic, payloadlen, payload, qos, retain, properties); if(rc == MOSQ_ERR_NOT_FOUND){ /* If the client does not exist this is the will message of a non-persistent client. */ rc = publish_will_msg(topic, payloadlen, payload, qos, retain, properties); }else if(rc == MOSQ_ERR_SUCCESS && (sqlite3_column_int64(stmt, 7) == 0 && sqlite3_column_int64(stmt, 8) == 0)){ /* If the client is a persistent client and was connected at the moment of a crash and has no will delay we publish it's will message now, but need a new copy of the properties. */ properties = json_to_properties((const char *)sqlite3_column_text(stmt, 6)); rc = publish_will_msg(topic, payloadlen, payload, qos, retain, properties); } if(rc == MOSQ_ERR_SUCCESS){ count++; }else{ mosquitto_property_free_all(&properties); failed++; } } sqlite3_finalize(stmt); mosquitto_log_printf(MOSQ_LOG_INFO, "sqlite: Restored %ld will messages (%ld failed)", count, failed); return rc; } int persist_sqlite__restore_cb(int event, void *event_data, void *userdata) { struct mosquitto_sqlite *ms = userdata; UNUSED(event); UNUSED(event_data); if(base_msg_restore(ms)){ return MOSQ_ERR_UNKNOWN; } if(retain_restore(ms)){ return MOSQ_ERR_UNKNOWN; } if(client_restore(ms)){ return MOSQ_ERR_UNKNOWN; } if(subscription_restore(ms)){ return MOSQ_ERR_UNKNOWN; } if(client_msg_restore(ms)){ return MOSQ_ERR_UNKNOWN; } if(will_restore(ms)){ return MOSQ_ERR_UNKNOWN; } return 0; } ================================================ FILE: plugins/persist-sqlite/retain_msgs.c ================================================ /* Copyright (c) 2021 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 "mosquitto/broker.h" #include "persist_sqlite.h" int persist_sqlite__retain_msg_set_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_retain_msg *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = MOSQ_ERR_UNKNOWN; UNUSED(event); if(sqlite3_bind_text(ms->retain_msg_set_stmt, 1, ed->topic, (int)strlen(ed->topic), SQLITE_STATIC) == SQLITE_OK && sqlite3_bind_int64(ms->retain_msg_set_stmt, 2, (int64_t)ed->store_id) == SQLITE_OK ){ ms->event_count++; rc = sqlite3_step(ms->retain_msg_set_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } sqlite3_reset(ms->retain_msg_set_stmt); return rc; } int persist_sqlite__retain_msg_remove_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_retain_msg *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = 1; UNUSED(event); if(sqlite3_bind_text(ms->retain_msg_remove_stmt, 1, ed->topic, (int)strlen(ed->topic), SQLITE_STATIC) == SQLITE_OK){ ms->event_count++; rc = sqlite3_step(ms->retain_msg_remove_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } sqlite3_reset(ms->retain_msg_remove_stmt); return rc; } ================================================ FILE: plugins/persist-sqlite/subscriptions.c ================================================ /* Copyright (c) 2021 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 "mosquitto/broker.h" #include "persist_sqlite.h" int persist_sqlite__subscription_add_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_subscription *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = MOSQ_ERR_UNKNOWN; UNUSED(event); if(sqlite3_bind_text(ms->subscription_add_stmt, 1, ed->data.clientid, (int)strlen(ed->data.clientid), SQLITE_STATIC) == SQLITE_OK){ if(sqlite3_bind_text(ms->subscription_add_stmt, 2, ed->data.topic_filter, (int)strlen(ed->data.topic_filter), SQLITE_STATIC) == SQLITE_OK){ if(sqlite3_bind_int(ms->subscription_add_stmt, 3, ed->data.options) == SQLITE_OK){ if(sqlite3_bind_int(ms->subscription_add_stmt, 4, (int)ed->data.identifier) == SQLITE_OK){ ms->event_count++; rc = sqlite3_step(ms->subscription_add_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } } } } sqlite3_reset(ms->subscription_add_stmt); return rc; } int persist_sqlite__subscription_remove_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_subscription *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = 1; UNUSED(event); if(sqlite3_bind_text(ms->subscription_remove_stmt, 1, ed->data.clientid, (int)strlen(ed->data.clientid), SQLITE_STATIC) == SQLITE_OK){ if(sqlite3_bind_text(ms->subscription_remove_stmt, 2, ed->data.topic_filter, (int)strlen(ed->data.topic_filter), SQLITE_STATIC) == SQLITE_OK){ ms->event_count++; rc = sqlite3_step(ms->subscription_remove_stmt); if(rc == SQLITE_DONE){ rc = MOSQ_ERR_SUCCESS; }else{ rc = MOSQ_ERR_UNKNOWN; } } } sqlite3_reset(ms->subscription_remove_stmt); return rc; } ================================================ FILE: plugins/persist-sqlite/test.conf ================================================ persistence_location . plugin ./mosquitto_persist_sqlite.so plugin_opt_page_size 4096 plugin_opt_flush_period 5 ================================================ FILE: plugins/persist-sqlite/test.sh ================================================ ../../src/mosquitto -c test.conf -v ================================================ FILE: plugins/persist-sqlite/tick.c ================================================ /* Copyright (c) 2021 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 "mosquitto/mqtt_protocol.h" #include "mosquitto.h" #include "mosquitto/broker.h" #include "persist_sqlite.h" int persist_sqlite__tick_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_tick *ed = event_data; struct mosquitto_sqlite *ms = userdata; UNUSED(event); if(ms->event_count > 0){ ms->event_count = 0; sqlite3_exec(ms->db, "END;", NULL, NULL, NULL); sqlite3_exec(ms->db, "BEGIN;", NULL, NULL, NULL); } ed->next_s = ms->flush_period; return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/persist-sqlite/util.h ================================================ /* Copyright (c) 2025 Cedalo GmbH 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 */ #include #include static inline int sqlite3_bind_text_from_c_str(sqlite3_stmt *stmt, int col_index, const char *str) { return sqlite3_bind_text(stmt, col_index, str, (int)strlen(str), SQLITE_STATIC); } static inline int sqlite3_bind_text_from_optional_c_str(sqlite3_stmt *stmt, int col_index, const char *str) { return str ? sqlite3_bind_text_from_c_str(stmt, col_index, str) : sqlite3_bind_null(stmt, col_index); } static inline int sqlite3_bind_blob_optional(sqlite3_stmt *stmt, int col_index, const void *ptr, int blob_len) { return ptr ? sqlite3_bind_blob(stmt, col_index, ptr, blob_len, SQLITE_STATIC) : sqlite3_bind_null(stmt, col_index); } static inline int sqlite3_single_step_stmt(int rc, struct mosquitto_sqlite *ms, sqlite3_stmt *stmt) { if(rc != MOSQ_ERR_SUCCESS){ return rc; } ms->event_count++; return sqlite3_step(stmt) == SQLITE_DONE ? MOSQ_ERR_SUCCESS : MOSQ_ERR_UNKNOWN; } static inline char *properties_to_json_str(const mosquitto_property *properties) { cJSON *array; char *json_str; array = mosquitto_properties_to_json(properties); if(!array){ return NULL; } json_str = cJSON_PrintUnformatted(array); cJSON_Delete(array); return json_str; } ================================================ FILE: plugins/persist-sqlite/will.c ================================================ /* Copyright (c) 2025 Cedalo GmbH 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 */ #include #include #include "mosquitto.h" #include "mosquitto/broker.h" #include "persist_sqlite.h" #include "util.h" int persist_sqlite__will_add_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_will_msg *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = MOSQ_ERR_SUCCESS; char *propties_json_str = NULL; UNUSED(event); if(!ed->data.clientid || !ed->data.topic){ return MOSQ_ERR_INVAL; } if(ed->data.properties){ propties_json_str = properties_to_json_str(ed->data.properties); if(!propties_json_str){ return MOSQ_ERR_NOMEM; } } if(sqlite3_bind_text_from_c_str(ms->will_add_stmt, 1, ed->data.clientid) != SQLITE_OK || sqlite3_bind_blob_optional(ms->will_add_stmt, 2, ed->data.payload, (int)ed->data.payloadlen) != SQLITE_OK || sqlite3_bind_text_from_c_str(ms->will_add_stmt, 3, ed->data.topic) != SQLITE_OK || sqlite3_bind_int64(ms->will_add_stmt, 4, (int64_t)ed->data.payloadlen) != SQLITE_OK || sqlite3_bind_int(ms->will_add_stmt, 5, ed->data.qos) != SQLITE_OK || sqlite3_bind_int(ms->will_add_stmt, 6, ed->data.retain) != SQLITE_OK || sqlite3_bind_text_from_optional_c_str(ms->will_add_stmt, 7, propties_json_str) != SQLITE_OK){ rc = MOSQ_ERR_UNKNOWN; } rc = sqlite3_single_step_stmt(rc, ms, ms->will_add_stmt); sqlite3_reset(ms->will_add_stmt); mosquitto_free(propties_json_str); return rc; } int persist_sqlite__will_remove_cb(int event, void *event_data, void *userdata) { struct mosquitto_evt_persist_will_msg *ed = event_data; struct mosquitto_sqlite *ms = userdata; int rc = MOSQ_ERR_SUCCESS; UNUSED(event); if(sqlite3_bind_text_from_c_str(ms->will_remove_stmt, 1, ed->data.clientid) != SQLITE_OK){ rc = MOSQ_ERR_UNKNOWN; } rc = sqlite3_single_step_stmt(rc, ms, ms->will_remove_stmt); sqlite3_reset(ms->will_remove_stmt); return rc; } ================================================ FILE: plugins/plugin.mk ================================================ .PHONY : all binary check clean reallyclean test test-compile install uninstall LOCAL_CFLAGS+=-fPIC LOCAL_CPPFLAGS+= LOCAL_LIBADD+= LOCAL_LDFLAGS+=-fPIC -shared ifeq ($(UNAME),AIX) LOCAL_LDFLAGS+=-Wl,-G endif binary : ${PLUGIN_NAME}.so ${PLUGIN_NAME}.a ${PLUGIN_NAME}.a : ${OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}$(AR) cr $@ $^ ${PLUGIN_NAME}.so : ${OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}${CC} $(LOCAL_LDFLAGS) $^ -o $@ ${LOCAL_LIBADD} ${OBJS} : %.o: %.c ${EXTRA_DEPS} ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ reallyclean : clean clean: -rm -f *.o ${PLUGIN_NAME}.a ${PLUGIN_NAME}.so *.gcda *.gcno test-compile: check: test test: test-compile ifeq ($(PLUGIN_NOINST),) install: all $(INSTALL) -d "${DESTDIR}$(libdir)" $(INSTALL) ${STRIP_OPTS} ${PLUGIN_NAME}.so "${DESTDIR}${libdir}/${PLUGIN_NAME}.so" uninstall : -rm -f "${DESTDIR}${libdir}/${PLUGIN_NAME}.so" endif ================================================ FILE: plugins/sparkplug-aware/CMakeLists.txt ================================================ set(PLUGIN_NAME mosquitto_sparkplug_aware) set(SRCLIST on_message.c plugin.c ) set(INCLIST ) set(LINKLIST ) add_mosquitto_plugin("${PLUGIN_NAME}" "${SRCLIST}" "${INCLIST}" "${LINKLIST}") ================================================ FILE: plugins/sparkplug-aware/Makefile ================================================ R=../.. include ${R}/config.mk PLUGIN_NAME=mosquitto_sparkplug_aware LOCAL_CFLAGS+= LOCAL_CPPFLAGS+= LOCAL_LDFLAGS+= LOCAL_LDADD+= # Objects for this plugin only, built from source in this directory OBJS = \ on_message.o \ plugin.o # Objects from e.g. the common directory that are not in this directory OBJS_EXTERNAL = all : binary include ${R}/plugins/plugin.mk ================================================ FILE: plugins/sparkplug-aware/README.md ================================================ # Mosquitto Sparkplug Aware This plugin implements the requirements of the Sparkplug 3.0 specification "awareness". It is not tested with the official TCK, because that is only capable of testing one brand of broker, and hence it is not possible to validate any other broker. See https://github.com/eclipse-sparkplug/sparkplug/issues/478 ================================================ FILE: plugins/sparkplug-aware/on_message.c ================================================ /* Copyright (c) 2023 Cedalo Gmbh */ #include "config.h" #include #include #include "mosquitto.h" #include "plugin_global.h" int plugin__message_in_callback(int event, void *event_data, void *user_data) { struct mosquitto_evt_message *ed = event_data; bool match; UNUSED(event); UNUSED(user_data); mosquitto_topic_matches_sub("spBv1.0/+/NBIRTH/+", ed->topic, &match); if(!match){ mosquitto_topic_matches_sub("spBv1.0/+/DBIRTH/+/+", ed->topic, &match); } if(match){ size_t len = strlen("$sparkplug/certificates/") + strlen(ed->topic) + 1; char *topic = mosquitto_malloc(len); if(topic){ snprintf(topic, len, "$sparkplug/certificates/%s", ed->topic); mosquitto_broker_publish_copy(NULL, topic, (int)ed->payloadlen, ed->payload, ed->qos, true, ed->properties); mosquitto_free(topic); } } return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/sparkplug-aware/plugin.c ================================================ /* Copyright (c) 2023 Cedalo Gmbh */ #include "config.h" #include #include #include "mosquitto/broker.h" #include "mosquitto/broker_plugin.h" #include "plugin_global.h" MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *mosq_pid = NULL; int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *options, int option_count) { int rc; UNUSED(user_data); UNUSED(options); UNUSED(option_count); mosq_pid = identifier; mosquitto_plugin_set_info(identifier, PLUGIN_NAME, PLUGIN_VERSION); rc = mosquitto_callback_register(mosq_pid, MOSQ_EVT_MESSAGE_IN, plugin__message_in_callback, NULL, NULL); if(rc){ return rc; } return MOSQ_ERR_SUCCESS; } ================================================ FILE: plugins/sparkplug-aware/plugin_global.h ================================================ /* Copyright (c) 2023 Cedalo Gmbh */ #ifndef PLUGIN_GLOBAL_H #define PLUGIN_GLOBAL_H #include "config.h" /* PLUGIN_NAME and PLUGIN_VERSION reported to the broker */ #define PLUGIN_NAME "sparkplug-aware" #define PLUGIN_VERSION "1.0" int plugin__message_in_callback(int event, void *event_data, void *user_data); #endif ================================================ FILE: plugins/sparkplug-aware/test.conf ================================================ listener 1883 allow_anonymous true plugin ./mosquitto_sparkplug_aware.so ================================================ FILE: plugins/sparkplug-aware/test.sh ================================================ #VG="valgrind --log-file=vglog" ${VG} ../../src/mosquitto -c test.conf -v ================================================ FILE: pskfile.example ================================================ id:deadbeef easy:12345 ================================================ FILE: pwfile.example ================================================ roger:$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== ================================================ FILE: run_tests.py ================================================ #!/usr/bin/env python3 import inspect import os import sys sys.path.insert(0, "test") import ptest import test.apps.ctrl.test as p_ctrl import test.apps.db_dump.test as p_db_dump import test.apps.passwd.test as p_passwd import test.apps.signal.test as p_signal import test.broker.test as p_broker import test.client.test as p_client import test.lib.test as p_lib test = ptest.PTest() test.add_tests(p_client.tests, "test/client") test.add_tests(p_lib.tests, "test/lib") test.add_tests(p_ctrl.tests, "test/apps/ctrl") test.add_tests(p_db_dump.tests, "test/apps/db_dump") test.add_tests(p_passwd.tests, "test/apps/ctrl") test.add_tests(p_signal.tests, "test/apps/signal") test.add_tests(p_broker.tests, "test/broker") test.run() ================================================ FILE: security/mosquitto.apparmor ================================================ /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, } ================================================ FILE: service/monit/mosquitto.monit ================================================ check process mosquitto with pidfile /run/mosquitto.pid start = "/etc/init.d/mosquitto start" stop = "/etc/init.d/mosquitto stop" ================================================ FILE: service/svscan/run ================================================ #!/bin/sh /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf ================================================ FILE: service/systemd/README ================================================ Select 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). ================================================ FILE: service/systemd/mosquitto.service.notify ================================================ [Unit] Description=Mosquitto MQTT Broker Documentation=man:mosquitto.conf(5) man:mosquitto(8) After=network-online.target Wants=network-online.target [Service] User=mosquitto Type=notify WatchdogSec=3min NotifyAccess=main ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf ExecReload=/bin/kill -HUP $MAINPID Restart=on-failure RuntimeDirectory=mosquitto LogsDirectory=mosquitto [Install] WantedBy=multi-user.target ================================================ FILE: service/systemd/mosquitto.service.simple ================================================ [Unit] Description=Mosquitto MQTT Broker Documentation=man:mosquitto.conf(5) man:mosquitto(8) After=network-online.target Wants=network-online.target [Service] User=mosquitto ExecStart=/usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf ExecReload=/bin/kill -HUP $MAINPID Restart=on-failure RuntimeDirectory=mosquitto LogsDirectory=mosquitto [Install] WantedBy=multi-user.target ================================================ FILE: service/upstart/mosquitto.conf ================================================ description "Mosquitto MQTTv3.1 broker" author "Roger Light " start on net-device-up respawn exec /usr/local/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf ================================================ FILE: set-version.sh ================================================ #!/bin/sh MAJOR=2 MINOR=1 REVISION=2 sed -i "s/^VERSION=.*/VERSION=${MAJOR}.${MINOR}.${REVISION}/" config.mk sed -i "s/^#define LIBMOSQUITTO_MAJOR .*/#define LIBMOSQUITTO_MAJOR ${MAJOR}/" include/mosquitto.h sed -i "s/^#define LIBMOSQUITTO_MINOR .*/#define LIBMOSQUITTO_MINOR ${MINOR}/" include/mosquitto.h sed -i "s/^#define LIBMOSQUITTO_REVISION .*/#define LIBMOSQUITTO_REVISION ${REVISION}/" include/mosquitto.h sed -i "s/^set (VERSION .*)/set (VERSION ${MAJOR}.${MINOR}.${REVISION})/" CMakeLists.txt sed -i "s/^!define VERSION .*/!define VERSION ${MAJOR}.${MINOR}.${REVISION}/" installer/*.nsi sed -i "s/^version: .*/version: ${MAJOR}.${MINOR}.${REVISION}/" snap/snapcraft.yaml sed -i "s/\"version-string\": \".*\",/\"version-string\": \"${MAJOR}.${MINOR}.${REVISION}\",/" vcpkg.json ================================================ FILE: snap/local/default_config.conf ================================================ persistence false user root ================================================ FILE: snap/local/launcher.sh ================================================ #!/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 $@ ================================================ FILE: snap/snapcraft.yaml ================================================ name: mosquitto version: 2.1.2 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 a microcontroller for example. confinement: strict grade: stable base: core24 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] signal: command: usr/bin/mosquitto_signal 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 dashboard: plugin: dump source: dashboard/src organize: '*': dashboard/ mosquitto: plugin: cmake cmake-parameters: - -DCMAKE_INSTALL_PREFIX=/usr - -DHTTP_API_DIR="/snap/mosquitto/current/dashboard/" - -DWITH_TESTS=OFF source: https://github.com/eclipse-mosquitto/mosquitto source-type: git build-packages: - docbook-xsl - g++ - gcc - libcjson-dev - libedit-dev - libmicrohttpd-dev - libsqlite3-dev - libssl-dev - xsltproc stage-packages: - ca-certificates - libcjson1 - libmicrohttpd12t64 - libssl3t64 prime: - usr/sbin/mosquitto - usr/bin/mosquitto_ctrl - usr/bin/mosquitto_db_dump - usr/bin/mosquitto_pub - usr/bin/mosquitto_rr - usr/bin/mosquitto_signal - usr/bin/mosquitto_sub - usr/bin/mosquitto_passwd - usr/include/mosquitto.h - usr/include/mosquitto/*.h - usr/include/mosquitto_broker.h - usr/include/mosquitto_plugin.h - usr/include/mosquittopp.h - usr/include/mqtt_protocol.h - usr/lib/*-linux-gnu/libcjson.so* - usr/lib/*-linux-gnu/libcrypto.so* - usr/lib/*-linux-gnu/libmicrohttpd.so* - usr/lib/*-linux-gnu/libmosquitto.so* - usr/lib/*-linux-gnu/libmosquitto_common.so* - usr/lib/*-linux-gnu/libmosquittopp.so* - usr/lib/*-linux-gnu/libssl.so* - usr/lib/*-linux-gnu/mosquitto_acl_file.so* - usr/lib/*-linux-gnu/mosquitto_dynamic_security.so* - usr/lib/*-linux-gnu/mosquitto_password_file.so* - usr/lib/*-linux-gnu/mosquitto_persist_sqlite.so* - usr/lib/*-linux-gnu/mosquitto_sparkplug_aware.so* ================================================ FILE: src/CMakeLists.txt ================================================ add_executable(mosquitto acl_file.c acl_file.h ../plugins/acl-file/acl_check.c ../plugins/acl-file/acl_parse.c ../lib/alias_mosq.c ../lib/alias_mosq.h bridge.c bridge_topic.c broker_control.c conf.c conf_includedir.c context.c control.c control_common.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 http_serv.c ../common/json_help.c ../common/json_help.h keepalive.c ../common/lib_load.h listeners.c logging.c loop.c mosquitto.c ../include/mosquitto_broker.h mosquitto_broker_internal.h mux.c mux.h mux_epoll.c mux_kqueue.c mux_poll.c net.c ../lib/net_mosq_ocsp.c ../lib/net_mosq.c ../lib/net_mosq.h ../lib/net_ws.c ../lib/packet_datatypes.c ../lib/packet_mosq.c ../lib/packet_mosq.h password_file.c password_file.h ../plugins/password-file/password_check.c ../plugins/password-file/password_parse.c persist_read_v234.c persist_read_v5.c persist_read.c persist_write_v5.c persist_write.c persist.h plugin_callbacks.c plugin_v5.c plugin_v4.c plugin_v3.c plugin_v2.c plugin_init.c plugin_cleanup.c plugin_persist.c plugin_acl_check.c plugin_basic_auth.c plugin_connect.c plugin_disconnect.c plugin_client_offline.c plugin_extended_auth.c plugin_message.c plugin_psk_key.c plugin_public.c plugin_reload.c plugin_subscribe.c plugin_tick.c plugin_unsubscribe.c property_broker.c proxy_v1.c proxy_v2.c ../lib/property_mosq.c ../lib/property_mosq.h psk_file.c read_handle.c ../lib/read_handle.h retain.c security_default.c ../lib/send_mosq.c ../lib/send_mosq.h send_auth.c send_connack.c ../lib/send_connect.c ../lib/send_disconnect.c ../lib/send_publish.c send_suback.c signals.c ../lib/send_subscribe.c send_unsuback.c ../lib/send_unsubscribe.c session_expiry.c subs.c sys_tree.c sys_tree.h ../lib/tls_mosq.c topic_tok.c ../lib/util_mosq.c ../lib/util_mosq.h watchdog.c websockets.c will_delay.c ../lib/will_mosq.c ../lib/will_mosq.h ) CHECK_INCLUDE_FILES(sys/event.h HAVE_SYS_EVENT_H) if(HAVE_SYS_EVENT_H) target_compile_definitions(mosquitto PRIVATE "WITH_KQUEUE") endif() find_path(HAVE_SYS_EPOLL_H sys/epoll.h) if(HAVE_SYS_EPOLL_H) target_compile_definitions(mosquitto PRIVATE "WITH_EPOLL") endif() option(INC_BRIDGE_SUPPORT "Include bridge support for connecting to other brokers?" ON) if(INC_BRIDGE_SUPPORT) target_sources(mosquitto PRIVATE bridge.c) target_compile_definitions(mosquitto PRIVATE "WITH_BRIDGE") endif() option(WITH_HTTP_API "Include http_api support for listeners?" ON) set(HTTP_API_DIR "Default http_api directory" CACHE STRING "") if(WITH_HTTP_API) if(WIN32) find_library(MICROHTTPD_LIBRARY NAMES microhttpd-dll) else() find_library(MICROHTTPD_LIBRARY NAMES microhttpd) endif() if(MICROHTTPD_LIBRARY) target_sources(mosquitto PRIVATE http_api.c) target_compile_definitions(mosquitto PRIVATE "WITH_HTTP_API") target_link_libraries(mosquitto PRIVATE ${MICROHTTPD_LIBRARY}) if(HTTP_API_DIR) target_compile_definitions(mosquitto PRIVATE "HTTP_API_DIR=\"${HTTP_API_DIR}\"") endif() else() message(WARNING "microhttpd not found, disabling WITH_HTTP_API") endif() endif() option(USE_LIBWRAP "Include tcp-wrappers support?" OFF) if(USE_LIBWRAP) target_link_libraries(mosquitto PRIVATE wrap) target_compile_definitions(mosquitto PRIVATE "WITH_WRAP") endif() option(INC_DB_UPGRADE "Include database upgrade support? (recommended)" ON) if(INC_MEMTRACK) target_compile_definitions(mosquitto PUBLIC "WITH_MEMORY_TRACKING") endif() option(WITH_PERSISTENCE "Include persistence support?" ON) if(WITH_PERSISTENCE) target_compile_definitions(mosquitto PRIVATE "WITH_PERSISTENCE") endif() option(WITH_SYS_TREE "Include $SYS tree support?" ON) if(WITH_SYS_TREE) target_compile_definitions(mosquitto PRIVATE "WITH_SYS_TREE") endif() option(WITH_OLD_KEEPALIVE "Use legacy keepalive check mechanism?" OFF) if (WITH_OLD_KEEPALIVE) add_definitions("-DWITH_OLD_KEEPALIVE") endif (WITH_OLD_KEEPALIVE) option(WITH_ADNS "Include ADNS support?" OFF) if(CMAKE_SYSTEM_NAME STREQUAL Linux) option(WITH_SYSTEMD "Include systemd support?" OFF) if(WITH_SYSTEMD) target_compile_definitions(mosquitto PRIVATE "WITH_SYSTEMD") find_library(SYSTEMD_LIBRARY systemd) target_link_libraries(mosquitto PRIVATE ${SYSTEMD_LIBRARY}) endif() endif() option(STATIC_WEBSOCKETS "Use the static libwebsockets library?" OFF) option(WITH_CONTROL "Include $CONTROL topic support?" ON) if(WITH_CONTROL) target_compile_definitions(mosquitto PRIVATE "WITH_CONTROL") endif() if(WIN32 OR CYGWIN) target_sources(mosquitto PRIVATE service.c) endif() target_compile_definitions(mosquitto PRIVATE "WITH_BROKER") if(WITH_TLS) target_link_libraries(mosquitto PRIVATE OpenSSL::SSL) endif() # Check for getaddrinfo_a # Prior to glibc 2.34 this required linking with anl if(WITH_ADNS) cmake_push_check_state() set(ANL_CODE " #define _GNU_SOURCE #include #include int main(){ return getaddrinfo_a(0, NULL, 0, NULL); } ") check_source_compiles(C "${ANL_CODE}" HAVE_GETADDRINFO_A) if(HAVE_GETADDRINFO_A) target_compile_definitions(mosquitto PRIVATE "WITH_ADNS") else() set(CMAKE_REQUIRED_LIBRARIES "anl") check_source_compiles(C "${ANL_CODE}" HAVE_GETADDRINFO_A_LIBANL) if(HAVE_GETADDRINFO_A_LIBANL) target_compile_definitions(mosquitto PRIVATE "WITH_ADNS") target_link_libraries(mosquitto PRIVATE anl) else() message(FATAL_ERROR "WITH_ADNS is set, but getaddrinfo_a() is not available.") endif() endif() cmake_pop_check_state() endif() if(UNIX) if(APPLE) target_link_libraries(mosquitto PRIVATE dl m) elseif (${CMAKE_SYSTEM_NAME} MATCHES "OpenBSD") target_link_libraries(mosquitto PRIVATE m) elseif (${CMAKE_SYSTEM_NAME} MATCHES "NetBSD") target_link_libraries(mosquitto PRIVATE m) elseif (${CMAKE_SYSTEM_NAME} MATCHES "Haiku") target_link_libraries(mosquitto PRIVATE m network) elseif(QNX) target_link_libraries(mosquitto PRIVATE m socket) else() target_link_libraries(mosquitto PRIVATE dl m) endif() endif() if(WIN32) target_link_libraries(mosquitto PRIVATE ws2_32) endif() if(WITH_WEBSOCKETS) if(WITH_WEBSOCKETS_BUILTIN) target_compile_definitions(mosquitto PRIVATE "WITH_WEBSOCKETS=WS_IS_BUILTIN") target_sources(mosquitto PRIVATE ${mosquitto_SOURCE_DIR}/deps/picohttpparser/picohttpparser.c) else() find_package(libwebsockets) target_compile_definitions(mosquitto PRIVATE "WITH_WEBSOCKETS=WS_IS_LWS") endif() endif() if (ANDROID) target_link_libraries(mosquitto PRIVATE log) endif (ANDROID) if(WITH_WEBSOCKETS) if(WITH_WEBSOCKETS_BUILTIN) target_include_directories(mosquitto PRIVATE "${mosquitto_SOURCE_DIR}/deps/picohttpparser") else() if(STATIC_WEBSOCKETS) target_link_libraries(mosquitto PRIVATE websockets) if(WIN32) target_link_libraries(mosquitto PRIVATE iphlpapi) endif() else(STATIC_WEBSOCKETS) target_link_libraries(mosquitto PRIVATE websockets_shared) endif() endif() endif() if(WITH_DLT) message(STATUS "DLT_LIBDIR = ${DLT_LIBDIR}") target_link_directories(mosquitto PRIVATE ${DLT_LIBDIR}) target_link_libraries(mosquitto PRIVATE ${DLT_LIBRARIES}) target_compile_definitions(mosquitto PRIVATE "WITH_DLT") endif() target_link_libraries(mosquitto PRIVATE cJSON) target_include_directories(mosquitto PUBLIC "${mosquitto_SOURCE_DIR}/include" PRIVATE "${mosquitto_SOURCE_DIR}/common" "${mosquitto_SOURCE_DIR}/lib" "${mosquitto_SOURCE_DIR}/libcommon" "${mosquitto_SOURCE_DIR}/src" "${CJSON_INCLUDE_DIRS}" ) target_link_libraries(mosquitto PUBLIC libmosquitto_common PRIVATE common-options ${MOSQ_LIBS} ) if (WITH_THREADING AND NOT WIN32) set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) target_link_libraries(mosquitto PRIVATE Threads::Threads) endif() set_target_properties(mosquitto PROPERTIES ENABLE_EXPORTS 1 ARCHIVE_OUTPUT_NAME "mosquitto_broker" ) if(UNIX) if(APPLE) set_target_properties(mosquitto PROPERTIES LINK_FLAGS "-Wl,-exported_symbols_list -Wl,${mosquitto_SOURCE_DIR}/src/linker-macosx.syms" ) elseif (AIX) else() set_target_properties(mosquitto PROPERTIES LINK_FLAGS "-Wl,-dynamic-list=${mosquitto_SOURCE_DIR}/src/linker.syms" ) endif() endif() install(TARGETS mosquitto RUNTIME DESTINATION "${CMAKE_INSTALL_SBINDIR}" ) ================================================ FILE: src/Makefile ================================================ R=.. include ${R}/config.mk .PHONY: all install uninstall clean reallyclean LOCAL_CFLAGS+= LOCAL_CPPFLAGS+=-DWITH_BROKER -I${R}/lib -I${R}/libcommon LOCAL_LDFLAGS+= LOCAL_LDADD+=-lcjson -lm ${LIBMOSQ_COMMON} # ------------------------------------------ # Platform specific # ------------------------------------------ ifneq ($(or $(findstring $(UNAME),AIX), $(findstring $(UNAME),FreeBSD), $(findstring $(UNAME),OpenBSD), $(findstring $(UNAME),NetBSD)),) LOCAL_LDFLAGS+=-Wl,--dynamic-list=linker.syms else LOCAL_LDADD+=-ldl endif ifeq ($(UNAME),AIX) LOCAL_LDFLAGS+=-Wl,-bE:linker-aix.syms endif ifeq ($(UNAME),Linux) LOCAL_LDADD+= LOCAL_LDFLAGS+=-Wl,--dynamic-list=linker.syms endif ifeq ($(UNAME),QNX) LOCAL_LDADD+= -lsocket endif # ------------------------------------------ # Compile time options # ------------------------------------------ include ${R}/make/broker.mk # ------------------------------------------ # Targets # ------------------------------------------ ifeq ($(WITH_FUZZING),yes) all : mosquitto_broker.a else all : mosquitto endif OBJS= mosquitto.o \ acl_file.o \ bridge.o \ bridge_topic.o \ broker_control.o \ conf.o \ conf_includedir.o \ context.o \ control.o \ control_common.o \ database.o \ handle_auth.o \ handle_connack.o \ handle_connect.o \ handle_disconnect.o \ handle_publish.o \ handle_subscribe.o \ handle_unsubscribe.o \ http_api.o \ http_serv.o \ keepalive.o \ listeners.o \ logging.o \ loop.o \ mux.o \ mux_epoll.o \ mux_kqueue.o \ mux_poll.o \ net.o \ password_file.o \ property_broker.o \ persist_read.o \ persist_read_v234.o \ persist_read_v5.o \ persist_write.o \ persist_write_v5.o \ plugin_callbacks.o \ plugin_v2.o \ plugin_v3.o \ plugin_v4.o \ plugin_v5.o \ plugin_acl_check.o \ plugin_basic_auth.o \ plugin_cleanup.o \ plugin_client_offline.o \ plugin_connect.o \ plugin_disconnect.o \ plugin_extended_auth.o \ plugin_init.o \ plugin_message.o \ plugin_persist.o \ plugin_psk_key.o \ plugin_public.o \ plugin_reload.o \ plugin_subscribe.o \ plugin_tick.o \ plugin_unsubscribe.o \ proxy_v1.o \ proxy_v2.o \ psk_file.o \ read_handle.o \ retain.o \ security_default.o \ send_auth.o \ send_connack.o \ send_suback.o \ send_unsuback.o \ service.o \ session_expiry.o \ signals.o \ subs.o \ sys_tree.o \ topic_tok.o \ watchdog.o \ websockets.o \ will_delay.o \ xtreport.o OBJS_EXTERNAL= \ acl_check.o \ acl_parse.o \ alias_mosq.o \ handle_ping.o \ handle_pubackcomp.o \ handle_pubrec.o \ handle_pubrel.o \ handle_suback.o \ handle_unsuback.o \ json_help.o \ net_mosq.o \ net_mosq_ocsp.o \ net_ws.o \ packet_datatypes.o \ packet_mosq.o \ password_check.o \ password_parse.o \ property_mosq.o \ send_connect.o \ send_disconnect.o \ send_mosq.o \ send_publish.o \ send_subscribe.o \ send_unsubscribe.o \ tls_mosq.o \ util_mosq.o \ will_mosq.o ifeq ($(WITH_WEBSOCKETS),yes) OBJS_EXTERNAL+=${R}/deps/picohttpparser/picohttpparser.o endif mosquitto : ${OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}${CC} ${LOCAL_LDFLAGS} $^ -o $@ $(LOCAL_LDADD) mosquitto_broker.a : ${OBJS} ${OBJS_EXTERNAL} ${CROSS_COMPILE}$(AR) cr $@ $^ ${OBJS} : %.o: %.c mosquitto_broker_internal.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ acl_check.o : ${R}/plugins/acl-file/acl_check.c acl_file.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ acl_parse.o : ${R}/plugins/acl-file/acl_parse.c acl_file.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ alias_mosq.o : ${R}/lib/alias_mosq.c ${R}/lib/alias_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ handle_ping.o : ${R}/lib/handle_ping.c ${R}/lib/read_handle.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ handle_pubackcomp.o : ${R}/lib/handle_pubackcomp.c ${R}/lib/read_handle.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ handle_pubrec.o : ${R}/lib/handle_pubrec.c ${R}/lib/read_handle.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ handle_pubrel.o : ${R}/lib/handle_pubrel.c ${R}/lib/read_handle.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ handle_suback.o : ${R}/lib/handle_suback.c ${R}/lib/read_handle.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ handle_unsuback.o : ${R}/lib/handle_unsuback.c ${R}/lib/read_handle.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ json_help.o : ${R}/common/json_help.c ${R}/common/json_help.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ net_mosq_ocsp.o : ${R}/lib/net_mosq_ocsp.c ${R}/lib/net_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ net_mosq.o : ${R}/lib/net_mosq.c ${R}/lib/net_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ net_ws.o : ${R}/lib/net_ws.c ${R}/lib/net_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ packet_datatypes.o : ${R}/lib/packet_datatypes.c ${R}/lib/packet_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ packet_mosq.o : ${R}/lib/packet_mosq.c ${R}/lib/packet_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ password_check.o : ${R}/plugins/password-file/password_check.c password_file.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ password_parse.o : ${R}/plugins/password-file/password_parse.c password_file.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ ${R}/deps/picohttpparser/picohttpparser.o : ${R}/deps/picohttpparser/picohttpparser.c ${R}/deps/picohttpparser/picohttpparser.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ property_mosq.o : ${R}/lib/property_mosq.c ${R}/lib/property_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ send_connect.o : ${R}/lib/send_connect.c ${R}/lib/send_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ send_disconnect.o : ${R}/lib/send_disconnect.c ${R}/lib/send_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ send_mosq.o : ${R}/lib/send_mosq.c ${R}/lib/send_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ send_publish.o : ${R}/lib/send_publish.c ${R}/lib/send_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ send_subscribe.o : ${R}/lib/send_subscribe.c ${R}/lib/send_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ send_unsubscribe.o : ${R}/lib/send_unsubscribe.c ${R}/lib/send_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ tls_mosq.o : ${R}/lib/tls_mosq.c ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ util_mosq.o : ${R}/lib/util_mosq.c ${R}/lib/util_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ will_mosq.o : ${R}/lib/will_mosq.c ${R}/lib/will_mosq.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ install : all $(INSTALL) -d "${DESTDIR}$(prefix)/sbin" $(INSTALL) ${STRIP_OPTS} mosquitto "${DESTDIR}${prefix}/sbin/mosquitto" 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 ${OBJS} ${OBJS_EXTERNAL} mosquitto mosquitto_broker.a *.gcda *.gcno reallyclean : clean -rm -rf *.orig *.db ================================================ FILE: src/acl_file.c ================================================ /* Copyright (c) 2011-2021 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 "acl_file.h" #include "mosquitto_broker_internal.h" #include "mosquitto/mqtt_protocol.h" #include "send_mosq.h" #include "util_mosq.h" int broker_acl_file__init(void) { int rc; /* Load acl data if required. */ if(db.config->per_listener_settings){ for(int i=0; ilistener_count; i++){ if(db.config->listeners[i].security_options->acl_data.acl_file){ rc = acl_file__parse(&db.config->listeners[i].security_options->acl_data); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error opening acl file \"%s\".", db.config->listeners[i].security_options->acl_data.acl_file); return rc; } if(db.config->listeners[i].security_options->plugin_count == 0){ config__plugin_add_secopt(db.config->listeners[i].security_options->pid, db.config->listeners[i].security_options); } mosquitto_callback_register(db.config->listeners[i].security_options->pid, MOSQ_EVT_ACL_CHECK, acl_file__check, NULL, &db.config->listeners[i].security_options->acl_data); } } }else{ if(db.config->security_options.acl_data.acl_file){ rc = acl_file__parse(&db.config->security_options.acl_data); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error opening acl file \"%s\".", db.config->security_options.acl_data.acl_file); return rc; } if(db.config->security_options.plugin_count == 0){ config__plugin_add_secopt(db.config->security_options.pid, &db.config->security_options); } mosquitto_callback_register(db.config->security_options.pid, MOSQ_EVT_ACL_CHECK, acl_file__check, NULL, &db.config->security_options.acl_data); } } return MOSQ_ERR_SUCCESS; } void broker_acl_file__cleanup(void) { if(db.config->per_listener_settings){ for(int 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_ACL_CHECK, acl_file__check, NULL); acl_file__cleanup(&db.config->listeners[i].security_options->acl_data); } } }else{ if(db.config->security_options.pid){ mosquitto_callback_unregister(db.config->security_options.pid, MOSQ_EVT_ACL_CHECK, acl_file__check, NULL); acl_file__cleanup(&db.config->security_options.acl_data); } } } ================================================ FILE: src/acl_file.h ================================================ /* Copyright (c) 2011-2021 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 ACL_FILE_H #define ACL_FILE_H #include struct acl__entry { struct acl__entry *next, *prev; char *topic; int access; int ucount; int ccount; }; struct acl__user { UT_hash_handle hh; char *username; struct acl__entry *acl; }; struct acl_file_data { char *acl_file; struct acl__user *acl_users; struct acl__user acl_anon; struct acl__entry *acl_patterns; }; int acl_file__parse(struct acl_file_data *data); int acl_file__check(int event, void *event_data, void *userdata); int acl_file__reload(int event, void *event_data, void *userdata); void acl_file__cleanup(struct acl_file_data *data); #endif ================================================ FILE: src/bridge.c ================================================ /* Copyright (c) 2009-2021 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 #include #include #else #include #include #endif #ifndef WIN32 #include #else #include #include #include #endif #include "mosquitto.h" #include "mosquitto_broker_internal.h" #include "mosquitto_internal.h" #include "net_mosq.h" #include "packet_mosq.h" #include "property_common.h" #include "send_mosq.h" #include "sys_tree.h" #include "tls_mosq.h" #include "util_mosq.h" #include "will_mosq.h" #include "utlist.h" #ifdef WITH_BRIDGE static void bridge__update_backoff(struct mosquitto__bridge *bridge); #if defined(__GLIBC__) && defined(WITH_ADNS) static int bridge__connect_step1(struct mosquitto *context); static int bridge__connect_step2(struct mosquitto *context); #endif static void bridge__packet_cleanup(struct mosquitto *context); static struct mosquitto *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); if(!local_id){ return NULL; } 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(); if(!new_context){ mosquitto_FREE(local_id); return NULL; } new_context->id = local_id; context__add_to_by_id(new_context); } new_context->transport = mosq_t_tcp; new_context->bridge = bridge; new_context->is_bridge = true; new_context->username = bridge->remote_username; new_context->password = bridge->remote_password; #ifdef WITH_TLS new_context->tls_cafile = bridge->tls_cafile; new_context->tls_capath = bridge->tls_capath; new_context->tls_certfile = bridge->tls_certfile; new_context->tls_keyfile = bridge->tls_keyfile; new_context->tls_cert_reqs = SSL_VERIFY_PEER; new_context->tls_ocsp_required = bridge->tls_ocsp_required; new_context->tls_version = bridge->tls_version; new_context->tls_insecure = bridge->tls_insecure; new_context->tls_alpn = bridge->tls_alpn; new_context->tls_ciphers = bridge->tls_ciphers; new_context->tls_13_ciphers = bridge->tls_13_ciphers; new_context->tls_engine = NULL; new_context->tls_keyform = mosq_k_pem; new_context->tls_use_os_certs = bridge->tls_use_os_certs; new_context->ssl_ctx_defaults = true; #ifdef FINAL_WITH_TLS_PSK new_context->tls_psk_identity = bridge->tls_psk_identity; new_context->tls_psk = 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; if(!bridge->clean_start_local){ new_context->session_expiry_interval = MQTT_SESSION_EXPIRY_NEVER; plugin_persist__handle_client_add(new_context); if(new_context->expiry_list_item){ /* We've restored from persistence and been added to the session * expiry list, even though we should never be expired */ session_expiry__remove(new_context); } } 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 NULL; } return new_context; } static void bridge__destroy(struct mosquitto *context) { send__disconnect(context, MQTT_RC_SUCCESS, NULL); context__cleanup(context, true); } void bridge__start_all(void) { for(int i=0; ibridge_count; i++){ struct mosquitto *context; int ret; context = bridge__new(db.config->bridges[i]); if(!context){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return; } assert(context); #if defined(__GLIBC__) && defined(WITH_ADNS) context->bridge->restart_t = 1; /* force quick restart of bridge */ loop__update_next_event(1000); ret = bridge__connect_step1(context); #else ret = bridge__connect(context); #endif if(ret && ret != MOSQ_ERR_CONN_PENDING){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Unable to connect bridge %s.", context->bridge->name); } db.config->bridges[i] = NULL; } } static int bridge__set_tcp_keepalive(struct mosquitto *context) { unsigned int enabled = 1; bool ret; if(context->bridge->tcp_keepalive_idle == 0 || context->bridge->tcp_keepalive_interval == 0 || context->bridge->tcp_keepalive_counter == 0){ return MOSQ_ERR_SUCCESS; } #ifdef WIN32 # define SETSOCKOPT_TYPE char * #else # define SETSOCKOPT_TYPE const void * #endif ret = setsockopt(context->sock, SOL_SOCKET, SO_KEEPALIVE, (SETSOCKOPT_TYPE)&enabled, sizeof(enabled)); #ifdef TCP_KEEPIDLE ret = ret || setsockopt(context->sock, IPPROTO_TCP, TCP_KEEPIDLE, (SETSOCKOPT_TYPE)&context->bridge->tcp_keepalive_idle, sizeof(context->bridge->tcp_keepalive_idle)); #endif #ifdef TCP_KEEPINTVL ret = ret || setsockopt(context->sock, IPPROTO_TCP, TCP_KEEPINTVL, (SETSOCKOPT_TYPE)&context->bridge->tcp_keepalive_interval, sizeof(context->bridge->tcp_keepalive_interval)); #endif #ifdef TCP_KEEPCNT ret = ret || setsockopt(context->sock, IPPROTO_TCP, TCP_KEEPCNT, (SETSOCKOPT_TYPE)&context->bridge->tcp_keepalive_counter, sizeof(context->bridge->tcp_keepalive_counter)); #endif #undef SETSOCKOPT_TYPE if(ret){ return MOSQ_ERR_UNKNOWN; } return MOSQ_ERR_SUCCESS; } #ifdef WITH_TCP_USER_TIMEOUT static int bridge__set_tcp_user_timeout(struct mosquitto *context) { int timeout = context->bridge->tcp_user_timeout; if(timeout >= 0){ if(setsockopt(context->sock, IPPROTO_TCP, TCP_USER_TIMEOUT, (char *)&timeout, sizeof(timeout))){ return MOSQ_ERR_UNKNOWN; } } return MOSQ_ERR_SUCCESS; } #endif #if defined(__GLIBC__) && defined(WITH_ADNS) static int bridge__connect_step1(struct mosquitto *context) { int rc; char *notification_topic; size_t notification_topic_len; uint8_t notification_payload; struct mosquitto__bridge_topic *cur_topic; 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); LL_FOREACH(context->bridge->topics, cur_topic){ if(cur_topic->direction == bd_out || cur_topic->direction == bd_both){ log__printf(NULL, MOSQ_LOG_DEBUG, "Bridge %s doing local SUBSCRIBE on topic %s", context->id, cur_topic->local_topic); if(cur_topic->qos > context->max_qos){ qos = context->max_qos; }else{ qos = cur_topic->qos; } struct mosquitto_subscription sub; sub.topic_filter = cur_topic->local_topic; sub.identifier = 0; sub.options = MQTT_SUB_OPT_NO_LOCAL | MQTT_SUB_OPT_RETAIN_AS_PUBLISHED | qos; if(sub__add(context, &sub) > 0){ return 1; } retain__queue(context, &sub); } } 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, MSG_EXPIRY_INFINITE, 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, MSG_EXPIRY_INFINITE, 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; } static 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; mosquitto_property receive_maximum; mosquitto_property session_expiry_interval; mosquitto_property topic_alias_max; mosquitto_property *properties = NULL; 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; loop__update_next_event(5000); } if(bridge__set_tcp_keepalive(context) != MOSQ_ERR_SUCCESS){ return MOSQ_ERR_UNKNOWN; } #ifdef WITH_TCP_USER_TIMEOUT if(bridge__set_tcp_user_timeout(context)){ return MOSQ_ERR_UNKNOWN; } #endif if(context->bridge->receive_maximum != 0){ receive_maximum.value.i16 = context->bridge->receive_maximum; receive_maximum.identifier = MQTT_PROP_RECEIVE_MAXIMUM; receive_maximum.property_type = MQTT_PROP_TYPE_INT16; receive_maximum.client_generated = false; receive_maximum.next = properties; properties = &receive_maximum; } if(context->bridge->session_expiry_interval != MQTT_SESSION_EXPIRY_IMMEDIATE){ session_expiry_interval.value.i32 = context->bridge->session_expiry_interval; session_expiry_interval.identifier = MQTT_PROP_SESSION_EXPIRY_INTERVAL; session_expiry_interval.property_type = MQTT_PROP_TYPE_INT32; session_expiry_interval.client_generated = false; session_expiry_interval.next = properties; properties = &session_expiry_interval; } if(context->bridge->max_topic_alias != 0){ topic_alias_max.value.i16 = context->bridge->max_topic_alias; topic_alias_max.identifier = MQTT_PROP_TOPIC_ALIAS_MAXIMUM; topic_alias_max.property_type = MQTT_PROP_TYPE_INT16; topic_alias_max.client_generated = false; topic_alias_max.next = properties; properties = &topic_alias_max; } rc = send__connect(context, context->keepalive, context->clean_start, properties); 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; char *notification_topic = NULL; size_t notification_topic_len; uint8_t notification_payload; struct mosquitto__bridge_topic *cur_topic; uint8_t qos; mosquitto_property receive_maximum; mosquitto_property session_expiry_interval; mosquitto_property topic_alias_max; mosquitto_property *properties = NULL; if(!context || !context->bridge){ return MOSQ_ERR_INVAL; } mosquitto__set_state(context, mosq_cs_new); context->sock = INVALID_SOCKET; /* coverity[missing_lock] - broker is single threaded, so no lock required */ context->last_msg_in = db.now_s; /* coverity[missing_lock] - broker is single threaded, so no lock required */ 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); LL_FOREACH(context->bridge->topics, cur_topic){ if(cur_topic->direction == bd_out || cur_topic->direction == bd_both){ log__printf(NULL, MOSQ_LOG_DEBUG, "Bridge %s doing local SUBSCRIBE on topic %s", context->id, cur_topic->local_topic); if(cur_topic->qos > context->max_qos){ qos = context->max_qos; }else{ qos = cur_topic->qos; } struct mosquitto_subscription sub; sub.topic_filter = cur_topic->local_topic; sub.identifier = 0; sub.options = MQTT_SUB_OPT_NO_LOCAL | MQTT_SUB_OPT_RETAIN_AS_PUBLISHED | qos; if(sub__add(context, &sub) > 0){ return 1; } } } 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, MSG_EXPIRY_INFINITE, 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, MSG_EXPIRY_INFINITE, 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); if(bridge__set_tcp_keepalive(context) != MOSQ_ERR_SUCCESS){ return MOSQ_ERR_UNKNOWN; } #ifdef WITH_TCP_USER_TIMEOUT if(bridge__set_tcp_user_timeout(context)){ return MOSQ_ERR_UNKNOWN; } #endif if(context->bridge->receive_maximum != 0){ receive_maximum.value.i16 = context->bridge->receive_maximum; receive_maximum.identifier = MQTT_PROP_RECEIVE_MAXIMUM; receive_maximum.property_type = MQTT_PROP_TYPE_INT16; receive_maximum.client_generated = false; receive_maximum.next = properties; properties = &receive_maximum; } if(context->bridge->session_expiry_interval != MQTT_SESSION_EXPIRY_IMMEDIATE){ session_expiry_interval.value.i32 = context->bridge->session_expiry_interval; session_expiry_interval.identifier = MQTT_PROP_SESSION_EXPIRY_INTERVAL; session_expiry_interval.property_type = MQTT_PROP_TYPE_INT32; session_expiry_interval.client_generated = false; session_expiry_interval.next = properties; properties = &session_expiry_interval; } if(context->bridge->max_topic_alias != 0){ topic_alias_max.value.i16 = context->bridge->max_topic_alias; topic_alias_max.identifier = MQTT_PROP_TOPIC_ALIAS_MAXIMUM; topic_alias_max.property_type = MQTT_PROP_TYPE_INT16; topic_alias_max.client_generated = false; topic_alias_max.next = properties; properties = &topic_alias_max; } rc2 = send__connect(context, context->keepalive, context->clean_start, properties); 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) { char *notification_topic; size_t notification_topic_len; struct mosquitto__bridge_topic *cur_topic; 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; } char 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, 0, NULL, 0)){ return 1; } } db__messages_easy_queue(context, context->bridge->notification_topic, qos, 1, ¬ification_payload, 1, MSG_EXPIRY_INFINITE, 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, 0, NULL, 0)){ mosquitto_FREE(notification_topic); return 1; } } db__messages_easy_queue(context, notification_topic, qos, 1, ¬ification_payload, 1, MSG_EXPIRY_INFINITE, NULL); mosquitto_FREE(notification_topic); } } LL_FOREACH(context->bridge->topics, cur_topic){ if(cur_topic->direction == bd_in || cur_topic->direction == bd_both){ if(cur_topic->qos > context->max_qos){ sub_opts = context->max_qos; }else{ sub_opts = cur_topic->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, &cur_topic->remote_topic, sub_opts, NULL)){ return 1; } }else{ if(context->bridge->attempt_unsubscribe){ if(send__unsubscribe(context, NULL, 1, &cur_topic->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; } } } } struct mosquitto_subscription sub; memset(&sub, 0, sizeof(sub)); LL_FOREACH(context->bridge->topics, cur_topic){ sub.topic_filter = cur_topic->local_topic; if(cur_topic->direction == bd_out || cur_topic->direction == bd_both){ if(cur_topic->qos > context->max_qos){ sub.options = context->max_qos; }else{ sub.options = cur_topic->qos; } retain__queue(context, &sub); } } context->bridge->connected_at = db.now_s; 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__new(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__reload(void) { int i; int j; // destroy old bridges that dissappeared for(i=0; ibridge_count; j++){ if(!strcmp(db.bridges[i]->bridge->name, db.config->bridges[j]->name)){ break; } } if(j==db.config->bridge_count){ bridge__destroy(db.bridges[i]); } } for(i=0; ibridge_count; i++){ for(j=0; jbridges[i]->name, db.bridges[j]->bridge->name)){ break; } } if(j==db.bridge_count){ // a new bridge was found, create it bridge__new(db.config->bridges[i]); db.config->bridges[i] = NULL; continue; } if(db.config->bridges[i]->reload_type == brt_immediate){ // in this case, an existing bridge should match for(j=0; jbridges[i]->name, db.bridges[j]->bridge->name)){ break; } } assert(jwill_delay_interval = 0; bridge__destroy(db.bridges[j]); bridge__new(db.config->bridges[i]); db.config->bridges[i] = NULL; } } } void bridge__db_cleanup(void) { int i; for(i=0; i 0); for(i=0; ibridge->name); mosquitto_FREE(context->bridge->local_clientid); mosquitto_FREE(context->bridge->local_username); mosquitto_FREE(context->bridge->local_password); #ifdef WITH_TLS mosquitto_FREE(context->bridge->tls_certfile); mosquitto_FREE(context->bridge->tls_keyfile); #endif 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 for(i=0; ibridge->address_count; i++){ mosquitto_FREE(context->bridge->addresses[i].address); } mosquitto_FREE(context->bridge->addresses); config__bridge_cleanup(context->bridge); context->bridge = NULL; } static void bridge__packet_cleanup(struct mosquitto *context) { struct mosquitto__packet *packet; if(!context){ return; } while(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; metrics__int_dec(mosq_gauge_out_packets, context->out_packet_count); metrics__int_dec(mosq_gauge_out_packet_bytes, context->out_packet_bytes); context->out_packet_count = 0; context->out_packet_bytes = 0; packet__cleanup(&(context->in_packet)); } static int rand_between(int low, int high) { int r; mosquitto_getrandom(&r, sizeof(int)); return (abs(r) % (high - low)) + low; } static void bridge__backoff_step(struct mosquitto__bridge *bridge) { /* “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__bridge *bridge) { bridge->restart_timeout = bridge->backoff_base; } static void bridge__update_backoff(struct mosquitto__bridge *bridge) { if(!bridge){ return; } if(!bridge->backoff_cap){ /* skip if not using jitter */ return; } if(bridge->connected_at && db.now_s - bridge->connected_at >= bridge->stable_connection_period){ log__printf(NULL, MOSQ_LOG_INFO, "Bridge %s connection was stable enough, resetting backoff", bridge->name); bridge__backoff_reset(bridge); }else{ bridge__backoff_step(bridge); } bridge->connected_at = 0; log__printf(NULL, MOSQ_LOG_INFO, "Bridge %s next backoff will be %d ms", bridge->name, bridge->restart_timeout); } 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; } } } static bool reload_if_needed(struct mosquitto *context) { int i; for(i=0; ibridge_count; i++){ if(db.config->bridges[i] && !strcmp(context->bridge->name, db.config->bridges[i]->name)){ bridge__destroy(context); bridge__new(db.config->bridges[i]); db.config->bridges[i] = NULL; loop__update_next_event(100); return true; } } return false; } 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; ibridge->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; loop__update_next_event(5000); } }else{ COMPAT_CLOSE(context->bridge->primary_retry_sock); context->bridge->primary_retry_sock = INVALID_SOCKET; context->bridge->primary_retry = db.now_s+5; loop__update_next_event(5000); } } } }else{ if(reload_if_needed(context)){ continue; } /* Want to try to restart the bridge connection */ if(!context->bridge->restart_t){ bridge__update_backoff(context->bridge); context->bridge->restart_t = 1000*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; } loop__update_next_event(context->bridge->restart_timeout); }else{ if((context->bridge->start_type == bst_lazy && context->bridge->lazy_reconnect) || (context->bridge->start_type == bst_automatic && 1000*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__new(context); if(context->out_packet){ mux__add_out(context); } }else if(rc == MOSQ_ERR_CONN_PENDING){ mux__new(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->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; loop__update_next_event(1000); } } #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; loop__update_next_event(5000); } mux__new(context); if(context->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 ================================================ FILE: src/bridge_topic.c ================================================ /* Copyright (c) 2009-2021 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 "utlist.h" #ifdef WITH_BRIDGE static int bridge__create_remap_topic(const char *prefix, const char *topic, char **remap_topic) { if(prefix){ if(topic){ size_t 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(!prefix || strlen(prefix) != 0){ 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; } static struct mosquitto__bridge_topic *bridge__find_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 *cur_topic = NULL; bool found = false; LL_FOREACH(bridge->topics, cur_topic){ if(cur_topic->direction != direction){ continue; } if(cur_topic->qos != qos){ continue; } if(cur_topic->topic != NULL && topic != NULL){ if(strcmp(cur_topic->topic, topic)){ continue; } } if(cur_topic->local_prefix != NULL && local_prefix != NULL){ if(strcmp(cur_topic->local_prefix, local_prefix)){ continue; } } if(cur_topic->remote_prefix != NULL && remote_prefix != NULL){ if(strcmp(cur_topic->remote_prefix, remote_prefix)){ continue; } } found = true; break; } if(!found){ cur_topic = NULL; } return cur_topic; } void bridge__cleanup_topics(struct mosquitto__bridge *bridge) { struct mosquitto__bridge_topic *topic, *topic_tmp; if(!bridge){ return; } LL_FOREACH_SAFE(bridge->topics, topic, topic_tmp){ LL_DELETE(bridge->topics, topic); mosquitto_free(topic->local_prefix); mosquitto_free(topic->remote_prefix); mosquitto_free(topic->local_topic); mosquitto_free(topic->remote_topic); mosquitto_free(topic->topic); mosquitto_free(topic); } } /* 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 *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; } if(bridge__find_topic(bridge, topic, direction, qos, local_prefix, remote_prefix) != NULL){ log__printf(NULL, MOSQ_LOG_INFO, "Duplicate bridge topic '%s', skipping", topic); return MOSQ_ERR_SUCCESS; } bridge->topic_count++; cur_topic = mosquitto_calloc(1, sizeof(struct mosquitto__bridge_topic)); if(cur_topic == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_topic->next = NULL; 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){ goto error; } } 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")){ goto error; } } if(remote_prefix){ if(bridge__create_prefix(&cur_topic->remote_prefix, cur_topic->topic, remote_prefix, "local")){ goto error; } } } if(bridge__create_remap_topic(cur_topic->local_prefix, cur_topic->topic, &cur_topic->local_topic)){ goto error; } if(bridge__create_remap_topic(cur_topic->remote_prefix, cur_topic->topic, &cur_topic->remote_topic)){ goto error; } LL_APPEND(bridge->topics, cur_topic); return MOSQ_ERR_SUCCESS; error: mosquitto_FREE(cur_topic->local_prefix); mosquitto_FREE(cur_topic->remote_prefix); mosquitto_FREE(cur_topic->local_topic); mosquitto_FREE(cur_topic->remote_topic); mosquitto_FREE(cur_topic->topic); mosquitto_FREE(cur_topic); log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } int bridge__remap_topic_in(struct mosquitto *context, char **topic) { struct mosquitto__bridge_topic *cur_topic; bool match; if(context->bridge && context->bridge->topics && context->bridge->topic_remapping){ LL_FOREACH(context->bridge->topics, cur_topic){ 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 */ int rc = mosquitto_topic_matches_sub(cur_topic->remote_topic, *topic, &match); if(rc){ mosquitto_FREE(*topic); return rc; } if(match){ char *topic_temp; 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. */ size_t 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 ================================================ FILE: src/broker_control.c ================================================ /* Copyright (c) 2021 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 "json_help.h" #include "mosquitto.h" #include "mosquitto_broker_internal.h" #include "mosquitto/broker.h" #include "mosquitto/broker_control.h" #include "mosquitto/broker_plugin.h" #include "mosquitto/mqtt_protocol.h" static mosquitto_plugin_id_t plg_id; static int broker__handle_control(struct mosquitto_control_cmd *cmd, void *userdata); static int add_plugin_info(cJSON *j_plugins, mosquitto_plugin_id_t *pid) { cJSON *j_plugin, *j_eps, *j_ep; struct control_endpoint *ep; if(pid->plugin_name == NULL){ return MOSQ_ERR_SUCCESS; } j_plugin = cJSON_CreateObject(); if(j_plugin == NULL){ return MOSQ_ERR_NOMEM; } if(cJSON_AddStringToObject(j_plugin, "name", pid->plugin_name) == NULL || (pid->plugin_version && cJSON_AddStringToObject(j_plugin, "version", pid->plugin_version) == NULL) || (pid->listener && cJSON_AddNumberToObject(j_plugin, "port", pid->listener->port) == NULL) || (j_eps = cJSON_AddArrayToObject(j_plugin, "control-endpoints")) == NULL ){ cJSON_Delete(j_plugin); return MOSQ_ERR_NOMEM; } DL_FOREACH(pid->control_endpoints, ep){ j_ep = cJSON_CreateString(ep->topic); if(j_ep == NULL){ cJSON_Delete(j_plugin); return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_eps, j_ep); } cJSON_AddItemToArray(j_plugins, j_plugin); return MOSQ_ERR_SUCCESS; } static int broker__process_list_plugins(struct mosquitto_control_cmd *cmd) { cJSON *tree, *j_data, *j_plugins; const char *admin_clientid, *admin_username; tree = cJSON_CreateObject(); if(tree == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "Broker: %s/%s | listPlugins", admin_clientid, admin_username); if(cJSON_AddStringToObject(tree, "command", "listPlugins") == NULL || ((j_data = cJSON_AddObjectToObject(tree, "data")) == NULL) || (cmd->correlation_data && cJSON_AddStringToObject(tree, "correlationData", cmd->correlation_data) == NULL) ){ goto internal_error; } j_plugins = cJSON_AddArrayToObject(j_data, "plugins"); if(j_plugins == NULL){ goto internal_error; } for(int i=0; ij_responses, tree); return MOSQ_ERR_SUCCESS; internal_error: cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } static int add_listener(cJSON *j_listeners, struct mosquitto__listener *listener) { cJSON *j_listener; const char *protocol = NULL; j_listener = cJSON_CreateObject(); if(j_listener == NULL){ return MOSQ_ERR_NOMEM; } cJSON_AddItemToArray(j_listeners, j_listener); if(listener->protocol == mp_mqtt){ protocol = "mqtt"; }else if(listener->protocol == mp_websockets){ protocol = "mqtt+websockets"; } if(cJSON_AddNumberToObject(j_listener, "port", listener->port) == NULL || (protocol && cJSON_AddStringToObject(j_listener, "protocol", protocol) == NULL) || (listener->host && cJSON_AddStringToObject(j_listener, "bind-address", listener->host) == NULL) #ifdef WITH_UNIX_SOCKETS || (listener->unix_socket_path && cJSON_AddStringToObject(j_listener, "socket-path", listener->unix_socket_path) == NULL) #endif ){ return MOSQ_ERR_NOMEM; } #ifdef WITH_TLS if(cJSON_AddBoolToObject(j_listener, "tls", listener->ssl_ctx != NULL) == NULL ){ return MOSQ_ERR_NOMEM; } #endif return MOSQ_ERR_SUCCESS; } static int broker__process_list_listeners(struct mosquitto_control_cmd *cmd) { cJSON *tree, *j_data, *j_listeners; const char *admin_clientid, *admin_username; tree = cJSON_CreateObject(); if(tree == NULL){ mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } admin_clientid = mosquitto_client_id(cmd->client); admin_username = mosquitto_client_username(cmd->client); mosquitto_log_printf(MOSQ_LOG_INFO, "Broker: %s/%s | listListeners", admin_clientid, admin_username); if(cJSON_AddStringToObject(tree, "command", "listListeners") == NULL || ((j_data = cJSON_AddObjectToObject(tree, "data")) == NULL) || (cmd->correlation_data && cJSON_AddStringToObject(tree, "correlationData", cmd->correlation_data) == NULL) ){ goto internal_error; } j_listeners = cJSON_AddArrayToObject(j_data, "listeners"); if(j_listeners == NULL){ goto internal_error; } for(int i=0; ilistener_count; i++){ if(add_listener(j_listeners, &db.config->listeners[i])){ goto internal_error; } } cJSON_AddItemToArray(cmd->j_responses, tree); return MOSQ_ERR_SUCCESS; internal_error: cJSON_Delete(tree); mosquitto_control_command_reply(cmd, "Internal error"); return MOSQ_ERR_NOMEM; } static int broker_control_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_control *ed = event_data; UNUSED(event); return mosquitto_control_generic_callback(ed, "$CONTROL/broker/v1/response", userdata, broker__handle_control); } void broker_control__init(void) { memset(&plg_id, 0, sizeof(plg_id)); if(db.config->enable_control_api){ mosquitto_callback_register(&plg_id, MOSQ_EVT_CONTROL, broker_control_callback, "$CONTROL/broker/v1", NULL); } } void broker_control__cleanup(void) { mosquitto_callback_unregister(&plg_id, MOSQ_EVT_CONTROL, broker_control_callback, "$CONTROL/broker/v1"); } void broker_control__reload(void) { broker_control__cleanup(); broker_control__init(); } /* ################################################################ * # * # $CONTROL/broker/v1 handler * # * ################################################################ */ static int broker__handle_control(struct mosquitto_control_cmd *cmd, void *userdata) { int rc = MOSQ_ERR_SUCCESS; UNUSED(userdata); if(!strcasecmp(cmd->command_name, "listPlugins")){ rc = broker__process_list_plugins(cmd); }else if(!strcasecmp(cmd->command_name, "listListeners")){ rc = broker__process_list_listeners(cmd); /* Unknown */ }else{ mosquitto_control_command_reply(cmd, "Unknown command"); rc = MOSQ_ERR_INVAL; } return rc; } ================================================ FILE: src/conf.c ================================================ /* Copyright (c) 2009-2021 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 "tls_mosq.h" #include "util_mosq.h" #include "mosquitto/mqtt_protocol.h" #include "utlist.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 #define REQUIRE_LISTENER(A) \ do{ \ if(cur_listener == NULL){ \ log__printf(NULL, MOSQ_LOG_ERR, "Error: The '%s' option requires a listener to be defined first.", (A)); \ return MOSQ_ERR_INVAL; \ } \ }while(0) #define REQUIRE_LISTENER_OR_DEFAULT_LISTENER(A) \ do{ \ if(cur_listener == NULL){ \ if(config__create_default_listener(config, (A))){ \ return MOSQ_ERR_NOMEM; \ } \ cur_listener = config->default_listener; \ } \ }while(0) #define REQUIRE_LISTENER_IF_PER_LISTENER(A) \ do{ \ if(config->per_listener_settings == true && cur_listener == NULL){ \ log__printf(NULL, MOSQ_LOG_ERR, "Error: The '%s' option requires a listener to be defined first.", (A)); \ return MOSQ_ERR_INVAL; \ } \ }while(0) #define REQUIRE_NON_DEFAULT_LISTENER(A) \ do{ \ if(cur_listener == config->default_listener || cur_listener == NULL){ \ log__printf(NULL, MOSQ_LOG_ERR, "Error: The '%s' option requires a listener to be defined first.", (A)); \ return MOSQ_ERR_INVAL; \ } \ }while(0) #define REQUIRE_BRIDGE(A) \ do{ \ if(cur_bridge == NULL){ \ log__printf(NULL, MOSQ_LOG_ERR, "Error: The '%s' option requires a bridge to be defined first.", (A)); \ return MOSQ_ERR_INVAL; \ } \ }while(0) #define REQUIRE_PLUGIN(A) \ do{ \ if(cur_plugin == NULL){ \ log__printf(NULL, MOSQ_LOG_ERR, "Error: The '%s' option requires plugin/global_plugin/plugin_load to be defined first.", (A)); \ return MOSQ_ERR_INVAL; \ } \ }while(0) #define OPTION_DEPRECATED(A, B) \ log__printf(NULL, MOSQ_LOG_NOTICE, "The '%s' option is now deprecated and will be removed in version 3.0. %s", (A), (B)) #define OPTION_UNAVAILABLE(A) \ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: The '%s' option is no longer available.", (A)); #define REQUIRE_NON_EMPTY_OPTION(A, B) \ do{ \ if(!(A)){ \ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty '%s' value in configuration.", (B)); \ return MOSQ_ERR_INVAL; \ } \ }while(0) #define PER_LISTENER_ALTERNATIVE(A, B) \ if(config->per_listener_settings){ \ log__printf(NULL, MOSQ_LOG_NOTICE, "You are using the '%s' option with 'per_listener_settings true'. Please replace this with '%s'.", A, B); \ } \ #ifdef FINAL_WITH_TLS_PSK # define REQUIRE_BRIDGE_NO_TLS_PSK(A) \ do{ \ if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ \ log__printf(NULL, MOSQ_LOG_ERR, "Error: '%s': Cannot use both certificate and psk encryption in a single bridge.", (A)); \ return MOSQ_ERR_INVAL; \ } \ }while(0) # define REQUIRE_BRIDGE_NO_X509(A) \ do{ \ if(cur_bridge->tls_cafile || cur_bridge->tls_capath || cur_bridge->tls_certfile || cur_bridge->tls_keyfile){ \ log__printf(NULL, MOSQ_LOG_ERR, "Error: '%s': Cannot use both certificate and identity encryption in a single bridge.", (A)); \ return MOSQ_ERR_INVAL; \ } \ }while(0) #else # define REQUIRE_BRIDGE_NO_TLS_PSK(A) # define REQUIRE_BRIDGE_NO_X509(A) #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(void); #ifdef WITH_BRIDGE static int config__check_bridges(struct mosquitto__config *config); #endif static int config__add_listener(struct mosquitto__config *config) { struct mosquitto__listener *listener; struct mosquitto__listener *new_listeners; int def_listener = -1; if(config->default_listener){ for(int i=0; ilistener_count; i++){ if(&config->listeners[i] == config->default_listener){ def_listener = i; break; } } } new_listeners = mosquitto_realloc(config->listeners, sizeof(struct mosquitto__listener)*(size_t)(config->listener_count+1)); if(!new_listeners){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } config->listeners = new_listeners; listener = &config->listeners[config->listener_count]; memset(listener, 0, sizeof(struct mosquitto__listener)); listener->security_options = mosquitto_calloc(1, sizeof(struct mosquitto__security_options)); if(!listener->security_options){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } if(def_listener != -1){ config->default_listener = &config->listeners[def_listener]; } config->listener_count++; return MOSQ_ERR_SUCCESS; } static int config__create_default_listener(struct mosquitto__config *config, const char *option_name) { if(config->default_listener){ return MOSQ_ERR_SUCCESS; } log__printf(NULL, MOSQ_LOG_INFO, "Creating default listener due to '%s' option.", option_name); log__printf(NULL, MOSQ_LOG_INFO, "It is best practice to define a 'listener' first. Using the '%s' option without a listener will be disabled in the future.", option_name); if(config__add_listener(config)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } config->default_listener = &config->listeners[config->listener_count-1]; listener__set_defaults(config->default_listener); config->default_listener->port = 1883; return MOSQ_ERR_SUCCESS; } static void conf__set_cur_security_options(struct mosquitto__config *config, struct mosquitto__listener **cur_listener, struct mosquitto__security_options **security_options, const char *option_name) { if(config->per_listener_settings){ if(*cur_listener == NULL){ if(config__create_default_listener(config, option_name)){ return; } *cur_listener = config->default_listener; } (*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) { /* Set defaults */ for(int i=0; ilistener_count; i++){ listener__set_defaults(&config->listeners[i]); } config->local_only = true; config->allow_duplicate_messages = true; mosquitto_FREE(config->security_options.acl_data.acl_file); mosquitto_FREE(config->security_options.password_data.password_file); mosquitto_FREE(config->security_options.psk_file); 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; 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); #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.quiet){ config->log_type = 0; }else 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->global_max_clients = -1; config->global_max_connections = -1; config->log_timestamp_format = NULL; config->max_keepalive = 0; config->max_packet_size = 2000000; 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); mosquitto_FREE(config->persistence_file); config->persistent_client_expiration = 0; config->queue_qos0_messages = false; config->retain_available = true; config->retain_expiry_interval = 0; config->set_tcp_nodelay = false; config->sys_interval = 10; config->upgrade_outgoing_qos = false; config->packet_buffer_size = 4096; config->packet_max_auth = 100000; config->packet_max_connect = 100000; config->packet_max_sub = 100000; config->packet_max_simple = 10000; } static void config__cleanup_plugin_config(mosquitto_plugin_id_t *plugin) { mosquitto_FREE(plugin->config.path); mosquitto_FREE(plugin->config.name); if(plugin->config.options){ for(int j=0; jconfig.option_count; j++){ mosquitto_FREE(plugin->config.options[j].key); mosquitto_FREE(plugin->config.options[j].value); } mosquitto_FREE(plugin->config.options); plugin->config.option_count = 0; } mosquitto_FREE(plugin->config.security_options); mosquitto_FREE(plugin); } static void config__cleanup_plugins(void) { for(int i=0; idaemon = false; } void config__cleanup(struct mosquitto__config *config) { 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_data.acl_file); mosquitto_FREE(config->security_options.password_data.password_file); mosquitto_FREE(config->security_options.psk_file); mosquitto_FREE(config->security_options.plugins); mosquitto_FREE(config->pid_file); mosquitto_FREE(config->user); mosquitto_FREE(config->log_timestamp_format); if(config->listeners){ for(int 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); if(config->listeners[i].security_options){ mosquitto_FREE(config->listeners[i].security_options->auto_id_prefix); mosquitto_FREE(config->listeners[i].security_options->acl_data.acl_file); mosquitto_FREE(config->listeners[i].security_options->password_data.password_file); mosquitto_FREE(config->listeners[i].security_options->psk_file); mosquitto_FREE(config->listeners[i].security_options->plugins); mosquitto_FREE(config->listeners[i].security_options); } #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].tls_version); mosquitto_FREE(config->listeners[i].tls_engine); mosquitto_FREE(config->listeners[i].tls_engine_kpass_sha1); #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS if(!config->listeners[i].ws_context) /* libwebsockets frees its own SSL_CTX */ #endif { SSL_CTX_free(config->listeners[i].ssl_ctx); config->listeners[i].ssl_ctx = NULL; } #endif #if defined(WITH_WEBSOCKETS) || defined(WITH_HTTP_API) mosquitto_FREE(config->listeners[i].http_dir); #endif #ifdef WITH_WEBSOCKETS for(int j=0; jlisteners[i].ws_origin_count; j++){ mosquitto_FREE(config->listeners[i].ws_origins[j]); } mosquitto_FREE(config->listeners[i].ws_origins); #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(int i=0; ibridge_count; i++){ config__bridge_cleanup(config->bridges[i]); } mosquitto_FREE(config->bridges); } #endif config__cleanup_plugins(); 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; } } #ifdef WITH_BRIDGE void config__bridge_cleanup(struct mosquitto__bridge *bridge) { if(bridge == NULL){ return; } mosquitto_FREE(bridge->name); if(bridge->addresses){ for(int i=0; iaddress_count; i++){ mosquitto_FREE(bridge->addresses[i].address); } mosquitto_FREE(bridge->addresses); } mosquitto_FREE(bridge->bind_address); mosquitto_FREE(bridge->remote_clientid); mosquitto_FREE(bridge->remote_username); mosquitto_FREE(bridge->remote_password); mosquitto_FREE(bridge->local_clientid); mosquitto_FREE(bridge->local_username); mosquitto_FREE(bridge->local_password); if(bridge->topics){ struct mosquitto__bridge_topic *cur_topic, *topic_tmp; LL_FOREACH_SAFE(bridge->topics, cur_topic, topic_tmp){ mosquitto_FREE(cur_topic->topic); mosquitto_FREE(cur_topic->local_prefix); mosquitto_FREE(cur_topic->remote_prefix); mosquitto_FREE(cur_topic->local_topic); mosquitto_FREE(cur_topic->remote_topic); LL_DELETE(bridge->topics, cur_topic); mosquitto_FREE(cur_topic); } mosquitto_FREE(bridge->topics); } mosquitto_FREE(bridge->notification_topic); #ifdef WITH_TLS mosquitto_FREE(bridge->tls_certfile); mosquitto_FREE(bridge->tls_keyfile); mosquitto_FREE(bridge->tls_version); mosquitto_FREE(bridge->tls_cafile); mosquitto_FREE(bridge->tls_capath); mosquitto_FREE(bridge->tls_alpn); mosquitto_FREE(bridge->tls_ciphers); mosquitto_FREE(bridge->tls_13_ciphers); #ifdef FINAL_WITH_TLS_PSK mosquitto_FREE(bridge->tls_psk_identity); mosquitto_FREE(bridge->tls_psk); #endif #endif mosquitto_FREE(bridge); } #endif static void print_version(void) { printf("mosquitto %s\n", VERSION); printf("Copyright © 2025 Roger Light.\n"); printf("License EPL-2.0 OR BSD-3-Clause.\n"); } 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] [-v]\n"); printf(" [--tls-keylog file]\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(" -q : quiet mode - disable all logging types. This overrides\n"); printf(" any logging options given in the config file, and -v.\n"); printf(" -v : verbose mode - enable all logging types. This overrides\n"); printf(" any logging options given in the config file.\n"); printf(" --test-config : test config file and exit\n"); printf(" --tls-keylog : log TLS connection information to a file, to allow\n"); printf(" debugging with e.g. wireshark. Do not use on a production\n"); printf(" server.\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_UNKNOWN; }else if(!strcmp(argv[i], "--version")){ print_version(); return MOSQ_ERR_UNKNOWN; }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], "--tls-keylog")){ #ifdef WITH_TLS if(itest_configuration = true; }else{ fprintf(stderr, "Error: Unknown option '%s'.\n", argv[i]); print_usage(); return MOSQ_ERR_INVAL; } } /* 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.quiet){ config->log_type = 0; }else if(db.verbose){ config->log_type = UINT_MAX; } if(getenv("MOSQUITTO_PERSISTENCE_LOCATION")){ mosquitto_FREE(config->persistence_location); config->persistence_location = mosquitto_strdup(getenv("MOSQUITTO_PERSISTENCE_LOCATION")); if(!config->persistence_location){ return MOSQ_ERR_NOMEM; } } return config__check(config); } static void config__copy(struct mosquitto__config *src, struct mosquitto__config *dest) { mosquitto_FREE(dest->security_options.acl_data.acl_file); dest->security_options.acl_data.acl_file = src->security_options.acl_data.acl_file; acl_file__cleanup(&dest->security_options.acl_data); dest->security_options.acl_data.acl_users = src->security_options.acl_data.acl_users; dest->security_options.acl_data.acl_patterns = src->security_options.acl_data.acl_patterns; dest->security_options.acl_data.acl_anon.username = src->security_options.acl_data.acl_anon.username; dest->security_options.acl_data.acl_anon.acl = src->security_options.acl_data.acl_anon.acl; 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_data.password_file); dest->security_options.password_data.password_file = src->security_options.password_data.password_file; password_file__cleanup(&dest->security_options.password_data); dest->security_options.password_data.unpwd = src->security_options.password_data.unpwd; mosquitto_FREE(dest->security_options.psk_file); dest->security_options.psk_file = src->security_options.psk_file; mosquitto_FREE(dest->security_options.plugins); dest->security_options.plugin_count = src->security_options.plugin_count; dest->security_options.plugins = src->security_options.plugins; 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; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS dest->websockets_log_level = src->websockets_log_level; #endif #ifdef WITH_BRIDGE for(int i=0; ibridge_count; i++){ if(dest->bridges[i]){ config__bridge_cleanup(dest->bridges[i]); } } mosquitto_FREE(dest->bridges); dest->bridges = src->bridges; dest->bridge_count = src->bridge_count; #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 == false){ 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.quiet){ config->log_type = 0; }else if(db.verbose){ config->log_type = UINT_MAX; }else if(cr.log_type_set){ config->log_type = cr.log_type; } #ifdef WITH_BRIDGE return config__check_bridges(config); #else return MOSQ_ERR_SUCCESS; #endif } static mosquitto_plugin_id_t *config__plugin_find(const char *name) { if(db.plugins && name){ for(int i=0; iconfig.name && !strcmp(db.plugins[i]->config.name, name)){ return db.plugins[i]; } } } return NULL; } static mosquitto_plugin_id_t *config__plugin_load(const char *name, const char *path) { mosquitto_plugin_id_t *plugin = NULL; mosquitto_plugin_id_t **plugins = NULL; if(name && config__plugin_find(name)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate plugin name '%s'.", name); return NULL; } if(!path || !strcmp(path, "")){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Missing plugin path for plugin name '%s'.", name); return NULL; } plugin = mosquitto_calloc(1, sizeof(mosquitto_plugin_id_t)); if(!plugin){ goto error; } if(name){ plugin->config.name = mosquitto_strdup(name); } plugin->config.path = mosquitto_strdup(path); if((name && !plugin->config.name) || !plugin->config.path){ goto error; } plugin->config.options = NULL; plugin->config.option_count = 0; plugin->config.deny_special_chars = true; /* Add to db list */ plugins = mosquitto_realloc(db.plugins, (size_t)(db.plugin_count+1)*sizeof(struct mosquitto__plugin_config *)); if(!plugins){ goto error; } plugins[db.plugin_count] = plugin; db.plugins = plugins; db.plugin_count++; return plugin; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); if(plugin){ mosquitto_FREE(plugin->config.name); mosquitto_FREE(plugin->config.path); } mosquitto_FREE(plugin); return NULL; } int config__plugin_add_secopt(mosquitto_plugin_id_t *plugin, struct mosquitto__security_options *security_options) { struct mosquitto__security_options **new_options; mosquitto_plugin_id_t **new_plugins; new_options = mosquitto_realloc(plugin->config.security_options, (size_t)(plugin->config.security_option_count+1)*sizeof(struct mosquitto__security_options *)); new_plugins = mosquitto_realloc(security_options->plugins, (size_t)(security_options->plugin_count+1)*sizeof(mosquitto_plugin_id_t *)); if(!new_options || !new_plugins){ mosquitto_FREE(new_options); mosquitto_FREE(new_plugins); log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } new_options[plugin->config.security_option_count] = security_options; plugin->config.security_options = new_options; plugin->config.security_option_count++; new_plugins[security_options->plugin_count] = plugin; security_options->plugins = new_plugins; security_options->plugin_count++; 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 mosquitto_plugin_id_t *cur_plugin = NULL; char *key; struct mosquitto__listener *cur_listener = NULL; int i; int lineno_ext = 0; size_t prefix_len; size_t slen; #ifdef WITH_WEBSOCKETS char **ws_origins = NULL; #endif *lineno = 0; while(mosquitto_fgets(buf, buflen, fptr)){ (*lineno)++; if((*buf)[0] != '#' && (*buf)[0] != 10 && (*buf)[0] != 13){ slen = strlen(*buf); if(slen == 0){ continue; } while((*buf)[slen-1] == 10 || (*buf)[slen-1] == 13){ (*buf)[slen-1] = 0; slen = strlen(*buf); if(slen == 0){ continue; } } token = strtok_r((*buf), " ", &saveptr); if(token){ if(!strcmp(token, "accept_protocol_versions")){ REQUIRE_NON_DEFAULT_LISTENER(token); cur_listener->disable_protocol_v3 = true; cur_listener->disable_protocol_v4 = true; cur_listener->disable_protocol_v5 = true; if(saveptr == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty '%s' value in configuration.", "accept_protocol_versions"); return MOSQ_ERR_INVAL; } token = strtok_r(saveptr, ", \t", &saveptr); REQUIRE_NON_EMPTY_OPTION(token, "accept_protocol_versions"); while(token){ if(!strcmp(token, "3")){ cur_listener->disable_protocol_v3 = false; }else if(!strcmp(token, "4")){ cur_listener->disable_protocol_v4 = false; }else if(!strcmp(token, "5")){ cur_listener->disable_protocol_v5 = false; } token = strtok_r(NULL, ", \t", &saveptr); } }else if(!strcmp(token, "acl_file")){ REQUIRE_LISTENER_IF_PER_LISTENER(token); conf__set_cur_security_options(config, &cur_listener, &cur_security_options, token); mosquitto_FREE(cur_security_options->acl_data.acl_file); if(conf__parse_string(&token, "acl_file", &cur_security_options->acl_data.acl_file, &saveptr)){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "address") || !strcmp(token, "addresses")){ #ifdef WITH_BRIDGE REQUIRE_BRIDGE(token); if(cur_bridge->addresses){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration, 'address' only allowed once."); return MOSQ_ERR_INVAL; } while((token = strtok_r(NULL, " ", &saveptr))){ if(token[0] == '#'){ break; } struct bridge_address *new_addresses = mosquitto_realloc(cur_bridge->addresses, sizeof(struct bridge_address)*(size_t)(cur_bridge->address_count+1)); if(!new_addresses){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_bridge->address_count++; cur_bridge->addresses = new_addresses; memset(&cur_bridge->addresses[cur_bridge->address_count-1], 0, sizeof(struct bridge_address)); cur_bridge->addresses[cur_bridge->address_count-1].address = mosquitto_strdup(token); if(!cur_bridge->addresses[cur_bridge->address_count-1].address){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } 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 bridge 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; } 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")){ REQUIRE_LISTENER_IF_PER_LISTENER(token); PER_LISTENER_ALTERNATIVE(token, "listener_allow_anonymous"); conf__set_cur_security_options(config, &cur_listener, &cur_security_options, token); 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")){ OPTION_DEPRECATED(token, "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")){ REQUIRE_LISTENER_IF_PER_LISTENER(token); conf__set_cur_security_options(config, &cur_listener, &cur_security_options, token); 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. */ } REQUIRE_PLUGIN(token); 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 'plugin_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: Empty 'plugin_opt_' config option."); mosquitto_FREE(key); return MOSQ_ERR_INVAL; } token = saveptr; if(token && token[0]){ while(token[0] == ' ' || token[0] == '\t'){ token++; } struct mosquitto_opt *new_options = mosquitto_realloc(cur_plugin->config.options, (size_t)(cur_plugin->config.option_count+1)*sizeof(struct mosquitto_opt)); if(!new_options){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); mosquitto_FREE(key); return MOSQ_ERR_NOMEM; } cur_plugin->config.option_count++; cur_plugin->config.options = new_options; cur_plugin->config.options[cur_plugin->config.option_count-1].key = key; cur_plugin->config.options[cur_plugin->config.option_count-1].value = mosquitto_strdup(token); if(!cur_plugin->config.options[cur_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") || !strcmp(token, "global_plugin")){ if(reload){ continue; /* plugin not currently valid for reloading. */ } if(!strcmp(token, "global_plugin")){ cur_security_options = &db.config->security_options; }else{ REQUIRE_LISTENER_IF_PER_LISTENER(token); conf__set_cur_security_options(config, &cur_listener, &cur_security_options, token); } cur_plugin = config__plugin_load(NULL, saveptr); if(cur_plugin == NULL){ return MOSQ_ERR_INVAL; } if(config__plugin_add_secopt(cur_plugin, cur_security_options)){ 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_plugin){ log__printf(NULL, MOSQ_LOG_ERR, "Error: An auth_plugin_deny_special_chars option exists in the config file without a plugin."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "auth_plugin_deny_special_chars", &cur_plugin->config.deny_special_chars, &saveptr)){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "plugin_load")){ char *name = NULL; if(reload){ continue; /* plugin not currently valid for reloading. */ } name = strtok_r(NULL, " ", &saveptr); REQUIRE_NON_EMPTY_OPTION(name, "plugin_load"); cur_plugin = config__plugin_load(name, saveptr); if(cur_plugin == NULL){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "plugin_use")){ char *name = NULL; if(reload){ continue; /* plugin not currently valid for reloading. */ } REQUIRE_NON_DEFAULT_LISTENER(token); if(conf__parse_string(&token, "plugin_use", &name, &saveptr)){ return MOSQ_ERR_INVAL; } cur_plugin = config__plugin_find(name); if(!cur_plugin){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Plugin '%s' not previously loaded.", name); mosquitto_FREE(name); return MOSQ_ERR_INVAL; } mosquitto_FREE(name); if(config__plugin_add_secopt(cur_plugin, cur_listener->security_options)){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "auto_id_prefix")){ REQUIRE_LISTENER_IF_PER_LISTENER(token); OPTION_DEPRECATED(token, "Please use 'listener_auto_id_prefix' instead."); conf__set_cur_security_options(config, &cur_listener, &cur_security_options, token); 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){ if(strlen(cur_security_options->auto_id_prefix) > 50){ log__printf(NULL, MOSQ_LOG_ERR, "Error: auto_id_prefix length must be <= 50."); return MOSQ_ERR_INVAL; } 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")){ OPTION_DEPRECATED(token, ""); config->local_only = false; if(reload){ continue; /* Rebinding listeners not valid during reloading. */ } if(config__create_default_listener(config, token)){ return MOSQ_ERR_NOMEM; } cur_listener = config->default_listener; 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; /* Rebinding listeners not valid during reloading. */ } REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); 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 REQUIRE_BRIDGE(token); 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) REQUIRE_BRIDGE(token); REQUIRE_BRIDGE_NO_TLS_PSK(token); 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) REQUIRE_BRIDGE(token); 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_ciphers")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) REQUIRE_BRIDGE(token); if(conf__parse_string(&token, "bridge_ciphers", &cur_bridge->tls_ciphers, &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_ciphers_tls1.3")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) REQUIRE_BRIDGE(token); if(conf__parse_string(&token, "bridge_ciphers_tls1.3", &cur_bridge->tls_13_ciphers, &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) REQUIRE_BRIDGE(token); 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) REQUIRE_BRIDGE(token); REQUIRE_BRIDGE_NO_TLS_PSK(token); 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) REQUIRE_BRIDGE(token); REQUIRE_BRIDGE_NO_TLS_PSK(token); 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) REQUIRE_BRIDGE(token); REQUIRE_BRIDGE_NO_X509(token); 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) REQUIRE_BRIDGE(token); 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) REQUIRE_BRIDGE(token); 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) REQUIRE_BRIDGE(token); 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_max_topic_alias")){ #ifdef WITH_BRIDGE REQUIRE_BRIDGE(token); if(conf__parse_int(&token, "bridge_max_topic_alias", &tmp_int, &saveptr)){ return MOSQ_ERR_INVAL; } if(tmp_int < 0 || tmp_int > UINT16_MAX){ log__printf(NULL, MOSQ_LOG_ERR, "Error: bridge_max_topic_alias must be > 0 and <= 65535."); return MOSQ_ERR_INVAL; } cur_bridge->max_topic_alias = (uint16_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) REQUIRE_BRIDGE(token); 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) REQUIRE_BRIDGE(token); REQUIRE_BRIDGE_NO_TLS_PSK(token); mosquitto_FREE(cur_bridge->tls_keyfile); 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 REQUIRE_BRIDGE(token); token = strtok_r(NULL, "", &saveptr); REQUIRE_NON_EMPTY_OPTION(token, "bridge_protocol_version"); 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_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_psk")){ #if defined(WITH_BRIDGE) && defined(FINAL_WITH_TLS_PSK) REQUIRE_BRIDGE(token); REQUIRE_BRIDGE_NO_X509(token); 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_receive_maximum")){ #if defined(WITH_BRIDGE) REQUIRE_BRIDGE(token); if(conf__parse_int(&token, "bridge_receive_maximum", &tmp_int, &saveptr)){ return MOSQ_ERR_INVAL; } if(tmp_int <= 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: bridge_receive_maximum must be greater than 0."); return MOSQ_ERR_INVAL; }else if((uint64_t)tmp_int > (uint64_t)UINT16_MAX){ log__printf(NULL, MOSQ_LOG_ERR, "Error: bridge_receive_maximum must be lower than %u.", UINT16_MAX); return MOSQ_ERR_INVAL; } cur_bridge->receive_maximum = (uint16_t)tmp_int; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_reload_type")){ #ifdef WITH_BRIDGE REQUIRE_BRIDGE(token); token = strtok_r(NULL, " ", &saveptr); REQUIRE_NON_EMPTY_OPTION(token, "bridge_reload_type"); if(!strcmp(token, "lazy")){ cur_bridge->reload_type = brt_lazy; }else if(!strcmp(token, "immediate")){ cur_bridge->reload_type = brt_immediate; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid 'bridge_reload_type' value in configuration (%s).", token); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_session_expiry_interval")){ #if defined(WITH_BRIDGE) REQUIRE_BRIDGE(token); if(conf__parse_int(&token, "bridge_session_expiry_interval", &tmp_int, &saveptr)){ return MOSQ_ERR_INVAL; } if(tmp_int < 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: bridge_session_expiry_interval must not be negative."); return MOSQ_ERR_INVAL; }else if((uint64_t)tmp_int > (uint64_t)MQTT_SESSION_EXPIRY_NEVER){ log__printf(NULL, MOSQ_LOG_ERR, "Error: bridge_session_expiry_interval must be lower than %u.", MQTT_SESSION_EXPIRY_NEVER); return MOSQ_ERR_INVAL; } cur_bridge->session_expiry_interval = (uint32_t)tmp_int; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_tcp_keepalive")){ #ifdef WITH_BRIDGE REQUIRE_BRIDGE(token); if(conf__parse_int(&token, "bridge_tcp_keepalive_idle", &tmp_int, &saveptr)){ return MOSQ_ERR_INVAL; } if(tmp_int <= 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: invalid TCP keepalive idle value."); return MOSQ_ERR_INVAL; } cur_bridge->tcp_keepalive_idle = (unsigned int)tmp_int; if(conf__parse_int(&token, "bridge_tcp_keepalive_interval", &tmp_int, &saveptr)){ return MOSQ_ERR_INVAL; } if(tmp_int <= 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: invalid TCP keepalive interval value."); return MOSQ_ERR_INVAL; } cur_bridge->tcp_keepalive_interval = (unsigned int)tmp_int; if(conf__parse_int(&token, "bridge_tcp_keepalive_counter", &tmp_int, &saveptr)){ return MOSQ_ERR_INVAL; } if(tmp_int <= 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: invalid TCP keepalive counter value."); return MOSQ_ERR_INVAL; } cur_bridge->tcp_keepalive_counter = (unsigned int)tmp_int; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_tcp_user_timeout")){ #ifdef WITH_BRIDGE REQUIRE_BRIDGE(token); #ifdef WITH_TCP_USER_TIMEOUT if(conf__parse_int(&token, "bridge_tcp_user_timeout", &tmp_int, &saveptr)){ return MOSQ_ERR_INVAL; } if(tmp_int < 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: invalid TCP user timeout value."); return MOSQ_ERR_INVAL; } cur_bridge->tcp_user_timeout = tmp_int; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge TCP user timeout support not available."); #endif #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_tls_use_os_certs")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) REQUIRE_BRIDGE(token); if(conf__parse_bool(&token, "bridge_tls_use_os_certs", &cur_bridge->tls_use_os_certs, &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_tls_version")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) REQUIRE_BRIDGE(token); 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) REQUIRE_LISTENER(token); 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; } mosquitto_FREE(cur_listener->cafile); 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 REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); mosquitto_FREE(cur_listener->capath); 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 REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); 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; } mosquitto_FREE(cur_listener->certfile); 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")){ 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 REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); mosquitto_FREE(cur_listener->ciphers); 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) || LIBRESSL_VERSION_NUMBER > 0x3040000FL) REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); mosquitto_FREE(cur_listener->ciphers_tls13); 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 REQUIRE_BRIDGE(token); 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 REQUIRE_BRIDGE(token); 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 REQUIRE_BRIDGE(token); 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")){ OPTION_DEPRECATED(token, ""); mosquitto_FREE(config->clientid_prefixes); if(conf__parse_string(&token, "clientid_prefixes", &config->clientid_prefixes, &saveptr)){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "connection")){ #ifdef WITH_BRIDGE token = strtok_r(NULL, " ", &saveptr); REQUIRE_NON_EMPTY_OPTION(token, "connection"); /* 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; } } struct mosquitto__bridge **bridges_new = mosquitto_realloc(config->bridges, (size_t)(config->bridge_count+1)*sizeof(struct mosquitto__bridge *)); if(!bridges_new){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } config->bridges = bridges_new; cur_bridge = mosquitto_malloc(sizeof(struct mosquitto__bridge)); if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } config->bridge_count++; config->bridges[config->bridge_count-1] = cur_bridge; 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 * 1000; cur_bridge->backoff_cap = 30 * 1000; cur_bridge->stable_connection_period = 0; 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; cur_bridge->reload_type = brt_lazy; cur_bridge->max_topic_alias = 10; #ifdef WITH_TCP_USER_TIMEOUT cur_bridge->tcp_user_timeout = -1; #endif #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 REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); mosquitto_FREE(cur_listener->crlfile); 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")){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: dhparamfile is no longer required."); }else if(!strcmp(token, "disable_client_cert_date_checks")){ #ifdef WITH_TLS REQUIRE_LISTENER(token); if(conf__parse_bool(&token, "disable_client_cert_date_checks", &cur_listener->disable_client_cert_date_checks, &saveptr)){ return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "enable_control_api")){ #ifdef WITH_CONTROL if(conf__parse_bool(&token, "enable_control_api", &config->enable_control_api, &saveptr)){ return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: $CONTROL support not available (enable_control_api)."); #endif }else if(!strcmp(token, "enable_proxy_protocol")){ #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS log__printf(NULL, MOSQ_LOG_ERR, "Error: PROXY support not available with libwebsockets."); return MOSQ_ERR_INVAL; #endif REQUIRE_LISTENER(token); if(conf__parse_int(&token, "enable_proxy_protocol", &cur_listener->enable_proxy_protocol, &saveptr)){ return MOSQ_ERR_INVAL; } if(cur_listener->enable_proxy_protocol < 1 || cur_listener->enable_proxy_protocol > 2){ log__printf(NULL, MOSQ_LOG_ERR, "Error: enable_proxy_protocol must be 1 or 2."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "global_max_clients")){ if(conf__parse_int(&token, "global_max_clients", &config->global_max_clients, &saveptr)){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "global_max_connections")){ if(conf__parse_int(&token, "global_max_connections", &config->global_max_connections, &saveptr)){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "http_dir")){ #if defined(WITH_WEBSOCKETS) || defined(WITH_HTTP_API) if(reload){ continue; /* Not valid for reloading. */ } REQUIRE_LISTENER(token); if(conf__parse_string(&token, "http_dir", &cur_listener->http_dir, &saveptr)){ return MOSQ_ERR_INVAL; } #ifdef WIN32 char *http_dir_canonical = _fullpath(NULL, cur_listener->http_dir, 0); const char sep = '\\'; #else char *http_dir_canonical = realpath(cur_listener->http_dir, NULL); const char sep = '/'; #endif if(!http_dir_canonical){ return MOSQ_ERR_NOMEM; } size_t http_dir_len = strlen(http_dir_canonical) + sizeof(sep) + 1; char *http_dir_canonical_sep = mosquitto_calloc(http_dir_len, sizeof(char)); if(!http_dir_canonical_sep){ free(http_dir_canonical); return MOSQ_ERR_NOMEM; } snprintf(http_dir_canonical_sep, http_dir_len, "%s%c", http_dir_canonical, sep); free(http_dir_canonical); mosquitto_FREE(cur_listener->http_dir); cur_listener->http_dir = http_dir_canonical_sep; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: http_dir support not available."); #endif }else if(!strcmp(token, "idle_timeout")){ #ifdef WITH_BRIDGE REQUIRE_BRIDGE(token); 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){ char **files; int file_count; /* Only process include_dir from the main config file. */ token = strtok_r(NULL, "", &saveptr); REQUIRE_NON_EMPTY_OPTION(token, "include_dir"); 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 REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); mosquitto_FREE(cur_listener->keyfile); 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; if(conf__parse_int(&token, "listener port", &tmp_int, &saveptr)){ return MOSQ_ERR_INVAL; } #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{ if(config__add_listener(config)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_listener = &config->listeners[config->listener_count-1]; } listener__set_defaults(cur_listener); cur_listener->port = (uint16_t)tmp_int; mosquitto_FREE(cur_listener->host); #ifdef WITH_UNIX_SOCKETS mosquitto_FREE(cur_listener->unix_socket_path); #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 if(!strcmp(token, "listener_allow_anonymous")){ REQUIRE_LISTENER(token); if(conf__parse_bool(&token, "listener_allow_anonymous", (bool *)&cur_listener->security_options->allow_anonymous, &saveptr)){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "listener_auto_id_prefix")){ REQUIRE_LISTENER(token); if(conf__parse_string(&token, "listener_auto_id_prefix", &cur_listener->security_options->auto_id_prefix, &saveptr)){ return MOSQ_ERR_INVAL; } if(cur_listener->security_options->auto_id_prefix){ if(strlen(cur_listener->security_options->auto_id_prefix) > 50){ log__printf(NULL, MOSQ_LOG_ERR, "Error: 'listener_auto_id_prefix' length must be <= 50."); return MOSQ_ERR_INVAL; } cur_listener->security_options->auto_id_prefix_len = (uint16_t)strlen(cur_listener->security_options->auto_id_prefix); }else{ cur_listener->security_options->auto_id_prefix_len = 0; } }else if(!strcmp(token, "local_clientid")){ #ifdef WITH_BRIDGE REQUIRE_BRIDGE(token); 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 REQUIRE_BRIDGE(token); 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 REQUIRE_BRIDGE(token); 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); REQUIRE_NON_EMPTY_OPTION(token, "log_dest"); 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; #ifdef ANDROID }else if(!strcmp(token, "android")){ cr->log_dest |= MQTT3_LOG_ANDROID; #endif }else if(!strcmp(token, "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 = saveptr; if(token && token[0]){ while(token[0] == ' ' || token[0] == '\t'){ token++; } } /* Duplicate "token" check here saves a log__printf() */ if(token && 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; } cr->log_dest |= MQTT3_LOG_FILE; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty \"log_dest file\" value in configuration."); return MOSQ_ERR_INVAL; } cr->log_dest |= MQTT3_LOG_FILE; }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 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); REQUIRE_NON_EMPTY_OPTION(token, "log_type"); 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 if(!strcmp(token, "max_connections")){ REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); if(conf__parse_int(&token, token, &cur_listener->max_connections, &saveptr)){ return MOSQ_ERR_INVAL; } if(cur_listener->max_connections < 0){ cur_listener->max_connections = -1; } }else if(!strcmp(token, "maximum_qos") || !strcmp(token, "max_qos")){ REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); 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 < 0 || 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: 'max_packet_size' must be >= 20."); 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; } mosquitto_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")){ REQUIRE_LISTENER(token); mosquitto_FREE(cur_listener->mount_point); 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' value (%s). Does it contain a wildcard character?", cur_listener->mount_point); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "notifications")){ #ifdef WITH_BRIDGE REQUIRE_BRIDGE(token); 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 REQUIRE_BRIDGE(token); 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 REQUIRE_BRIDGE(token); 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 REQUIRE_BRIDGE(token); 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")){ REQUIRE_LISTENER_IF_PER_LISTENER(token); conf__set_cur_security_options(config, &cur_listener, &cur_security_options, token); mosquitto_FREE(cur_security_options->password_data.password_file); if(conf__parse_string(&token, "password_file", &cur_security_options->password_data.password_file, &saveptr)){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "per_listener_settings")){ OPTION_DEPRECATED(token, "Please see the documentation for how to achieve the same effect."); if(config->per_listener_settings){ /* Once this is set, don't let it be unset. It should be the first config option ideally. */ continue; } 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); REQUIRE_NON_EMPTY_OPTION(token, "persistent_client_expiration"); time_t expiration_mult; switch(token[strlen(token)-1]){ case 's': expiration_mult = 1; break; 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 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")){ OPTION_DEPRECATED(token, "Please use 'listener' instead."); config->local_only = false; if(reload){ continue; /* Listeners not valid for reloading. */ } if(config__create_default_listener(config, token)){ return MOSQ_ERR_NOMEM; } cur_listener = config->default_listener; 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")){ REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); token = strtok_r(NULL, " ", &saveptr); REQUIRE_NON_EMPTY_OPTION(token, "protocol"); 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 if(!strcmp(token, "http_api")){ #ifdef WITH_HTTP_API cur_listener->protocol = mp_http_api; #else log__printf(NULL, MOSQ_LOG_ERR, "Error: HTTP API 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 if(!strcmp(token, "proxy_protocol_v2_require_tls")){ #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS log__printf(NULL, MOSQ_LOG_ERR, "Error: PROXY support not available with libwebsockets."); return MOSQ_ERR_INVAL; #endif REQUIRE_LISTENER(token); if(conf__parse_bool(&token, "proxy_protocol_v2_require_tls", &cur_listener->proxy_protocol_v2_require_tls, &saveptr)){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "psk_file")){ #ifdef FINAL_WITH_TLS_PSK REQUIRE_LISTENER_IF_PER_LISTENER(token); conf__set_cur_security_options(config, &cur_listener, &cur_security_options, token); if(cur_listener && cur_listener->certfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single listener."); return MOSQ_ERR_INVAL; } mosquitto_FREE(cur_security_options->psk_file); 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; /* PSK file not valid for reloading. */ } REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); 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 REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); 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 REQUIRE_BRIDGE(token); cur_bridge->backoff_cap = 0; /* set backoff to constant mode, unless cap is specified further down */ token = strtok_r(NULL, " ", &saveptr); REQUIRE_NON_EMPTY_OPTION(token, "restart_timeout"); cur_bridge->restart_timeout = atoi(token); cur_bridge->backoff_base = 0; cur_bridge->backoff_cap = 0; 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; }else if(cur_bridge->restart_timeout > 3600){ log__printf(NULL, MOSQ_LOG_NOTICE, "restart_timeout interval too high, using 3600 seconds."); cur_bridge->restart_timeout = 3600; } 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 if(cur_bridge->backoff_cap > 7200){ log__printf(NULL, MOSQ_LOG_ERR, "Error: backoff cap too high, using 7200 seconds."); cur_bridge->backoff_cap = 7200; } token = strtok_r(NULL, " ", &saveptr); if(token){ cur_bridge->stable_connection_period = atoi(token); if(cur_bridge->stable_connection_period < 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: stable connection period cannot be negative."); return MOSQ_ERR_INVAL; } } } cur_bridge->restart_timeout *= 1000; /* backoff is tracked in ms */ cur_bridge->backoff_base *= 1000; cur_bridge->backoff_cap *= 1000; #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, "retain_expiry_interval")){ if(conf__parse_int(&token, token, &config->retain_expiry_interval, &saveptr)){ return MOSQ_ERR_INVAL; } if(config->retain_expiry_interval < 1){ log__printf(NULL, MOSQ_LOG_WARNING, "Error: retain_expiry_interval must be >= 1."); return MOSQ_ERR_INVAL; }else if(config->retain_expiry_interval > 10000000){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: retain_expiry_interval being capped at 19 years."); config->retain_expiry_interval = 10000000; } config->retain_expiry_interval *= 60; }else if(!strcmp(token, "retry_interval")){ OPTION_UNAVAILABLE(token); }else if(!strcmp(token, "round_robin")){ #ifdef WITH_BRIDGE REQUIRE_BRIDGE(token); 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 REQUIRE_BRIDGE(token); token = strtok_r(NULL, " ", &saveptr); REQUIRE_NON_EMPTY_OPTION(token, "start_type"); 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_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "socket_domain")){ if(reload){ continue; /* socket_domain not valid for reloading. */ } REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); token = strtok_r(NULL, " ", &saveptr); REQUIRE_NON_EMPTY_OPTION(token, "start_type"); 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 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 REQUIRE_BRIDGE(token); 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; /* tls_engine not valid for reloading. */ } REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); 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; /* tls_engine not valid for reloading. */ } char *kpass_sha = NULL, *kpass_sha_bin = NULL; REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); 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; } mosquitto_free(cur_listener->tls_engine_kpass_sha1); 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; /* tls_engine not valid for reloading. */ } REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); char *keyform = NULL; if(conf__parse_string(&token, "tls_keyform", &keyform, &saveptr)){ return MOSQ_ERR_INVAL; } cur_listener->tls_keyform = mosq_k_pem; if(!strcmp(keyform, "engine")){ cur_listener->tls_keyform = mosq_k_engine; } mosquitto_FREE(keyform); #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "tls_version")){ #if defined(WITH_TLS) if(reload){ continue; /* tls_version not valid for reloading. */ } REQUIRE_LISTENER(token); 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; REQUIRE_BRIDGE(token); token = strtok_r(NULL, " ", &saveptr); REQUIRE_NON_EMPTY_OPTION(token, "topic"); // Check if the topic is quoted (e.g. for spaces within topic names), but not the // special case of "" if(token[0] == '"' && token [1] != '"'){ if(strchr(saveptr, '"') == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Missing closing quote in topic value (%s).", saveptr); return MOSQ_ERR_INVAL; } char *topic_in_quotes = strtok_r(NULL, "\"", &saveptr); size_t tlen = 1; if(topic_in_quotes){ tlen = strlen(topic_in_quotes); } topic = mosquitto_malloc(strlen(token) + tlen + 1); if(!topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } strcpy(topic, token + 1); strcat(topic, " "); if(topic_in_quotes){ strcat(topic, topic_in_quotes); } }else{ topic = mosquitto_strdup(token); if(!topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } 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); mosquitto_FREE(topic); 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); mosquitto_FREE(topic); 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)){ mosquitto_FREE(topic); return MOSQ_ERR_INVAL; } mosquitto_FREE(topic); #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "max_topic_alias")){ REQUIRE_LISTENER(token); if(conf__parse_int(&token, "max_topic_alias", &tmp_int, &saveptr)){ return MOSQ_ERR_INVAL; } 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 if(!strcmp(token, "max_topic_alias_broker")){ REQUIRE_LISTENER(token); if(conf__parse_int(&token, "max_topic_alias_broker", &tmp_int, &saveptr)){ return MOSQ_ERR_INVAL; } if(tmp_int < 0 || tmp_int > UINT16_MAX){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid 'max_topic_alias_broker' value in configuration."); return MOSQ_ERR_INVAL; } cur_listener->max_topic_alias_broker = (uint16_t)tmp_int; }else if(!strcmp(token, "try_private")){ #ifdef WITH_BRIDGE REQUIRE_BRIDGE(token); 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 REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); 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 REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); 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")){ REQUIRE_LISTENER_OR_DEFAULT_LISTENER(token); 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 REQUIRE_BRIDGE(token); 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")){ #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS if(conf__parse_int(&token, "websockets_log_level", &config->websockets_log_level, &saveptr)){ return MOSQ_ERR_INVAL; } #endif }else if(!strcmp(token, "websockets_headers_size") || !strcmp(token, "packet_buffer_size")){ if(conf__parse_int(&token, token, &tmp_int, &saveptr)){ return MOSQ_ERR_INVAL; } if(tmp_int < 0 || tmp_int > UINT16_MAX){ log__printf(NULL, MOSQ_LOG_WARNING, "Error: Packet buffer size must be between 0 and 65535 inclusive."); return MOSQ_ERR_INVAL; } config->packet_buffer_size = (uint16_t)tmp_int; }else if(!strcmp(token, "websockets_origin")){ #ifdef WITH_WEBSOCKETS # if LWS_LIBRARY_VERSION_NUMBER >= 3001000 || WITH_WEBSOCKETS == WS_IS_BUILTIN REQUIRE_LISTENER(token); ws_origins = mosquitto_realloc(cur_listener->ws_origins, sizeof(char *)*(size_t)(cur_listener->ws_origin_count+1)); if(ws_origins == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } ws_origins[cur_listener->ws_origin_count] = NULL; cur_listener->ws_origins = ws_origins; if(conf__parse_string(&token, "websockets_origin", &ws_origins[cur_listener->ws_origin_count], &saveptr)){ return MOSQ_ERR_INVAL; } cur_listener->ws_origin_count++; # else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: websockets_origin support not available, libwebsockets version is too old."); # endif #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_proxy(struct mosquitto__config *config) { for(int i=0; ilistener_count; i++){ struct mosquitto__listener *l = &config->listeners[i]; if(l->enable_proxy_protocol == 2){ #ifdef WITH_TLS if(l->use_subject_as_username){ log__printf(NULL, MOSQ_LOG_ERR, "Error: use_subject_as_username cannot be used with `enable_proxy_protocol 2`."); return MOSQ_ERR_INVAL; } if(l->certfile || l->keyfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: certfile and keyfile cannot be used with `enable_proxy_protocol 2`."); return MOSQ_ERR_INVAL; } #endif } } return MOSQ_ERR_SUCCESS; } static int config__check(struct mosquitto__config *config) { /* Checks that are easy to make after the config has been loaded. */ const char *id_prefix; int id_prefix_len; if(config->security_options.auto_id_prefix){ id_prefix = config->security_options.auto_id_prefix; id_prefix_len = config->security_options.auto_id_prefix_len; }else{ id_prefix = "auto-"; id_prefix_len = (int)strlen("auto-"); } /* Default to auto_id_prefix = 'auto-' if none set. */ for(int i=0; ilistener_count; i++){ if(!config->listeners[i].security_options->auto_id_prefix){ config->listeners[i].security_options->auto_id_prefix = mosquitto_strdup(id_prefix); if(!config->listeners[i].security_options->auto_id_prefix){ return MOSQ_ERR_NOMEM; } config->listeners[i].security_options->auto_id_prefix_len = (uint16_t)id_prefix_len; } } return config__check_proxy(config); } #ifdef WITH_BRIDGE static int config__check_bridges(struct mosquitto__config *config) { struct mosquitto__bridge *bridge1, *bridge2; char hostname[256]; size_t len; /* Check for bridge duplicate local_clientid, need to generate missing IDs * first. */ for(int 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(int i=0; ibridge_count; i++){ bridge1 = config->bridges[i]; for(int 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; } } } #ifdef WITH_TLS /* Check for missing TLS cafile/capath/certfile/keyfile */ for(int i=0; ilistener_count; i++){ bool cafile = !!config->listeners[i].cafile; bool capath = !!config->listeners[i].capath; bool certfile = !!config->listeners[i].certfile; bool keyfile = !!config->listeners[i].keyfile; if((certfile && !keyfile) || (!certfile && keyfile)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Both certfile and keyfile must be provided to enable a TLS listener."); return MOSQ_ERR_INVAL; } if(cafile && !certfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: cafile specified without certfile and keyfile."); return MOSQ_ERR_INVAL; } if(capath && !certfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: capath specified without certfile and keyfile."); return MOSQ_ERR_INVAL; } } #endif return MOSQ_ERR_SUCCESS; } #endif 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){ char *endptr = NULL; long l = strtol(*token, &endptr, 0); if(endptr == *token || endptr[0] != '\0'){ log__printf(NULL, MOSQ_LOG_ERR, "Error: '%s' value not a number.", name); return MOSQ_ERR_INVAL; } if(l > INT_MAX || l < INT_MIN){ log__printf(NULL, MOSQ_LOG_ERR, "Error: '%s' value out of range.", name); return MOSQ_ERR_INVAL; } *value = (int)l; }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 = mosquitto_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; } ================================================ FILE: src/conf_includedir.c ================================================ /* Copyright (c) 2009-2021 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(__HAIKU__) # include #elif !defined(WIN32) && !defined(__CYGWIN__) && !defined(__QNX__) # include #endif #include "mosquitto_broker_internal.h" #include "tls_mosq.h" #include "util_mosq.h" #include "mosquitto/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((unsigned char)s1[0]) - toupper((unsigned char)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; 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(int 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){ goto error; } l_files = files_tmp; l_files[l_file_count-1] = mosquitto_malloc(len+1); if(!l_files[l_file_count-1]){ goto error; } snprintf(l_files[l_file_count-1], len, "%s/%s", include_dir, de->d_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; error: for(int 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 #if defined(__APPLE__) || defined(_AIX) #include #endif #include "mosquitto_broker_internal.h" #include "alias_mosq.h" #include "packet_mosq.h" #include "property_mosq.h" #include "sys_tree.h" #include "util_mosq.h" #include "will_mosq.h" #include "uthash.h" int context__init_sock(struct mosquitto *context, mosq_sock_t sock, bool get_address) { context->sock = sock; if((int)context->sock >= 0){ if(get_address){ char address[1024]; if(!net__socket_get_address(context->sock, address, sizeof(address), &context->remote_port)){ context->address = mosquitto_strdup(address); } if(!context->address){ /* getpeername and inet_ntop failed and not a bridge */ return MOSQ_ERR_NOMEM; } } HASH_ADD(hh_sock, db.contexts_by_sock, sock, sizeof(context->sock), context); } return MOSQ_ERR_SUCCESS; } struct mosquitto *context__init(void) { struct mosquitto *context; context = mosquitto_calloc(1, sizeof(struct mosquitto)); if(!context){ return NULL; } context->in_packet.packet_buffer_size = db.config->packet_buffer_size; context->in_packet.packet_buffer = mosquitto_calloc(1, context->in_packet.packet_buffer_size); if(!context->in_packet.packet_buffer){ mosquitto_FREE(context); return NULL; } #if defined(WITH_EPOLL) || defined(WITH_KQUEUE) context->ident = id_client; #else context->pollfd_index = -1; #endif 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 + 20; context->keepalive = 20; /* Default to 20s */ 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; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN memset(&context->wsd, 0, sizeof(context->wsd)); context->wsd.opcode = UINT8_MAX; context->wsd.mask = UINT8_MAX; context->wsd.disconnect_reason = 0xE8; #endif /* 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->out_packet_count = 0; context->out_packet_bytes = 0; context->address = NULL; context->bridge = NULL; context->msgs_in.inflight_maximum = db.config->max_inflight_messages; context->msgs_in.inflight_quota = db.config->max_inflight_messages; context->msgs_out.inflight_maximum = 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 return context; } static void context__cleanup_out_packets(struct mosquitto *context) { struct mosquitto__packet *packet; if(!context){ return; } while(context->out_packet){ packet = context->out_packet; context->out_packet = context->out_packet->next; mosquitto_free(packet); } metrics__int_dec(mosq_gauge_out_packets, context->out_packet_count); metrics__int_dec(mosq_gauge_out_packet_bytes, context->out_packet_bytes); context->out_packet_count = 0; context->out_packet_bytes = 0; } /* * 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) { if(!context){ return; } if(force_free){ context->clean_start = true; } #ifdef WITH_BRIDGE if(context->bridge){ bridge__cleanup(context); } #endif mosquitto_FREE(context->in_packet.packet_buffer); context->in_packet.packet_buffer_size = 0; alias__free_all(context); keepalive__remove(context); context__cleanup_out_packets(context); mosquitto_FREE(context->auth_method); mosquitto_FREE(context->username); mosquitto_FREE(context->password); net__socket_close(context); if(force_free){ sub__clean_session(context); } db__messages_delete(context, force_free); mosquitto_FREE(context->address); context__send_will(context); if(context->id){ context__remove_from_by_id(context); mosquitto_FREE(context->id); } packet__cleanup(&(context->in_packet)); context__cleanup_out_packets(context); #if defined(WITH_BROKER) && defined(__GLIBC__) && defined(WITH_ADNS) if(context->adns){ gai_cancel(context->adns); struct addrinfo *ar_request = (struct addrinfo *)context->adns->ar_request; mosquitto_FREE(ar_request); mosquitto_FREE(context->adns); } #endif #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN mosquitto_FREE(context->http_request); #endif mosquitto_FREE(context->proxy.buf); if(force_free){ mosquitto_FREE(context); } } void context__send_will(struct mosquitto *ctxt) { if(ctxt->state != mosq_cs_disconnecting && ctxt->will){ if(ctxt->session_expiry_interval > 0 && 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, ctxt->will->properties, 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, int reason) { if(mosquitto__get_state(context) == mosq_cs_disconnected){ return; } #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN if(context->transport == mosq_t_ws){ uint8_t buf[4] = {0x88, 0x02, 0x03, context->wsd.disconnect_reason}; /* Send the disconnect reason, but don't care if it fails */ if(send(context->sock, buf, 4, 0)){ } } #endif if(context->id){ struct mosquitto *context_found; HASH_FIND(hh_id, db.contexts_by_id_delayed_auth, context->id, strlen(context->id), context_found); if(context_found == context){ net__socket_close(context); context__add_to_disused(context); return; } } context__send_will(context); if(context->session_expiry_interval == MQTT_SESSION_EXPIRY_IMMEDIATE){ plugin__handle_disconnect(context, reason); }else{ plugin__handle_client_offline(context, reason); } net__socket_close(context); #ifdef WITH_BRIDGE if(context->bridge == NULL) /* Outgoing bridge connection never expire */ #endif { if(context->session_expiry_interval == MQTT_SESSION_EXPIRY_IMMEDIATE){ plugin_persist__handle_client_delete(context); /* Client session is due to be expired now */ 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); alias__free_all(context); context__cleanup_out_packets(context); } void context__add_to_disused(struct mosquitto *context) { if(context->state == mosq_cs_disused){ return; } mosquitto__set_state(context, mosq_cs_disused); context__remove_from_by_id(context); context->for_free_next = db.ll_for_free; db.ll_for_free = context; } void context__free_disused(void) { struct mosquitto *context, *next; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS struct mosquitto *last = NULL; #endif context = db.ll_for_free; db.ll_for_free = NULL; while(context){ #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS 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__add_to_by_id(struct mosquitto *context) { if(context->in_by_id == false){ context->in_by_id = true; HASH_VALUE(context->id, strlen(context->id), context->id_hashv); HASH_ADD_KEYPTR_BYHASHVALUE(hh_id, db.contexts_by_id, context->id, strlen(context->id), context->id_hashv, context); } } void context__remove_from_by_id(struct mosquitto *context) { struct mosquitto *context_found; if(!context->id){ return; } if(context->in_by_id){ HASH_FIND(hh_id, db.contexts_by_id, context->id, strlen(context->id), context_found); if(context_found == context){ HASH_DELETE(hh_id, db.contexts_by_id, context_found); } context->id_hashv = 0; context->in_by_id = false; return; } HASH_FIND(hh_id, db.contexts_by_id_delayed_auth, context->id, strlen(context->id), context_found); if(context_found == context){ HASH_DELETE(hh_id, db.contexts_by_id_delayed_auth, context_found); } } ================================================ FILE: src/control.c ================================================ /* Copyright (c) 2020-2021 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/mqtt_protocol.h" #include "mosquitto_broker_internal.h" #include "send_mosq.h" #ifdef WITH_CONTROL static void control__negative_reply(const char *clientid, const char *request_topic) { size_t response_topic_len; char *response_topic; const char payload[] = "{\"error\": \"endpoint not available\"}"; response_topic_len = strlen(request_topic) + sizeof("/response") + 1; response_topic = mosquitto_calloc(1, response_topic_len); if(!response_topic){ return; } snprintf(response_topic, response_topic_len, "%s/response", request_topic); mosquitto_broker_publish_copy(clientid, response_topic, (int)strlen(payload), payload, 0, false, NULL); mosquitto_FREE(response_topic); } /* Process messages coming in on $CONTROL/. These messages aren't * passed on to other clients. */ int control__process(struct mosquitto *context, struct mosquitto__base_msg *base_msg) { 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; int rc2; /* Check global plugins and non-per-listener settings first */ opts = &db.config->security_options; HASH_FIND(hh, opts->plugin_callbacks.control, base_msg->data.topic, strlen(base_msg->data.topic), cb_found); /* If not found, check for per-listener plugins. */ if(cb_found == NULL && db.config->per_listener_settings){ if(!context->listener){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: $CONTROL command received from client with no listener, when per_listener_settings is true."); log__printf(NULL, MOSQ_LOG_WARNING, " If this is a bridge, please be aware this does not work."); return MOSQ_ERR_SUCCESS; } opts = context->listener->security_options; HASH_FIND(hh, opts->plugin_callbacks.control, base_msg->data.topic, strlen(base_msg->data.topic), cb_found); } if(cb_found){ memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.topic = base_msg->data.topic; event_data.payload = base_msg->data.payload; event_data.payloadlen = base_msg->data.payloadlen; event_data.qos = base_msg->data.qos; event_data.retain = base_msg->data.retain; event_data.properties = base_msg->data.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){ /* Not a critical error if this fails */ (void)mosquitto_property_add_string(&properties, MQTT_PROP_REASON_STRING, event_data.reason_string); } } SAFE_FREE(event_data.reason_string); }else{ control__negative_reply(context->id, base_msg->data.topic); } if(base_msg->data.qos == 1){ rc2 = send__puback(context, base_msg->data.source_mid, MQTT_RC_SUCCESS, properties); if(rc2){ rc = rc2; } }else if(base_msg->data.qos == 2){ rc2 = send__pubrec(context, base_msg->data.source_mid, MQTT_RC_SUCCESS, properties); if(rc2){ rc = rc2; } } mosquitto_property_free_all(&properties); return rc; } #endif int control__register_callback(mosquitto_plugin_id_t *pid, MOSQ_FUNC_generic_callback cb_func, const char *topic, void *userdata) { #ifdef WITH_CONTROL struct mosquitto__security_options *opts; 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; } opts = &db.config->security_options; 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.topic = mosquitto_strdup(topic); if(cb_new->data.topic == NULL){ mosquitto_FREE(cb_new); return MOSQ_ERR_NOMEM; } cb_new->identifier = pid; cb_new->cb = cb_func; cb_new->userdata = userdata; HASH_ADD_KEYPTR(hh, opts->plugin_callbacks.control, cb_new->data.topic, strlen(cb_new->data.topic), cb_new); if(pid->plugin_name){ struct control_endpoint *ep; ep = mosquitto_malloc(sizeof(struct control_endpoint) + topic_len + 2); if(ep){ ep->next = NULL; ep->prev = NULL; snprintf(ep->topic, topic_len+1, "%s", topic); DL_APPEND(pid->control_endpoints, ep); } log__printf(NULL, MOSQ_LOG_INFO, "Plugin %s has registered to receive 'control' events on topic %s.", pid->plugin_name, topic); } return MOSQ_ERR_SUCCESS; #else UNUSED(pid); UNUSED(cb_func); UNUSED(topic); UNUSED(userdata); return MOSQ_ERR_NOT_SUPPORTED; #endif } int control__unregister_callback(mosquitto_plugin_id_t *identifier, MOSQ_FUNC_generic_callback cb_func, const char *topic) { #ifdef WITH_CONTROL struct mosquitto__security_options *opts; struct mosquitto__callback *cb_found; size_t topic_len; struct control_endpoint *ep; 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; } opts = &db.config->security_options; 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.topic); mosquitto_FREE(cb_found); DL_FOREACH(identifier->control_endpoints, ep){ if(!strcmp(topic, ep->topic)){ DL_DELETE(identifier->control_endpoints, ep); mosquitto_FREE(ep); break; } } return MOSQ_ERR_SUCCESS; } return MOSQ_ERR_NOT_FOUND; #else UNUSED(identifier); UNUSED(cb_func); UNUSED(topic); return MOSQ_ERR_NOT_SUPPORTED; #endif } /* Unregister all control callbacks for a single plugin */ void control__unregister_all_callbacks(mosquitto_plugin_id_t *identifier) { struct mosquitto__security_options *opts; struct mosquitto__callback *cb_found; struct control_endpoint *ep, *ep_tmp; opts = &db.config->security_options; DL_FOREACH_SAFE(identifier->control_endpoints, ep, ep_tmp){ HASH_FIND(hh, opts->plugin_callbacks.control, ep->topic, strlen(ep->topic), cb_found); if(cb_found){ HASH_DELETE(hh, opts->plugin_callbacks.control, cb_found); mosquitto_FREE(cb_found->data.topic); mosquitto_FREE(cb_found); } DL_DELETE(identifier->control_endpoints, ep); mosquitto_FREE(ep); } } ================================================ FILE: src/control_common.c ================================================ #include "config.h" #include #include #include #include #include #include #define CJSON_VERSION_FULL (CJSON_VERSION_MAJOR*1000000+CJSON_VERSION_MINOR*1000+CJSON_VERSION_PATCH) void mosquitto_control_command_reply(struct mosquitto_control_cmd *cmd, const char *error) { cJSON *j_response; j_response = cJSON_CreateObject(); if(j_response == NULL){ return; } if(cJSON_AddStringToObject(j_response, "command", cmd->command_name) == NULL || (error && cJSON_AddStringToObject(j_response, "error", error) == NULL) || (cmd->correlation_data && cJSON_AddStringToObject(j_response, "correlationData", cmd->correlation_data) == NULL) ){ cJSON_Delete(j_response); return; } cJSON_AddItemToArray(cmd->j_responses, j_response); } void mosquitto_control_send_response(cJSON *tree, const char *topic) { 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, topic, (int)payload_len, payload, 0, 0, NULL); } static int control__generic_handle_commands(struct mosquitto_control_cmd *cmd, cJSON *commands, void *userdata, int (*cmd_cb)(struct mosquitto_control_cmd *cmd, void *userdata)) { cJSON *aiter; cJSON_ArrayForEach(aiter, commands){ cmd->command_name = "Unknown command"; if(cJSON_IsObject(aiter)){ cJSON *j_tmp = cJSON_GetObjectItem(aiter, "command"); const char *command = cJSON_GetStringValue(j_tmp); if(command){ cmd->j_command = aiter; cmd->correlation_data = NULL; cmd->command_name = command; j_tmp = cJSON_GetObjectItem(aiter, "correlationData"); if(j_tmp){ if(cJSON_IsString(j_tmp)){ cmd->correlation_data = cJSON_GetStringValue(j_tmp); }else{ mosquitto_control_command_reply(cmd, "Invalid correlationData data type."); return MOSQ_ERR_INVAL; } } cmd_cb(cmd, userdata); }else{ mosquitto_control_command_reply(cmd, "Missing command"); return MOSQ_ERR_INVAL; } }else{ mosquitto_control_command_reply(cmd, "Command not an object"); return MOSQ_ERR_INVAL; } } return MOSQ_ERR_SUCCESS; } int mosquitto_control_generic_callback(struct mosquitto_evt_control *event_data, const char *response_topic, void *userdata, int (*cmd_cb)(struct mosquitto_control_cmd *cmd, void *userdata)) { struct mosquitto_evt_control *ed = event_data; struct mosquitto_control_cmd cmd; cJSON *tree, *commands; cJSON *j_response_tree; if(!event_data || !cmd_cb){ return MOSQ_ERR_INVAL; } memset(&cmd, 0, sizeof(cmd)); cmd.command_name = "Unknown command"; cmd.client = ed->client; /* Create object for responses */ j_response_tree = cJSON_CreateObject(); if(j_response_tree == NULL){ return MOSQ_ERR_NOMEM; } cmd.j_responses = cJSON_AddArrayToObject(j_response_tree, "responses"); if(cmd.j_responses == NULL){ cJSON_Delete(j_response_tree); return MOSQ_ERR_NOMEM; } /* 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){ mosquitto_control_command_reply(&cmd, "Payload not valid JSON"); mosquitto_control_send_response(j_response_tree, response_topic); return MOSQ_ERR_SUCCESS; } commands = cJSON_GetObjectItem(tree, "commands"); if(commands == NULL || !cJSON_IsArray(commands)){ cJSON_Delete(tree); mosquitto_control_command_reply(&cmd, "Invalid/missing commands"); mosquitto_control_send_response(j_response_tree, response_topic); return MOSQ_ERR_SUCCESS; } /* Handle commands */ control__generic_handle_commands(&cmd, commands, userdata, cmd_cb); cJSON_Delete(tree); mosquitto_control_send_response(j_response_tree, response_topic); return MOSQ_ERR_SUCCESS; } ================================================ FILE: src/database.c ================================================ /* Copyright (c) 2009-2021 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 "send_mosq.h" #include "sys_tree.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->inflight_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->inflight_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->inflight_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->queued_bytes12; source_count = msg_data->queued_count12; } adjust_count = msg_data->inflight_maximum; /* nothing in flight for offline clients */ if(!net__is_connected(context)){ 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; } void db__msg_add_to_inflight_stats(struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg *client_msg) { msg_data->inflight_count++; msg_data->inflight_bytes += client_msg->base_msg->data.payloadlen; if(client_msg->data.qos != 0){ msg_data->inflight_count12++; msg_data->inflight_bytes12 += client_msg->base_msg->data.payloadlen; } } static void db__msg_remove_from_inflight_stats(struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg *client_msg) { msg_data->inflight_count--; msg_data->inflight_bytes -= client_msg->base_msg->data.payloadlen; if(client_msg->data.qos != 0){ msg_data->inflight_count12--; msg_data->inflight_bytes12 -= client_msg->base_msg->data.payloadlen; } } void db__msg_add_to_queued_stats(struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg *client_msg) { msg_data->queued_count++; msg_data->queued_bytes += client_msg->base_msg->data.payloadlen; if(client_msg->data.qos != 0){ msg_data->queued_count12++; msg_data->queued_bytes12 += client_msg->base_msg->data.payloadlen; } } static void db__msg_remove_from_queued_stats(struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg *client_msg) { msg_data->queued_count--; msg_data->queued_bytes -= client_msg->base_msg->data.payloadlen; if(client_msg->data.qos != 0){ msg_data->queued_count12--; msg_data->queued_bytes12 -= client_msg->base_msg->data.payloadlen; } } int db__open(struct mosquitto__config *config) { if(!config){ return MOSQ_ERR_INVAL; } 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.normal_subs = NULL; db.shared_subs = NULL; sub__init(); 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); HASH_DELETE(hh, *subhier, peer); mosquitto_FREE(peer); } } int db__close(void) { subhier_clean(&db.normal_subs); subhier_clean(&db.shared_subs); retain__clean(&db.retains); db__msg_store_clean(); return MOSQ_ERR_SUCCESS; } int db__msg_store_add(struct mosquitto__base_msg *base_msg) { struct mosquitto__base_msg *found; unsigned hashv; HASH_VALUE(&base_msg->data.store_id, sizeof(base_msg->data.store_id), hashv); HASH_FIND_BYHASHVALUE(hh, db.msg_store, &base_msg->data.store_id, sizeof(base_msg->data.store_id), hashv, found); if(found == NULL){ HASH_ADD_KEYPTR_BYHASHVALUE(hh, db.msg_store, &base_msg->data.store_id, sizeof(base_msg->data.store_id), hashv, base_msg); return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ALREADY_EXISTS; } } void db__msg_store_free(struct mosquitto__base_msg *base_msg) { mosquitto_FREE(base_msg->data.source_id); mosquitto_FREE(base_msg->data.source_username); if(base_msg->dest_ids){ for(int i=0; idest_id_count; i++){ mosquitto_FREE(base_msg->dest_ids[i]); } mosquitto_FREE(base_msg->dest_ids); } mosquitto_FREE(base_msg->data.topic); mosquitto_property_free_all(&base_msg->data.properties); mosquitto_FREE(base_msg->data.payload); mosquitto_FREE(base_msg); } void db__msg_store_remove(struct mosquitto__base_msg *base_msg, bool notify) { if(base_msg == NULL){ return; } HASH_DELETE(hh, db.msg_store, base_msg); db.msg_store_count--; db.msg_store_bytes -= base_msg->data.payloadlen; if(notify == true){ plugin_persist__handle_base_msg_delete(base_msg); } db__msg_store_free(base_msg); } void db__msg_store_clean(void) { struct mosquitto__base_msg *base_msg, *base_msg_tmp; HASH_ITER(hh, db.msg_store, base_msg, base_msg_tmp){ db__msg_store_remove(base_msg, false); } } void db__msg_store_ref_inc(struct mosquitto__base_msg *base_msg) { base_msg->ref_count++; } void db__msg_store_ref_dec(struct mosquitto__base_msg **base_msg) { (*base_msg)->ref_count--; if((*base_msg)->ref_count == 0){ db__msg_store_remove(*base_msg, true); *base_msg = NULL; } } void db__msg_store_compact(void) { struct mosquitto__base_msg *base_msg, *base_msg_tmp; HASH_ITER(hh, db.msg_store, base_msg, base_msg_tmp){ if(base_msg->ref_count < 1){ db__msg_store_remove(base_msg, true); } } } static void db__message_remove_inflight(struct mosquitto *context, struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg *item) { if(!context || !msg_data || !item){ return; } plugin_persist__handle_client_msg_delete(context, item); DL_DELETE(msg_data->inflight, item); if(item->base_msg){ db__msg_remove_from_inflight_stats(msg_data, item); db__msg_store_ref_dec(&item->base_msg); } mosquitto_FREE(item); } static void db__message_remove_queued(struct mosquitto *context, struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg *item) { if(!context || !msg_data || !item){ return; } plugin_persist__handle_client_msg_delete(context, item); DL_DELETE(msg_data->queued, item); if(item->base_msg){ db__msg_remove_from_queued_stats(msg_data, item); db__msg_store_ref_dec(&item->base_msg); } mosquitto_FREE(item); } static void db__fill_inflight_out_from_queue(struct mosquitto *context) { struct mosquitto__client_msg *client_msg, *tmp; DL_FOREACH_SAFE(context->msgs_out.queued, client_msg, tmp){ if(!db__ready_for_flight(context, mosq_md_out, client_msg->data.qos)){ return; } switch(client_msg->data.qos){ case 0: client_msg->data.state = mosq_ms_publish_qos0; break; case 1: client_msg->data.state = mosq_ms_publish_qos1; break; case 2: client_msg->data.state = mosq_ms_publish_qos2; break; } if(client_msg->base_msg->data.expiry_time && db.now_real_s > client_msg->base_msg->data.expiry_time){ db__message_remove_queued(context, &context->msgs_out, client_msg); continue; } plugin_persist__handle_client_msg_update(context, client_msg); db__message_dequeue_first(context, &context->msgs_out); } } void db__message_dequeue_first(struct mosquitto *context, struct mosquitto_msg_data *msg_data) { struct mosquitto__client_msg *client_msg; UNUSED(context); client_msg = msg_data->queued; DL_DELETE(msg_data->queued, client_msg); DL_APPEND(msg_data->inflight, client_msg); if(msg_data->inflight_quota > 0){ msg_data->inflight_quota--; } db__msg_remove_from_queued_stats(msg_data, client_msg); db__msg_add_to_inflight_stats(msg_data, client_msg); } int db__message_delete_outgoing(struct mosquitto *context, uint16_t mid, enum mosquitto_msg_state expect_state, int qos) { struct mosquitto__client_msg *client_msg, *tmp; bool deleted = false; if(!context){ return MOSQ_ERR_INVAL; } DL_FOREACH_SAFE(context->msgs_out.inflight, client_msg, tmp){ if(client_msg->data.mid == mid){ if(client_msg->data.qos != qos){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: Mismatched QoS (%d:%d) when deleting outgoing message.", context->id, client_msg->data.qos, qos); return MOSQ_ERR_PROTOCOL; }else if(qos == 2 && client_msg->data.state != expect_state && expect_state != mosq_ms_any){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: Mismatched state (%d:%d) when deleting outgoing message.", context->id, client_msg->data.state, expect_state); return MOSQ_ERR_PROTOCOL; } db__message_remove_inflight(context, &context->msgs_out, client_msg); deleted = true; break; } } if(deleted == false){ DL_FOREACH_SAFE(context->msgs_out.queued, client_msg, tmp){ if(client_msg->data.mid == mid){ if(client_msg->data.qos != qos){ return MOSQ_ERR_PROTOCOL; }else if(qos == 2 && client_msg->data.state != expect_state && expect_state != mosq_ms_any){ return MOSQ_ERR_PROTOCOL; } db__message_remove_queued(context, &context->msgs_out, client_msg); break; } } } db__fill_inflight_out_from_queue(context); #ifdef WITH_PERSISTENCE db.persistence_changes++; #endif return db__message_write_inflight_out_latest(context); } /* Only for QoS 2 messages */ int db__message_insert_incoming(struct mosquitto *context, uint64_t cmsg_id, struct mosquitto__base_msg *base_msg, bool persist) { struct mosquitto__client_msg *client_msg; struct mosquitto_msg_data *msg_data; enum mosquitto_msg_state state = mosq_ms_invalid; int rc = 0; assert(base_msg); if(!context){ return MOSQ_ERR_INVAL; } if(!context->id){ /* Protect against unlikely "client is disconnected but not entirely freed" scenario */ return MOSQ_ERR_SUCCESS; } msg_data = &context->msgs_in; if(db__ready_for_flight(context, mosq_md_in, base_msg->data.qos)){ state = mosq_ms_wait_for_pubrel; }else if(base_msg->data.qos != 0 && db__ready_for_queue(context, base_msg->data.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); } metrics__int_inc(mosq_counter_mqtt_publish_dropped, 1); context->stats.messages_dropped++; return 2; } assert(state != mosq_ms_invalid); #ifdef WITH_PERSISTENCE if(state == mosq_ms_queued){ db.persistence_changes++; } #endif client_msg = mosquitto_malloc(sizeof(struct mosquitto__client_msg)); if(!client_msg){ return MOSQ_ERR_NOMEM; } client_msg->prev = NULL; client_msg->next = NULL; if(cmsg_id){ client_msg->data.cmsg_id = cmsg_id; }else{ client_msg->data.cmsg_id = ++context->last_cmsg_id; } client_msg->base_msg = base_msg; db__msg_store_ref_inc(client_msg->base_msg); client_msg->data.mid = base_msg->data.source_mid; client_msg->data.direction = mosq_md_in; client_msg->data.state = (uint8_t)state; client_msg->data.dup = false; if(base_msg->data.qos > context->max_qos){ client_msg->data.qos = context->max_qos; }else{ client_msg->data.qos = base_msg->data.qos; } client_msg->data.retain = base_msg->data.retain; client_msg->data.subscription_identifier = 0; if(state == mosq_ms_queued){ DL_APPEND(msg_data->queued, client_msg); db__msg_add_to_queued_stats(msg_data, client_msg); }else{ DL_APPEND(msg_data->inflight, client_msg); db__msg_add_to_inflight_stats(msg_data, client_msg); } if(persist && context->is_persisted){ plugin_persist__handle_base_msg_add(client_msg->base_msg); plugin_persist__handle_client_msg_add(context, client_msg); } if(client_msg->base_msg->data.qos > 0){ util__decrement_receive_quota(context); } return rc; } int db__message_insert_outgoing(struct mosquitto *context, uint64_t cmsg_id, uint16_t mid, uint8_t qos, bool retain, struct mosquitto__base_msg *base_msg, uint32_t subscription_identifier, bool update, bool persist) { struct mosquitto__client_msg *client_msg; struct mosquitto_msg_data *msg_data; enum mosquitto_msg_state state = mosq_ms_invalid; int rc = 0; char **dest_ids; assert(base_msg); if(!context){ return MOSQ_ERR_INVAL; } if(!context->id){ /* Protect against unlikely "client is disconnected but not entirely freed" scenario */ return MOSQ_ERR_SUCCESS; } context->stats.messages_sent++; msg_data = &context->msgs_out; /* 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 && retain == false && base_msg->dest_ids){ for(int i=0; idest_id_count; i++){ if(base_msg->dest_ids[i] && !strcmp(base_msg->dest_ids[i], context->id)){ /* We have already sent this message to this client. */ return MOSQ_ERR_SUCCESS; } } } if(!net__is_connected(context)){ /* Client is not connected only queue messages with QoS>0. */ if(qos == 0 && !db.config->queue_qos0_messages){ if(!context->bridge){ return 2; }else{ if(context->bridge->start_type != bst_lazy){ return 2; } } } if(context->bridge && context->bridge->clean_start_local == true){ return 2; } } if(net__is_connected(context)){ if(db__ready_for_flight(context, mosq_md_out, qos)){ 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 != 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); } metrics__int_inc(mosq_counter_mqtt_publish_dropped, 1); return 2; } }else{ if(db__ready_for_queue(context, qos, msg_data)){ state = mosq_ms_queued; }else{ metrics__int_inc(mosq_counter_mqtt_publish_dropped, 1); 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); } return 2; } } assert(state != mosq_ms_invalid); #ifdef WITH_PERSISTENCE if(state == mosq_ms_queued){ db.persistence_changes++; } #endif client_msg = mosquitto_malloc(sizeof(struct mosquitto__client_msg)); if(!client_msg){ return MOSQ_ERR_NOMEM; } client_msg->prev = NULL; client_msg->next = NULL; if(cmsg_id){ client_msg->data.cmsg_id = cmsg_id; }else{ client_msg->data.cmsg_id = ++context->last_cmsg_id; } client_msg->base_msg = base_msg; db__msg_store_ref_inc(client_msg->base_msg); client_msg->data.mid = mid; client_msg->data.direction = mosq_md_out; client_msg->data.state = (uint8_t)state; client_msg->data.dup = false; if(qos > context->max_qos){ client_msg->data.qos = context->max_qos; }else{ client_msg->data.qos = qos; } client_msg->data.retain = retain; client_msg->data.subscription_identifier = subscription_identifier; if(state == mosq_ms_queued){ DL_APPEND(msg_data->queued, client_msg); db__msg_add_to_queued_stats(msg_data, client_msg); }else{ DL_APPEND(msg_data->inflight, client_msg); db__msg_add_to_inflight_stats(msg_data, client_msg); } if(persist && context->is_persisted){ plugin_persist__handle_base_msg_add(client_msg->base_msg); plugin_persist__handle_client_msg_add(context, client_msg); } if(db.config->allow_duplicate_messages == false && 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(base_msg->dest_ids, sizeof(char *)*(size_t)(base_msg->dest_id_count+1)); if(dest_ids){ base_msg->dest_ids = dest_ids; base_msg->dest_id_count++; base_msg->dest_ids[base_msg->dest_id_count-1] = mosquitto_strdup(context->id); if(!base_msg->dest_ids[base_msg->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 && !net__is_connected(context) && context->msgs_out.inflight_count + context->msgs_out.queued_count >= context->bridge->threshold){ context->bridge->lazy_reconnect = true; } #endif if(client_msg->data.qos > 0 && state != mosq_ms_queued){ util__decrement_send_quota(context); } if(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; } static inline int db__message_update_outgoing_state(struct mosquitto *context, struct mosquitto__client_msg *head, uint16_t mid, enum mosquitto_msg_state state, int qos, bool persist) { struct mosquitto__client_msg *client_msg; DL_FOREACH(head, client_msg){ if(client_msg->data.mid == mid){ if(client_msg->data.qos != qos){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: Mismatched QoS (%d:%d) when updating outgoing message.", context->id, client_msg->data.qos, qos); return MOSQ_ERR_PROTOCOL; } client_msg->data.state = (uint8_t)state; if(persist){ plugin_persist__handle_client_msg_update(context, client_msg); } return MOSQ_ERR_SUCCESS; } } return MOSQ_ERR_NOT_FOUND; } int db__message_update_outgoing(struct mosquitto *context, uint16_t mid, enum mosquitto_msg_state state, int qos, bool persist) { int rc; rc = db__message_update_outgoing_state(context, context->msgs_out.inflight, mid, state, qos, persist); if(!persist && rc == MOSQ_ERR_NOT_FOUND){ rc = db__message_update_outgoing_state(context, context->msgs_out.queued, mid, state, qos, persist); } return rc; } static void db__messages_delete_list(struct mosquitto__client_msg **head) { struct mosquitto__client_msg *client_msg, *tmp; DL_FOREACH_SAFE(*head, client_msg, tmp){ DL_DELETE(*head, client_msg); db__msg_store_ref_dec(&client_msg->base_msg); mosquitto_FREE(client_msg); } *head = NULL; } int db__messages_delete_incoming(struct mosquitto *context) { if(!context){ return MOSQ_ERR_INVAL; } db__messages_delete_list(&context->msgs_in.inflight); db__messages_delete_list(&context->msgs_in.queued); context->msgs_in.inflight_bytes = 0; context->msgs_in.inflight_bytes12 = 0; context->msgs_in.inflight_count = 0; context->msgs_in.inflight_count12 = 0; context->msgs_in.queued_bytes = 0; context->msgs_in.queued_bytes12 = 0; context->msgs_in.queued_count = 0; context->msgs_in.queued_count12 = 0; return MOSQ_ERR_SUCCESS; } int db__messages_delete_outgoing(struct mosquitto *context) { if(!context){ return MOSQ_ERR_INVAL; } db__messages_delete_list(&context->msgs_out.inflight); db__messages_delete_list(&context->msgs_out.queued); context->msgs_out.inflight_bytes = 0; context->msgs_out.inflight_bytes12 = 0; context->msgs_out.inflight_count = 0; context->msgs_out.inflight_count12 = 0; context->msgs_out.queued_bytes = 0; context->msgs_out.queued_bytes12 = 0; context->msgs_out.queued_count = 0; context->msgs_out.queued_count12 = 0; return MOSQ_ERR_SUCCESS; } 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_incoming(context); } if(force_free || (context->bridge && context->bridge->clean_start_local) || (context->bridge == NULL && context->clean_start)){ db__messages_delete_outgoing(context); } 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__base_msg *base_msg; const char *source_id; enum mosquitto_msg_origin origin; if(!topic){ return MOSQ_ERR_INVAL; } base_msg = mosquitto_calloc(1, sizeof(struct mosquitto__base_msg)); if(base_msg == NULL){ return MOSQ_ERR_NOMEM; } base_msg->data.topic = mosquitto_strdup(topic); if(base_msg->data.topic == NULL){ db__msg_store_free(base_msg); return MOSQ_ERR_INVAL; } base_msg->data.qos = qos; if(db.config->retain_available == false){ base_msg->data.retain = 0; }else{ base_msg->data.retain = retain; } base_msg->data.payloadlen = payloadlen; if(payloadlen > 0){ base_msg->data.payload = mosquitto_malloc(base_msg->data.payloadlen+1); if(base_msg->data.payload == NULL){ db__msg_store_free(base_msg); return MOSQ_ERR_NOMEM; } /* Ensure payload is always zero terminated, this is the reason for the extra byte above */ ((uint8_t *)base_msg->data.payload)[base_msg->data.payloadlen] = 0; memcpy(base_msg->data.payload, payload, base_msg->data.payloadlen); } if(context && context->id){ source_id = context->id; }else{ source_id = ""; } if(properties){ base_msg->data.properties = *properties; *properties = NULL; } if(context){ origin = mosq_mo_client; }else{ origin = mosq_mo_broker; } if(db__message_store(context, base_msg, &message_expiry_interval, origin)){ return 1; } return sub__messages_queue(source_id, base_msg->data.topic, base_msg->data.qos, base_msg->data.retain, &base_msg); } #define MOSQ_UUID_EPOCH 1637168273 /* db__new_msg_id() attempts to generate a new unique id on the broker, or a * number of brokers. It uses the 10-bit node ID, which can be set by plugins * to allow different brokers to share the same plugin persistence database * without overlapping one another. * * The message ID is a 64-bit unsigned integer arranged as follows: * * 10-bit ID 31-bit seconds 23-bit fractional seconds * iiiiiiiiiisssssssssssssssssssssssssssssssnnnnnnnnnnnnnnnnnnnnnnn * * 10-bit ID gives a total of 1024 brokers can produce unique values (complete overkill) * 31-bit seconds gives a roll over date of 68 years after MOSQ_UUID_EPOCH - 2089. * This roll over date would affect messages that have been queued waiting * for a client to receive them, or retained messages only. If either of * those remains for 68 years unchanged, then there will potentially be a * collision. Ideally we need to ensure, however, that the message id is * continually increasing for sorting purposes. * 23-bit fractional seconds gives a resolution of 120ns, or 8.4 million * messages per second per broker. */ uint64_t db__new_msg_id(void) { #ifdef WIN32 FILETIME ftime; uint64_t ftime64; #else struct timespec ts; #endif uint64_t id; uint64_t tmp; time_t sec; long nsec; id = db.node_id_shifted; /* Top 10-bits */ #ifdef WIN32 GetSystemTimePreciseAsFileTime(&ftime); ftime64 = (((uint64_t)ftime.dwHighDateTime)<<32) + ftime.dwLowDateTime; tmp = ftime64 - 116444736000000000LL; /* Convert offset to unix epoch, still in counts of 100ns */ sec = tmp / 10000000; /* Convert to seconds */ nsec = (long)(tmp - sec)*100; /* Remove seconds, convert to counts of 1ns */ #else clock_gettime(CLOCK_REALTIME, &ts); sec = ts.tv_sec; nsec = ts.tv_nsec; #endif tmp = (sec - MOSQ_UUID_EPOCH) & 0x7FFFFFFF; id = id | (tmp << 23); /* Seconds, 31-bits (68 years) */ tmp = (nsec & 0x7FFFFF80); /* top 23-bits of the bottom 30 bits (1 billion ns), ~100 ns resolution */ id = id | (tmp >> 7); if(id <= db.last_db_id){ id = db.last_db_id + 1; } db.last_db_id = id; return id; } /* 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__base_msg *base_msg, uint32_t *message_expiry_interval, enum mosquitto_msg_origin origin) { int rc; assert(base_msg); if(source && source->id){ base_msg->data.source_id = mosquitto_strdup(source->id); }else{ base_msg->data.source_id = mosquitto_strdup(""); } if(!base_msg->data.source_id){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); db__msg_store_free(base_msg); return MOSQ_ERR_NOMEM; } if(source && source->username){ base_msg->data.source_username = mosquitto_strdup(source->username); if(!base_msg->data.source_username){ db__msg_store_free(base_msg); return MOSQ_ERR_NOMEM; } } if(source){ base_msg->source_listener = source->listener; } base_msg->origin = origin; if(message_expiry_interval){ if(*message_expiry_interval > 0 && *message_expiry_interval != MSG_EXPIRY_INFINITE){ base_msg->data.expiry_time = db.now_real_s + *message_expiry_interval; }else{ base_msg->data.expiry_time = 0; } } base_msg->dest_ids = NULL; base_msg->dest_id_count = 0; db.msg_store_count++; db.msg_store_bytes += base_msg->data.payloadlen; if(!base_msg->data.store_id){ base_msg->data.store_id = db__new_msg_id(); } rc = db__msg_store_add(base_msg); if(rc){ db__msg_store_free(base_msg); return rc; } return MOSQ_ERR_SUCCESS; } int db__message_store_find(struct mosquitto *context, uint16_t mid, struct mosquitto__client_msg **client_msg) { struct mosquitto__client_msg *cmsg; *client_msg = NULL; if(!context){ return MOSQ_ERR_INVAL; } DL_FOREACH(context->msgs_in.inflight, cmsg){ if(cmsg->base_msg->data.source_mid == mid){ *client_msg = cmsg; return MOSQ_ERR_SUCCESS; } } DL_FOREACH(context->msgs_in.queued, cmsg){ if(cmsg->base_msg->data.source_mid == mid){ *client_msg = cmsg; 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 *client_msg, *tmp; context->msgs_out.inflight_bytes = 0; context->msgs_out.inflight_bytes12 = 0; context->msgs_out.inflight_count = 0; context->msgs_out.inflight_count12 = 0; context->msgs_out.queued_bytes = 0; context->msgs_out.queued_bytes12 = 0; context->msgs_out.queued_count = 0; context->msgs_out.queued_count12 = 0; context->msgs_out.inflight_quota = context->msgs_out.inflight_maximum; DL_FOREACH_SAFE(context->msgs_out.inflight, client_msg, tmp){ db__msg_add_to_inflight_stats(&context->msgs_out, client_msg); if(client_msg->data.qos > 0){ util__decrement_send_quota(context); } switch(client_msg->data.qos){ case 0: client_msg->data.state = mosq_ms_publish_qos0; break; case 1: client_msg->data.state = mosq_ms_publish_qos1; break; case 2: if(client_msg->data.state == mosq_ms_wait_for_pubcomp){ client_msg->data.state = mosq_ms_resend_pubrel; }else{ client_msg->data.state = mosq_ms_publish_qos2; } break; } plugin_persist__handle_client_msg_update(context, client_msg); } /* 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, client_msg, tmp){ db__msg_add_to_queued_stats(&context->msgs_out, client_msg); } db__fill_inflight_out_from_queue(context); 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 *client_msg, *tmp; context->msgs_in.inflight_bytes = 0; context->msgs_in.inflight_bytes12 = 0; context->msgs_in.inflight_count = 0; context->msgs_in.inflight_count12 = 0; context->msgs_in.queued_bytes = 0; context->msgs_in.queued_bytes12 = 0; context->msgs_in.queued_count = 0; context->msgs_in.queued_count12 = 0; context->msgs_in.inflight_quota = context->msgs_in.inflight_maximum; DL_FOREACH_SAFE(context->msgs_in.inflight, client_msg, tmp){ db__msg_add_to_inflight_stats(&context->msgs_in, client_msg); if(client_msg->data.qos > 0){ util__decrement_receive_quota(context); } if(client_msg->data.qos != 2){ /* Anything msgs_in, client_msg); }else{ /* Message state can be preserved here because it should match * whatever the client has got. */ client_msg->data.dup = 0; } } /* 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, client_msg, tmp){ client_msg->data.dup = 0; db__msg_add_to_queued_stats(&context->msgs_in, client_msg); if(db__ready_for_flight(context, mosq_md_in, client_msg->data.qos)){ switch(client_msg->data.qos){ case 0: client_msg->data.state = mosq_ms_publish_qos0; break; case 1: client_msg->data.state = mosq_ms_publish_qos1; break; case 2: client_msg->data.state = mosq_ms_publish_qos2; break; } db__message_dequeue_first(context, &context->msgs_in); plugin_persist__handle_client_msg_update(context, client_msg); } } 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 *client_msg, *tmp; if(!context){ return MOSQ_ERR_INVAL; } DL_FOREACH_SAFE(context->msgs_in.inflight, client_msg, tmp){ if(client_msg->data.mid == mid){ if(client_msg->base_msg->data.qos != 2){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: Incorrect QoS (%d) when deleting incoming message.", context->id, client_msg->base_msg->data.qos); return MOSQ_ERR_PROTOCOL; } db__message_remove_inflight(context, &context->msgs_in, client_msg); return MOSQ_ERR_SUCCESS; } } return MOSQ_ERR_NOT_FOUND; } int db__message_release_incoming(struct mosquitto *context, uint16_t mid) { struct mosquitto__client_msg *client_msg, *tmp; int retain; char *topic; char *source_id; bool deleted = false; int rc; if(!context){ return MOSQ_ERR_INVAL; } DL_FOREACH_SAFE(context->msgs_in.inflight, client_msg, tmp){ if(client_msg->data.mid == mid){ if(client_msg->base_msg->data.qos != 2){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: Incorrect QoS (%d) when releasing incoming message.", context->id, client_msg->base_msg->data.qos); return MOSQ_ERR_PROTOCOL; } topic = client_msg->base_msg->data.topic; retain = client_msg->data.retain; source_id = client_msg->base_msg->data.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_inflight(context, &context->msgs_in, client_msg); deleted = true; }else{ rc = sub__messages_queue(source_id, topic, 2, retain, &client_msg->base_msg); if(rc == MOSQ_ERR_SUCCESS || rc == MOSQ_ERR_NO_SUBSCRIBERS){ db__message_remove_inflight(context, &context->msgs_in, client_msg); deleted = true; }else{ return 1; } } } } DL_FOREACH_SAFE(context->msgs_in.queued, client_msg, tmp){ if(db__ready_for_flight(context, mosq_md_in, client_msg->data.qos)){ break; } if(client_msg->data.qos == 2){ send__pubrec(context, client_msg->data.mid, 0, NULL); client_msg->data.state = mosq_ms_wait_for_pubrel; db__message_dequeue_first(context, &context->msgs_in); plugin_persist__handle_client_msg_update(context, client_msg); } } if(deleted){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOT_FOUND; } } void db__expire_all_messages(struct mosquitto *context) { struct mosquitto__client_msg *client_msg, *tmp; DL_FOREACH_SAFE(context->msgs_out.inflight, client_msg, tmp){ if(client_msg->base_msg->data.expiry_time && db.now_real_s > client_msg->base_msg->data.expiry_time){ if(client_msg->data.qos > 0){ util__increment_send_quota(context); } db__message_remove_inflight(context, &context->msgs_out, client_msg); } } db__fill_inflight_out_from_queue(context); DL_FOREACH_SAFE(context->msgs_out.queued, client_msg, tmp){ if(client_msg->base_msg->data.expiry_time && db.now_real_s > client_msg->base_msg->data.expiry_time){ db__message_remove_queued(context, &context->msgs_out, client_msg); } } DL_FOREACH_SAFE(context->msgs_in.inflight, client_msg, tmp){ if(client_msg->base_msg->data.expiry_time && db.now_real_s > client_msg->base_msg->data.expiry_time){ if(client_msg->data.qos > 0){ util__increment_receive_quota(context); } db__message_remove_inflight(context, &context->msgs_in, client_msg); } } DL_FOREACH_SAFE(context->msgs_in.queued, client_msg, tmp){ if(client_msg->base_msg->data.expiry_time && db.now_real_s > client_msg->base_msg->data.expiry_time){ db__message_remove_queued(context, &context->msgs_in, client_msg); } } } static void db__client_messages_check_acl(struct mosquitto *context, struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg **head, void (*decrement_stats_fn)(struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg *client_msg)) { struct mosquitto__client_msg *client_msg, *tmp; struct mosquitto__base_msg *base_msg; int access; DL_FOREACH_SAFE((*head), client_msg, tmp){ base_msg = client_msg->base_msg; if(client_msg->data.direction == mosq_md_out){ access = MOSQ_ACL_READ; }else{ access = MOSQ_ACL_WRITE; } if(mosquitto_acl_check(context, base_msg->data.topic, base_msg->data.payloadlen, base_msg->data.payload, base_msg->data.qos, base_msg->data.retain, base_msg->data.properties, access) != MOSQ_ERR_SUCCESS){ DL_DELETE((*head), client_msg); decrement_stats_fn(msg_data, client_msg); plugin_persist__handle_client_msg_delete(context, client_msg); db__msg_store_ref_dec(&client_msg->base_msg); mosquitto_FREE(client_msg); } } } void db__check_acl_of_all_messages(struct mosquitto *context) { db__client_messages_check_acl(context, &context->msgs_in, &context->msgs_in.inflight, &db__msg_remove_from_inflight_stats); db__client_messages_check_acl(context, &context->msgs_in, &context->msgs_in.queued, &db__msg_remove_from_queued_stats); db__client_messages_check_acl(context, &context->msgs_out, &context->msgs_out.inflight, &db__msg_remove_from_inflight_stats); db__client_messages_check_acl(context, &context->msgs_out, &context->msgs_out.queued, &db__msg_remove_from_queued_stats); } static int db__message_write_inflight_out_single(struct mosquitto *context, struct mosquitto__client_msg *client_msg) { struct mosquitto__base_msg *base_msg; mosquitto_property *base_msg_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; uint32_t subscription_id; base_msg = client_msg->base_msg; expiry_interval = 0; if(base_msg->data.expiry_time){ if(db.now_real_s > base_msg->data.expiry_time){ /* Message is expired, must not send. */ if(client_msg->data.direction == mosq_md_out && client_msg->data.qos > 0){ util__increment_send_quota(context); } db__message_remove_inflight(context, &context->msgs_out, client_msg); db__fill_inflight_out_from_queue(context); return MOSQ_ERR_SUCCESS; }else{ expiry_interval = (uint32_t)(base_msg->data.expiry_time - db.now_real_s); } } mid = client_msg->data.mid; retries = client_msg->data.dup; retain = client_msg->data.retain; topic = base_msg->data.topic; qos = (uint8_t)client_msg->data.qos; payloadlen = base_msg->data.payloadlen; payload = base_msg->data.payload; subscription_id = client_msg->data.subscription_identifier; base_msg_props = base_msg->data.properties; switch(client_msg->data.state){ case mosq_ms_publish_qos0: rc = send__publish(context, mid, topic, payloadlen, payload, qos, retain, retries, subscription_id, base_msg_props, expiry_interval); if(rc == MOSQ_ERR_SUCCESS || rc == MOSQ_ERR_OVERSIZE_PACKET){ db__message_remove_inflight(context, &context->msgs_out, client_msg); }else{ return rc; } break; case mosq_ms_publish_qos1: rc = send__publish(context, mid, topic, payloadlen, payload, qos, retain, retries, subscription_id, base_msg_props, expiry_interval); if(rc == MOSQ_ERR_SUCCESS){ client_msg->data.dup = 1; /* Any retry attempts are a duplicate. */ client_msg->data.state = mosq_ms_wait_for_puback; plugin_persist__handle_client_msg_update(context, client_msg); }else if(rc == MOSQ_ERR_OVERSIZE_PACKET){ db__message_remove_inflight(context, &context->msgs_out, client_msg); }else{ return rc; } break; case mosq_ms_publish_qos2: rc = send__publish(context, mid, topic, payloadlen, payload, qos, retain, retries, subscription_id, base_msg_props, expiry_interval); if(rc == MOSQ_ERR_SUCCESS){ client_msg->data.dup = 1; /* Any retry attempts are a duplicate. */ client_msg->data.state = mosq_ms_wait_for_pubrec; plugin_persist__handle_client_msg_update(context, client_msg); }else if(rc == MOSQ_ERR_OVERSIZE_PACKET){ db__message_remove_inflight(context, &context->msgs_out, client_msg); }else{ return rc; } break; case mosq_ms_resend_pubrel: rc = send__pubrel(context, mid, NULL); if(!rc){ client_msg->data.state = mosq_ms_wait_for_pubcomp; plugin_persist__handle_client_msg_update(context, client_msg); }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 *client_msg, *tmp; int rc; if(context->state != mosq_cs_active || !net__is_connected(context)){ return MOSQ_ERR_SUCCESS; } DL_FOREACH_SAFE(context->msgs_out.inflight, client_msg, tmp){ rc = db__message_write_inflight_out_single(context, client_msg); if(rc){ return rc; } } return MOSQ_ERR_SUCCESS; } int db__message_write_inflight_out_latest(struct mosquitto *context) { struct mosquitto__client_msg *client_msg, *next; int rc; if(context->state != mosq_cs_active || !net__is_connected(context) || 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 */ client_msg = context->msgs_out.inflight->prev; while(client_msg != context->msgs_out.inflight && (client_msg->data.state == mosq_ms_publish_qos0 || client_msg->data.state == mosq_ms_publish_qos1 || client_msg->data.state == mosq_ms_publish_qos2)){ client_msg = client_msg->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(client_msg != context->msgs_out.inflight){ client_msg = client_msg->next; } while(client_msg){ next = client_msg->next; rc = db__message_write_inflight_out_single(context, client_msg); if(rc){ return rc; } client_msg = next; } return MOSQ_ERR_SUCCESS; } int db__message_write_queued_in(struct mosquitto *context) { struct mosquitto__client_msg *client_msg, *tmp; int rc; if(context->state != mosq_cs_active){ return MOSQ_ERR_SUCCESS; } DL_FOREACH_SAFE(context->msgs_in.queued, client_msg, tmp){ if(context->msgs_in.inflight_maximum != 0 && context->msgs_in.inflight_quota == 0){ break; } if(client_msg->data.qos == 2){ client_msg->data.state = mosq_ms_send_pubrec; db__message_dequeue_first(context, &context->msgs_in); rc = send__pubrec(context, client_msg->data.mid, 0, NULL); if(!rc){ client_msg->data.state = mosq_ms_wait_for_pubrel; plugin_persist__handle_client_msg_update(context, client_msg); }else{ plugin_persist__handle_client_msg_update(context, client_msg); return rc; } } } return MOSQ_ERR_SUCCESS; } int db__message_write_queued_out(struct mosquitto *context) { if(context->state != mosq_cs_active){ return MOSQ_ERR_SUCCESS; } db__fill_inflight_out_from_queue(context); return MOSQ_ERR_SUCCESS; } ================================================ FILE: src/handle_auth.c ================================================ /* Copyright (c) 2018-2021 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 "mosquitto/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__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){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: AUTH packet when session not MQTT v5.0.", context->id); return MOSQ_ERR_PROTOCOL; } if(context->auth_method == NULL){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: AUTH packet without existing auth-method.", context->id); return MOSQ_ERR_PROTOCOL; } if(context->in_packet.command != CMD_AUTH){ return MOSQ_ERR_MALFORMED_PACKET; } 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); log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: AUTH packet with reason-code = %d.", context->id, reason_code); 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); log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: AUTH reauthentication packet before session is active,", context->id); log__printf(NULL, MOSQ_LOG_INFO, " or attempted to continue authentication when no authentication in progress."); 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); log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: AUTH packet without auth-method property.", context->id); 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); log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: AUTH packet with non-matching auth-method property (%s:%s).", context->id, context->auth_method, auth_method); 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); SAFE_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); SAFE_FREE(auth_data_out); return rc; }else{ SAFE_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){ if(context->state == mosq_cs_authenticating){ send__connack(context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); mosquitto_FREE(context->id); }else{ send__disconnect(context, MQTT_RC_NOT_AUTHORIZED, NULL); } return MOSQ_ERR_PROTOCOL; }else if(rc == MOSQ_ERR_NOT_SUPPORTED){ /* Client has requested extended authentication, but we don't support it. */ if(context->state == mosq_cs_authenticating){ send__connack(context, 0, MQTT_RC_BAD_AUTHENTICATION_METHOD, NULL); mosquitto_FREE(context->id); }else{ send__disconnect(context, MQTT_RC_BAD_AUTHENTICATION_METHOD, NULL); } return MOSQ_ERR_PROTOCOL; }else{ if(context->state == mosq_cs_authenticating){ mosquitto_FREE(context->id); } return rc; } } } ================================================ FILE: src/handle_connack.c ================================================ /* Copyright (c) 2009-2021 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 "mosquitto/mqtt_protocol.h" #include "packet_mosq.h" #include "send_mosq.h" #include "util_mosq.h" static int handle__connack_properties(struct mosquitto *context) { int rc; mosquitto_property *properties = NULL; uint16_t inflight_maximum; uint8_t max_qos = 255; uint32_t maximum_packet_size; uint16_t server_keepalive; uint16_t max_topic_alias; uint8_t retain_available; 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); if(max_qos != 255){ context->max_qos = max_qos; } /* 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 */ inflight_maximum = context->msgs_out.inflight_maximum; mosquitto_property_read_int16(properties, MQTT_PROP_RECEIVE_MAXIMUM, &inflight_maximum, false); if(context->msgs_out.inflight_maximum != inflight_maximum){ context->msgs_out.inflight_maximum = inflight_maximum; db__message_reconnect_reset(context); } /* 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; } /* topic-alias-maximum */ if(mosquitto_property_read_int16(properties, MQTT_PROP_TOPIC_ALIAS_MAXIMUM, &max_topic_alias, false)){ if(max_topic_alias < context->bridge->max_topic_alias){ context->alias_max_l2r = max_topic_alias; }else{ context->alias_max_l2r = context->bridge->max_topic_alias; } } mosquitto_property_free_all(&properties); return MOSQ_ERR_SUCCESS; } int handle__connack(struct mosquitto *context) { int rc; uint8_t connect_acknowledge; uint8_t reason_code; if(context == NULL){ return MOSQ_ERR_INVAL; } if(context->bridge == NULL){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: CONNACK when not a bridge.", context->id); return MOSQ_ERR_PROTOCOL; } if(context->in_packet.command != CMD_CONNACK){ return MOSQ_ERR_MALFORMED_PACKET; } 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 = handle__connack_properties(context); if(rc){ return rc; } } if(reason_code == MQTT_RC_SUCCESS){ #ifdef WITH_BRIDGE if(context->bridge){ rc = bridge__on_connect(context); if(rc){ return rc; } } #endif 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(context->max_qos != 0){ context->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: bad user name or password"); 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; } ================================================ FILE: src/handle_connect.c ================================================ /* Copyright (c) 2009-2021 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 "mosquitto/mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "send_mosq.h" #include "sys_tree.h" #include "tls_mosq.h" #include "util_mosq.h" #include "will_mosq.h" #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS # 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 *clientid_gen(uint16_t *idlen, const char *auto_id_prefix, uint16_t auto_id_prefix_len) { char *clientid; uint8_t rnd[16]; int pos; if(mosquitto_getrandom(rnd, 16)){ return NULL; } *idlen = (uint16_t)(auto_id_prefix_len + 36); clientid = (char *)mosquitto_calloc((size_t)(*idlen) + 1, sizeof(char)); if(!clientid){ return NULL; } if(auto_id_prefix){ memcpy(clientid, auto_id_prefix, auto_id_prefix_len); } pos = 0; for(int i=0; i<16; i++){ clientid[auto_id_prefix_len + pos + 0] = nibble_to_hex(rnd[i] & 0x0F); clientid[auto_id_prefix_len + pos + 1] = nibble_to_hex((rnd[i] >> 4) & 0x0F); pos += 2; if(pos == 8 || pos == 13 || pos == 18 || pos == 23){ clientid[auto_id_prefix_len + pos] = '-'; pos++; } } return clientid; } 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 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(!net__is_connected(found_context)){ /* 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(context->clean_start == true){ sub__clean_session(found_context); found_context->session_expiry_interval = MQTT_SESSION_EXPIRY_IMMEDIATE; plugin_persist__handle_client_delete(found_context); } context->is_persisted = found_context->is_persisted; found_context->is_persisted = false; /* stops persistence for context being removed */ if(context->clean_start == false && found_context->session_expiry_interval != MQTT_SESSION_EXPIRY_IMMEDIATE){ 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)); context->last_cmsg_id = found_context->last_cmsg_id; 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->subs_capacity = found_context->subs_capacity; context->subs_count = found_context->subs_count; found_context->subs_capacity = 0; found_context->subs_count = 0; context->last_mid = found_context->last_mid; for(int i=0; isubs_capacity; i++){ if(context->subs[i]){ leaf = context->subs[i]->hier->subs; while(leaf){ if(leaf->context == found_context){ leaf->context = context; } leaf = leaf->next; } if(context->subs[i]->shared){ leaf = context->subs[i]->shared->subs; while(leaf){ if(leaf->context == found_context){ leaf->context = context; } leaf = leaf->next; } } } } } if((found_context->protocol == mosq_p_mqtt5 && found_context->session_expiry_interval == MQTT_SESSION_EXPIRY_IMMEDIATE) || (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 = MQTT_SESSION_EXPIRY_IMMEDIATE; mosquitto__set_state(found_context, mosq_cs_duplicate); if(found_context->protocol == mosq_p_mqtt5){ send__disconnect(found_context, MQTT_RC_SESSION_TAKEN_OVER, NULL); } do_disconnect(found_context, MOSQ_ERR_SESSION_TAKEN_OVER); } if(db.config->global_max_clients > 0 && HASH_CNT(hh_id, db.contexts_by_id) >= (unsigned int)db.config->global_max_clients){ if(context->protocol == mosq_p_mqtt5){ send__connack(context, 0, MQTT_RC_SERVER_BUSY, NULL); } rc = MOSQ_ERR_INVAL; goto error; } 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."); } } #ifdef WITH_TLS if(context->ssl){ log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s negotiated %s cipher %s", context->id, SSL_get_cipher_version(context->ssl), SSL_get_cipher_name(context->ssl)); } #endif context->ping_t = 0; context->is_dropping = false; /* Remove any queued messages that are no longer allowed through ACL, * assuming a possible change of username. */ db__check_acl_of_all_messages(context); context__add_to_by_id(context); #ifdef WITH_PERSISTENCE if(!context->clean_start){ db.persistence_changes++; } #endif context->max_qos = context->listener->max_qos; if(db.config->max_keepalive && (context->keepalive > db.config->max_keepalive || context->keepalive == 0)){ keepalive__remove(context); context->keepalive = db.config->max_keepalive; keepalive__add(context); if(context->protocol == mosq_p_mqtt5){ if(mosquitto_property_add_int16(&connack_props, MQTT_PROP_SERVER_KEEP_ALIVE, context->keepalive)){ rc = MOSQ_ERR_NOMEM; goto error; } }else{ send__connack(context, connect_ack, CONNACK_REFUSED_IDENTIFIER_REJECTED, NULL); rc = MOSQ_ERR_INVAL; goto error; } } 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(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; } } } } SAFE_FREE(auth_data_out); 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; } db__expire_all_messages(context); rc = db__message_write_queued_out(context); if(rc){ return rc; } rc = db__message_write_inflight_out_all(context); if(rc == MOSQ_ERR_SUCCESS){ plugin__handle_connect(context); if(context->session_expiry_interval != MQTT_SESSION_EXPIRY_IMMEDIATE){ plugin_persist__handle_client_add(context); }else if(context->will){ plugin_persist__handle_will_add(context); } } return rc; error: SAFE_FREE(auth_data_out); mosquitto_property_free_all(&connack_props); return rc; } static int will__read(struct mosquitto *context, const char *clientid, 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){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: Will with empty topic.", context->id); 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; } if(!strncmp(will_struct->msg.topic, "$CONTROL/", strlen("$CONTROL/"))){ rc = MOSQ_ERR_ACL_DENIED; goto error_cleanup; } 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", clientid); 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; } static int check_protocol_version(struct mosquitto__listener *listener, int protocol_version) { /* Allow bridge protocol as well. */ protocol_version &= 0x7F; if((protocol_version == 3 && listener->disable_protocol_v3 == false) || (protocol_version == 4 && listener->disable_protocol_v4 == false) || (protocol_version == 5 && listener->disable_protocol_v5 == false) ){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_NOT_SUPPORTED; } } inline static int send__connack_error_and_return(struct mosquitto *context, uint8_t err_code, int rc) { send__connack(context, 0, err_code, NULL); return rc; } inline static int send__connack_bad_username_or_password_error(struct mosquitto *context, int rc) { uint8_t err_code = context->protocol == mosq_p_mqtt5 ? (uint8_t)MQTT_RC_BAD_USERNAME_OR_PASSWORD : (uint8_t)CONNACK_REFUSED_BAD_USERNAME_PASSWORD; return send__connack_error_and_return(context, err_code, rc); } static int read_protocol_name(struct mosquitto *context, char protocol_name[7]) { /* 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. */ uint16_t slen = 0; if(packet__read_uint16(&context->in_packet, &slen)){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with missing protocol string length.", context->address, context->remote_port); return MOSQ_ERR_PROTOCOL; } if(slen != 4 /* MQTT */ && slen != 6 /* MQIsdp */){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with incorrect protocol string length (%d).", context->address, context->remote_port, slen); return MOSQ_ERR_PROTOCOL; } if(packet__read_bytes(&context->in_packet, protocol_name, slen)){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with missing protocol string.", context->address, context->remote_port); return MOSQ_ERR_PROTOCOL; } protocol_name[slen] = '\0'; return MOSQ_ERR_SUCCESS; } static int read_and_verify_protocol_version(struct mosquitto *context, const char *protocol_name, uint8_t *protocol_version) { uint8_t tmp_protocol_version = 0; if(packet__read_byte(&context->in_packet, &tmp_protocol_version)){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with missing protocol version.", context->address, context->remote_port); return MOSQ_ERR_PROTOCOL; } if(check_protocol_version(context->listener, tmp_protocol_version)){ if(tmp_protocol_version == 3 || tmp_protocol_version == 4){ context->protocol = mosq_p_mqtt311; send__connack(context, 0, CONNACK_REFUSED_PROTOCOL_VERSION, NULL); }else{ context->protocol = mosq_p_mqtt5; send__connack(context, 0, MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION, NULL); } return MOSQ_ERR_NOT_SUPPORTED; } if(!strcmp(protocol_name, PROTOCOL_NAME_v31)){ if((tmp_protocol_version&0x7F) != PROTOCOL_VERSION_v31){ if(db.config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with invalid protocol version (%d).", context->address, context->remote_port, tmp_protocol_version); } send__connack(context, 0, CONNACK_REFUSED_PROTOCOL_VERSION, NULL); return MOSQ_ERR_PROTOCOL; } context->protocol = mosq_p_mqtt31; if((tmp_protocol_version&0x80) == 0x80){ context->is_bridge = true; } }else if(!strcmp(protocol_name, PROTOCOL_NAME)){ if((tmp_protocol_version&0x7F) == PROTOCOL_VERSION_v311){ context->protocol = mosq_p_mqtt311; if((tmp_protocol_version&0x80) == 0x80){ context->is_bridge = true; } }else if((tmp_protocol_version&0x7F) == PROTOCOL_VERSION_v5){ context->protocol = mosq_p_mqtt5; }else{ if(db.config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with invalid protocol version (%d).", context->address, context->remote_port, tmp_protocol_version); } send__connack(context, 0, CONNACK_REFUSED_PROTOCOL_VERSION, NULL); return MOSQ_ERR_PROTOCOL; } if((context->in_packet.command&0x0F) != 0x00){ /* Reserved flags not set to 0, must disconnect. */ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with non-zero reserved flags (%02X).", context->address, context->remote_port, context->in_packet.command); return MOSQ_ERR_PROTOCOL; } }else{ if(db.config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with invalid protocol \"%s\".", context->address, context->remote_port, protocol_name); } return MOSQ_ERR_PROTOCOL; } if((tmp_protocol_version&0x7F) != PROTOCOL_VERSION_v31 && context->in_packet.command != CMD_CONNECT){ return MOSQ_ERR_MALFORMED_PACKET; } *protocol_version = tmp_protocol_version; return MOSQ_ERR_SUCCESS; } static int read_and_verify_connect_flags(struct mosquitto *context, uint8_t *connect_flags) { if(packet__read_byte(&context->in_packet, connect_flags)){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with missing connect flags.", context->address, context->remote_port); return MOSQ_ERR_PROTOCOL; } if(context->protocol == mosq_p_mqtt311 || context->protocol == mosq_p_mqtt5){ if((*connect_flags & 0x01) != 0x00){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with non-zero connect reserved flag (%02X).", context->address, context->remote_port, *connect_flags); return MOSQ_ERR_PROTOCOL; } } return MOSQ_ERR_SUCCESS; } static void set_session_expiry_interval(struct mosquitto *context, uint8_t clean_start, uint8_t protocol_version) { /* session_expiry_interval will be overridden 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 = MQTT_SESSION_EXPIRY_NEVER; }else{ context->session_expiry_interval = MQTT_SESSION_EXPIRY_IMMEDIATE; } } static int read_and_reset_keepalive(struct mosquitto *context) { /* _remove here because net__socket_accept() uses _add and we must have the * correct keepalive value */ keepalive__remove(context); if(packet__read_uint16(&context->in_packet, &(context->keepalive))){ log__printf(NULL, MOSQ_LOG_INFO, "%s sent CONNECT with missing keepalive.", context->id); return MOSQ_ERR_PROTOCOL; } keepalive__add(context); return MOSQ_ERR_SUCCESS; } static int read_and_verify_v5_connect_properties(struct mosquitto *context, mosquitto_property **properties, uint8_t protocol_version) { int rc; if(protocol_version == PROTOCOL_VERSION_v5){ rc = property__read_all(CMD_CONNECT, &context->in_packet, properties); if(rc == MOSQ_ERR_DUPLICATE_PROPERTY || rc == MOSQ_ERR_PROTOCOL){ send__connack(context, 0, MQTT_RC_PROTOCOL_ERROR, NULL); }else if(rc == MOSQ_ERR_MALFORMED_PACKET){ send__connack(context, 0, MQTT_RC_MALFORMED_PACKET, NULL); } if(rc){ return rc; } } rc = property__process_connect(context, properties); if(rc != MOSQ_ERR_SUCCESS){ return send__connack_error_and_return(context, MQTT_RC_PROTOCOL_ERROR, rc); } return MOSQ_ERR_SUCCESS; } static int verify_will_options(struct mosquitto *context, uint8_t will, uint8_t will_qos, uint8_t will_retain, uint8_t protocol_version) { if(will_qos == 3){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid Will QoS in CONNECT from %s.", context->address); return MOSQ_ERR_PROTOCOL; } 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); } return MOSQ_ERR_NOT_SUPPORTED; } if(will && will_qos > context->listener->max_qos){ if(protocol_version == mosq_p_mqtt5){ send__connack(context, 0, MQTT_RC_QOS_NOT_SUPPORTED, NULL); } return MOSQ_ERR_NOT_SUPPORTED; } return MOSQ_ERR_SUCCESS; } static int handle_zero_length_clientid(struct mosquitto *context, char **clientid, bool *allow_zero_length_clientid, uint8_t clean_start) { if(context->protocol == mosq_p_mqtt31){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: v3.1 CONNECT with zero length clientid.", context->address, context->remote_port); send__connack(context, 0, CONNACK_REFUSED_IDENTIFIER_REJECTED, NULL); return MOSQ_ERR_PROTOCOL; } /* mqtt311/mqtt5 */ mosquitto_FREE(*clientid); if(db.config->per_listener_settings){ *allow_zero_length_clientid = context->listener->security_options->allow_zero_length_clientid; }else{ *allow_zero_length_clientid = db.config->security_options.allow_zero_length_clientid; } if((context->protocol == mosq_p_mqtt311 && clean_start == 0) || *allow_zero_length_clientid == false){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with zero length clientid when forbidden.", context->address, context->remote_port); uint8_t err_code = context->protocol == mosq_p_mqtt311 ? (uint8_t)CONNACK_REFUSED_IDENTIFIER_REJECTED : (uint8_t)MQTT_RC_UNSPECIFIED; return send__connack_error_and_return(context, err_code, MOSQ_ERR_PROTOCOL); } *clientid = clientid_gen(&(uint16_t){0}, context->listener->security_options->auto_id_prefix, context->listener->security_options->auto_id_prefix_len); if(*clientid == NULL){ return MOSQ_ERR_NOMEM; } context->assigned_id = true; return MOSQ_ERR_SUCCESS; } static int check_clientid_prefixes(struct mosquitto *context, const char *clientid) { if(db.config->clientid_prefixes){ if(strncmp(db.config->clientid_prefixes, clientid, strlen(db.config->clientid_prefixes))){ uint8_t err_code = context->protocol == mosq_p_mqtt5 ? (uint8_t)MQTT_RC_NOT_AUTHORIZED : (uint8_t)CONNACK_REFUSED_NOT_AUTHORIZED; return send__connack_error_and_return(context, err_code, MOSQ_ERR_AUTH); } } return MOSQ_ERR_SUCCESS; } static int read_and_verify_clientid_from_packet(struct mosquitto *context, char **clientid, bool *allow_zero_length_clientid, uint8_t clean_start) { int rc; uint16_t slen; rc = packet__read_string(&context->in_packet, clientid, &slen); if(rc == MOSQ_ERR_MALFORMED_UTF8){ if(context->protocol == mosq_p_mqtt5){ send__connack(context, 0, MQTT_RC_CLIENTID_NOT_VALID, NULL); } return MOSQ_ERR_CLIENT_IDENTIFIER_NOT_VALID; }else if(rc > 0){ return MOSQ_ERR_PROTOCOL; } if(slen == 0){ rc = handle_zero_length_clientid(context, clientid, allow_zero_length_clientid, clean_start); if(rc != MOSQ_ERR_SUCCESS){ return rc; } } rc = check_clientid_prefixes(context, *clientid); if(rc != MOSQ_ERR_SUCCESS){ return rc; } return MOSQ_ERR_SUCCESS; } static int set_username_from_packet(struct mosquitto *context, char **username, const char *clientid) { int rc; rc = packet__read_string(&context->in_packet, username, &(uint16_t){0}); if(rc == MOSQ_ERR_NOMEM){ return MOSQ_ERR_NOMEM; } if(rc != MOSQ_ERR_SUCCESS){ if(context->protocol == mosq_p_mqtt31){ /* Username flag given, but no username. Ignore. */ /* NOTE: Removed setting of username_flag to zero as it is unused afterwards */ }else{ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: CONNECT with username flag but no username.", clientid); return MOSQ_ERR_PROTOCOL; } } return MOSQ_ERR_SUCCESS; } static int set_password_from_packet(struct mosquitto *context, char **password, uint16_t *password_len, const char *clientid) { int rc; rc = packet__read_binary(&context->in_packet, (uint8_t **)password, password_len); if(rc == MOSQ_ERR_NOMEM){ return MOSQ_ERR_NOMEM; } if(rc == MOSQ_ERR_MALFORMED_PACKET){ if(context->protocol == mosq_p_mqtt31){ /* Password flag given, but no password. Ignore. */ }else{ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: CONNECT with password flag but no password.", clientid); return MOSQ_ERR_PROTOCOL; } } return MOSQ_ERR_SUCCESS; } static int read_and_verify_client_credentials_from_packet(struct mosquitto *context, char **username, uint8_t username_flag, char **password, uint16_t *password_len, uint8_t password_flag, const char *clientid) { int rc; if(username_flag){ rc = set_username_from_packet(context, username, clientid); if(rc != MOSQ_ERR_SUCCESS){ return rc; } }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.", clientid); return MOSQ_ERR_PROTOCOL; } } } if(password_flag){ rc = set_password_from_packet(context, password, password_len, clientid); if(rc != MOSQ_ERR_SUCCESS){ return rc; } } return MOSQ_ERR_SUCCESS; } static int check_additional_trailing_data(struct mosquitto *context, uint8_t protocol_version) { if(context->in_packet.pos != context->in_packet.remaining_length){ /* Surplus data at end of packet, this must be an error. */ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: CONNECT packet with overlong remaining length (%d:%d).", context->id, context->in_packet.pos, context->in_packet.remaining_length); if(protocol_version == PROTOCOL_VERSION_v5){ send__connack(context, 0, MQTT_RC_MALFORMED_PACKET, NULL); } return MOSQ_ERR_PROTOCOL; } return MOSQ_ERR_SUCCESS; } #ifdef WITH_TLS inline static int get_client_cert_and_subject_name(struct mosquitto *context, X509 **client_cert, X509_NAME **name) { *client_cert = SSL_get_peer_certificate(context->ssl); if(*client_cert == NULL){ return send__connack_bad_username_or_password_error(context, MOSQ_ERR_AUTH); } *name = X509_get_subject_name(*client_cert); if(*name == NULL){ X509_free(*client_cert); return send__connack_bad_username_or_password_error(context, MOSQ_ERR_AUTH); } return MOSQ_ERR_SUCCESS; } inline static int free_x509_and_send_connack_error(struct mosquitto *context, X509 *client_cert, int rc) { X509_free(client_cert); return send__connack_bad_username_or_password_error(context, rc); } inline static int free_x509_and_BIO_and_send_connack_error(struct mosquitto *context, X509 *client_cert, BIO *subject_name, int rc) { BIO_free(subject_name); return free_x509_and_send_connack_error(context, client_cert, rc); } static int set_username_from_cert_identity(struct mosquitto *context) { X509 *client_cert = NULL; X509_NAME *name = NULL; if(get_client_cert_and_subject_name(context, &client_cert, &name)){ return MOSQ_ERR_AUTH; } int i = -1; X509_NAME_ENTRY *name_entry = NULL; i = X509_NAME_get_index_by_NID(name, NID_commonName, -1); if(i == -1){ return free_x509_and_send_connack_error(context, client_cert, MOSQ_ERR_AUTH); } name_entry = X509_NAME_get_entry(name, i); if(!name_entry){ goto success; } ASN1_STRING *name_asn1 = NULL; name_asn1 = X509_NAME_ENTRY_get_data(name_entry); if(name_asn1 == NULL){ return free_x509_and_send_connack_error(context, client_cert, MOSQ_ERR_AUTH); } const char *cert_identity = (const char *)ASN1_STRING_get0_data(name_asn1); if(!cert_identity || mosquitto_validate_utf8(cert_identity, (int)strlen(cert_identity))){ return free_x509_and_send_connack_error(context, client_cert, MOSQ_ERR_AUTH); } mosquitto_free(context->username); context->username = mosquitto_strdup(cert_identity); if(context->username == NULL){ return free_x509_and_send_connack_error(context, client_cert, MOSQ_ERR_NOMEM); } /* Make sure there isn't an embedded NUL character in the CN */ if((size_t)ASN1_STRING_length(name_asn1) != strlen(context->username)){ return free_x509_and_send_connack_error(context, client_cert, MOSQ_ERR_AUTH); } success: X509_free(client_cert); client_cert = NULL; return MOSQ_ERR_SUCCESS; } static int set_username_from_cert_subject_name(struct mosquitto *context) { X509 *client_cert = NULL; X509_NAME *name = NULL; if(get_client_cert_and_subject_name(context, &client_cert, &name)){ return MOSQ_ERR_AUTH; } char *subject = NULL; char *data_start = NULL; BIO *subject_bio = NULL; long name_length = 0; 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){ return free_x509_and_BIO_and_send_connack_error(context, client_cert, subject_bio, MOSQ_ERR_NOMEM); } memcpy(subject, data_start, (size_t)name_length); subject[name_length] = '\0'; BIO_free(subject_bio); if(mosquitto_validate_utf8(subject, (int)strlen(subject))){ mosquitto_free(subject); return free_x509_and_send_connack_error(context, client_cert, MOSQ_ERR_AUTH); } context->username = subject; if(!context->username){ X509_free(client_cert); return MOSQ_ERR_AUTH; } X509_free(client_cert); client_cert = NULL; return MOSQ_ERR_SUCCESS; } #endif static int handle_username_from_cert_options(struct mosquitto *context, char **username, char **password, uint16_t password_len) { int rc; #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); mosquitto_FREE(*password); if(!context->ssl){ return send__connack_bad_username_or_password_error(context, MOSQ_ERR_AUTH); } #ifdef FINAL_WITH_TLS_PSK if(context->listener->psk_hint){ /* Client should have provided an identity to get this far. */ if(!context->username){ return send__connack_bad_username_or_password_error(context, MOSQ_ERR_AUTH); } }else #endif /* FINAL_WITH_TLS_PSK */ { if(context->listener->use_identity_as_username){ rc = set_username_from_cert_identity(context); }else{ /* use_subject_as_username */ rc = set_username_from_cert_subject_name(context); } if(rc){ return rc; } } }else #endif /* WITH_TLS */ { #ifdef WITH_TLS if(context->listener->use_identity_as_username && context->listener->require_certificate){ mosquitto_FREE(*username); mosquitto_FREE(*password); if(!context->username){ return send__connack_bad_username_or_password_error(context, MOSQ_ERR_AUTH); } }else #endif { /* FIXME - these ensure the mosquitto_clientid() and * mosquitto_client_username() functions work, but is hacky */ context->username = *username; context->password = *password; context->password_len = password_len; *username = NULL; /* Avoid free() in error: below. */ *password = NULL; } } return MOSQ_ERR_SUCCESS; } static int handle_username_as_clientid_option(struct mosquitto *context) { if(context->username){ mosquitto_FREE(context->id); context->id = mosquitto_strdup(context->username); if(!context->id){ return MOSQ_ERR_NOMEM; } }else{ uint8_t err_code = context->protocol == mosq_p_mqtt5 ? (uint8_t)MQTT_RC_NOT_AUTHORIZED : (uint8_t)CONNACK_REFUSED_NOT_AUTHORIZED; return send__connack_error_and_return(context, err_code, MOSQ_ERR_AUTH); } return MOSQ_ERR_SUCCESS; } int handle__connect(struct mosquitto *context) { char protocol_name[7]; uint8_t protocol_version; uint8_t connect_flags; char *clientid = NULL; struct mosquitto *found_context; 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; uint16_t password_len = 0; int rc; 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; 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:%d sending multiple CONNECT messages.", context->address, context->remote_port); rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } #ifdef WITH_TLS if(context->in_packet.command == 0x16 && context->listener->ssl_ctx == NULL){ /* 0x16 is TLS handshake client hello */ log__printf(NULL, MOSQ_LOG_NOTICE, "Client from %s:%d appears to be using TLS to connect to a non-TLS listener.", context->address, context->remote_port); rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } #endif rc = read_protocol_name(context, protocol_name); if(rc != MOSQ_ERR_SUCCESS){ goto handle_connect_error; } rc = read_and_verify_protocol_version(context, protocol_name, &protocol_version); if(rc != MOSQ_ERR_SUCCESS){ if(rc == MOSQ_ERR_MALFORMED_PACKET){ return rc; } goto handle_connect_error; } rc = read_and_verify_connect_flags(context, &connect_flags); if(rc != MOSQ_ERR_SUCCESS){ goto handle_connect_error; } clean_start = (connect_flags & 0x02) >> 1; set_session_expiry_interval(context, clean_start, protocol_version); rc = read_and_reset_keepalive(context); if(rc != MOSQ_ERR_SUCCESS){ goto handle_connect_error; } rc = read_and_verify_v5_connect_properties(context, &properties, protocol_version); if(rc != MOSQ_ERR_SUCCESS){ goto handle_connect_error; } will = connect_flags & 0x04; will_qos = (connect_flags & 0x18) >> 3; if(will_qos == 3){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d: CONNECT with invalid Will QoS (%d).", context->address, context->remote_port, will_qos); rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } will_retain = ((connect_flags & 0x20) == 0x20); rc = verify_will_options(context, will, will_qos, will_retain, protocol_version); if(rc != MOSQ_ERR_SUCCESS){ goto handle_connect_error; } 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); if(auth_data && !context->auth_method){ send__connack(context, 0, MQTT_RC_PROTOCOL_ERROR, NULL); log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s:%d CONNECT with missing clientid string.", context->address, context->remote_port); rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } rc = read_and_verify_clientid_from_packet(context, &clientid, &allow_zero_length_clientid, clean_start); if(rc != MOSQ_ERR_SUCCESS){ goto handle_connect_error; } if(will){ rc = will__read(context, clientid, &will_struct, will_qos, will_retain); if(rc){ if(context->protocol == mosq_p_mqtt5){ if(rc == MOSQ_ERR_DUPLICATE_PROPERTY || rc == MOSQ_ERR_PROTOCOL){ send__connack(context, 0, MQTT_RC_PROTOCOL_ERROR, NULL); }else if(rc == MOSQ_ERR_MALFORMED_PACKET){ send__connack(context, 0, MQTT_RC_MALFORMED_PACKET, NULL); } } goto handle_connect_error; } }else{ if(context->protocol == mosq_p_mqtt311 || context->protocol == mosq_p_mqtt5){ if(will_qos != 0 || will_retain != 0){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: CONNECT without Will with non-zero QoS (%d) or retain (%d).", clientid, will_qos, will_retain); rc = MOSQ_ERR_PROTOCOL; goto handle_connect_error; } } } // Client credentials password_flag = connect_flags & 0x40; username_flag = connect_flags & 0x80; rc = read_and_verify_client_credentials_from_packet(context, &username, username_flag, &password, &password_len, password_flag, clientid); if(rc != MOSQ_ERR_SUCCESS){ goto handle_connect_error; } rc = check_additional_trailing_data(context, protocol_version); if(rc != MOSQ_ERR_SUCCESS){ 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 = clientid; clientid = NULL; /* use_identity_as_username or use_subject_as_username */ rc = handle_username_from_cert_options(context, &username, &password, password_len); if(rc != MOSQ_ERR_SUCCESS){ goto handle_connect_error; } /* use_username_as_clientid */ if(context->listener->use_username_as_clientid){ rc = handle_username_as_clientid_option(context); if(rc != MOSQ_ERR_SUCCESS){ goto handle_connect_error; } } /* Check for an existing delayed auth check, reject if present */ HASH_FIND(hh_id, db.contexts_by_id_delayed_auth, context->id, strlen(context->id), found_context); if(found_context){ rc = MOSQ_ERR_UNKNOWN; 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); 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); SAFE_FREE(auth_data_out); return rc; }else{ SAFE_FREE(auth_data_out); will__clear(context); if(rc == MOSQ_ERR_AUTH){ send__connack(context, 0, MQTT_RC_NOT_AUTHORIZED, NULL); mosquitto_FREE(context->id); 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); goto handle_connect_error; }else{ mosquitto_FREE(context->id); 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_basic_auth(context); switch(rc){ case MOSQ_ERR_SUCCESS: break; case MOSQ_ERR_AUTH_DELAYED: mosquitto__set_state(context, mosq_cs_delayed_auth); HASH_ADD_KEYPTR(hh_id, db.contexts_by_id_delayed_auth, context->id, strlen(context->id), context); return 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); } goto handle_connect_error; break; case MOSQ_ERR_UNSPECIFIED: case MOSQ_ERR_IMPLEMENTATION_SPECIFIC: case MOSQ_ERR_CLIENT_IDENTIFIER_NOT_VALID: case MOSQ_ERR_BAD_USERNAME_OR_PASSWORD: case MOSQ_ERR_SERVER_UNAVAILABLE: case MOSQ_ERR_SERVER_BUSY: case MOSQ_ERR_BANNED: case MOSQ_ERR_BAD_AUTHENTICATION_METHOD: case MOSQ_ERR_CONNECTION_RATE_EXCEEDED: if(context->protocol == mosq_p_mqtt5){ send__connack(context, 0, (uint8_t)rc, NULL); }else{ send__connack(context, 0, CONNACK_REFUSED_NOT_AUTHORIZED, NULL); } 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_property_free_all(&properties); mosquitto_FREE(auth_data); mosquitto_FREE(clientid); 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); } will__clear(context); /* We return an error here which means the client is freed later on. */ context->clean_start = true; context->session_expiry_interval = MQTT_SESSION_EXPIRY_IMMEDIATE; context->will_delay_interval = 0; return rc; } ================================================ FILE: src/handle_disconnect.c ================================================ /* Copyright (c) 2009-2021 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/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->in_packet.command != CMD_DISCONNECT){ return MOSQ_ERR_MALFORMED_PACKET; } 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){ 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){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: DISCONNECT packet with overlong remaining length (%d:%d).", context->id, 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){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: DISCONNECT packet with incorrect flags %02X.", context->id, context->in_packet.command); 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; } ================================================ FILE: src/handle_publish.c ================================================ /* Copyright (c) 2009-2021 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 "mosquitto/mqtt_protocol.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" static int process_bad_message(struct mosquitto *context, struct mosquitto__base_msg *base_msg, uint8_t reason_code) { int rc = MOSQ_ERR_UNKNOWN; if(base_msg){ switch(base_msg->data.qos){ case 0: rc = MOSQ_ERR_SUCCESS; break; case 1: if(context){ rc = send__puback(context, base_msg->data.source_mid, reason_code, NULL); }else{ rc = MOSQ_ERR_SUCCESS; } break; case 2: if(context){ rc = send__pubrec(context, base_msg->data.source_mid, reason_code, NULL); }else{ rc = MOSQ_ERR_SUCCESS; } break; } db__msg_store_free(base_msg); } if(context && db.config->max_queued_messages > 0 && context->out_packet_count >= db.config->max_queued_messages){ rc = MQTT_RC_QUOTA_EXCEEDED; } return rc; } int handle__accepted_publish(struct mosquitto *context, struct mosquitto__base_msg *base_msg, uint16_t mid, int dup, uint32_t *message_expiry_interval) { int rc; int rc2; struct mosquitto__base_msg *stored = NULL; struct mosquitto__client_msg *cmsg_stored = NULL; { rc = plugin__handle_message_in(context, &base_msg->data); 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, base_msg->data.qos, base_msg->data.retain, base_msg->data.source_mid, base_msg->data.topic, (long)base_msg->data.payloadlen); return process_bad_message(context, base_msg, MQTT_RC_NOT_AUTHORIZED); }else if(rc == MOSQ_ERR_QUOTA_EXCEEDED){ log__printf(NULL, MOSQ_LOG_DEBUG, "Rejected PUBLISH from %s, quota exceeded.", context->id); return process_bad_message(context, base_msg, MQTT_RC_QUOTA_EXCEEDED); }else if(rc != MOSQ_ERR_SUCCESS){ db__msg_store_free(base_msg); return rc; } } if(base_msg->data.qos > 0){ db__message_store_find(context, base_msg->data.source_mid, &cmsg_stored); } if(cmsg_stored && base_msg->data.source_mid != 0 && (cmsg_stored->base_msg->data.qos != base_msg->data.qos || cmsg_stored->base_msg->data.payloadlen != base_msg->data.payloadlen || strcmp(cmsg_stored->base_msg->data.topic, base_msg->data.topic) || memcmp(cmsg_stored->base_msg->data.payload, base_msg->data.payload, base_msg->data.payloadlen))){ log__printf(NULL, MOSQ_LOG_WARNING, "Reused message ID %u from %s detected. Clearing from storage.", base_msg->data.source_mid, context->id); db__message_remove_incoming(context, base_msg->data.source_mid); cmsg_stored = NULL; } if(!cmsg_stored){ if(base_msg->data.qos > 0 && context->msgs_in.inflight_quota == 0){ log__printf(NULL, MOSQ_LOG_WARNING, "Client %s has exceeded its receive-maximum quota. This behaviour must be fixed on the client.", context->id); #if 0 /* Badly behaving clients like on the esp32 fall foul of this * check, so report it for now but don't disconnect, to give chance * for the bad behaviour to be fixed. */ /* Client isn't allowed any more incoming messages, so fail early */ db__msg_store_free(base_msg); return MOSQ_ERR_RECEIVE_MAXIMUM_EXCEEDED; #endif } if(base_msg->data.qos == 0 || db__ready_for_flight(context, mosq_md_in, base_msg->data.qos) ){ dup = 0; rc = db__message_store(context, base_msg, message_expiry_interval, mosq_mo_client); if(rc){ return rc; } }else{ /* Client isn't allowed any more incoming messages, so fail early */ return process_bad_message(context, base_msg, MQTT_RC_QUOTA_EXCEEDED); } stored = base_msg; base_msg = NULL; dup = 0; }else{ db__msg_store_free(base_msg); base_msg = NULL; stored = cmsg_stored->base_msg; cmsg_stored->data.dup++; dup = cmsg_stored->data.dup; } switch(stored->data.qos){ case 0: rc2 = sub__messages_queue(context->id, stored->data.topic, stored->data.qos, stored->data.retain, &stored); if(rc2 > 0){ rc = rc2; } break; case 1: util__decrement_receive_quota(context); rc2 = sub__messages_queue(context->id, stored->data.topic, stored->data.qos, stored->data.retain, &stored); /* stored may now be free, so don't refer to it */ if(rc2 == MOSQ_ERR_SUCCESS || context->protocol != mosq_p_mqtt5){ rc2 = send__puback(context, mid, 0, NULL); if(rc2){ rc = rc2; } }else if(rc2 == MOSQ_ERR_NO_SUBSCRIBERS){ rc2 = send__puback(context, mid, MQTT_RC_NO_MATCHING_SUBSCRIBERS, NULL); if(rc2){ rc = rc2; } }else{ rc = rc2; } break; case 2: { int res; if(dup == 0){ res = db__message_insert_incoming(context, 0, stored, true); }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(dup == 0 || dup == 1){ rc2 = send__pubrec(context, stored->data.source_mid, 0, NULL); if(rc2){ rc = rc2; } }else{ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBLISH with dup = %d.", context->id, dup); return MOSQ_ERR_PROTOCOL; } }else{ rc = res; } break; } } db__message_write_queued_in(context); return rc; } int handle__publish(struct mosquitto *context) { uint8_t dup; int rc = 0; uint8_t header = context->in_packet.command; struct mosquitto__base_msg *base_msg; size_t len; uint16_t slen; char *topic_mount; mosquitto_property *properties = NULL; uint32_t message_expiry_interval = MSG_EXPIRY_INFINITE; int topic_alias = -1; uint16_t mid = 0; if(context->state != mosq_cs_active){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBLISH before session is active.", context->id); return MOSQ_ERR_PROTOCOL; } context->stats.messages_received++; base_msg = mosquitto_calloc(1, sizeof(struct mosquitto__base_msg)); if(base_msg == NULL){ return MOSQ_ERR_NOMEM; } dup = (header & 0x08)>>3; base_msg->data.qos = (header & 0x06)>>1; if(dup == 1 && base_msg->data.qos == 0){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid PUBLISH (QoS=0 and DUP=1) from %s, disconnecting.", context->id); db__msg_store_free(base_msg); return MOSQ_ERR_MALFORMED_PACKET; } if(base_msg->data.qos == 3){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid QoS in PUBLISH from %s, disconnecting.", context->id); db__msg_store_free(base_msg); return MOSQ_ERR_MALFORMED_PACKET; } if(base_msg->data.qos > context->max_qos){ log__printf(NULL, MOSQ_LOG_INFO, "Too high QoS in PUBLISH from %s, disconnecting.", context->id); db__msg_store_free(base_msg); return MOSQ_ERR_QOS_NOT_SUPPORTED; } base_msg->data.retain = (header & 0x01); if(base_msg->data.retain && db.config->retain_available == false){ db__msg_store_free(base_msg); return MOSQ_ERR_RETAIN_NOT_SUPPORTED; } if(packet__read_string(&context->in_packet, &base_msg->data.topic, &slen)){ db__msg_store_free(base_msg); return MOSQ_ERR_MALFORMED_PACKET; } if(!slen && context->protocol != mosq_p_mqtt5){ /* Invalid publish topic, disconnect client. */ db__msg_store_free(base_msg); return MOSQ_ERR_MALFORMED_PACKET; } if(base_msg->data.qos > 0){ if(packet__read_uint16(&context->in_packet, &mid)){ db__msg_store_free(base_msg); return MOSQ_ERR_MALFORMED_PACKET; } if(mid == 0){ db__msg_store_free(base_msg); log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBLISH packet with mid = 0.", context->id); 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. */ base_msg->data.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(base_msg); return rc; } rc = property__process_publish(base_msg, &properties, &topic_alias, &message_expiry_interval, context->bridge); if(rc){ mosquitto_property_free_all(&properties); db__msg_store_free(base_msg); return MOSQ_ERR_PROTOCOL; } } mosquitto_property_free_all(&properties); if(topic_alias == 0 || (context->listener && topic_alias > context->listener->max_topic_alias)){ db__msg_store_free(base_msg); return MOSQ_ERR_TOPIC_ALIAS_INVALID; }else if(topic_alias > 0){ if(base_msg->data.topic){ rc = alias__add_r2l(context, base_msg->data.topic, (uint16_t)topic_alias); if(rc){ db__msg_store_free(base_msg); return rc; } }else{ rc = alias__find_by_alias(context, ALIAS_DIR_R2L, (uint16_t)topic_alias, &base_msg->data.topic); if(rc){ db__msg_store_free(base_msg); log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: PUBLISH invalid topic alias (%d).", context->id, topic_alias); return MOSQ_ERR_PROTOCOL; } } } #ifdef WITH_BRIDGE rc = bridge__remap_topic_in(context, &base_msg->data.topic); if(rc){ db__msg_store_free(base_msg); return rc; } #endif if(mosquitto_pub_topic_check(base_msg->data.topic) != MOSQ_ERR_SUCCESS){ /* Invalid publish topic, just swallow it. */ db__msg_store_free(base_msg); return MOSQ_ERR_MALFORMED_PACKET; } base_msg->data.payloadlen = context->in_packet.remaining_length - context->in_packet.pos; metrics__int_inc(mosq_counter_pub_bytes_received, base_msg->data.payloadlen); if(context->listener && context->listener->mount_point){ len = strlen(context->listener->mount_point) + strlen(base_msg->data.topic) + 1; topic_mount = mosquitto_malloc(len+1); if(!topic_mount){ db__msg_store_free(base_msg); return MOSQ_ERR_NOMEM; } snprintf(topic_mount, len, "%s%s", context->listener->mount_point, base_msg->data.topic); topic_mount[len] = '\0'; mosquitto_FREE(base_msg->data.topic); base_msg->data.topic = topic_mount; } if(base_msg->data.payloadlen){ if(db.config->message_size_limit && base_msg->data.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, base_msg->data.qos, base_msg->data.retain, base_msg->data.source_mid, base_msg->data.topic, (long)base_msg->data.payloadlen); return process_bad_message(context, base_msg, MQTT_RC_PACKET_TOO_LARGE); } base_msg->data.payload = mosquitto_malloc(base_msg->data.payloadlen+1); if(base_msg->data.payload == NULL){ db__msg_store_free(base_msg); return MOSQ_ERR_NOMEM; } /* Ensure payload is always zero terminated, this is the reason for the extra byte above */ ((uint8_t *)base_msg->data.payload)[base_msg->data.payloadlen] = 0; if(packet__read_bytes(&context->in_packet, base_msg->data.payload, base_msg->data.payloadlen)){ db__msg_store_free(base_msg); return MOSQ_ERR_MALFORMED_PACKET; } } /* Check for topic access */ rc = mosquitto_acl_check(context, base_msg->data.topic, base_msg->data.payloadlen, base_msg->data.payload, base_msg->data.qos, base_msg->data.retain, base_msg->data.properties, 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, base_msg->data.qos, base_msg->data.retain, base_msg->data.source_mid, base_msg->data.topic, (long)base_msg->data.payloadlen); return process_bad_message(context, base_msg, MQTT_RC_NOT_AUTHORIZED); }else if(rc != MOSQ_ERR_SUCCESS){ db__msg_store_free(base_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, base_msg->data.qos, base_msg->data.retain, base_msg->data.source_mid, base_msg->data.topic, (long)base_msg->data.payloadlen); if(!strncmp(base_msg->data.topic, "$CONTROL/", 9)){ #ifdef WITH_CONTROL rc = control__process(context, base_msg); db__msg_store_free(base_msg); return rc; #else return process_bad_message(context, base_msg, MQTT_RC_IMPLEMENTATION_SPECIFIC); #endif } return handle__accepted_publish(context, base_msg, mid, dup, &message_expiry_interval); } ================================================ FILE: src/handle_subscribe.c ================================================ /* Copyright (c) 2009-2021 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 "mosquitto/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; 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; struct mosquitto_subscription sub; uint32_t subscription_identifier = 0; if(!context){ return MOSQ_ERR_INVAL; } if(context->state != mosq_cs_active){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: SUBSCRIBE before session is active.", context->id); return MOSQ_ERR_PROTOCOL; } if(context->in_packet.command != (CMD_SUBSCRIBE|2)){ return MOSQ_ERR_MALFORMED_PACKET; } 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){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: SUBSCRIBE packet with invalid properties.", context->id); 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){ memset(&sub, 0, sizeof(sub)); sub.identifier = subscription_identifier; sub.properties = properties; if(packet__read_string(&context->in_packet, &sub.topic_filter, &slen)){ mosquitto_FREE(payload); return MOSQ_ERR_MALFORMED_PACKET; } if(sub.topic_filter){ if(!slen){ log__printf(NULL, MOSQ_LOG_INFO, "Empty subscription string from %s, disconnecting.", context->address); mosquitto_FREE(sub.topic_filter); mosquitto_FREE(payload); return MOSQ_ERR_MALFORMED_PACKET; } if(mosquitto_sub_topic_check(sub.topic_filter)){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid subscription string from %s, disconnecting.", context->address); mosquitto_FREE(sub.topic_filter); mosquitto_FREE(payload); return MOSQ_ERR_MALFORMED_PACKET; } if(packet__read_byte(&context->in_packet, &sub.options)){ mosquitto_FREE(sub.topic_filter); mosquitto_FREE(payload); return MOSQ_ERR_MALFORMED_PACKET; } if(sub.options & MQTT_SUB_OPT_NO_LOCAL && !strncmp(sub.topic_filter, "$share/", strlen("$share/"))){ mosquitto_FREE(sub.topic_filter); mosquitto_FREE(payload); log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: $share subscription with no-local set.", context->id); return MOSQ_ERR_PROTOCOL; } if(context->protocol == mosq_p_mqtt31 || context->protocol == mosq_p_mqtt311){ qos = sub.options; sub.options = 0; if(context->is_bridge){ sub.options |= MQTT_SUB_OPT_RETAIN_AS_PUBLISHED | MQTT_SUB_OPT_NO_LOCAL; } }else{ qos = sub.options & 0x03; sub.options &= 0xFC; if(MQTT_SUB_OPT_GET_NO_LOCAL(sub.options) && !strncmp(sub.topic_filter, "$share/", 7)){ mosquitto_FREE(sub.topic_filter); mosquitto_FREE(payload); return MOSQ_ERR_PROTOCOL; } retain_handling = MQTT_SUB_OPT_GET_RETAIN_HANDLING(sub.options); if(retain_handling == 0x30 || (sub.options & 0xC0) != 0){ mosquitto_FREE(sub.topic_filter); 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.topic_filter); mosquitto_FREE(payload); return MOSQ_ERR_MALFORMED_PACKET; } if(qos > context->max_qos){ qos = context->max_qos; } sub.options |= 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.topic_filter); mosquitto_FREE(payload); return MOSQ_ERR_NOMEM; } snprintf(sub_mount, len, "%s%s", context->listener->mount_point, sub.topic_filter); sub_mount[len] = '\0'; mosquitto_FREE(sub.topic_filter); sub.topic_filter = sub_mount; } allowed = true; rc2 = mosquitto_acl_check(context, sub.topic_filter, 0, NULL, qos, false, properties, 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.topic_filter); mosquitto_FREE(payload); return rc2; } if(qos > 127){ log__printf(NULL, MOSQ_LOG_DEBUG, "\t%s (denied)", sub.topic_filter); }else{ log__printf(NULL, MOSQ_LOG_DEBUG, "\t%s (QoS %d)", sub.topic_filter, qos); } if(allowed){ rc2 = plugin__handle_subscribe(context, &sub); if(rc2){ mosquitto_FREE(sub.topic_filter); mosquitto_FREE(payload); return rc2; } rc2 = sub__add(context, &sub); if(rc2 > 0){ mosquitto_FREE(sub.topic_filter); mosquitto_FREE(payload); 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)){ mosquitto_FREE(sub.topic_filter); mosquitto_FREE(payload); return rc; } } }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)){ mosquitto_FREE(sub.topic_filter); mosquitto_FREE(payload); return rc; } } } log__printf(NULL, MOSQ_LOG_SUBSCRIBE, "%s %d %s", context->id, qos, sub.topic_filter); plugin_persist__handle_subscription_add(context, &sub); } mosquitto_FREE(sub.topic_filter); 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->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; } ================================================ FILE: src/handle_unsubscribe.c ================================================ /* Copyright (c) 2009-2021 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 "mosquitto/mqtt_protocol.h" #include "packet_mosq.h" #include "send_mosq.h" int handle__unsubscribe(struct mosquitto *context) { uint16_t mid; 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; struct mosquitto_subscription sub; if(!context){ return MOSQ_ERR_INVAL; } if(context->state != mosq_cs_active){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: UNSUBSCRIBE before session is active.", context->id); return MOSQ_ERR_PROTOCOL; } if(context->in_packet.command != (CMD_UNSUBSCRIBE|2)){ return MOSQ_ERR_MALFORMED_PACKET; } 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){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: UNSUBSCRIBE packet with invalid properties.", context->id); 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){ memset(&sub, 0, sizeof(sub)); sub.properties = properties; if(packet__read_string(&context->in_packet, &sub.topic_filter, &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.topic_filter); mosquitto_FREE(reason_codes); return MOSQ_ERR_MALFORMED_PACKET; } if(mosquitto_sub_topic_check(sub.topic_filter)){ log__printf(NULL, MOSQ_LOG_INFO, "Invalid unsubscription string from %s, disconnecting.", context->id); mosquitto_FREE(sub.topic_filter); mosquitto_FREE(reason_codes); return MOSQ_ERR_MALFORMED_PACKET; } /* ACL check */ allowed = true; rc = mosquitto_acl_check(context, sub.topic_filter, 0, NULL, 0, false, properties, 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.topic_filter); mosquitto_FREE(reason_codes); return rc; } log__printf(NULL, MOSQ_LOG_DEBUG, "\t%s", sub.topic_filter); if(allowed){ rc = plugin__handle_unsubscribe(context, &sub); if(rc){ mosquitto_FREE(sub.topic_filter); mosquitto_FREE(reason_codes); return rc; } rc = sub__remove(context, sub.topic_filter, &reason); plugin_persist__handle_subscription_delete(context, sub.topic_filter); }else{ rc = MOSQ_ERR_SUCCESS; } log__printf(NULL, MOSQ_LOG_UNSUBSCRIBE, "%s %s", context->id, sub.topic_filter); mosquitto_FREE(sub.topic_filter); 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; } ================================================ FILE: src/http_api.c ================================================ /* Copyright (c) 2025 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef WITH_HTTP_API #include #include #include #include #include #include #ifndef WIN32 # include #endif #include "json_help.h" #include "mosquitto_broker_internal.h" #include "mosquitto/mqtt_protocol.h" #include "sys_tree.h" #ifndef HTTP_API_DIR # define HTTP_API_DIR "" #endif struct metric { int64_t current; int64_t next; const char *topic, *topic_alias; bool is_max; }; time_t broker_uptime(void); struct MHD_Daemon *mhd = NULL; #ifdef WITH_SYS_TREE extern struct metric metrics[mosq_metric_max]; #endif #define HTTP_RESPONSE_BUFLEN 10000 #ifdef WIN32 #define DIR_SEP '\\' #define PATH_MAX MAX_PATH #else #define DIR_SEP '/' #endif #ifndef S_ISREG #define S_ISREG(mode) (((mode)&S_IFMT) == S_IFREG) #endif static char *http__canonical_filename( const char *url, const char *http_dir, int *error_code) { size_t urllen, slen; char *filename, *filename_canonical; urllen = strlen(url); if(url[urllen-1] == '/'){ slen = strlen(http_dir) + urllen + strlen("/index.html") + 2; }else{ slen = strlen(http_dir) + urllen + 2; } filename = mosquitto_malloc(slen); if(!filename){ *error_code = MHD_HTTP_INTERNAL_SERVER_ERROR; return NULL; } if(((char *)url)[urllen-1] == '/'){ snprintf(filename, slen, "%s%c%sindex.html", http_dir, DIR_SEP, url); }else{ snprintf(filename, slen, "%s%c%s", http_dir, DIR_SEP, url); } /* Get canonical path and check it is within our http_dir */ filename_canonical = mosquitto_calloc(1, PATH_MAX); if(!filename_canonical){ *error_code = MHD_HTTP_INTERNAL_SERVER_ERROR; return NULL; } #ifdef WIN32 char *resolved = _fullpath(filename_canonical, filename, PATH_MAX); mosquitto_FREE(filename); if(!resolved){ *error_code = MHD_HTTP_INTERNAL_SERVER_ERROR; mosquitto_FREE(filename_canonical); return NULL; } #else char *resolved = realpath(filename, filename_canonical); mosquitto_FREE(filename); if(!resolved){ if(errno == EACCES){ *error_code = MHD_HTTP_FORBIDDEN; }else if(errno == EINVAL || errno == EIO || errno == ELOOP){ *error_code = MHD_HTTP_INTERNAL_SERVER_ERROR; }else if(errno == ENAMETOOLONG){ *error_code = MHD_HTTP_URI_TOO_LONG; }else if(errno == ENOENT || errno == ENOTDIR){ *error_code = MHD_HTTP_NOT_FOUND; } mosquitto_FREE(filename_canonical); return NULL; } #endif if(strncmp(http_dir, filename_canonical, strlen(http_dir))){ /* Requested file isn't within http_dir, deny access because it's not found. */ mosquitto_FREE(filename_canonical); *error_code = MHD_HTTP_NOT_FOUND; return NULL; } return filename_canonical; } static enum MHD_Result http_api__send_error_response(struct MHD_Connection *connection, const char *error_str, unsigned int error_code) { struct MHD_Response *response = MHD_create_response_from_buffer(strlen(error_str), (void *)error_str, MHD_RESPMEM_MUST_COPY); enum MHD_Result ret = MHD_queue_response(connection, error_code, response); MHD_destroy_response(response); return ret; } static enum MHD_Result http_api__send_response_with_headers(struct MHD_Connection *connection, const char *buf) { enum MHD_Result ret; struct MHD_Response *response = MHD_create_response_from_buffer(strlen(buf), (void *)buf, MHD_RESPMEM_MUST_COPY); ret = MHD_add_response_header(response, "Access-Control-Allow-Origin", "*"); if(ret != MHD_YES){ MHD_destroy_response(response); return ret; } ret = MHD_queue_response(connection, MHD_HTTP_OK, response); MHD_destroy_response(response); return ret; } static enum MHD_Result http_api__process_version(struct MHD_Connection *connection) { return http_api__send_response_with_headers(connection, VERSION); } static enum MHD_Result http_api__process_listeners(struct MHD_Connection *connection) { char *buf; enum MHD_Result ret; cJSON *j_tree = cJSON_CreateObject(); if(!j_tree){ return http_api__send_error_response(connection, "Internal server error.\n", MHD_HTTP_INTERNAL_SERVER_ERROR); } cJSON *j_listeners = cJSON_AddArrayToObject(j_tree, "listeners"); if(!j_listeners){ cJSON_Delete(j_tree); return http_api__send_error_response(connection, "Internal server error.\n", MHD_HTTP_INTERNAL_SERVER_ERROR); } for(int i=0; ilistener_count; i++){ cJSON *j_listener = cJSON_CreateObject(); if(!j_listener){ cJSON_Delete(j_tree); return http_api__send_error_response(connection, "Internal server error.\n", MHD_HTTP_INTERNAL_SERVER_ERROR); } cJSON_AddItemToArray(j_listeners, j_listener); struct mosquitto__listener *listener = &db.config->listeners[i]; #ifdef WITH_UNIX_SOCKETS if(listener->unix_socket_path){ cJSON_AddStringToObject(j_listener, "path", listener->unix_socket_path); }else #endif { cJSON_AddIntToObject(j_listener, "port", listener->port); } switch(listener->protocol){ case mp_mqtt: cJSON_AddStringToObject(j_listener, "protocol", "mqtt"); break; case mp_mqttsn: cJSON_AddStringToObject(j_listener, "protocol", "mqtt-sn"); break; case mp_websockets: cJSON_AddStringToObject(j_listener, "protocol", "websockets"); break; case mp_http_api: cJSON_AddStringToObject(j_listener, "protocol", "httpapi"); break; } #ifdef WITH_TLS cJSON_AddBoolToObject(j_listener, "tls", listener->certfile && listener->keyfile); cJSON_AddBoolToObject(j_listener, "mtls", listener->require_certificate); #endif if(listener->security_options->allow_anonymous == -1){ cJSON_AddBoolToObject(j_listener, "allow_anonymous", db.config->security_options.allow_anonymous); }else{ cJSON_AddBoolToObject(j_listener, "allow_anonymous", listener->security_options->allow_anonymous); } } buf = cJSON_Print(j_tree); cJSON_Delete(j_tree); if(buf){ ret = http_api__send_response_with_headers(connection, buf); free(buf); }else{ ret = http_api__send_error_response(connection, "Internal server error.\n", MHD_HTTP_INTERNAL_SERVER_ERROR); } return ret; } static enum MHD_Result http_api__process_systree(struct MHD_Connection *connection) { enum MHD_Result ret; #ifdef WITH_SYS_TREE char *buf; cJSON *j_tree = cJSON_CreateObject(); for(int i=0; ihttp_dir){ http_api__send_error_response(connection, "Not found.\n", 404); return MHD_YES; } canonical_filename = http__canonical_filename(url, listener->http_dir, &error_code); if(!canonical_filename){ http_api__send_error_response(connection, "Not found.\n", 404); return MHD_YES; } FILE *fptr = fopen(canonical_filename, "rb"); mosquitto_FREE(canonical_filename); if(!fptr){ http_api__send_error_response(connection, "Not found.\n", 404); return MHD_YES; } struct stat statbuf; if(fstat(fileno(fptr), &statbuf)){ fclose(fptr); http_api__send_error_response(connection, "Internal server error.\n", 500); return MHD_YES; } if(!S_ISREG(statbuf.st_mode)){ fclose(fptr); http_api__send_error_response(connection, "Not found.\n", 404); return MHD_YES; } uint64_t flen = (uint64_t )statbuf.st_size; /* Using MHD_create_response_from_fd would be easier here, but is less portable */ struct MHD_Response *response = MHD_create_response_from_callback( flen, 65536, http_file_read_cb, fptr, http_file_free_cb); enum MHD_Result ret = MHD_queue_response(connection, 200, response); MHD_destroy_response(response); return ret; } static enum MHD_Result http_api__process_api(struct MHD_Connection *connection, const char *url) { if(strcmp(url, "/api/v1/systree") == 0){ return http_api__process_systree(connection); }else if(strcmp(url, "/api/v1/listeners") == 0){ return http_api__process_listeners(connection); }else if(strcmp(url, "/api/v1/version") == 0){ return http_api__process_version(connection); }else{ return http_api__send_error_response(connection, "Not found.\n", 404); } } static int check_access(struct mosquitto__listener *listener, struct MHD_Connection *connection, const char *url) { struct mosquitto context = {0}; int auth_rc, acl_rc = MOSQ_ERR_SUCCESS; context.listener = listener; context.id = (char *)"http-api"; context.username = MHD_basic_auth_get_username_password(connection, &context.password); /* Authentication */ auth_rc = mosquitto_basic_auth(&context); if(auth_rc == MOSQ_ERR_SUCCESS){ acl_rc = mosquitto_acl_check(&context, url, 0, NULL, 0, false, NULL, MOSQ_ACL_READ); } MHD_free(context.username); MHD_free(context.password); if(auth_rc || acl_rc){ const char *buf = "Not authorised\n"; struct MHD_Response *response = MHD_create_response_from_buffer(strlen(buf), (void *)buf, MHD_RESPMEM_MUST_COPY); MHD_queue_basic_auth_fail_response(connection, "Mosquitto API", response); MHD_destroy_response(response); return MOSQ_ERR_AUTH; } return MOSQ_ERR_SUCCESS; } static enum MHD_Result http_api_handler(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls) { UNUSED(version); UNUSED(upload_data); UNUSED(upload_data_size); UNUSED(con_cls); struct mosquitto__listener *listener = cls; if(strcmp(method, "GET") != 0){ char *buf = "Invalid HTTP Method\n"; struct MHD_Response *response = MHD_create_response_from_buffer(strlen(buf), (void *)buf, MHD_RESPMEM_MUST_COPY); enum MHD_Result ret = MHD_queue_response(connection, MHD_HTTP_METHOD_NOT_ALLOWED, response); MHD_destroy_response(response); return ret; } if(check_access(listener, connection, url) != MOSQ_ERR_SUCCESS){ return MHD_YES; } if(!strncasecmp(url, "/api/", strlen("/api/"))){ return http_api__process_api(connection, url); }else{ return http_api__process_file(listener, connection, url); } } int http_api__start_local(struct mosquitto__listener *listener) { listener->security_options = mosquitto_calloc(1, sizeof(struct mosquitto__security_options)); if(listener->security_options == NULL){ return MOSQ_ERR_NOMEM; } listener->host = mosquitto_strdup("127.0.0.1"); if(!listener->host){ mosquitto_FREE(listener->security_options); return MOSQ_ERR_NOMEM; } listener->port = 9883; if(db.config->security_options.allow_anonymous == -1){ listener->security_options->allow_anonymous = true; }else{ listener->security_options->allow_anonymous = db.config->security_options.allow_anonymous; } if(listener->http_dir == NULL && strlen(HTTP_API_DIR) > 0){ #ifdef WIN32 char *http_dir_canonical = _fullpath(NULL, HTTP_API_DIR, 0); #else char *http_dir_canonical = realpath(HTTP_API_DIR, NULL); #endif if(!http_dir_canonical){ return MOSQ_ERR_NOMEM; } mosquitto_FREE(listener->http_dir); listener->http_dir = mosquitto_strdup(http_dir_canonical); mosquitto_FREE(http_dir_canonical); } return http_api__start(listener); } int http_api__start(struct mosquitto__listener *listener) { unsigned int flags = MHD_USE_AUTO_INTERNAL_THREAD; const char *bind_address; uint16_t port = 9883; char *x509_cert = NULL; char *x509_key = NULL; if(!listener->security_options){ listener->security_options = mosquitto_calloc(1, sizeof(struct mosquitto__security_options)); if(listener->security_options == NULL){ return MOSQ_ERR_NOMEM; } } listener->protocol = mp_http_api; bind_address = listener->host; port = listener->port; #ifdef WITH_TLS if(listener->certfile && listener->keyfile){ if(mosquitto_read_file(listener->certfile, false, &x509_cert, NULL)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load server certificate \"%s\". Check certfile.", listener->certfile); return MOSQ_ERR_INVAL; } if(mosquitto_read_file(listener->keyfile, false, &x509_key, NULL)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load server key file \"%s\". Check keyfile.", listener->keyfile); mosquitto_FREE(x509_cert); return MOSQ_ERR_INVAL; } flags |= MHD_USE_TLS; } #endif if(bind_address){ char service[10]; struct addrinfo hints; struct addrinfo *ainfo, *rp; snprintf(service, sizeof(service), "%d", port); memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_flags = AI_PASSIVE; hints.ai_socktype = SOCK_STREAM; int rc = getaddrinfo(bind_address, service, &hints, &ainfo); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Unable to start http api listener."); mosquitto_FREE(x509_cert); mosquitto_FREE(x509_key); return MOSQ_ERR_ERRNO; } for(rp = ainfo; rp; rp = rp->ai_next){ if(rp->ai_family == AF_INET || rp->ai_family == AF_INET6){ break; } } if(!rp){ log__printf(NULL, MOSQ_LOG_ERR, "Unable to start http api listener, could not find address."); freeaddrinfo(ainfo); mosquitto_FREE(x509_cert); mosquitto_FREE(x509_key); return MOSQ_ERR_INVAL; } if(rp->ai_family == AF_INET6){ flags |= MHD_USE_IPv6; } if(x509_cert && x509_key){ listener->mhd = MHD_start_daemon(flags, port, NULL, NULL, &http_api_handler, listener, MHD_OPTION_SOCK_ADDR, rp->ai_addr, MHD_OPTION_HTTPS_MEM_CERT, x509_cert, MHD_OPTION_HTTPS_MEM_KEY, x509_key, MHD_OPTION_END); }else{ listener->mhd = MHD_start_daemon(flags, port, NULL, NULL, &http_api_handler, listener, MHD_OPTION_SOCK_ADDR, rp->ai_addr, MHD_OPTION_END); } freeaddrinfo(ainfo); }else{ if(x509_cert && x509_key){ listener->mhd = MHD_start_daemon(flags | MHD_USE_DUAL_STACK, port, NULL, NULL, &http_api_handler, listener, MHD_OPTION_HTTPS_MEM_CERT, x509_cert, MHD_OPTION_HTTPS_MEM_KEY, x509_key, MHD_OPTION_END); }else{ listener->mhd = MHD_start_daemon(flags | MHD_USE_DUAL_STACK, port, NULL, NULL, &http_api_handler, listener, MHD_OPTION_END); } } mosquitto_FREE(x509_cert); mosquitto_FREE(x509_key); if(listener->mhd){ log__printf(NULL, MOSQ_LOG_INFO, "Opening http api listen socket on port %d.", port); if(listener->http_dir){ log__printf(NULL, MOSQ_LOG_INFO, "Using http_dir %s", listener->http_dir); } return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_UNKNOWN; } } void http_api__stop(struct mosquitto__listener *listener) { MHD_stop_daemon(listener->mhd); listener->mhd = NULL; } #endif ================================================ FILE: src/http_serv.c ================================================ /* Copyright (c) 2021 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN #include #include #include #include "mosquitto_broker_internal.h" #include "mosquitto/mqtt_protocol.h" #include "net_mosq.h" #include "packet_mosq.h" #include "read_handle.h" #include "sys_tree.h" #include "util_mosq.h" #include "picohttpparser.h" int http__context_init(struct mosquitto *context) { context->transport = mosq_t_http; return MOSQ_ERR_SUCCESS; } int http__context_cleanup(struct mosquitto *context) { UNUSED(context); return MOSQ_ERR_SUCCESS; } int http__read(struct mosquitto *mosq) { ssize_t read_length; ssize_t header_length; enum mosquitto_client_state state; size_t hlen; const char *http_method, *http_path; size_t http_method_len, http_path_len; int http_minor_version; size_t http_header_count = 100; struct phr_header http_headers[100]; const char *client_key = NULL; size_t client_key_len = 0; char *accept_key; bool header_have_upgrade; bool header_have_connection; struct mosquitto__packet *packet; int rc; const char *subprotocol = NULL; int subprotocol_len = 0; 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; } hlen = strlen((char *)mosq->in_packet.packet_buffer); read_length = net__read(mosq, &mosq->in_packet.packet_buffer[hlen], mosq->in_packet.packet_buffer_size-hlen); if(read_length <= 0){ 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; } } } mosq->in_packet.packet_buffer[mosq->in_packet.packet_buffer_size-1] = '\0'; /* Always 0 terminate */ header_length = phr_parse_request((char *)mosq->in_packet.packet_buffer, strlen((char *)mosq->in_packet.packet_buffer), &http_method, &http_method_len, &http_path, &http_path_len, &http_minor_version, http_headers, &http_header_count, 0); // FIXME - deal with partial read ! if(header_length == -2){ // Partial read return MOSQ_ERR_SUCCESS; }else if(header_length == -1){ // Error return MOSQ_ERR_UNKNOWN; }else if(header_length < read_length){ /* Excess data which can't be handled because the client doesn't have a key yet */ return MOSQ_ERR_MALFORMED_PACKET; } if(strncmp(http_method, "GET", http_method_len) && strncmp(http_method, "HEAD", http_method_len)){ /* FIXME Not supported - send 501 response */ return MOSQ_ERR_UNKNOWN; } header_have_upgrade = false; header_have_connection = false; subprotocol = NULL; for(size_t i=0; ilistener){ bool have_match = false; for(int j=0; jlistener->ws_origin_count; j++){ if(!strncmp(mosq->listener->ws_origins[j], http_headers[i].value, http_headers[i].value_len)){ have_match = true; break; } } if(!have_match && mosq->listener->ws_origin_count > 0){ return MOSQ_ERR_HTTP_BAD_ORIGIN; } } }else{ /* Unknown header */ } } if(subprotocol == NULL){ // FIXME ? return MOSQ_ERR_UNKNOWN; } if(header_have_upgrade == false || header_have_connection == false || client_key == NULL || client_key_len == 0){ // FIXME - 404 return MOSQ_ERR_UNKNOWN; } if(ws__create_accept_key(client_key, client_key_len, &accept_key)){ return MOSQ_ERR_UNKNOWN; } packet = mosquitto_calloc(1, sizeof(struct mosquitto__packet) + 1024 + WS_PACKET_OFFSET); if(!packet){ SAFE_FREE(accept_key); return MOSQ_ERR_NOMEM; } packet->packet_length = (uint32_t )snprintf((char *)&packet->payload[WS_PACKET_OFFSET], 1024, "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: WebSocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: %s\r\n" "Sec-WebSocket-Protocol: %.*s\r\n" "\r\n", accept_key, subprotocol_len, subprotocol) + WS_PACKET_OFFSET; SAFE_FREE(accept_key); packet->to_process = packet->packet_length; memset(mosq->in_packet.packet_buffer, 0, db.config->packet_buffer_size); rc = packet__queue(mosq, packet); http__context_cleanup(mosq); ws__context_init(mosq); return rc; } #endif ================================================ FILE: src/keepalive.c ================================================ /* Copyright (c) 2009-2021 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 /* This contains code for checking whether clients have exceeded their keepalive timeouts. * There are two versions. * * The old version can be used by compiling with `make WITH_OLD_KEEPALIVE=yes`. * It will scan the entire list of connected clients every 5 seconds to see if * they have expired. Hence it scales with O(n) and with e.g. 60000 clients can * have a measurable effect on CPU usage in the low single digit percent range. * * The new version scales with O(1). It uses a ring buffer that contains * max_keepalive*1.5+1 entries. The current time in integer seconds, modulus * the number of entries, points to the head of the ring buffer. Any clients * will appear after this point at the position indexed by the time at which * they will expire if they do not send another message, assuming they do not * have keepalive==0 - in which case they are not part of this check. So a * client that connects with keepalive=60 will be added at `now + 60*1.5`. * * A client is added to an entry with a doubly linked list. When the client * sends a new message, it is removed from the old position and added to the * new. * * As time moves on, if the linked list at the current entry is not empty, all * of the clients are expired. * * The ring buffer size is determined by max_keepalive. At the default, it is * 65535*1.5+1=98303 entries long. On a 64-bit machine that is 786424 bytes. * If this is too big a burden and you do not need many clients connected, then * the old check is sufficient. You can reduce the number of entries by setting * a lower max_keepalive value. A value as low as 600 still gives a 10 minute * keepalive and reduces the memory for the ring buffer to 7208 bytes. * * *NOTE* It is likely that the old check routine will be removed in the * future, and max_keepalive set to a sensible default value. If this is a * problem for you please get in touch. */ static time_t last_keepalive_check = 0; #ifndef WITH_OLD_KEEPALIVE static int keepalive_list_max = 0; static struct mosquitto **keepalive_list = NULL; #endif #ifndef WITH_OLD_KEEPALIVE static int calc_index(struct mosquitto *context) { return (int)(context->last_msg_in + context->keepalive*3/2) % keepalive_list_max; } #endif int keepalive__init(void) { #ifndef WITH_OLD_KEEPALIVE struct mosquitto *context, *ctxt_tmp; if(db.config->max_keepalive <= 0){ keepalive_list_max = (UINT16_MAX * 3)/2 + 1; }else{ keepalive_list_max = (db.config->max_keepalive * 3)/2 + 1; } keepalive_list = mosquitto_calloc((size_t)keepalive_list_max, sizeof(struct mosquitto *)); if(keepalive_list == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); keepalive_list_max = 0; return MOSQ_ERR_NOMEM; } /* Add existing clients - should only be applicable on MOSQ_EVT_RELOAD */ HASH_ITER(hh_sock, db.contexts_by_sock, context, ctxt_tmp){ if(net__is_connected(context) && !context->bridge && context->keepalive > 0){ keepalive__add(context); } } #endif last_keepalive_check = db.now_s; return MOSQ_ERR_SUCCESS; } void keepalive__cleanup(void) { #ifndef WITH_OLD_KEEPALIVE for(int idx=0; idxkeepalive <= 0 || !net__is_connected(context)){ return MOSQ_ERR_SUCCESS; } #ifdef WITH_BRIDGE if(context->bridge){ return MOSQ_ERR_SUCCESS; } #endif DL_APPEND2(keepalive_list[calc_index(context)], context, keepalive_prev, keepalive_next); context->keepalive_add_time = db.now_s; #else UNUSED(context); #endif return MOSQ_ERR_SUCCESS; } #ifndef WITH_OLD_KEEPALIVE void keepalive__check(void) { struct mosquitto *context, *ctxt_tmp; time_t timeout; if(db.contexts_by_sock){ /* Check the next 5 seconds for upcoming expiries */ /* FIXME - find the actual next entry without having to iterate over * the whole list */ timeout = 5; for(time_t i=5; i>0; i--){ if(keepalive_list[(db.now_s + i) % keepalive_list_max]){ timeout = i; } } loop__update_next_event(timeout*1000); } for(time_t i=last_keepalive_check; ikeepalive_add_time <= last_keepalive_check && net__is_connected(context)){ /* Client has exceeded keepalive*1.5 */ do_disconnect(context, MOSQ_ERR_KEEPALIVE); } } } } last_keepalive_check = db.now_s; } #else void keepalive__check(void) { struct mosquitto *context, *ctxt_tmp; time_t timeout; if(db.contexts_by_sock){ timeout = (last_keepalive_check + 5 - db.now_s); if(timeout <= 0){ timeout = 5; } loop__update_next_event(timeout*1000); } if(last_keepalive_check + 5 <= db.now_s){ last_keepalive_check = db.now_s; HASH_ITER(hh_sock, db.contexts_by_sock, context, ctxt_tmp){ if(net__is_connected(context)){ /* 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); } } } } } #endif int keepalive__remove(struct mosquitto *context) { #ifndef WITH_OLD_KEEPALIVE int idx; if(context->keepalive <= 0 || context->keepalive_prev == NULL){ return MOSQ_ERR_SUCCESS; } idx = calc_index(context); if(keepalive_list[idx]){ DL_DELETE2(keepalive_list[idx], context, keepalive_prev, keepalive_next); context->keepalive_next = NULL; context->keepalive_prev = NULL; } #else UNUSED(context); #endif return MOSQ_ERR_SUCCESS; } int keepalive__update(struct mosquitto *context) { #ifndef WITH_OLD_KEEPALIVE keepalive__remove(context); /* coverity[missing_lock] - broker is single threaded, so no lock required */ context->last_msg_in = db.now_s; keepalive__add(context); #else UNUSED(context); #endif return MOSQ_ERR_SUCCESS; } ================================================ FILE: src/linker-aix.syms ================================================ mosquitto_apply_on_all_clients mosquitto_broker_node_id_set mosquitto_broker_publish mosquitto_broker_publish_copy mosquitto_callback_register mosquitto_callback_unregister mosquitto_calloc mosquitto_client mosquitto_client_address mosquitto_client_certificate mosquitto_client_clean_session mosquitto_client_id mosquitto_client_id_hashv mosquitto_client_keepalive mosquitto_client_port mosquitto_client_protocol mosquitto_client_protocol_version mosquitto_client_sub_count mosquitto_client_username mosquitto_complete_basic_auth mosquitto_control_command_reply mosquitto_control_generic_callback mosquitto_control_send_response mosquitto_free mosquitto_kick_client_by_clientid mosquitto_kick_client_by_username mosquitto_log_printf mosquitto_log_vprintf mosquitto_malloc mosquitto_persist_base_msg_add mosquitto_persist_base_msg_delete mosquitto_persist_client_add mosquitto_persist_client_delete mosquitto_persist_client_msg_add mosquitto_persist_client_msg_clear mosquitto_persist_client_msg_delete mosquitto_persist_client_msg_update mosquitto_persist_client_update mosquitto_persist_retain_msg_delete mosquitto_persist_retain_msg_set mosquitto_persistence_location mosquitto_plugin_set_info 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_identifier mosquitto_property_identifier_to_string mosquitto_property_next 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_pub_topic_check2 mosquitto_pub_topic_check mosquitto_realloc mosquitto_set_clientid mosquitto_set_username mosquitto_strdup mosquitto_string_to_property_info mosquitto_strndup mosquitto_sub_matches_acl mosquitto_sub_matches_acl_with_pattern mosquitto_sub_topic_check2 mosquitto_sub_topic_check mosquitto_subscription_add mosquitto_subscription_delete mosquitto_topic_matches_sub2 mosquitto_topic_matches_sub mosquitto_topic_matches_sub_with_pattern mosquitto_validate_utf8 ================================================ FILE: src/linker-macosx.syms ================================================ _mosquitto_apply_on_all_clients _mosquitto_broker_node_id_set _mosquitto_broker_publish _mosquitto_broker_publish_copy _mosquitto_callback_register _mosquitto_callback_unregister _mosquitto_calloc _mosquitto_client _mosquitto_client_address _mosquitto_client_certificate _mosquitto_client_clean_session _mosquitto_client_id _mosquitto_client_id_hashv _mosquitto_client_keepalive _mosquitto_client_port _mosquitto_client_protocol _mosquitto_client_protocol_version _mosquitto_client_sub_count _mosquitto_client_username _mosquitto_client_will_set _mosquitto_complete_basic_auth _mosquitto_control_command_reply _mosquitto_control_generic_callback _mosquitto_control_send_response _mosquitto_free _mosquitto_kick_client_by_clientid _mosquitto_kick_client_by_username _mosquitto_log_printf _mosquitto_log_vprintf _mosquitto_malloc _mosquitto_persist_base_msg_add _mosquitto_persist_base_msg_delete _mosquitto_persist_client_add _mosquitto_persist_client_delete _mosquitto_persist_client_msg_add _mosquitto_persist_client_msg_clear _mosquitto_persist_client_msg_delete _mosquitto_persist_client_msg_update _mosquitto_persist_client_update _mosquitto_persist_retain_msg_delete _mosquitto_persist_retain_msg_set _mosquitto_persistence_location _mosquitto_plugin_set_info _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_identifier _mosquitto_property_identifier_to_string _mosquitto_property_next _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_pub_topic_check _mosquitto_pub_topic_check2 _mosquitto_realloc _mosquitto_set_clientid _mosquitto_set_username _mosquitto_strdup _mosquitto_string_to_property_info _mosquitto_strndup _mosquitto_sub_matches_acl _mosquitto_sub_matches_acl_with_pattern _mosquitto_sub_topic_check _mosquitto_sub_topic_check2 _mosquitto_subscription_add _mosquitto_subscription_delete _mosquitto_topic_matches_sub _mosquitto_topic_matches_sub2 _mosquitto_topic_matches_sub_with_pattern _mosquitto_validate_utf8 ================================================ FILE: src/linker.syms ================================================ { mosquitto_apply_on_all_clients; mosquitto_broker_node_id_set; mosquitto_broker_publish; mosquitto_broker_publish_copy; mosquitto_callback_register; mosquitto_callback_unregister; mosquitto_calloc; mosquitto_client; mosquitto_client_address; mosquitto_client_certificate; mosquitto_client_clean_session; mosquitto_client_id; mosquitto_client_id_hashv; mosquitto_client_keepalive; mosquitto_client_port; mosquitto_client_protocol; mosquitto_client_protocol_version; mosquitto_client_sub_count; mosquitto_client_username; mosquitto_client_will_set; mosquitto_complete_basic_auth; mosquitto_control_command_reply; mosquitto_control_generic_callback; mosquitto_control_send_response; mosquitto_free; mosquitto_kick_client_by_clientid; mosquitto_kick_client_by_username; mosquitto_log_printf; mosquitto_log_vprintf; mosquitto_malloc; mosquitto_persist_base_msg_add; mosquitto_persist_base_msg_delete; mosquitto_persist_client_add; mosquitto_persist_client_delete; mosquitto_persist_client_msg_add; mosquitto_persist_client_msg_clear; mosquitto_persist_client_msg_delete; mosquitto_persist_client_msg_update; mosquitto_persist_client_update; mosquitto_persist_retain_msg_delete; mosquitto_persist_retain_msg_set; mosquitto_persistence_location; mosquitto_plugin_set_info; 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_identifier; mosquitto_property_identifier_to_string; mosquitto_property_next; 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_pub_topic_check2; mosquitto_pub_topic_check; mosquitto_realloc; mosquitto_set_clientid; mosquitto_set_username; mosquitto_strdup; mosquitto_string_to_property_info; mosquitto_strndup; mosquitto_sub_matches_acl; mosquitto_sub_matches_acl_with_pattern; mosquitto_sub_topic_check2; mosquitto_sub_topic_check; mosquitto_subscription_add; mosquitto_subscription_delete; mosquitto_topic_matches_sub2; mosquitto_topic_matches_sub; mosquitto_topic_matches_sub_with_pattern; mosquitto_validate_utf8; }; ================================================ FILE: src/listeners.c ================================================ /* Copyright (c) 2009-2021 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 "net_mosq.h" #include "mosquitto_broker_internal.h" static int listensock_index = 0; extern int g_run; void listener__set_defaults(struct mosquitto__listener *listener) { listener->disable_protocol_v3 = false; listener->disable_protocol_v4 = false; listener->disable_protocol_v5 = false; listener->max_connections = -1; listener->max_qos = 2; listener->max_topic_alias = 10; listener->max_topic_alias_broker = 10; listener->protocol = mp_mqtt; mosquitto_FREE(listener->mount_point); mosquitto_FREE(listener->security_options->acl_data.acl_file); mosquitto_FREE(listener->security_options->password_data.password_file); mosquitto_FREE(listener->security_options->psk_file); listener->security_options->allow_anonymous = -1; listener->security_options->allow_zero_length_clientid = true; mosquitto_FREE(listener->security_options->auto_id_prefix); listener->security_options->auto_id_prefix_len = 0; #ifdef WITH_TLS listener->require_certificate = false; listener->use_identity_as_username = false; listener->use_subject_as_username = false; listener->use_username_as_clientid = false; listener->disable_client_cert_date_checks = false; #endif #if defined(WITH_WEBSOCKETS) && (LWS_LIBRARY_VERSION_NUMBER >= 3001000 || WITH_WEBSOCKETS == WS_IS_BUILTIN) for(int i=0; iws_origin_count; i++){ mosquitto_FREE(listener->ws_origins[i]); } mosquitto_FREE(listener->ws_origins); listener->ws_origin_count = 0; #endif } void listeners__reload_all_certificates(void) { #ifdef WITH_TLS for(int i=0; ilistener_count; i++){ struct mosquitto__listener *listener = &db.config->listeners[i]; if(listener->ssl_ctx && listener->certfile && listener->keyfile){ int 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) { struct mosquitto__listener_sock *listensock_new; if(net__socket_listen(listener)){ return 1; } g_listensock_count += listener->sock_count; listensock_new = mosquitto_realloc(g_listensock, sizeof(struct mosquitto__listener_sock)*(size_t)g_listensock_count); if(!listensock_new){ return 1; } g_listensock = listensock_new; for(int i=0; isock_count; i++){ if(listener->socks[i] == INVALID_SOCKET){ return 1; } g_listensock[listensock_index].sock = listener->socks[i]; g_listensock[listensock_index].listener = listener; #if defined(WITH_EPOLL) || defined(WITH_KQUEUE) g_listensock[listensock_index].ident = id_listener; #endif listensock_index++; } return MOSQ_ERR_SUCCESS; } #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS void listeners__add_websockets(struct lws_context *ws_context, mosq_sock_t fd) { struct mosquitto__listener *listener = NULL; struct mosquitto__listener_sock *listensock_new; /* Don't add more listeners after we've started the main loop */ if(g_run || ws_context == NULL){ return; } /* Find context */ for(int i=0; ilistener_count; i++){ if(db.config->listeners[i].ws_in_init){ listener = &db.config->listeners[i]; break; } } if(listener == NULL){ return; } g_listensock_count++; listensock_new = mosquitto_realloc(g_listensock, sizeof(struct mosquitto__listener_sock)*(size_t)g_listensock_count); if(!listensock_new){ return; } g_listensock = listensock_new; g_listensock[listensock_index].sock = fd; g_listensock[listensock_index].listener = listener; #if defined(WITH_EPOLL) || defined(WITH_KQUEUE) g_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; bool allow_anonymous; listeners = db.config->listeners; if(db.config->security_options.allow_anonymous == -1){ allow_anonymous = true; }else{ allow_anonymous = db.config->security_options.allow_anonymous; } listeners[db.config->listener_count].security_options = mosquitto_calloc(1, sizeof(struct mosquitto__security_options)); if(listeners[db.config->listener_count].security_options == NULL){ return MOSQ_ERR_NOMEM; } listener__set_defaults(&listeners[db.config->listener_count]); listeners[db.config->listener_count].security_options->allow_anonymous = allow_anonymous; listeners[db.config->listener_count].security_options->auto_id_prefix = mosquitto_strdup("auto-"); if(listeners[db.config->listener_count].security_options->auto_id_prefix == NULL){ mosquitto_FREE(listeners[db.config->listener_count].security_options); return MOSQ_ERR_NOMEM; } listeners[db.config->listener_count].security_options->auto_id_prefix_len = (int)strlen("auto-"); listeners[db.config->listener_count].port = port; listeners[db.config->listener_count].host = mosquitto_strdup(host); if(listeners[db.config->listener_count].host == NULL){ mosquitto_FREE(listeners[db.config->listener_count].security_options->auto_id_prefix); mosquitto_FREE(listeners[db.config->listener_count].security_options); return MOSQ_ERR_NOMEM; } if(listeners__start_single_mqtt(&listeners[db.config->listener_count])){ mosquitto_FREE(listeners[db.config->listener_count].security_options->auto_id_prefix); mosquitto_FREE(listeners[db.config->listener_count].security_options); mosquitto_FREE(listeners[db.config->listener_count].host); 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 rc; struct mosquitto__listener *listeners; size_t count; if(db.config->cmd_port_count == 0){ count = 2; }else{ count = (size_t)(db.config->cmd_port_count*2); } #ifdef WITH_HTTP_API count++; #endif listeners = mosquitto_realloc(db.config->listeners, count*sizeof(struct mosquitto__listener)); if(listeners == NULL){ return MOSQ_ERR_NOMEM; } memset(listeners, 0, count*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(int 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){ #ifdef WITH_HTTP_API db.config->listener_count++; http_api__start_local(&db.config->listeners[db.config->listener_count-1]); #endif return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_UNKNOWN; } } int listeners__start(void) { g_listensock_count = 0; if(db.config->local_only){ if(listeners__start_local_only()){ db__close(); if(db.config->pid_file){ (void)remove(db.config->pid_file); } return 1; } mux__add_listeners(g_listensock, g_listensock_count); return MOSQ_ERR_SUCCESS; } for(int 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){ #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS 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; } #elif defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN if(listeners__start_single_mqtt(&db.config->listeners[i])){ db__close(); if(db.config->pid_file){ (void)remove(db.config->pid_file); } return 1; } #endif #ifdef WITH_HTTP_API }else if(db.config->listeners[i].protocol == mp_http_api){ http_api__start(&db.config->listeners[i]); #endif } } if(g_listensock == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to start any listening sockets, exiting."); return 1; } mux__add_listeners(g_listensock, g_listensock_count); return MOSQ_ERR_SUCCESS; } void listeners__stop(void) { mux__delete_listeners(g_listensock, g_listensock_count); for(int i=0; ilistener_count; i++){ #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS 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 #ifdef WITH_HTTP_API if(db.config->listeners[i].mhd){ http_api__stop(&db.config->listeners[i]); } #endif } for(int 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 #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 "util_mosq.h" #ifdef WIN32 HANDLE syslog_h; #endif #ifdef ANDROID #include static const char *LOG_TAG = "mosquitto"; #endif static char log_fptr_buffer[BUFSIZ]; static void libcommon__vprintf(const char *fmt, va_list va); /* 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; /* 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)){ int 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; libcommon_vprintf = libcommon__vprintf; 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); } } #ifndef WIN32 if(log_destinations & MQTT3_LOG_STDOUT){ setvbuf(stdout, NULL, _IOLBF, 0); } #endif #ifdef WITH_DLT if(log_destinations & MQTT3_LOG_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 #ifdef ANDROID android_LogPriority get_android_level(unsigned int priority) { switch(priority){ case MOSQ_LOG_ERR: return ANDROID_LOG_ERROR; case MOSQ_LOG_WARNING: return ANDROID_LOG_WARN; case MOSQ_LOG_INFO: return ANDROID_LOG_INFO; case MOSQ_LOG_DEBUG: return ANDROID_LOG_DEBUG; case MOSQ_LOG_NOTICE: case MOSQ_LOG_SUBSCRIBE: case MOSQ_LOG_UNSUBSCRIBE: return ANDROID_LOG_VERBOSE; default: return ANDROID_LOG_DEBUG; } } #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; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS 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), "%" PRIu64, (uint64_t)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 #ifdef ANDROID if(log_destinations & MQTT3_LOG_ANDROID && priority != MOSQ_LOG_INTERNAL){ __android_log_write(get_android_level(priority), LOG_TAG, 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 } BROKER_EXPORT int mosquitto_log_vprintf(int level, const char *fmt, va_list va) { return log__vprintf((unsigned int)level, fmt, va); } BROKER_EXPORT 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); } static void libcommon__vprintf(const char *fmt, va_list va) { log__vprintf(MOSQ_LOG_INFO, fmt, va); } ================================================ FILE: src/loop.c ================================================ /* Copyright (c) 2009-2021 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 #ifndef WIN32 #include #else #include #include #include #endif #include #include #include #include #ifndef WIN32 # include #endif #include #include #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS # include #endif #include "mosquitto_broker_internal.h" #include "mosquitto/mqtt_protocol.h" #include "packet_mosq.h" #include "property_common.h" #include "send_mosq.h" #include "sys_tree.h" #include "util_mosq.h" extern int g_run; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS && 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 *pub_msg, uint32_t message_expiry) { struct mosquitto__base_msg *base_msg; uint16_t mid; base_msg = mosquitto_calloc(1, sizeof(struct mosquitto__base_msg)); if(base_msg == NULL){ return MOSQ_ERR_NOMEM; } base_msg->data.topic = pub_msg->topic; pub_msg->topic = NULL; base_msg->data.retain = 0; base_msg->data.payloadlen = (uint32_t)pub_msg->payloadlen; base_msg->data.payload = mosquitto_malloc(base_msg->data.payloadlen+1); if(base_msg->data.payload == NULL){ db__msg_store_free(base_msg); return MOSQ_ERR_NOMEM; } /* Ensure payload is always zero terminated, this is the reason for the extra byte above */ ((uint8_t *)base_msg->data.payload)[base_msg->data.payloadlen] = 0; memcpy(base_msg->data.payload, pub_msg->payload, base_msg->data.payloadlen); if(pub_msg->properties){ base_msg->data.properties = pub_msg->properties; pub_msg->properties = NULL; } if(db__message_store(context, base_msg, &message_expiry, mosq_mo_broker)){ return 1; } if(pub_msg->qos){ mid = mosquitto__mid_generate(context); }else{ mid = 0; } return db__message_insert_outgoing(context, 0, mid, (uint8_t)pub_msg->qos, 0, base_msg, 0, true, true); } static void read_message_expiry_interval(mosquitto_property **proplist, uint32_t *message_expiry) { mosquitto_property *p, *previous = NULL; *message_expiry = MSG_EXPIRY_INFINITE; if(!proplist){ return; } p = *proplist; while(p){ if(mosquitto_property_identifier(p) == MQTT_PROP_MESSAGE_EXPIRY_INTERVAL){ *message_expiry = mosquitto_property_int32_value(p); if(p == *proplist){ *proplist = mosquitto_property_next(p); }else{ previous->next = mosquitto_property_next(p); } mosquitto_property_free(&p); return; } previous = p; p = mosquitto_property_next(p); } } 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); } } void loop__update_next_event(time_t new_ms) { if(new_ms > 0 && new_ms < db.next_event_ms){ db.next_event_ms = new_ms; } } int mosquitto_main_loop(struct mosquitto__listener_sock *listensock, int listensock_count) { #ifdef WITH_PERSISTENCE time_t last_backup = mosquitto_time(); #endif int rc; watchdog__init(); #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS && 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(g_run){ retain__expiry_check(); queue_plugin_msgs(); context__free_disused(); db.next_event_ms = 86400000; #ifdef WITH_SYS_TREE if(db.config->sys_interval > 0){ sys_tree__update(false); } #endif keepalive__check(); watchdog__check(); #ifdef WITH_BRIDGE bridge_check(); #endif plugin__handle_tick(); session_expiry__check(); will_delay__check(); rc = mux__handle(listensock, listensock_count); if(rc){ return rc; } #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 rc = signal__flag_check(); if(rc){ return rc; } #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS for(int 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 } return MOSQ_ERR_SUCCESS; } void do_disconnect(struct mosquitto *context, int reason) { const char *id; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS bool is_duplicate = false; #endif if(context->state == mosq_cs_disconnected){ return; } #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS 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 = context->address; } 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 [%s:%d] disconnected: malformed packet.", id, context->address, context->remote_port); break; case MOSQ_ERR_PROTOCOL: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: protocol error.", id, context->address, context->remote_port); break; case MOSQ_ERR_CONN_LOST: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: connection closed by client.", id, context->address, context->remote_port); break; case MOSQ_ERR_AUTH: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: not authorised.", id, context->address, context->remote_port); break; case MOSQ_ERR_KEEPALIVE: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: exceeded timeout.", id, context->address, context->remote_port); break; case MOSQ_ERR_OVERSIZE_PACKET: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: oversize packet.", id, context->address, context->remote_port); break; case MOSQ_ERR_PAYLOAD_SIZE: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: oversize payload.", id, context->address, context->remote_port); break; case MOSQ_ERR_NOMEM: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: out of memory.", id, context->address, context->remote_port); break; case MOSQ_ERR_NOT_SUPPORTED: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: used disallowed feature (QoS too high, retain not supported, or bad AUTH method).", id, context->address, context->remote_port); break; case MOSQ_ERR_ADMINISTRATIVE_ACTION: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: administrative action.", id, context->address, context->remote_port); break; case MOSQ_ERR_ERRNO: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: %s.", id, context->address, context->remote_port, strerror(errno)); break; case MOSQ_ERR_RECEIVE_MAXIMUM_EXCEEDED: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: receive maximum exceeded.", id, context->address, context->remote_port); break; case MOSQ_ERR_IMPLEMENTATION_SPECIFIC: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: implementation specific error.", id, context->address, context->remote_port); break; case MOSQ_ERR_CLIENT_IDENTIFIER_NOT_VALID: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: client identifier not valid.", id, context->address, context->remote_port); break; case MOSQ_ERR_BAD_USERNAME_OR_PASSWORD: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: bad username or password.", id, context->address, context->remote_port); break; case MOSQ_ERR_SERVER_UNAVAILABLE: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: server unavailable.", id, context->address, context->remote_port); break; case MOSQ_ERR_SERVER_BUSY: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: server busy.", id, context->address, context->remote_port); break; case MOSQ_ERR_BANNED: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: client banned.", id, context->address, context->remote_port); break; case MOSQ_ERR_BAD_AUTHENTICATION_METHOD: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: bad authentication method.", id, context->address, context->remote_port); break; case MOSQ_ERR_QUOTA_EXCEEDED: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: quota exceeded.", id, context->address, context->remote_port); break; case MOSQ_ERR_CONNECTION_RATE_EXCEEDED: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: connection rate exceeded.", id, context->address, context->remote_port); break; case MOSQ_ERR_SESSION_TAKEN_OVER: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: session taken over.", id, context->address, context->remote_port); break; case MOSQ_ERR_TOPIC_ALIAS_INVALID: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: topic alias invalid.", id, context->address, context->remote_port); break; case MOSQ_ERR_HTTP_BAD_ORIGIN: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: non-matching http origin.", id, context->address, context->remote_port); break; case MOSQ_ERR_PROXY: /* This was a proxy v2 health check connection, so don't report */ break; default: log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: bad socket read/write: %s", id, context->address, context->remote_port, mosquitto_strerror(reason)); break; } }else{ if(reason == MOSQ_ERR_ADMINISTRATIVE_ACTION){ log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected: administrative action.", id, context->address, context->remote_port); }else{ log__printf(NULL, MOSQ_LOG_NOTICE, "Client %s [%s:%d] disconnected.", id, context->address, context->remote_port); } } } mux__delete(context); context__disconnect(context, reason); } } ================================================ FILE: src/mosquitto.c ================================================ /* Copyright (c) 2009-2021 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 /* For umask() */ # include #endif #ifndef WIN32 #include #else #include #include #include #endif #ifndef WIN32 # include #endif #include #include #include #include #include #ifdef WITH_SYSTEMD # include #endif #ifdef WITH_WRAP #include #endif #include "mosquitto_broker_internal.h" #include "util_mosq.h" struct mosquitto_db db; struct mosquitto__listener_sock *g_listensock = NULL; int g_listensock_count = 0; int g_run = 0; #ifdef WITH_WRAP #include int allow_severity = LOG_INFO; int deny_severity = LOG_INFO; #endif static int set_umask(void) { #if !defined(__CYGWIN__) && !defined(WIN32) /* This affects files that are written to, apart from those that are * created using mosquitto_fopen(..., restrict_read=true), which sets a * umask of 077. */ const char *mask_s; char *endptr = NULL; long mask; mask_s = getenv("UMASK_SET"); if(mask_s){ errno = 0; mask = strtol(mask_s, &endptr, 8); if(errno || endptr == mask_s || *endptr != '\0'){ log__printf(NULL, MOSQ_LOG_ERR, "Error: UMASK_SET environment variable not a valid octal number."); return MOSQ_ERR_INVAL; } if(mask < 000 || mask > 0777){ log__printf(NULL, MOSQ_LOG_ERR, "Error: UMASK_SET environment variable out of range."); return MOSQ_ERR_INVAL; } umask((mode_t)mask); } #endif return MOSQ_ERR_SUCCESS; } /* coverity[ +tainted_string_sanitize_content : arg-0 ] */ static int check_uid(const char *s, const char *name) { char *endptr = NULL; long id; errno = 0; id = strtol(s, &endptr, 10); if(errno || endptr == s || *endptr != '\0'){ log__printf(NULL, MOSQ_LOG_ERR, "Error: %s not a valid ID '%s'", name, s); return -1; } if(id < 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: %s must not be negative", name); return -1; } if(id > INT_MAX){ log__printf(NULL, MOSQ_LOG_ERR, "Error: %s must not be less than %d", name, INT_MAX); return -1; } return (int)id; } /* Prints the name of the process user from its user id if not found * it simply prints out the user id */ static void print_pwname(void) { #ifndef WIN32 struct passwd *pwd = getpwuid(geteuid()); if(!pwd){ log__printf(NULL, MOSQ_LOG_INFO, "Info: running mosquitto as user id: %i.", geteuid()); }else{ log__printf(NULL, MOSQ_LOG_INFO, "Info: running mosquitto as user: %s.", pwd->pw_name); } #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. */ static int drop_privileges(struct mosquitto__config *config) { #if !defined(__CYGWIN__) && !defined(WIN32) struct passwd *pwd; char *err; int rc; const char *puid_s, *pgid_s; int puid; int pgid; 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; } /* PUID and PGID are docker custom user mappings */ puid_s = getenv("PUID"); pgid_s = getenv("PGID"); if(geteuid() == 0){ if(puid_s || pgid_s){ if(pgid_s){ pgid = check_uid(pgid_s, "PGID"); if(pgid < 0){ return MOSQ_ERR_INVAL; }else if(pgid > 0){ rc = setgid((gid_t)pgid); if(rc == -1){ err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error setting gid whilst dropping privileges: %s.", err); return MOSQ_ERR_ERRNO; } } } if(puid_s){ puid = check_uid(puid_s, "PUID"); if(puid < 0){ return MOSQ_ERR_INVAL; }else if(puid > 0){ rc = setuid((uid_t)puid); if(rc == -1){ err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error setting uid whilst dropping privileges: %s.", err); return MOSQ_ERR_ERRNO; } } } }else 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 MOSQ_ERR_INVAL; }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 MOSQ_ERR_ERRNO; } } } 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 MOSQ_ERR_ERRNO; } 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 MOSQ_ERR_ERRNO; } 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 MOSQ_ERR_ERRNO; } } print_pwname(); if(geteuid() == 0 || getegid() == 0){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Mosquitto should not be run as root/administrator."); } }else{ print_pwname(); } #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); } if(!freopen("/dev/null", "r", stdin)){ log__printf(NULL, MOSQ_LOG_ERR, "Error whilst daemonising (%s): %s", "stdin", strerror(errno)); exit(1); } if(!freopen("/dev/null", "w", stdout)){ log__printf(NULL, MOSQ_LOG_ERR, "Error whilst daemonising (%s): %s", "stdout", strerror(errno)); exit(1); } if(!freopen("/dev/null", "w", stderr)){ log__printf(NULL, MOSQ_LOG_ERR, "Error whilst daemonising (%s): %s", "stderr", strerror(errno)); exit(1); } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Can't start in daemon mode in Windows."); #endif } static int pid__write(void) { FILE *pid; if(db.config->pid_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 MOSQ_ERR_ERRNO; } } return MOSQ_ERR_SUCCESS; } static void report_features(void) { #ifdef WITH_BRIDGE log__printf(NULL, MOSQ_LOG_INFO, "Bridge support available."); #else log__printf(NULL, MOSQ_LOG_INFO, "Bridge support NOT available."); #endif #ifdef WITH_PERSISTENCE log__printf(NULL, MOSQ_LOG_INFO, "Persistence support available."); #else log__printf(NULL, MOSQ_LOG_INFO, "Persistence support NOT available."); #endif #ifdef WITH_TLS log__printf(NULL, MOSQ_LOG_INFO, "TLS support available."); #else log__printf(NULL, MOSQ_LOG_INFO, "TLS support NOT available."); #endif #ifdef FINAL_WITH_TLS_PSK log__printf(NULL, MOSQ_LOG_INFO, "TLS-PSK support available."); #else log__printf(NULL, MOSQ_LOG_INFO, "TLS-PSK support NOT available."); #endif #ifdef WITH_WEBSOCKETS log__printf(NULL, MOSQ_LOG_INFO, "Websockets support available."); #else log__printf(NULL, MOSQ_LOG_INFO, "Websockets support NOT available."); #endif if(getenv("MOSQUITTO_UNSAFE_ALLOW_SYMLINKS")){ log__printf(NULL, MOSQ_LOG_NOTICE, "MOSQUITTO_UNSAFE_ALLOW_SYMLINKS is set, loading of sensitive files through symbolic links is allowed."); } } static void post_shutdown_cleanup(void) { struct mosquitto *ctxt, *ctxt_tmp; /* 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(); /* Set to true only after persistence events have been processed */ db.shutdown = true; log__printf(NULL, MOSQ_LOG_INFO, "mosquitto version %s terminating", VERSION); broker_control__cleanup(); #ifdef WITH_PERSISTENCE persist__backup(true); #endif session_expiry__remove_all(); listeners__stop(); HASH_ITER(hh_id, db.contexts_by_id, ctxt, ctxt_tmp){ #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS if(!ctxt->wsi) #endif { ctxt->is_persisted = false; /* prevent persistence removal */ context__cleanup(ctxt, true); } } HASH_ITER(hh_sock, db.contexts_by_sock, ctxt, ctxt_tmp){ ctxt->is_persisted = false; /* prevent persistence removal */ context__cleanup(ctxt, true); } #ifdef WITH_BRIDGE bridge__db_cleanup(); #endif context__free_disused(); keepalive__cleanup(); #ifdef WITH_TLS mosquitto_FREE(db.tls_keylog); #endif db__close(); plugin__unload_all(); mosquitto_security_cleanup(false); if(db.config->pid_file){ (void)remove(db.config->pid_file); } mux__cleanup(); log__close(db.config); config__cleanup(db.config); net__broker_cleanup(); } static void cjson_init(void) { cJSON_Hooks hooks = {mosquitto_malloc, mosquitto_free}; cJSON_InitHooks(&hooks); } #ifdef WITH_FUZZING int mosquitto_fuzz_main(int argc, char *argv[]) #else int main(int argc, char *argv[]) #endif { struct mosquitto__config config; int rc; mosquitto_time_init(); cjson_init(); #if defined(WIN32) || defined(__CYGWIN__) if(argc == 2){ if(!strcmp(argv[1], "run")){ service_run(argv[0]); return 0; }else if(!strcmp(argv[1], "install")){ service_install(argv[0]); return 0; }else if(!strcmp(argv[1], "uninstall")){ service_uninstall(argv[0]); return 0; } } #endif #ifdef WIN32 if(_setmaxstdio(8192) != 8192){ /* Old limit was 2048 */ if(_setmaxstdio(2048) != 2048){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Unable to increase maximum allowed connections. This session may be limited to 512 connections."); } } #endif memset(&db, 0, sizeof(struct mosquitto_db)); db.now_s = mosquitto_time(); db.now_real_s = time(NULL); mosquitto_broker_node_id_set(0); net__broker_init(); db.config = &config; config__init(&config); rc = config__parse_args(&config, argc, argv); if(rc == MOSQ_ERR_UNKNOWN){ post_shutdown_cleanup(); return MOSQ_ERR_SUCCESS; }else if(rc != MOSQ_ERR_SUCCESS){ post_shutdown_cleanup(); return rc; } if(config.test_configuration){ if(!db.config_file){ log__printf(NULL, MOSQ_LOG_ERR, "Please provide a configuration file to test."); post_shutdown_cleanup(); return MOSQ_ERR_INVAL; }else{ log__printf(NULL, MOSQ_LOG_INFO, "Configuration file is OK."); post_shutdown_cleanup(); return MOSQ_ERR_SUCCESS; } } rc = keepalive__init(); if(rc){ post_shutdown_cleanup(); return rc; } /* 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){ post_shutdown_cleanup(); return rc; } /* Set umask based on environment variable */ rc = set_umask(); if(rc){ post_shutdown_cleanup(); return rc; } if(config.daemon){ mosquitto__daemonise(); } rc = pid__write(); if(rc){ post_shutdown_cleanup(); return rc; } rc = db__open(&config); if(rc != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Couldn't open database."); post_shutdown_cleanup(); return rc; } /* Initialise logging only after initialising the database in case we're * logging to topics */ rc = log__init(&config); if(rc){ post_shutdown_cleanup(); 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."); } report_features(); rc = plugin__load_all(); if(rc){ post_shutdown_cleanup(); return rc; } rc = mosquitto_security_init(false); if(rc){ post_shutdown_cleanup(); return rc; } plugin_persist__handle_restore(); session_expiry__check(); retain__expire(&db.retains); db__msg_store_compact(); #ifdef WITH_SYS_TREE sys_tree__init(); #endif rc = mux__init(); if(rc){ post_shutdown_cleanup(); return rc; } rc = listeners__start(); if(rc){ post_shutdown_cleanup(); return rc; } signal__setup(); #ifdef WITH_BRIDGE bridge__start_all(); #endif broker_control__init(); log__printf(NULL, MOSQ_LOG_INFO, "mosquitto version %s running", VERSION); #ifdef WITH_SYSTEMD sd_notify(0, "READY=1"); #endif g_run = 1; rc = mosquitto_main_loop(g_listensock, g_listensock_count); post_shutdown_cleanup(); return rc; } #ifdef WIN32 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { char **argv; int argc = 1; char *token; char *saveptr = NULL; int rc; UNUSED(hInstance); UNUSED(hPrevInstance); UNUSED(nCmdShow); argv = mosquitto_malloc(sizeof(char *)*1); argv[0] = "mosquitto"; token = strtok_r(lpCmdLine, " ", &saveptr); while(token){ argc++; argv = mosquitto_realloc(argv, sizeof(char *)*argc); if(!argv){ fprintf(stderr, "Error: Out of memory.\n"); return MOSQ_ERR_NOMEM; } argv[argc-1] = token; token = strtok_r(NULL, " ", &saveptr); } rc = main(argc, argv); mosquitto_FREE(argv); return rc; } #endif ================================================ FILE: src/mosquitto_broker_internal.h ================================================ /* Copyright (c) 2009-2021 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 #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS # 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 #ifdef WITH_HTTP_API # include #endif #ifdef __linux__ #define WITH_TCP_USER_TIMEOUT #endif #include "mosquitto_internal.h" #include "mosquitto/broker.h" #include "mosquitto/broker_plugin.h" #include "mosquitto.h" #include "logging_mosq.h" #include "tls_mosq.h" #include "uthash.h" #include "acl_file.h" #include "password_file.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 #ifdef ANDROID #define MQTT3_LOG_ANDROID 0x40 #endif #define MQTT3_LOG_ALL 0xFF #define CMD_PORT_LIMIT 10 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__plugin_lib { 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__plugin_config { char *path; char *name; struct mosquitto_opt *options; struct mosquitto__security_options **security_options; int option_count; int security_option_count; bool deny_special_chars; }; 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; union { char *topic; struct timespec next_tick; } data; mosquitto_plugin_id_t *identifier; }; struct plugin__callbacks { struct mosquitto__callback *tick; struct mosquitto__callback *acl_check; struct mosquitto__callback *basic_auth; struct mosquitto__callback *connect; struct mosquitto__callback *control; struct mosquitto__callback *disconnect; struct mosquitto__callback *client_offline; struct mosquitto__callback *ext_auth_continue; struct mosquitto__callback *ext_auth_start; struct mosquitto__callback *message_in; struct mosquitto__callback *message_out; struct mosquitto__callback *psk_key; struct mosquitto__callback *reload; struct mosquitto__callback *subscribe; struct mosquitto__callback *unsubscribe; struct mosquitto__callback *persist_restore; struct mosquitto__callback *persist_client_add; struct mosquitto__callback *persist_client_delete; struct mosquitto__callback *persist_client_update; struct mosquitto__callback *persist_subscription_add; struct mosquitto__callback *persist_subscription_delete; struct mosquitto__callback *persist_client_msg_add; struct mosquitto__callback *persist_client_msg_delete; struct mosquitto__callback *persist_client_msg_update; struct mosquitto__callback *persist_base_msg_add; struct mosquitto__callback *persist_base_msg_delete; struct mosquitto__callback *persist_retain_msg_set; struct mosquitto__callback *persist_retain_msg_delete; struct mosquitto__callback *persist_will_add; struct mosquitto__callback *persist_will_delete; }; /* This is owned by mosquitto__config or mosquitto__listener, and only referred * to by other structs */ 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__psk *psk_id; struct acl_file_data acl_data; struct password_file_data password_data; char *psk_file; mosquitto_plugin_id_t **plugins; int plugin_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" */ }; #if defined(WITH_EPOLL) || defined(WITH_KQUEUE) 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; uint16_t max_topic_alias_broker; #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; bool use_identity_as_username; bool use_subject_as_username; bool require_certificate; bool disable_client_cert_date_checks; enum mosquitto__keyform tls_keyform; #endif #ifdef WITH_WEBSOCKETS # if WITH_WEBSOCKETS == WS_IS_LWS struct lws_context *ws_context; bool ws_in_init; struct lws_protocols *ws_protocol; # endif char **ws_origins; int ws_origin_count; #endif #if defined(WITH_WEBSOCKETS) || defined(WITH_HTTP_API) char *http_dir; #endif struct mosquitto__security_options *security_options; #ifdef WITH_UNIX_SOCKETS char *unix_socket_path; #endif bool disable_protocol_v3; bool disable_protocol_v4; bool disable_protocol_v5; int enable_proxy_protocol; bool proxy_protocol_v2_require_tls; #ifdef WITH_HTTP_API struct MHD_Daemon *mhd; #endif }; struct mosquitto__listener_sock { #if defined(WITH_EPOLL) || defined(WITH_KQUEUE) /* This *must* be the first element in the struct. */ int ident; #endif mosq_sock_t sock; struct mosquitto__listener *listener; }; /* Callbacks belonging to a specific plugin * Doesn't include MOSQ_EVT_CONTROL events. */ struct plugin_own_callback { struct plugin_own_callback *next, *prev; MOSQ_FUNC_generic_callback cb_func; enum mosquitto_plugin_event event; }; struct mosquitto_plugin_id_t { struct mosquitto__plugin_config config; struct mosquitto__plugin_lib lib; struct mosquitto__listener *listener; char *plugin_name; char *plugin_version; struct control_endpoint *control_endpoints; struct plugin_own_callback *own_callbacks; struct timespec next_tick; }; 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; bool test_configuration; bool enable_control_api; int global_max_clients; int global_max_connections; struct mosquitto__listener *default_listener; /* Points to one of `listeners` */ 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; uint32_t packet_max_connect; uint32_t packet_max_simple; uint32_t packet_max_sub; uint32_t packet_max_auth; 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; int retain_expiry_interval; bool set_tcp_nodelay; int sys_interval; bool upgrade_outgoing_qos; char *user; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS int websockets_log_level; #endif uint16_t packet_buffer_size; #ifdef WITH_BRIDGE struct mosquitto__bridge **bridges; int bridge_count; #endif struct mosquitto__security_options security_options; }; struct mosquitto__subshared { UT_hash_handle hh; struct mosquitto__subleaf *subs; char name[]; }; struct mosquitto__subhier { UT_hash_handle hh; struct mosquitto__subhier *parent; struct mosquitto__subhier *children; struct mosquitto__subleaf *subs; struct mosquitto__subshared *shared; uint16_t topic_len; char topic[]; }; struct mosquitto__subleaf { struct mosquitto__subleaf *prev; struct mosquitto__subleaf *next; struct mosquitto *context; struct mosquitto__subhier *hier; struct mosquitto__subshared *shared; uint32_t identifier; uint8_t subscription_options; char topic_filter[]; }; struct sub__token { struct sub__token *next; uint16_t topic_len; char topic[]; }; struct mosquitto__retainhier { UT_hash_handle hh; struct mosquitto__retainhier *parent; struct mosquitto__retainhier *children; struct mosquitto__base_msg *retained; uint16_t topic_len; char topic[]; }; struct mosquitto__base_msg { UT_hash_handle hh; struct mosquitto_base_msg data; struct mosquitto__listener *source_listener; char **dest_ids; int dest_id_count; int ref_count; enum mosquitto_msg_origin origin; bool stored; }; struct mosquitto__client_msg { struct mosquitto_client_msg data; struct mosquitto__client_msg *prev; struct mosquitto__client_msg *next; struct mosquitto__base_msg *base_msg; }; struct mosquitto__psk { UT_hash_handle hh; char *username; char *password; }; struct mosquitto__message_v5 { struct mosquitto__message_v5 *next, *prev; char *topic; void *payload; mosquitto_property *properties; /* clientid is used only by mosquitto_broker_publish*() to indicate this message is for a specific client. */ char *clientid; int payloadlen; int qos; bool retain; }; struct mosquitto_db { dbid_t last_db_id; uint64_t node_id_shifted; struct mosquitto__subhier *normal_subs; struct mosquitto__subhier *shared_subs; struct mosquitto__retainhier *retains; struct mosquitto *contexts_by_id; struct mosquitto *contexts_by_sock; struct mosquitto *contexts_by_id_delayed_auth; struct mosquitto *contexts_for_free; mosquitto_plugin_id_t **plugins; int plugin_count; #ifdef WITH_BRIDGE struct mosquitto **bridges; int bridge_count; #endif struct clientid__index_hash *clientid_index_hash; struct mosquitto__base_msg *msg_store; time_t now_s; /* Monotonic clock, where possible */ time_t now_real_s; /* Read clock, for measuring session/message expiry */ uint64_t node_id; /* for unique db ids */ time_t next_event_ms; /* for mux timeout */ int msg_store_count; unsigned long msg_store_bytes; char *config_file; struct mosquitto__config *config; bool quiet; 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 #ifdef WITH_KQUEUE int kqueuefd; #endif struct mosquitto__message_v5 *plugin_msgs; #ifdef WITH_TLS /* tls_keylog can't be in the config struct because it is used before the config is allocated. Config probably shouldn't be separately allocated. */ char *tls_keylog; #endif bool shutdown; }; 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, }; enum mosquitto_bridge_reload_type { brt_lazy = 0, brt_immediate = 1, }; struct mosquitto__bridge_topic { struct mosquitto__bridge_topic *next; 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; unsigned int tcp_keepalive_idle; unsigned int tcp_keepalive_interval; unsigned int tcp_keepalive_counter; #ifdef WITH_TCP_USER_TIMEOUT int tcp_user_timeout; #endif struct mosquitto__bridge_topic *topics; int topic_count; bool topic_remapping; enum mosquitto__protocol protocol_version; time_t restart_t; time_t connected_at; 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 stable_connection_period; int threshold; uint32_t maximum_packet_size; uint32_t session_expiry_interval; uint16_t receive_maximum; bool lazy_reconnect; bool attempt_unsubscribe; bool initial_notification_done; bool outgoing_retain; enum mosquitto_bridge_reload_type reload_type; uint16_t max_topic_alias; #ifdef WITH_TLS bool tls_insecure; bool tls_ocsp_required; bool tls_use_os_certs; char *tls_cafile; char *tls_capath; char *tls_certfile; char *tls_keyfile; char *tls_version; char *tls_alpn; char *tls_ciphers; char *tls_13_ciphers; # ifdef FINAL_WITH_TLS_PSK char *tls_psk_identity; char *tls_psk; # endif #endif }; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS struct libws_mqtt_hack { char *http_dir; struct mosquitto__listener *listener; }; struct libws_mqtt_data { struct mosquitto *mosq; }; #endif #include struct control_endpoint { struct control_endpoint *next, *prev; char topic[]; }; extern struct mosquitto_db db; /* ============================================================ * Main functions * ============================================================ */ int mosquitto_main_loop(struct mosquitto__listener_sock *listensock, int listensock_count); void loop__update_next_event(time_t new_ms); /* ============================================================ * Config functions * ============================================================ */ /* Initialise config struct to default values. */ void config__init(struct mosquitto__config *config); #ifdef WITH_BRIDGE void config__bridge_cleanup(struct mosquitto__bridge *bridge); #endif /* 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); /* ============================================================ * 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_outgoing(struct mosquitto *context, uint64_t cmsg_id, uint16_t mid, uint8_t qos, bool retain, struct mosquitto__base_msg *base_msg, uint32_t subscription_identifier, bool update, bool persist); int db__message_insert_incoming(struct mosquitto *context, uint64_t cmsg_id, struct mosquitto__base_msg *base_msg, bool persist); 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, bool persist); 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_delete_incoming(struct mosquitto *context); int db__messages_delete_outgoing(struct mosquitto *context); 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__base_msg *base_msg, uint32_t *message_expiry_interval, enum mosquitto_msg_origin origin); int db__message_store_find(struct mosquitto *context, uint16_t mid, struct mosquitto__client_msg **client_msg); int db__msg_store_add(struct mosquitto__base_msg *base_msg); void db__msg_store_remove(struct mosquitto__base_msg *base_msg, bool notify); void db__msg_store_ref_inc(struct mosquitto__base_msg *base_msg); void db__msg_store_ref_dec(struct mosquitto__base_msg **base_msg); void db__msg_store_clean(void); void db__msg_store_compact(void); void db__msg_store_free(struct mosquitto__base_msg *base_msg); 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(bool force); 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); void db__msg_add_to_inflight_stats(struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg *msg); void db__msg_add_to_queued_stats(struct mosquitto_msg_data *msg_data, struct mosquitto__client_msg *msg); uint64_t db__new_msg_id(void); void db__expire_all_messages(struct mosquitto *context); void db__check_acl_of_all_messages(struct mosquitto *context); /* ============================================================ * Subscription functions * ============================================================ */ int sub__init(void); int sub__add(struct mosquitto *context, const struct mosquitto_subscription *sub); int sub__remove(struct mosquitto *context, const char *sub, 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__base_msg **base_msg); 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(void); int context__init_sock(struct mosquitto *context, mosq_sock_t sock, bool get_address); void context__cleanup(struct mosquitto *context, bool force_free); void context__disconnect(struct mosquitto *context, int reason); void context__add_to_disused(struct mosquitto *context); void context__free_disused(void); void context__send_will(struct mosquitto *context); void context__add_to_by_id(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__base_msg *base_msg); void control__cleanup(void); #endif int control__register_callback(mosquitto_plugin_id_t *pid, MOSQ_FUNC_generic_callback cb_func, const char *topic, void *userdata); int control__unregister_callback(mosquitto_plugin_id_t *pid, MOSQ_FUNC_generic_callback cb_func, const char *topic); void control__unregister_all_callbacks(mosquitto_plugin_id_t *identifier); /* ============================================================ * 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); void bridge__reload(void); void bridge__db_cleanup(void); void bridge__cleanup(struct mosquitto *context); int bridge__connect(struct mosquitto *context); #if defined(__GLIBC__) && defined(WITH_ADNS) int bridge__connect_step3(struct mosquitto *context); #endif int bridge__on_connect(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); void bridge__cleanup_topics(struct mosquitto__bridge *bridge); int bridge__remap_topic_in(struct mosquitto *context, char **topic); #endif /* ============================================================ * IO multiplex related functions * ============================================================ */ int mux__init(void); int mux__add_listeners(struct mosquitto__listener_sock *listensock, int listensock_count); int mux__delete_listeners(struct mosquitto__listener_sock *listensock, int listensock_count); int mux__loop_prepare(void); int mux__new(struct mosquitto *context); int mux__add_out(struct mosquitto *context); int mux__remove_out(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 * ============================================================ */ extern struct mosquitto__listener_sock *g_listensock; extern int g_listensock_count; void listener__set_defaults(struct mosquitto__listener *listener); void listeners__reload_all_certificates(void); #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS void listeners__add_websockets(struct lws_context *ws_context, mosq_sock_t fd); #endif int listeners__start(void); void listeners__stop(void); /* ============================================================ * Plugin related functions * ============================================================ */ int plugin__load_v5(mosquitto_plugin_id_t *plugin, void *lib); int plugin__load_v4(mosquitto_plugin_id_t *plugin, void *lib); int plugin__load_v3(mosquitto_plugin_id_t *plugin, void *lib); int plugin__load_v2(mosquitto_plugin_id_t *plugin, void *lib); int acl__pre_check(mosquitto_plugin_id_t *plugin, struct mosquitto *context, int access); void LIB_ERROR(void); void plugin__handle_connect(struct mosquitto *context); void plugin__handle_disconnect(struct mosquitto *context, int reason); void plugin__handle_client_offline(struct mosquitto *context, int reason); int plugin__handle_message_in(struct mosquitto *context, struct mosquitto_base_msg *base_msg); int plugin__handle_message_out(struct mosquitto *context, struct mosquitto_base_msg *base_msg); int plugin__handle_subscribe(struct mosquitto *context, struct mosquitto_subscription *sub); int plugin__handle_unsubscribe(struct mosquitto *context, struct mosquitto_subscription *sub); int plugin__handle_reload(void); void plugin__handle_tick(void); int plugin__callback_unregister_all(mosquitto_plugin_id_t *identifier); void plugin_persist__handle_restore(void); void plugin_persist__handle_client_add(struct mosquitto *context); void plugin_persist__handle_client_delete(struct mosquitto *context); void plugin_persist__handle_client_update(struct mosquitto *context); void plugin_persist__handle_subscription_add(struct mosquitto *context, const struct mosquitto_subscription *sub); void plugin_persist__handle_subscription_delete(struct mosquitto *context, char *sub); void plugin_persist__handle_client_msg_add(struct mosquitto *context, const struct mosquitto__client_msg *cmsg); void plugin_persist__handle_client_msg_delete(struct mosquitto *context, const struct mosquitto__client_msg *cmsg); void plugin_persist__handle_client_msg_update(struct mosquitto *context, const struct mosquitto__client_msg *cmsg); void plugin_persist__handle_base_msg_add(struct mosquitto__base_msg *base_msg); void plugin_persist__handle_base_msg_delete(struct mosquitto__base_msg *base_msg); void plugin_persist__handle_retain_msg_set(struct mosquitto__base_msg *base_msg); void plugin_persist__handle_retain_msg_delete(struct mosquitto__base_msg *base_msg); void plugin_persist__handle_will_add(struct mosquitto *context); void plugin_persist__handle_will_delete(struct mosquitto *context); /* ============================================================ * Property related functions * ============================================================ */ int keepalive__init(void); void keepalive__cleanup(void); int keepalive__add(struct mosquitto *context); void keepalive__check(void); int keepalive__remove(struct mosquitto *context); 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_publish(struct mosquitto__base_msg *base_msg, mosquitto_property **props, int *topic_alias, uint32_t *message_expiry_interval, bool is_bridge); 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 struct mosquitto_subscription *sub); int retain__store(const char *topic, struct mosquitto__base_msg *base_msg, char **split_topics, bool persist); void retain__expiry_check(void); void retain__expire(struct mosquitto__retainhier **retainhier); /* ============================================================ * Security related functions * ============================================================ */ int acl__find_acls(struct mosquitto *context); int plugin__load_all(void); int plugin__unload_all(void); int config__plugin_add_secopt(mosquitto_plugin_id_t *plugin, struct mosquitto__security_options *security_options); int mosquitto_security_init(bool reload); 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, mosquitto_property *properties, int access); int mosquitto_basic_auth(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(void); int mosquitto_security_apply_default(void); int mosquitto_security_cleanup_default(void); int mosquitto_psk_key_get_default(struct mosquitto *context, const char *hint, const char *identity, char *key, int max_key_len); int broker_acl_file__init(void); void broker_acl_file__cleanup(void); int broker_password_file__init(void); void broker_password_file__cleanup(void); int psk_file__init(void); int psk_file__cleanup(void); 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); int session_expiry__add_from_persistence(struct mosquitto *context, time_t expiry_time); 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 signal__setup(void); int signal__flag_check(void); /* ============================================================ * Window service and signal related functions * ============================================================ */ #if defined(WIN32) || defined(__CYGWIN__) void service_install(char *name); void service_uninstall(char *name); void service_run(char *name); #ifdef WIN32 DWORD WINAPI SigThreadProc(void *data); #endif #endif /* ============================================================ * Watchdog * ============================================================ */ void watchdog__init(void); void watchdog__check(void); /* ============================================================ * Websockets related functions * ============================================================ */ #ifdef WITH_WEBSOCKETS # if WITH_WEBSOCKETS == WS_IS_LWS void mosq_websockets_init(struct mosquitto__listener *listener, const struct mosquitto__config *conf); # endif int http__context_init(struct mosquitto *context); int http__context_cleanup(struct mosquitto *context); int http__read(struct mosquitto *context); #endif void do_disconnect(struct mosquitto *context, int reason); /* ============================================================ * PROXY related functions * ============================================================ */ int proxy_v2__read(struct mosquitto *context); int proxy_v1__read(struct mosquitto *context); /* ============================================================ * 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); /* ============================================================ * HTTP Info * ============================================================ */ int http_api__start_local(struct mosquitto__listener *listener); int http_api__start(struct mosquitto__listener *listener); void http_api__stop(struct mosquitto__listener *listener); /* ============================================================ * Other * ============================================================ */ #ifdef WITH_XTREPORT void xtreport(void); #endif void broker_control__init(void); void broker_control__cleanup(void); void broker_control__reload(void); #endif ================================================ FILE: src/mux.c ================================================ /* Copyright (c) 2009-2021 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 "mux.h" int mux__init(void) { #ifdef WITH_EPOLL return mux_epoll__init(); #elif defined(WITH_KQUEUE) return mux_kqueue__init(); #else return mux_poll__init(); #endif } int mux__add_listeners(struct mosquitto__listener_sock *listensock, int listensock_count) { #ifdef WITH_EPOLL return mux_epoll__add_listeners(listensock, listensock_count); #elif defined(WITH_KQUEUE) return mux_kqueue__add_listeners(listensock, listensock_count); #else return mux_poll__add_listeners(listensock, listensock_count); #endif } int mux__delete_listeners(struct mosquitto__listener_sock *listensock, int listensock_count) { #ifdef WITH_EPOLL return mux_epoll__delete_listeners(listensock, listensock_count); #elif defined(WITH_KQUEUE) return mux_kqueue__delete_listeners(listensock, listensock_count); #else return mux_poll__delete_listeners(listensock, listensock_count); #endif } int mux__add_out(struct mosquitto *context) { #ifdef WITH_EPOLL return mux_epoll__add_out(context); #elif defined(WITH_KQUEUE) return mux_kqueue__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); #elif defined(WITH_KQUEUE) return mux_kqueue__remove_out(context); #else return mux_poll__remove_out(context); #endif } int mux__new(struct mosquitto *context) { #ifdef WITH_EPOLL return mux_epoll__new(context); #elif defined(WITH_KQUEUE) return mux_kqueue__new(context); #else return mux_poll__new(context); #endif } int mux__delete(struct mosquitto *context) { #ifdef WITH_EPOLL return mux_epoll__delete(context); #elif defined(WITH_KQUEUE) return mux_kqueue__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(); #elif defined(WITH_KQUEUE) UNUSED(listensock); UNUSED(listensock_count); return mux_kqueue__handle(); #else return mux_poll__handle(listensock, listensock_count); #endif } int mux__cleanup(void) { #ifdef WITH_EPOLL return mux_epoll__cleanup(); #elif defined(WITH_KQUEUE) return mux_kqueue__cleanup(); #else return mux_poll__cleanup(); #endif } ================================================ FILE: src/mux.h ================================================ /* Copyright (c) 2020-2021 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(void); int mux_epoll__add_listeners(struct mosquitto__listener_sock *listensock, int listensock_count); int mux_epoll__delete_listeners(struct mosquitto__listener_sock *listensock, int listensock_count); int mux_epoll__new(struct mosquitto *context); int mux_epoll__add_out(struct mosquitto *context); int mux_epoll__remove_out(struct mosquitto *context); int mux_epoll__delete(struct mosquitto *context); int mux_epoll__handle(void); int mux_epoll__cleanup(void); int mux_kqueue__init(void); int mux_kqueue__add_listeners(struct mosquitto__listener_sock *listensock, int listensock_count); int mux_kqueue__delete_listeners(struct mosquitto__listener_sock *listensock, int listensock_count); int mux_kqueue__new(struct mosquitto *context); int mux_kqueue__add_out(struct mosquitto *context); int mux_kqueue__remove_out(struct mosquitto *context); int mux_kqueue__delete(struct mosquitto *context); int mux_kqueue__handle(void); int mux_kqueue__cleanup(void); int mux_poll__init(void); int mux_poll__add_listeners(struct mosquitto__listener_sock *listensock, int listensock_count); int mux_poll__delete_listeners(struct mosquitto__listener_sock *listensock, int listensock_count); int mux_poll__new(struct mosquitto *context); int mux_poll__add_out(struct mosquitto *context); int mux_poll__remove_out(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 ================================================ FILE: src/mux_epoll.c ================================================ /* Copyright (c) 2009-2021 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 #ifndef WIN32 # include # define MAX_EVENTS 1000 #endif #include #include #include "mosquitto_broker_internal.h" #include "mux.h" #include "packet_mosq.h" #include "util_mosq.h" static void loop_handle_reads_writes(struct mosquitto *context, uint32_t events); static struct epoll_event ep_events[MAX_EVENTS]; int mux_epoll__init(void) { 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; } return MOSQ_ERR_SUCCESS; } int mux_epoll__add_listeners(struct mosquitto__listener_sock *listensock, int listensock_count) { for(int i=0; ievents & EPOLLOUT)){ struct epoll_event ev; memset(&ev, 0, sizeof(struct epoll_event)); ev.data.ptr = context; ev.events = EPOLLIN | EPOLLOUT; if(epoll_ctl(db.epollfd, EPOLL_CTL_MOD, context->sock, &ev) == -1){ if((errno != ENOENT)||(epoll_ctl(db.epollfd, EPOLL_CTL_ADD, 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) { if(context->events & EPOLLOUT){ struct epoll_event ev; memset(&ev, 0, sizeof(struct epoll_event)); ev.data.ptr = context; ev.events = EPOLLIN; if(epoll_ctl(db.epollfd, EPOLL_CTL_MOD, context->sock, &ev) == -1){ if((errno != ENOENT)||(epoll_ctl(db.epollfd, EPOLL_CTL_ADD, 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__new(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) { if(context->sock != INVALID_SOCKET){ if(epoll_ctl(db.epollfd, EPOLL_CTL_DEL, context->sock, NULL) == -1){ return 1; } } return 0; } int mux_epoll__handle(void) { struct epoll_event ev; struct mosquitto *context; struct mosquitto__listener_sock *listensock; int event_count; memset(&ev, 0, sizeof(struct epoll_event)); #if defined(WITH_WEBSOCKETS) event_count = epoll_wait(db.epollfd, ep_events, MAX_EVENTS, 100); #else event_count = epoll_wait(db.epollfd, ep_events, MAX_EVENTS, db.next_event_ms); #endif 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(int 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){ } } #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS }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; } #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS 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{ switch(context->transport){ case mosq_t_tcp: case mosq_t_ws: rc = packet__read(context); break; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN case mosq_t_http: rc = http__read(context); break; #endif #if !defined(WITH_WEBSOCKETS) || WITH_WEBSOCKETS == WS_IS_BUILTIN /* Not supported with LWS */ case mosq_t_proxy_v2: rc = proxy_v2__read(context); break; case mosq_t_proxy_v1: rc = proxy_v1__read(context); break; #endif default: rc = MOSQ_ERR_INVAL; break; } 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 ================================================ FILE: src/mux_kqueue.c ================================================ /* Copyright (c) 2021 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 EDL-1.0 Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #ifdef WITH_KQUEUE #define MAX_EVENTS 1000 #include #include #include #include #include "mosquitto_broker_internal.h" #include "packet_mosq.h" #include "util_mosq.h" static void loop_handle_reads_writes(struct mosquitto *context, short events); static struct kevent event_list[MAX_EVENTS]; int mux_kqueue__init(void) { memset(&event_list, 0, sizeof(struct kevent)*MAX_EVENTS); db.kqueuefd = 0; if((db.kqueuefd = kqueue()) == -1){ log__printf(NULL, MOSQ_LOG_ERR, "Error in kqueue creating: %s", strerror(errno)); return MOSQ_ERR_UNKNOWN; } return MOSQ_ERR_SUCCESS; } int mux_kqueue__add_listeners(struct mosquitto__listener_sock *listensock, int listensock_count) { struct kevent ev; memset(&ev, 0, sizeof(struct kevent)); for(int i=0; ievents != EVFILT_WRITE){ EV_SET(&ev, context->sock, EVFILT_WRITE, EV_ADD, 0, 0, context); if(kevent(db.kqueuefd, &ev, 1, NULL, 0, NULL) == -1){ log__printf(NULL, MOSQ_LOG_DEBUG, "Error in kqueue re-registering to EVFILT_WRITE: %s", strerror(errno)); } context->events = EVFILT_WRITE; } return MOSQ_ERR_SUCCESS; } int mux_kqueue__remove_out(struct mosquitto *context) { struct kevent ev; if(context->events == EVFILT_WRITE){ EV_SET(&ev, context->sock, EVFILT_WRITE, EV_DELETE, 0, 0, context); if(kevent(db.kqueuefd, &ev, 1, NULL, 0, NULL) == -1){ log__printf(NULL, MOSQ_LOG_DEBUG, "Error in kqueue removing EVFILT_WRITE: %s", strerror(errno)); } context->events = 0; } return MOSQ_ERR_SUCCESS; } int mux_kqueue__new(struct mosquitto *context) { struct kevent ev; EV_SET(&ev, context->sock, EVFILT_READ, EV_ADD, 0, 0, context); if(kevent(db.kqueuefd, &ev, 1, NULL, 0, NULL) == -1){ log__printf(NULL, MOSQ_LOG_ERR, "Error in kqueue accepting: %s", strerror(errno)); } context->events = 0; return MOSQ_ERR_SUCCESS; } int mux_kqueue__delete(struct mosquitto *context) { struct kevent ev[2]; if(context->sock != INVALID_SOCKET){ EV_SET(&ev[0], context->sock, EVFILT_READ, EV_DELETE, 0, 0, context); EV_SET(&ev[1], context->sock, EVFILT_WRITE, EV_DELETE, 0, 0, context); if(kevent(db.kqueuefd, ev, 2, NULL, 0, NULL) == -1){ return 1; } } return 0; } int mux_kqueue__handle(void) { struct mosquitto *context; struct mosquitto__listener_sock *listensock; int event_count; struct timespec timeout; #ifdef WITH_WEBSOCKETS timeout.tv_sec = 0; timeout.tv_nsec = 100000000; /* 100 ms */ #else timeout.tv_sec = db.next_event_ms/1000; timeout.tv_nsec = (db.next_event_ms - timeout.tv_sec*1000) * 1000000; #endif event_count = kevent(db.kqueuefd, NULL, 0, event_list, MAX_EVENTS, &timeout); 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 kqueue waiting: %s.", strerror(errno)); } break; case 0: break; default: for(int i=0; iident == id_client){ loop_handle_reads_writes(context, event_list[i].filter); if(event_list[i].flags & (EV_EOF | EV_ERROR)){ do_disconnect(context, MOSQ_ERR_CONN_LOST); } }else if(context->ident == id_listener){ listensock = event_list[i].udata; if(event_list[i].filter == EVFILT_READ){ while((context = net__socket_accept(listensock)) != NULL){ } } #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_kqueue__cleanup(void) { (void)close(db.kqueuefd); db.kqueuefd = 0; return MOSQ_ERR_SUCCESS; } static void loop_handle_reads_writes(struct mosquitto *context, short event) { int err; socklen_t len; int rc; if(context->sock == INVALID_SOCKET){ return; } #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS if(context->wsi){ struct lws_pollfd wspoll; wspoll.fd = context->sock; int16_t lws_events; switch(event){ case EVFILT_READ: lws_events = LWS_POLLIN; break; case EVFILT_WRITE: lws_events = LWS_POLLOUT; break; default: lws_events = LWS_POLLHUP; break; } wspoll.events = lws_events; wspoll.revents = lws_events; lws_service_fd(lws_get_context(context->wsi), &wspoll); return; } #endif if(event == EVFILT_WRITE #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(event == EVFILT_READ #ifdef WITH_TLS || (context->ssl && context->state == mosq_cs_new) #endif ){ do{ switch(context->transport){ case mosq_t_tcp: case mosq_t_ws: rc = packet__read(context); break; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN case mosq_t_http: rc = http__read(context); break; #endif #if !defined(WITH_WEBSOCKETS) || WITH_WEBSOCKETS == WS_IS_BUILTIN /* Not supported with LWS */ case mosq_t_proxy_v2: rc = proxy_v2__read(context); break; case mosq_t_proxy_v1: rc = proxy_v1__read(context); break; #endif default: rc = MOSQ_ERR_INVAL; break; } if(rc){ do_disconnect(context, rc); return; } }while(SSL_DATA_PENDING(context)); } } #endif ================================================ FILE: src/mux_poll.c ================================================ /* Copyright (c) 2009-2021 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" #if !defined(WITH_EPOLL) && !defined(WITH_KQUEUE) #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 #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS # include #endif #include "mosquitto_broker_internal.h" #include "packet_mosq.h" #include "send_mosq.h" #include "sys_tree.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 = 0; int mux_poll__init(void) { #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(size_t 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(size_t 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__new(context); }else{ return MOSQ_ERR_SUCCESS; } } int mux_poll__new(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 fdcount; int timeout; #ifdef WITH_WEBSOCKETS timeout = 100; #else timeout = db.next_event_ms; #endif #ifndef WIN32 fdcount = poll(pollfds, pollfd_current_max+1, timeout); #else fdcount = WSAPoll(pollfds, pollfd_current_max+1, timeout); #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(int 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){ } } } } } return MOSQ_ERR_SUCCESS; } int mux_poll__cleanup(void) { mosquitto_FREE(pollfds); 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); #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS 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; } #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS 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{ switch(context->transport){ case mosq_t_tcp: case mosq_t_ws: rc = packet__read(context); break; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN case mosq_t_http: rc = http__read(context); break; #endif #if !defined(WITH_WEBSOCKETS) || WITH_WEBSOCKETS == WS_IS_BUILTIN /* Not supported with LWS */ case mosq_t_proxy_v2: rc = proxy_v2__read(context); break; case mosq_t_proxy_v1: rc = proxy_v1__read(context); break; #endif default: rc = MOSQ_ERR_INVAL; break; } 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 ================================================ FILE: src/net.c ================================================ /* Copyright (c) 2009-2021 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 # ifndef _AIX # include # endif # include # include # include # include # include #else # include # include #endif #include #include #include #include #ifdef WITH_WRAP # include #endif #ifdef HAVE_NETINET_IN_H # include #endif #if defined(WITH_UNIX_SOCKETS) || defined(WITH_TLS) # include "sys/stat.h" #endif #ifdef WITH_UNIX_SOCKETS # ifdef WIN32 # include # else # include # endif #endif #ifdef __QNX__ # include #endif #include "mosquitto_broker_internal.h" #include "mosquitto/mqtt_protocol.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; #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 WINDOWS_SET_ERRNO(); 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; } metrics__int_inc(mosq_counter_socket_connections, 1); 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 && listensock->listener->port){ 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(); 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->enable_proxy_protocol){ if(context__init_sock(new_context, new_sock, false) != MOSQ_ERR_SUCCESS){ context__cleanup(new_context, true); COMPAT_CLOSE(new_sock); return NULL; } if(new_context->listener->enable_proxy_protocol == 2){ new_context->transport = mosq_t_proxy_v2; }else{ new_context->transport = mosq_t_proxy_v1; } new_context->proxy.cmd = -1; }else{ if(context__init_sock(new_context, new_sock, true) != MOSQ_ERR_SUCCESS){ context__cleanup(new_context, true); COMPAT_CLOSE(new_sock); return NULL; } switch(new_context->listener->protocol){ case mp_mqtt: new_context->transport = mosq_t_tcp; break; #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN case mp_websockets: if(http__context_init(new_context)){ context__cleanup(new_context, true); return NULL; } break; #endif default: context__cleanup(new_context, true); return NULL; } } if((new_context->listener->max_connections > 0 && new_context->listener->client_count > new_context->listener->max_connections) || (db.config->global_max_connections > 0 && HASH_CNT(hh_sock, db.contexts_by_sock) > (unsigned int)db.config->global_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; } if(!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)){ context__cleanup(new_context, true); return NULL; } new_context->want_write = true; bio = BIO_new_socket(new_sock, BIO_NOCLOSE); SSL_set_bio(new_context->ssl, bio, bio); ERR_clear_error(); SSL_set_accept_state(new_context->ssl); } #endif if(db.config->connection_messages == true && !new_context->listener->enable_proxy_protocol){ 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); } mux__new(new_context); keepalive__add(new_context); return new_context; } #ifdef WITH_TLS static int client_certificate_verify(int preverify_ok, X509_STORE_CTX *ctx) { /* Preverify should check expiry, revocation. */ if(preverify_ok == 0){ SSL *ssl; ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); if(ssl){ struct mosquitto__listener *listener; listener = SSL_get_ex_data(ssl, tls_ex_index_listener); if(listener && listener->disable_client_cert_date_checks){ int err = X509_STORE_CTX_get_error(ctx); if(err == X509_V_ERR_CERT_NOT_YET_VALID || err == X509_V_ERR_CERT_HAS_EXPIRED){ preverify_ok = 1; } } } } 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){ if(mosquitto_validate_utf8(identity, (int)strlen(identity))){ mosquitto_free(psk_key); return 0; } 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 static void tls_keylog_callback(const SSL *ssl, const char *line) { UNUSED(ssl); if(db.tls_keylog){ FILE *fptr; fptr = mosquitto_fopen(db.tls_keylog, "at", true); if(fptr){ #ifndef WIN32 /* Until mosquitto_fopen enforces file permissions on all files, * enforce it here. We can enforce it here, because it isn't a * change of behaviour. */ struct stat statbuf; if(fstat(fileno(fptr), &statbuf) < 0 || statbuf.st_mode & (S_IRWXG | S_IRWXO)){ fclose(fptr); return; } #endif fprintf(fptr, "%s\n", line); fclose(fptr); }else{ #ifndef WIN32 if(errno == ELOOP){ log__printf(NULL, MOSQ_LOG_INFO, "Error: keylog file must not be a symbolic link"); }else #endif { log__printf(NULL, MOSQ_LOG_INFO, "Error: Unable to open keylog file: %s", strerror(errno)); } } } } int net__tls_server_ctx(struct mosquitto__listener *listener) { char buf[256]; int rc; 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(listener->ssl_ctx){ SSL_CTX_free(listener->ssl_ctx); listener->ssl_ctx = NULL; } listener->ssl_ctx = SSL_CTX_new(TLS_server_method()); if(!listener->ssl_ctx){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to create TLS context."); return MOSQ_ERR_TLS; } #ifdef SSL_OP_NO_TLSv1_3 if(db.config->per_listener_settings){ if(listener->security_options->psk_file){ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_TLSv1_3); } }else{ if(db.config->security_options.psk_file){ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_TLSv1_3); } } #endif if(listener->tls_version == NULL){ SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); #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); #endif }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); log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS v1.1 is insecure. It must only be used in the case " "where you have devices that cannot be upgraded to use a secure version of TLS. It is " "recommended to use as secure a set of ciphers as possible and that will restrict it to " "TLS v1.1 only, and to use a separate listener using TLS v1.2 and secure ciphers for your " "other devices."); log__printf(NULL, MOSQ_LOG_WARNING, "Please be aware that support for TLS v1.1 will go away eventually " "and that you should plan now to migrate away from it."); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unsupported tls_version \"%s\".", listener->tls_version); return MOSQ_ERR_TLS; } #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 SSL_CTX_set_dh_auto(listener->ssl_ctx, 1); #ifdef SSL_OP_NO_RENEGOTIATION SSL_CTX_set_options(listener->ssl_ctx, SSL_OP_NO_RENEGOTIATION); #endif if(db.tls_keylog){ log__printf(NULL, MOSQ_LOG_NOTICE, "TLS key logging to '%s' enabled for all listeners.", db.tls_keylog); log__printf(NULL, MOSQ_LOG_NOTICE, "TLS key logging is for DEBUGGING only."); SSL_CTX_set_keylog_callback(listener->ssl_ctx, tls_keylog_callback); } 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(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; } } return MOSQ_ERR_SUCCESS; } #endif #ifdef WITH_TLS static int net__load_crl_file(struct mosquitto__listener *listener) { 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, NULL); return MOSQ_ERR_TLS; } X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK); return MOSQ_ERR_SUCCESS; } #endif 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, NULL); return MOSQ_ERR_TLS; } if(listener->tls_engine == NULL || listener->tls_keyform == mosq_k_pem){ 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, 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, NULL); return MOSQ_ERR_TLS; } /* Load CRLs if they exist. */ if(listener->crlfile){ rc = net__load_crl_file(listener); if(rc){ return rc; } } #else UNUSED(listener); #endif return MOSQ_ERR_SUCCESS; } #if defined(WITH_TLS) && !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 static int net__load_engine(struct mosquitto__listener *listener) { 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, NULL); return MOSQ_ERR_TLS; } if(!ENGINE_init(engine)){ log__printf(NULL, MOSQ_LOG_ERR, "Failed engine initialisation\n"); net__print_ssl_error(NULL, 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, 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, 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, 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, NULL); return MOSQ_ERR_TLS; } } ENGINE_free(engine); /* release the structural reference from ENGINE_by_id() */ return MOSQ_ERR_SUCCESS; } #endif 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 STACK_OF(X509_NAME) *ca_names = NULL; if(listener->cafile || listener->capath){ ca_names = sk_X509_NAME_new_null(); } 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, NULL); return MOSQ_ERR_TLS; } STACK_OF(X509_NAME) *cert_names = SSL_load_client_CA_file(listener->cafile); if(cert_names){ for(int i=0; icapath){ 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, NULL); sk_X509_NAME_pop_free(ca_names, X509_NAME_free); return MOSQ_ERR_TLS; } SSL_add_dir_cert_subjects_to_stack(ca_names, listener->capath); } if(ca_names){ SSL_CTX_set_client_CA_list(listener->ssl_ctx, ca_names); } # endif # if !defined(OPENSSL_NO_ENGINE) && OPENSSL_API_LEVEL < 30000 if(net__load_engine(listener)){ return MOSQ_ERR_TLS; } # endif #endif return net__load_certificates(listener); } #if !defined(WIN32) && !defined(_AIX) 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; bool have_interface = false; if(getifaddrs(&ifaddr) < 0){ net__print_error(MOSQ_LOG_ERR, "Error: %s"); return MOSQ_ERR_ERRNO; } for(struct ifaddrs *ifa=ifaddr; ifa!=NULL; ifa=ifa->ifa_next){ if(ifa->ifa_addr == NULL){ continue; } if(!strcasecmp(listener->bind_interface, ifa->ifa_name)){ have_interface = true; if(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_ERR, "Error: 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_ERR, "Error: 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)); ((struct sockaddr_in6 *)rp->ai_addr)->sin6_scope_id = ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id; freeifaddrs(ifaddr); return MOSQ_ERR_SUCCESS; } } } } } freeifaddrs(ifaddr); if(have_interface){ 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_SUPPORTED; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Interface %s does not exist.", listener->bind_interface); 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; } #if !defined(WIN32) && !defined(_AIX) 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. */ rc = net__bind_interface(listener, rp); if(rc){ COMPAT_CLOSE(sock); listener->sock_count--; if(rc == MOSQ_ERR_NOT_FOUND || rc == MOSQ_ERR_INVAL){ freeaddrinfo(ainfo); return rc; }else{ 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; mosq_sock_t sock = INVALID_SOCKET; int rc; #ifndef WIN32 mode_t old_mask; #endif 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; } #ifdef WIN32 DeleteFile(listener->unix_socket_path); #else unlink(listener->unix_socket_path); #endif 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; #ifndef WIN32 old_mask = umask(0007); #endif rc = bind(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)); #ifndef WIN32 umask(old_mask); #endif 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 if(listener->psk_hint){ if(listener->certfile == NULL || listener->keyfile == 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, NULL); return 1; } } } # endif /* FINAL_WITH_TLS_PSK */ 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); } #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; } ================================================ FILE: src/password_file.c ================================================ /* Copyright (c) 2011-2021 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 "password_file.h" int broker_password_file__init(void) { int rc; /* Load username/password data if required. */ if(db.config->per_listener_settings){ for(int i=0; ilistener_count; i++){ if(db.config->listeners[i].security_options->password_data.password_file){ rc = password_file__parse(&db.config->listeners[i].security_options->password_data); if(rc){ return rc; } if(db.config->listeners[i].security_options->plugin_count == 0){ config__plugin_add_secopt(db.config->listeners[i].security_options->pid, db.config->listeners[i].security_options); } mosquitto_callback_register(db.config->listeners[i].security_options->pid, MOSQ_EVT_BASIC_AUTH, password_file__check, NULL, &db.config->listeners[i].security_options->password_data); } } }else{ if(db.config->security_options.password_data.password_file){ rc = password_file__parse(&db.config->security_options.password_data); if(rc){ return rc; } if(db.config->security_options.plugin_count == 0){ config__plugin_add_secopt(db.config->security_options.pid, &db.config->security_options); } mosquitto_callback_register(db.config->security_options.pid, MOSQ_EVT_BASIC_AUTH, password_file__check, NULL, &db.config->security_options.password_data); } } return MOSQ_ERR_SUCCESS; } void broker_password_file__cleanup(void) { if(db.config->per_listener_settings){ for(int 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, password_file__check, NULL); password_file__cleanup(&db.config->listeners[i].security_options->password_data); } } }else{ if(db.config->security_options.pid){ mosquitto_callback_unregister(db.config->security_options.pid, MOSQ_EVT_BASIC_AUTH, password_file__check, NULL); password_file__cleanup(&db.config->security_options.password_data); } } } ================================================ FILE: src/password_file.h ================================================ /* Copyright (c) 2011-2021 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 PASSWORD_FILE_H #define PASSWORD_FILE_H #include struct mosquitto__unpwd { UT_hash_handle hh; char *username; char *clientid; struct mosquitto_pw *pw; }; struct password_file_data { struct mosquitto__unpwd *unpwd; char *password_file; }; int password_file__parse(struct password_file_data *data); int password_file__check(int event, void *event_data, void *userdata); int password_file__reload(int event, void *event_data, void *userdata); void password_file__cleanup(struct password_file_data *data); #endif ================================================ FILE: src/persist.h ================================================ /* Copyright (c) 2010-2021 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_BASE_MSG 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){ rc = MOSQ_ERR_UNKNOWN; 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 *clientid; 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 *clientid; uint32_t subscription_identifier; }; struct PF_base_msg { 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_base_msg { struct PF_base_msg 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 *clientid; 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_base_msg_read_v234(FILE *db_fptr, struct P_base_msg *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_base_msg_read_v56(FILE *db_fptr, struct P_base_msg *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_base_msg *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 ================================================ FILE: src/persist_read.c ================================================ /* Copyright (c) 2010-2021 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 "persist.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 long base_msg_count = 0; static long retained_count = 0; static long client_count = 0; static long subscription_count = 0; static long client_msg_count = 0; static int persist__restore_sub(const struct mosquitto_subscription *sub); static struct mosquitto *persist__find_or_add_context(const char *clientid, uint16_t last_mid) { struct mosquitto *context; if(!clientid){ return NULL; } context = NULL; HASH_FIND(hh_id, db.contexts_by_id, clientid, strlen(clientid), context); if(!context){ context = context__init(); if(!context){ return NULL; } context->id = mosquitto_strdup(clientid); if(!context->id){ mosquitto_FREE(context); return NULL; } context->clean_start = false; context__add_to_by_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__base_msg *msg; struct mosquitto *context; struct mosquitto_msg_data *msg_data; HASH_FIND(hh, db.msg_store, &chunk->F.store_id, sizeof(chunk->F.store_id), msg); if(!msg){ /* Can't find message - probably expired */ return MOSQ_ERR_SUCCESS; } context = persist__find_or_add_context(chunk->clientid, 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->base_msg = NULL; cmsg->data.cmsg_id = ++context->last_cmsg_id; cmsg->data.mid = chunk->F.mid; cmsg->data.qos = chunk->F.qos; cmsg->data.retain = (chunk->F.retain_dup&0xF0)>>4; cmsg->data.direction = chunk->F.direction; cmsg->data.state = chunk->F.state; cmsg->data.dup = chunk->F.retain_dup&0x0F; cmsg->data.subscription_identifier = chunk->subscription_identifier; cmsg->base_msg = msg; db__msg_store_ref_inc(cmsg->base_msg); if(cmsg->data.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); db__msg_add_to_queued_stats(msg_data, cmsg); }else{ DL_APPEND(msg_data->inflight, cmsg); if(chunk->F.qos > 0 && msg_data->inflight_quota > 0){ msg_data->inflight_quota--; } db__msg_add_to_inflight_stats(msg_data, cmsg); } return MOSQ_ERR_SUCCESS; } static int persist__client_chunk_restore(FILE *db_fptr) { int 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.clientid, 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(int 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; } } } session_expiry__add_from_persistence(context, chunk.F.session_expiry_time); }else{ rc = 1; } mosquitto_FREE(chunk.clientid); mosquitto_FREE(chunk.username); if(rc == 0){ client_count++; } 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.clientid); if(rc == 0){ client_msg_count++; } return rc; } static int persist__base_msg_chunk_restore(FILE *db_fptr, uint32_t length) { struct P_base_msg chunk; struct mosquitto__base_msg *base_msg = NULL; int64_t message_expiry_interval64; uint32_t message_expiry_interval; uint32_t *p_message_expiry_interval = NULL; int rc = 0; memset(&chunk, 0, sizeof(struct P_base_msg)); if(db_version == 6 || db_version == 5){ rc = persist__chunk_base_msg_read_v56(db_fptr, &chunk, length); }else{ rc = persist__chunk_base_msg_read_v234(db_fptr, &chunk, db_version); } if(rc){ return rc; } if(chunk.F.topic_len == 0){ rc = MOSQ_ERR_INVAL; goto cleanup; } if(chunk.F.source_port){ for(int i=0; ilistener_count; i++){ if(db.config->listeners[i].port == chunk.F.source_port){ chunk.source.listener = &db.config->listeners[i]; break; } } } 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 */ rc = MOSQ_ERR_SUCCESS; goto cleanup; }else{ message_expiry_interval = (uint32_t)message_expiry_interval64; } p_message_expiry_interval = &message_expiry_interval; } base_msg = mosquitto_calloc(1, sizeof(struct mosquitto__base_msg)); if(base_msg == NULL){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); rc = MOSQ_ERR_NOMEM; goto cleanup; } base_msg->data.store_id = chunk.F.store_id; base_msg->data.source_mid = chunk.F.source_mid; base_msg->data.topic = chunk.topic; base_msg->data.qos = chunk.F.qos; base_msg->data.payloadlen = chunk.F.payloadlen; base_msg->data.retain = chunk.F.retain; base_msg->data.properties = chunk.properties; base_msg->data.payload = chunk.payload; base_msg->source_listener = chunk.source.listener; rc = db__message_store(&chunk.source, base_msg, p_message_expiry_interval, mosq_mo_client); mosquitto_FREE(chunk.source.id); mosquitto_FREE(chunk.source.username); if(rc == MOSQ_ERR_SUCCESS){ base_msg_count++; return MOSQ_ERR_SUCCESS; }else{ return rc; } cleanup: mosquitto_FREE(chunk.source.id); mosquitto_FREE(chunk.source.username); mosquitto_FREE(chunk.topic); mosquitto_FREE(chunk.payload); return rc; } static int persist__retain_chunk_restore(FILE *db_fptr) { struct mosquitto__base_msg *base_msg; 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, &chunk.F.store_id, sizeof(chunk.F.store_id), base_msg); if(base_msg){ rc = sub__topic_tokenise(base_msg->data.topic, &local_topic, &split_topics, NULL); if(rc){ return rc; } retain__store(base_msg->data.topic, base_msg, split_topics, true); mosquitto_FREE(local_topic); mosquitto_FREE(split_topics); retained_count++; }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; struct mosquitto_subscription sub; 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; } sub.clientid = chunk.clientid; sub.topic_filter = chunk.topic; sub.options = chunk.F.qos | chunk.F.options; sub.identifier = chunk.F.identifier; rc = persist__restore_sub(&sub); mosquitto_FREE(chunk.clientid); mosquitto_FREE(chunk.topic); if(rc == 0){ subscription_count++; } 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 PF_cfg cfg_chunk; assert(db.config); if(!db.config->persistence || db.config->persistence_filepath == NULL){ return MOSQ_ERR_SUCCESS; } db.msg_store = NULL; base_msg_count = 0; retained_count = 0; client_count = 0; subscription_count = 0; client_msg_count = 0; fptr = mosquitto_fopen(db.config->persistence_filepath, "rb", true); 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 MOSQ_ERR_INVAL; } } while(persist__chunk_header_read(fptr, &chunk, &length) == MOSQ_ERR_SUCCESS){ switch(chunk){ case DB_CHUNK_CFG: if(db_version == 6 || db_version == 5){ rc = persist__chunk_cfg_read_v56(fptr, &cfg_chunk); if(rc){ fclose(fptr); return rc; } }else{ rc = persist__chunk_cfg_read_v234(fptr, &cfg_chunk); if(rc){ fclose(fptr); return rc; } } 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 MOSQ_ERR_INVAL; } db.last_db_id = cfg_chunk.last_db_id; break; case DB_CHUNK_BASE_MSG: rc = persist__base_msg_chunk_restore(fptr, length); if(rc){ fclose(fptr); return rc; } break; case DB_CHUNK_CLIENT_MSG: rc = persist__client_msg_chunk_restore(fptr, length); if(rc){ fclose(fptr); return rc; } break; case DB_CHUNK_RETAIN: rc = persist__retain_chunk_restore(fptr); if(rc){ fclose(fptr); return rc; } break; case DB_CHUNK_SUB: rc = persist__sub_chunk_restore(fptr); if(rc){ fclose(fptr); return rc; } break; case DB_CHUNK_CLIENT: rc = persist__client_chunk_restore(fptr); if(rc){ fclose(fptr); return rc; } break; default: log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Unsupported chunk \"%d\" in persistent database file. Ignoring.", chunk); if(fseek(fptr, length, SEEK_CUR) < 0){ fclose(fptr); return MOSQ_ERR_INVAL; } break; } } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to restore persistent database. Unrecognised file format."); rc = 1; } fclose(fptr); log__printf(NULL, MOSQ_LOG_INFO, "Restored %ld base messages", base_msg_count); log__printf(NULL, MOSQ_LOG_INFO, "Restored %ld retained messages", retained_count); log__printf(NULL, MOSQ_LOG_INFO, "Restored %ld clients", client_count); log__printf(NULL, MOSQ_LOG_INFO, "Restored %ld subscriptions", subscription_count); log__printf(NULL, MOSQ_LOG_INFO, "Restored %ld client messages", client_msg_count); return rc; error: err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", err); if(fptr){ fclose(fptr); } return MOSQ_ERR_ERRNO; } static int persist__restore_sub(const struct mosquitto_subscription *sub) { struct mosquitto *context; if(!sub->clientid){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Persistence found a subscription with no client id, ignoring."); return MOSQ_ERR_SUCCESS; } if(!sub->topic_filter){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Persistence found a subscription with no topic filter, ignoring."); return MOSQ_ERR_SUCCESS; } context = persist__find_or_add_context(sub->clientid, 0); if(!context){ return MOSQ_ERR_INVAL; } return sub__add(context, sub); } #endif ================================================ FILE: src/persist_read_v234.c ================================================ /* Copyright (c) 2010-2021 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 "mosquitto_broker_internal.h" #include "persist.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) { int rc = MOSQ_ERR_UNKNOWN; 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 rc; } 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->clientid); 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->clientid); return 1; } int persist__chunk_client_msg_read_v234(FILE *db_fptr, struct P_client_msg *chunk) { uint16_t i16temp; int rc; uint8_t retain, dup; rc = persist__read_string(db_fptr, &chunk->clientid); 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: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); mosquitto_FREE(chunk->clientid); return 1; } int persist__chunk_base_msg_read_v234(FILE *db_fptr, struct P_base_msg *chunk, uint32_t db_version) { uint32_t i32temp; uint16_t i16temp; int rc = 0; size_t slen; 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){ goto error; } 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){ goto error; } if(!chunk->topic){ rc = MOSQ_ERR_INVAL; goto error; } slen = strlen(chunk->topic); if(slen > UINT16_MAX){ rc = MOSQ_ERR_INVAL; goto error; } chunk->F.topic_len = (uint16_t)slen; read_e(db_fptr, &chunk->F.qos, sizeof(uint8_t)); read_e(db_fptr, &chunk->F.retain, sizeof(uint8_t)); read_e(db_fptr, &i32temp, sizeof(uint32_t)); chunk->F.payloadlen = ntohl(i32temp); if(chunk->F.payloadlen){ if(chunk->F.payloadlen > MQTT_MAX_PAYLOAD){ rc = MOSQ_ERR_INVAL; goto error; } chunk->payload = mosquitto_malloc(chunk->F.payloadlen+1); if(chunk->payload == NULL){ rc = MOSQ_ERR_NOMEM; goto error; } read_e(db_fptr, chunk->payload, chunk->F.payloadlen); /* Ensure zero terminated regardless of contents */ ((uint8_t *)chunk->payload)[chunk->F.payloadlen] = 0; } return MOSQ_ERR_SUCCESS; error: mosquitto_FREE(chunk->payload); mosquitto_FREE(chunk->source.id); mosquitto_FREE(chunk->source.username); mosquitto_FREE(chunk->topic); return rc; } int persist__chunk_retain_read_v234(FILE *db_fptr, struct P_retain *chunk) { dbid_t i64temp; if(fread(&i64temp, sizeof(dbid_t), 1, db_fptr) != 1){ log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); 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; rc = persist__read_string(db_fptr, &chunk->clientid); if(rc){ goto error; } rc = persist__read_string(db_fptr, &chunk->topic); if(rc){ goto error; } read_e(db_fptr, &chunk->F.qos, sizeof(uint8_t)); return MOSQ_ERR_SUCCESS; error: mosquitto_FREE(chunk->clientid); mosquitto_FREE(chunk->topic); return rc; } #endif ================================================ FILE: src/persist_read_v5.c ================================================ /* Copyright (c) 2010-2021 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 "mosquitto_broker_internal.h" #include "mosquitto/mqtt_protocol.h" #include "persist.h" #include "property_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->clientid, chunk->F.id_len); if(rc){ return 1; }else if(chunk->clientid == 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->clientid); 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, *p; struct mosquitto__packet_in prop_packet; int rc; memset(&prop_packet, 0, sizeof(struct mosquitto__packet_in)); 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); if(length > MQTT_MAX_PAYLOAD){ goto error; } rc = persist__read_string_len(db_fptr, &chunk->clientid, chunk->F.id_len); if(rc){ return rc; } if(length > 0){ prop_packet.remaining_length = length; prop_packet.payload = mosquitto_malloc(length); if(!prop_packet.payload){ errno = ENOMEM; goto error; } 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->clientid); return rc; } if(properties){ p = properties; while(p){ if(mosquitto_property_identifier(p) == MQTT_PROP_SUBSCRIPTION_IDENTIFIER){ chunk->subscription_identifier = mosquitto_property_varint_value(p); } p = mosquitto_property_next(p); } mosquitto_property_free_all(&properties); } } return MOSQ_ERR_SUCCESS; error: mosquitto_FREE(chunk->clientid); mosquitto_FREE(prop_packet.payload); log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); return 1; } int persist__chunk_base_msg_read_v56(FILE *db_fptr, struct P_base_msg *chunk, uint32_t length) { int rc = 0; mosquitto_property *properties = NULL; struct mosquitto__packet_in prop_packet; memset(&prop_packet, 0, sizeof(struct mosquitto__packet_in)); read_e(db_fptr, &chunk->F, sizeof(struct PF_base_msg)); 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_base_msg) + chunk->F.payloadlen + chunk->F.source_id_len + chunk->F.source_username_len + chunk->F.topic_len); if(length > MQTT_MAX_PAYLOAD){ goto error; } if(chunk->F.source_id_len){ rc = persist__read_string_len(db_fptr, &chunk->source.id, chunk->F.source_id_len); if(rc){ goto error; } } if(chunk->F.source_username_len){ rc = persist__read_string_len(db_fptr, &chunk->source.username, chunk->F.source_username_len); if(rc){ goto error; } } rc = persist__read_string_len(db_fptr, &chunk->topic, chunk->F.topic_len); if(rc){ goto error; } if(chunk->F.payloadlen > 0){ chunk->payload = mosquitto_malloc(chunk->F.payloadlen+1); if(chunk->payload == NULL){ rc = MOSQ_ERR_NOMEM; goto error; } read_e(db_fptr, chunk->payload, chunk->F.payloadlen); /* Ensure zero terminated regardless of contents */ ((uint8_t *)chunk->payload)[chunk->F.payloadlen] = 0; } if(length > 0){ prop_packet.remaining_length = length; prop_packet.payload = mosquitto_malloc(length); if(!prop_packet.payload){ rc = MOSQ_ERR_NOMEM; goto error; } read_e(db_fptr, prop_packet.payload, length); rc = property__read_all(CMD_PUBLISH, &prop_packet, &properties); mosquitto_FREE(prop_packet.payload); if(rc){ rc = MOSQ_ERR_NOMEM; goto error; } } chunk->properties = properties; return MOSQ_ERR_SUCCESS; error: mosquitto_FREE(chunk->payload); mosquitto_FREE(chunk->source.id); mosquitto_FREE(chunk->source.username); mosquitto_FREE(chunk->topic); mosquitto_FREE(prop_packet.payload); return rc; } 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 = MOSQ_ERR_SUCCESS; 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->clientid, chunk->F.id_len); if(rc){ goto error; } rc = persist__read_string_len(db_fptr, &chunk->topic, chunk->F.topic_len); if(rc){ goto error; } return MOSQ_ERR_SUCCESS; error: mosquitto_FREE(chunk->clientid); return rc; } #endif ================================================ FILE: src/persist_write.c ================================================ /* Copyright (c) 2010-2021 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 "persist.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); cmsg = queue; while(cmsg){ if(!strncmp(cmsg->base_msg->data.topic, "$SYS", 4) && cmsg->base_msg->ref_count <= 1 && cmsg->base_msg->dest_id_count == 0){ /* This $SYS message won't have been persisted, so we can't persist * this client message. */ cmsg = cmsg->next; continue; } memset(&chunk, 0, sizeof(struct P_client_msg)); chunk.F.store_id = cmsg->base_msg->data.store_id; chunk.F.mid = cmsg->data.mid; chunk.F.id_len = (uint16_t)strlen(context->id); chunk.F.qos = cmsg->data.qos; chunk.F.retain_dup = (uint8_t)((cmsg->data.retain&0x0F)<<4 | (cmsg->data.dup&0x0F)); chunk.F.direction = (uint8_t)cmsg->data.direction; chunk.F.state = (uint8_t)cmsg->data.state; chunk.clientid = context->id; chunk.subscription_identifier = cmsg->data.subscription_identifier; 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_base_msg chunk; struct mosquitto__base_msg *base_msg, *base_msg_tmp; int rc; assert(db_fptr); base_msg = db.msg_store; HASH_ITER(hh, db.msg_store, base_msg, base_msg_tmp){ if(base_msg->ref_count < 1 || base_msg->data.topic == NULL){ continue; } memset(&chunk, 0, sizeof(struct P_base_msg)); if(!strncmp(base_msg->data.topic, "$SYS", 4)){ if(base_msg->ref_count <= 1 && base_msg->dest_id_count == 0){ /* $SYS messages that are only retained shouldn't be persisted. */ 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)base_msg->data.retain; } chunk.F.store_id = base_msg->data.store_id; chunk.F.expiry_time = base_msg->data.expiry_time; chunk.F.payloadlen = base_msg->data.payloadlen; chunk.F.source_mid = base_msg->data.source_mid; if(base_msg->data.source_id){ chunk.F.source_id_len = (uint16_t)strlen(base_msg->data.source_id); chunk.source.id = base_msg->data.source_id; }else{ chunk.F.source_id_len = 0; chunk.source.id = NULL; } if(base_msg->data.source_username){ chunk.F.source_username_len = (uint16_t)strlen(base_msg->data.source_username); chunk.source.username = base_msg->data.source_username; }else{ chunk.F.source_username_len = 0; chunk.source.username = NULL; } chunk.F.topic_len = (uint16_t)strlen(base_msg->data.topic); chunk.topic = base_msg->data.topic; if(base_msg->source_listener){ chunk.F.source_port = base_msg->source_listener->port; }else{ chunk.F.source_port = 0; } chunk.F.qos = base_msg->data.qos; chunk.payload = base_msg->data.payload; chunk.properties = base_msg->data.properties; rc = persist__chunk_message_store_write_v6(db_fptr, &chunk); if(rc){ return rc; } } 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); HASH_ITER(hh_id, db.contexts_by_id, context, ctxt_tmp){ memset(&chunk, 0, sizeof(struct P_client)); if(context && context->session_expiry_interval != MQTT_SESSION_EXPIRY_IMMEDIATE && #ifdef WITH_BRIDGE ((!context->bridge && context->clean_start == false) || (context->bridge && context->bridge->clean_start_local == false)) #else context->clean_start == false #endif ){ chunk.F.session_expiry_time = context->session_expiry_time; if(context->session_expiry_interval != MQTT_SESSION_EXPIRY_NEVER && context->session_expiry_time == 0){ chunk.F.session_expiry_time = context->session_expiry_interval + db.now_real_s; }else{ 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.clientid = 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; 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->session_expiry_interval != MQTT_SESSION_EXPIRY_IMMEDIATE && sub->context->clean_start == false && sub->context->id){ memset(&sub_chunk, 0, sizeof(struct P_sub)); 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 = MQTT_SUB_OPT_GET_QOS(sub->subscription_options); sub_chunk.F.options = sub->subscription_options & 0xFC; sub_chunk.clientid = 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.normal_subs, subhier, subhier_tmp){ if(subhier->children){ persist__subs_save(db_fptr, subhier->children, "", 0); } } HASH_ITER(hh, db.shared_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; if(node->retained && strncmp(node->retained->data.topic, "$SYS", 4)){ memset(&retain_chunk, 0, sizeof(struct P_retain)); /* Don't save $SYS messages. */ retain_chunk.F.store_id = node->retained->data.store_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; } static int persist__write_data(FILE *db_fptr, void *user_data); static void persist__log_write_error(const char *msg) { log__printf(NULL, MOSQ_LOG_ERR, "Error saving in-memory database, %s", msg); } int persist__backup(bool shutdown) { 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); return mosquitto_write_file(db.config->persistence_filepath, true, &persist__write_data, &shutdown, &persist__log_write_error); } static int persist__write_data(FILE *db_fptr, void *user_data) { bool shutdown = *(bool *)(user_data); uint32_t db_version_w = htonl(MOSQ_DB_VERSION); uint32_t crc = 0; const char *err; struct PF_cfg cfg_chunk; int rc = MOSQ_ERR_UNKNOWN; /* 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; } if(persist__client_save(db_fptr) || persist__subs_save_all(db_fptr) || persist__retain_save_all(db_fptr)){ goto error; } return MOSQ_ERR_SUCCESS; error: err = strerror(errno); log__printf(NULL, MOSQ_LOG_ERR, "Error during saving in-memory database %s: %s.", db.config->persistence_filepath, err); if(db_fptr){ fclose(db_fptr); } return rc; } #endif ================================================ FILE: src/persist_write_v5.c ================================================ /* Copyright (c) 2010-2021 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 "mosquitto/mqtt_protocol.h" #include "mosquitto_broker_internal.h" #include "persist.h" #include "packet_mosq.h" #include "property_common.h" #include "property_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->clientid, 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 = NULL; uint16_t id_len = chunk->F.id_len; uint32_t proplen = 0; int rc; mosquitto_property subscription_id_prop = { .next = NULL, .identifier = MQTT_PROP_SUBSCRIPTION_IDENTIFIER, .client_generated = true, .property_type = MQTT_PROP_TYPE_VARINT }; if(chunk->subscription_identifier){ subscription_id_prop.value.varint = chunk->subscription_identifier; proplen += mosquitto_property_get_remaining_length(&subscription_id_prop); } 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->clientid, id_len); if(chunk->subscription_identifier){ if(proplen > 0){ prop_packet = mosquitto_calloc(1, sizeof(struct mosquitto__packet)+proplen); if(prop_packet == NULL){ return MOSQ_ERR_NOMEM; } prop_packet->remaining_length = proplen; prop_packet->packet_length = proplen; rc = property__write_all(prop_packet, &subscription_id_prop, true); if(rc){ mosquitto_FREE(prop_packet); return rc; } write_e(db_fptr, prop_packet->payload, proplen); mosquitto_FREE(prop_packet); } } return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); mosquitto_FREE(prop_packet); return 1; } int persist__chunk_message_store_write_v6(FILE *db_fptr, struct P_base_msg *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; int rc; if(chunk->properties){ proplen += mosquitto_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_BASE_MSG); header.length = htonl((uint32_t)sizeof(struct PF_base_msg) + 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_base_msg)); 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){ struct mosquitto__packet *prop_packet = mosquitto_calloc(1, sizeof(struct mosquitto__packet)+proplen); if(prop_packet == NULL){ return MOSQ_ERR_NOMEM; } prop_packet->remaining_length = proplen; prop_packet->packet_length = proplen; rc = property__write_all(prop_packet, chunk->properties, true); if(rc){ mosquitto_FREE(prop_packet); return rc; } if(fwrite(prop_packet->payload, 1, proplen, db_fptr) != proplen){ mosquitto_FREE(prop_packet); goto error; } mosquitto_FREE(prop_packet); } } return MOSQ_ERR_SUCCESS; error: log__printf(NULL, MOSQ_LOG_ERR, "Error: %s.", strerror(errno)); 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->clientid, 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 ================================================ FILE: src/plugin_acl_check.c ================================================ /* Copyright (c) 2011-2021 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/broker_plugin.h" #include "lib_load.h" #include "utlist.h" int acl__pre_check(mosquitto_plugin_id_t *plugin, struct mosquitto *context, int access) { const char *username; username = mosquitto_client_username(context); if(plugin->config.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(plugin->lib.version == 4){ if(access == MOSQ_ACL_UNSUBSCRIBE){ return MOSQ_ERR_SUCCESS; } }else if(plugin->lib.version == 3){ if(access == MOSQ_ACL_UNSUBSCRIBE){ return MOSQ_ERR_SUCCESS; } }else if(plugin->lib.version == 2){ if(access == MOSQ_ACL_SUBSCRIBE || access == MOSQ_ACL_UNSUBSCRIBE){ return MOSQ_ERR_SUCCESS; } } return MOSQ_ERR_PLUGIN_DEFER; } 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; } } static int plugin__acl_check(struct mosquitto__security_options *opts, struct mosquitto *context, const char *topic, uint32_t payloadlen, void *payload, uint8_t qos, bool retain, mosquitto_property *properties, int access) { int rc = MOSQ_ERR_PLUGIN_DEFER; struct mosquitto_acl_msg msg; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto_evt_acl_check event_data; memset(&msg, 0, sizeof(msg)); msg.topic = topic; msg.payloadlen = payloadlen; msg.payload = payload; msg.qos = qos; msg.retain = retain; DL_FOREACH_SAFE(opts->plugin_callbacks.acl_check, cb_base, cb_next){ /* 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 = properties; rc = cb_base->cb(MOSQ_EVT_ACL_CHECK, &event_data, cb_base->userdata); if(rc != MOSQ_ERR_PLUGIN_DEFER && rc != MOSQ_ERR_PLUGIN_IGNORE){ return rc; } } return rc; } int mosquitto_acl_check(struct mosquitto *context, const char *topic, uint32_t payloadlen, void *payload, uint8_t qos, bool retain, mosquitto_property *properties, int access) { int rc; int rc_final; 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_final = MOSQ_ERR_SUCCESS; if(db.config->security_options.plugin_callbacks.acl_check){ rc = plugin__acl_check(&db.config->security_options, context, topic, payloadlen, payload, qos, retain, properties, access); if(rc == MOSQ_ERR_PLUGIN_IGNORE){ /* Do nothing, this is as if the plugin doesn't exist */ }else if(rc == MOSQ_ERR_PLUGIN_DEFER){ rc_final = MOSQ_ERR_PLUGIN_DEFER; }else{ return rc; } } if(context->listener){ if(context->listener->security_options->plugin_callbacks.acl_check){ rc = plugin__acl_check(context->listener->security_options, context, topic, payloadlen, payload, qos, retain, properties, access); if(rc == MOSQ_ERR_PLUGIN_IGNORE){ /* Do nothing, this is as if the plugin doesn't exist */ }else if(rc == MOSQ_ERR_PLUGIN_DEFER){ rc_final = MOSQ_ERR_PLUGIN_DEFER; }else{ return rc; } } }else{ if(db.config->per_listener_settings){ return MOSQ_ERR_ACL_DENIED; } } /* If all plugins deferred, this is a denial. If rc == MOSQ_ERR_SUCCESS * here, then no plugins were configured, or all plugins ignored. */ if(rc_final == MOSQ_ERR_PLUGIN_DEFER){ rc_final = MOSQ_ERR_ACL_DENIED; } return rc_final; } ================================================ FILE: src/plugin_basic_auth.c ================================================ /* Copyright (c) 2011-2021 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/broker_plugin.h" #include "lib_load.h" #include "utlist.h" static int plugin__basic_auth(struct mosquitto__security_options *opts, struct mosquitto *context) { struct mosquitto_evt_basic_auth event_data; struct mosquitto__callback *cb_base, *cb_next; int rc; int rc_final = MOSQ_ERR_PLUGIN_IGNORE; DL_FOREACH_SAFE(opts->plugin_callbacks.basic_auth, cb_base, cb_next){ memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.username = context->username; event_data.password = context->password; event_data.password_len = context->password_len; rc = cb_base->cb(MOSQ_EVT_BASIC_AUTH, &event_data, cb_base->userdata); if(rc == MOSQ_ERR_PLUGIN_IGNORE){ /* Do nothing, this is as if the plugin doesn't exist */ }else if(rc == MOSQ_ERR_PLUGIN_DEFER){ rc_final = MOSQ_ERR_PLUGIN_DEFER; }else{ return rc; } } return rc_final; } int mosquitto_basic_auth(struct mosquitto *context) { int rc; bool plugin_used = false; /* Global plugins */ if(db.config->security_options.plugin_callbacks.basic_auth){ rc = plugin__basic_auth(&db.config->security_options, context); if(rc == MOSQ_ERR_PLUGIN_IGNORE){ /* Do nothing */ }else if(rc == MOSQ_ERR_PLUGIN_DEFER){ plugin_used = true; }else{ return rc; } } if(context->listener && context->listener->security_options->plugin_callbacks.basic_auth){ rc = plugin__basic_auth(context->listener->security_options, context); if(rc == MOSQ_ERR_PLUGIN_IGNORE){ /* Do nothing */ }else if(rc == MOSQ_ERR_PLUGIN_DEFER){ plugin_used = true; }else{ return rc; } } /* If all plugins deferred, this is a denial. plugin_used == false * here, then no plugins were configured. * anonymous logins are allowed. */ if(plugin_used == false){ if((context->listener && context->listener->security_options->allow_anonymous == true) || (!db.config->per_listener_settings && db.config->security_options.allow_anonymous == true && context->listener && context->listener->security_options->allow_anonymous != false)){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } }else{ /* Can't have got here without at least one plugin returning MOSQ_ERR_PLUGIN_DEFER. * This will now be a denial, unless it is anon and allow anon is true. */ if(context->username == NULL && ((context->listener && context->listener->security_options->allow_anonymous == true) || (!db.config->per_listener_settings && db.config->security_options.allow_anonymous == true && context->listener && context->listener->security_options->allow_anonymous != false))){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } return rc; } ================================================ FILE: src/plugin_callbacks.c ================================================ /* Copyright (c) 2016-2021 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 "utlist.h" #include "lib_load.h" static const char *get_event_name(enum mosquitto_plugin_event event) { switch(event){ case MOSQ_EVT_RELOAD: return "reload"; case MOSQ_EVT_ACL_CHECK: return "acl-check"; case MOSQ_EVT_BASIC_AUTH: return "basic-auth"; case MOSQ_EVT_PSK_KEY: return "psk-key"; case MOSQ_EVT_EXT_AUTH_START: return "auth-start"; case MOSQ_EVT_EXT_AUTH_CONTINUE: return "auth-continue"; case MOSQ_EVT_CONTROL: return "control"; case MOSQ_EVT_MESSAGE_IN: return "message-in"; case MOSQ_EVT_MESSAGE_OUT: return "message-out"; case MOSQ_EVT_TICK: return "tick"; case MOSQ_EVT_DISCONNECT: return "disconnect"; case MOSQ_EVT_CONNECT: return "connect"; case MOSQ_EVT_CLIENT_OFFLINE: return "connect"; case MOSQ_EVT_SUBSCRIBE: return "subscribe"; case MOSQ_EVT_UNSUBSCRIBE: return "unsubscribe"; case MOSQ_EVT_PERSIST_RESTORE: return "persist-restore"; case MOSQ_EVT_PERSIST_BASE_MSG_ADD: return "persist-base-msg-add"; case MOSQ_EVT_PERSIST_BASE_MSG_DELETE: return "persist-base-msg-delete"; case MOSQ_EVT_PERSIST_RETAIN_MSG_SET: return "persist-retain-msg-set"; case MOSQ_EVT_PERSIST_RETAIN_MSG_DELETE: return "persist-retain-msg-delete"; case MOSQ_EVT_PERSIST_CLIENT_ADD: return "persist-client-add"; case MOSQ_EVT_PERSIST_CLIENT_DELETE: return "persist-client-delete"; case MOSQ_EVT_PERSIST_CLIENT_UPDATE: return "persist-client-update"; case MOSQ_EVT_PERSIST_SUBSCRIPTION_ADD: return "persist-subscription-add"; case MOSQ_EVT_PERSIST_SUBSCRIPTION_DELETE: return "persist-subscription-delete"; case MOSQ_EVT_PERSIST_CLIENT_MSG_ADD: return "persist-client-msg-add"; case MOSQ_EVT_PERSIST_CLIENT_MSG_DELETE: return "persist-client-msg-delete"; case MOSQ_EVT_PERSIST_CLIENT_MSG_UPDATE: return "persist-client-msg-update"; case MOSQ_EVT_PERSIST_WILL_ADD: return "persist-will-add"; case MOSQ_EVT_PERSIST_WILL_DELETE: return "persist-will-delete"; } return ""; } static bool check_callback_exists(struct mosquitto__callback *cb_base, mosquitto_plugin_id_t *identifier, MOSQ_FUNC_generic_callback cb_func) { struct mosquitto__callback *tail, *tmp; DL_FOREACH_SAFE(cb_base, tail, tmp){ if(tail->identifier == identifier && tail->cb == cb_func){ return true; } } return false; } static struct mosquitto__callback **plugin__get_callback_base(struct mosquitto__security_options *security_options, enum mosquitto_plugin_event event) { switch(event){ case MOSQ_EVT_RELOAD: return &security_options->plugin_callbacks.reload; case MOSQ_EVT_ACL_CHECK: return &security_options->plugin_callbacks.acl_check; case MOSQ_EVT_BASIC_AUTH: return &security_options->plugin_callbacks.basic_auth; case MOSQ_EVT_PSK_KEY: return &security_options->plugin_callbacks.psk_key; case MOSQ_EVT_EXT_AUTH_START: return &security_options->plugin_callbacks.ext_auth_start; case MOSQ_EVT_EXT_AUTH_CONTINUE: return &security_options->plugin_callbacks.ext_auth_continue; case MOSQ_EVT_CONTROL: return NULL; case MOSQ_EVT_MESSAGE_IN: /* same as MOSQ_EVT_MESSAGE */ return &security_options->plugin_callbacks.message_in; case MOSQ_EVT_TICK: return &security_options->plugin_callbacks.tick; case MOSQ_EVT_DISCONNECT: return &security_options->plugin_callbacks.disconnect; case MOSQ_EVT_CONNECT: return &security_options->plugin_callbacks.connect; case MOSQ_EVT_CLIENT_OFFLINE: return &security_options->plugin_callbacks.client_offline; case MOSQ_EVT_SUBSCRIBE: return &security_options->plugin_callbacks.subscribe; case MOSQ_EVT_UNSUBSCRIBE: return &security_options->plugin_callbacks.unsubscribe; case MOSQ_EVT_PERSIST_RESTORE: return &security_options->plugin_callbacks.persist_restore; case MOSQ_EVT_PERSIST_CLIENT_ADD: return &security_options->plugin_callbacks.persist_client_add; case MOSQ_EVT_PERSIST_CLIENT_DELETE: return &security_options->plugin_callbacks.persist_client_delete; case MOSQ_EVT_PERSIST_CLIENT_UPDATE: return &security_options->plugin_callbacks.persist_client_update; case MOSQ_EVT_PERSIST_SUBSCRIPTION_ADD: return &security_options->plugin_callbacks.persist_subscription_add; case MOSQ_EVT_PERSIST_SUBSCRIPTION_DELETE: return &security_options->plugin_callbacks.persist_subscription_delete; case MOSQ_EVT_PERSIST_CLIENT_MSG_ADD: return &security_options->plugin_callbacks.persist_client_msg_add; case MOSQ_EVT_PERSIST_CLIENT_MSG_DELETE: return &security_options->plugin_callbacks.persist_client_msg_delete; case MOSQ_EVT_PERSIST_CLIENT_MSG_UPDATE: return &security_options->plugin_callbacks.persist_client_msg_update; case MOSQ_EVT_PERSIST_BASE_MSG_ADD: return &security_options->plugin_callbacks.persist_base_msg_add; case MOSQ_EVT_PERSIST_BASE_MSG_DELETE: return &security_options->plugin_callbacks.persist_base_msg_delete; case MOSQ_EVT_PERSIST_RETAIN_MSG_SET: return &security_options->plugin_callbacks.persist_retain_msg_set; case MOSQ_EVT_PERSIST_RETAIN_MSG_DELETE: return &security_options->plugin_callbacks.persist_retain_msg_delete; case MOSQ_EVT_MESSAGE_OUT: return &security_options->plugin_callbacks.message_out; case MOSQ_EVT_PERSIST_WILL_ADD: return &security_options->plugin_callbacks.persist_will_add; case MOSQ_EVT_PERSIST_WILL_DELETE: return &security_options->plugin_callbacks.persist_will_delete; } return NULL; } static int remove_callback(mosquitto_plugin_id_t *plugin, struct plugin_own_callback *own) { struct mosquitto__security_options *security_options; struct mosquitto__callback *tail, *tmp; struct mosquitto__callback **cb_base = NULL; for(int i=0; iconfig.security_option_count; i++){ security_options = plugin->config.security_options[i]; cb_base = plugin__get_callback_base(security_options, own->event); if(cb_base == NULL){ return MOSQ_ERR_NOT_SUPPORTED; } DL_FOREACH_SAFE(*cb_base, tail, tmp){ if(tail->identifier == plugin && tail->cb == own->cb_func){ DL_DELETE(*cb_base, tail); mosquitto_FREE(tail); break; } } } DL_DELETE(plugin->own_callbacks, own); mosquitto_FREE(own); return MOSQ_ERR_SUCCESS; } BROKER_EXPORT 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; struct plugin_own_callback *own_callback; if(cb_func == NULL){ return MOSQ_ERR_INVAL; } if(db.config->persistence && (event == MOSQ_EVT_PERSIST_RESTORE || event == MOSQ_EVT_PERSIST_BASE_MSG_ADD || event == MOSQ_EVT_PERSIST_BASE_MSG_DELETE || event == MOSQ_EVT_PERSIST_RETAIN_MSG_SET || event == MOSQ_EVT_PERSIST_RETAIN_MSG_DELETE || event == MOSQ_EVT_PERSIST_CLIENT_ADD || event == MOSQ_EVT_PERSIST_CLIENT_DELETE || event == MOSQ_EVT_PERSIST_CLIENT_UPDATE || event == MOSQ_EVT_PERSIST_SUBSCRIPTION_ADD || event == MOSQ_EVT_PERSIST_SUBSCRIPTION_DELETE || event == MOSQ_EVT_PERSIST_CLIENT_MSG_ADD || event == MOSQ_EVT_PERSIST_CLIENT_MSG_DELETE || event == MOSQ_EVT_PERSIST_CLIENT_MSG_UPDATE || event == MOSQ_EVT_PERSIST_WILL_ADD || event == MOSQ_EVT_PERSIST_WILL_DELETE )){ log__printf(NULL, MOSQ_LOG_ERR, "Error: `persistence true` cannot be used with a persistence plugin."); return MOSQ_ERR_INVAL; } if(event == MOSQ_EVT_CONTROL){ return control__register_callback(identifier, cb_func, event_data, userdata); } own_callback = mosquitto_calloc(1, sizeof(struct plugin_own_callback)); if(own_callback == NULL){ return MOSQ_ERR_NOMEM; } own_callback->event = (enum mosquitto_plugin_event)event; own_callback->cb_func = cb_func; DL_APPEND(identifier->own_callbacks, own_callback); if(identifier->config.security_option_count == 0){ log__printf(NULL, MOSQ_LOG_WARNING, "Plugin could not register callback '%s'", get_event_name((enum mosquitto_plugin_event)event)); return MOSQ_ERR_INVAL; } for(int i=0; iconfig.security_option_count; i++){ security_options = identifier->config.security_options[i]; cb_base = plugin__get_callback_base(security_options, (enum mosquitto_plugin_event)event); if(cb_base == NULL){ return MOSQ_ERR_NOT_SUPPORTED; } if(check_callback_exists(*cb_base, identifier, cb_func)){ return MOSQ_ERR_ALREADY_EXISTS; } cb_new = mosquitto_calloc(1, sizeof(struct mosquitto__callback)); if(cb_new == NULL){ DL_DELETE(identifier->own_callbacks, own_callback); mosquitto_FREE(own_callback); return MOSQ_ERR_NOMEM; } DL_APPEND(*cb_base, cb_new); cb_new->identifier = identifier; cb_new->cb = cb_func; cb_new->userdata = userdata; } if(identifier->plugin_name){ log__printf(NULL, MOSQ_LOG_INFO, "Plugin %s has registered to receive '%s' events.", identifier->plugin_name, get_event_name((enum mosquitto_plugin_event)event)); }else{ log__printf(NULL, MOSQ_LOG_INFO, "Plugin has registered to receive '%s' events.", get_event_name((enum mosquitto_plugin_event)event)); } return MOSQ_ERR_SUCCESS; } int plugin__callback_unregister_all(mosquitto_plugin_id_t *plugin) { struct plugin_own_callback *own, *own_tmp; if(plugin == NULL){ return MOSQ_ERR_INVAL; } control__unregister_all_callbacks(plugin); DL_FOREACH_SAFE(plugin->own_callbacks, own, own_tmp){ remove_callback(plugin, own); } return MOSQ_ERR_SUCCESS; } BROKER_EXPORT int mosquitto_callback_unregister( mosquitto_plugin_id_t *identifier, int event, MOSQ_FUNC_generic_callback cb_func, const void *event_data) { struct plugin_own_callback *own, *own_tmp; if(identifier == NULL || cb_func == NULL){ return MOSQ_ERR_INVAL; } if(event == MOSQ_EVT_CONTROL){ return control__unregister_callback(identifier, cb_func, event_data); } DL_FOREACH_SAFE(identifier->own_callbacks, own, own_tmp){ if(own->event == (enum mosquitto_plugin_event)event && own->cb_func == cb_func){ return remove_callback(identifier, own); } } return MOSQ_ERR_NOT_FOUND; } ================================================ FILE: src/plugin_cleanup.c ================================================ /* Copyright (c) 2011-2021 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/broker_plugin.h" #include "lib_load.h" #include "utlist.h" static int plugin__security_cleanup_single(mosquitto_plugin_id_t *plugin, bool reload); static void plugin__unload_single(mosquitto_plugin_id_t *plugin) { struct control_endpoint *ep, *tmp; /* Run plugin cleanup function */ if(plugin->lib.version == 5){ if(plugin->lib.plugin_cleanup_v5){ plugin->lib.plugin_cleanup_v5( plugin->lib.user_data, plugin->config.options, plugin->config.option_count); } }else if(plugin->lib.version == 4){ if(plugin->lib.plugin_cleanup_v4){ plugin->lib.plugin_cleanup_v4( plugin->lib.user_data, plugin->config.options, plugin->config.option_count); } }else if(plugin->lib.version == 3){ if(plugin->lib.plugin_cleanup_v3){ plugin->lib.plugin_cleanup_v3( plugin->lib.user_data, plugin->config.options, plugin->config.option_count); } }else if(plugin->lib.version == 2){ if(plugin->lib.plugin_cleanup_v2){ plugin->lib.plugin_cleanup_v2( plugin->lib.user_data, (struct mosquitto_auth_opt *)plugin->config.options, plugin->config.option_count); } } plugin__callback_unregister_all(plugin); mosquitto_FREE(plugin->plugin_name); mosquitto_FREE(plugin->plugin_version); DL_FOREACH_SAFE(plugin->control_endpoints, ep, tmp){ DL_DELETE(plugin->control_endpoints, ep); mosquitto_FREE(ep); } if(plugin->lib.lib){ //LIB_CLOSE(plugin->lib.lib); } memset(&plugin->lib, 0, sizeof(struct mosquitto__plugin_lib)); } int plugin__unload_all(void) { for(int i=0; ilib.version == 5){ rc = MOSQ_ERR_SUCCESS; }else if(plugin->lib.version == 4){ rc = plugin->lib.security_cleanup_v4( plugin->lib.user_data, plugin->config.options, plugin->config.option_count, reload); }else if(plugin->lib.version == 3){ rc = plugin->lib.security_cleanup_v3( plugin->lib.user_data, plugin->config.options, plugin->config.option_count, reload); }else if(plugin->lib.version == 2){ rc = plugin->lib.security_cleanup_v2( plugin->lib.user_data, (struct mosquitto_auth_opt *)plugin->config.options, plugin->config.option_count, reload); }else{ rc = MOSQ_ERR_INVAL; } return rc; } int mosquitto_security_cleanup(bool reload) { for(int i=0; i Copyright (c) 2023 Cedalo Gmbh 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 "utlist.h" static void plugin__handle_client_offline_single(struct mosquitto__security_options *opts, struct mosquitto *context, int reason) { struct mosquitto_evt_client_offline event_data; struct mosquitto__callback *cb_base, *cb_next; if(context->id == NULL){ return; } memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.reason = reason; DL_FOREACH_SAFE(opts->plugin_callbacks.client_offline, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_CLIENT_OFFLINE, &event_data, cb_base->userdata); } } void plugin__handle_client_offline(struct mosquitto *context, int reason) { /* Global plugins */ plugin__handle_client_offline_single(&db.config->security_options, context, reason); /* Per listener plugins */ if(context->listener){ plugin__handle_client_offline_single(context->listener->security_options, context, reason); } } ================================================ FILE: src/plugin_connect.c ================================================ /* Copyright (c) 2016-2021 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 "utlist.h" static void plugin__handle_connect_single(struct mosquitto__security_options *opts, struct mosquitto *context) { struct mosquitto_evt_connect event_data; struct mosquitto__callback *cb_base, *cb_next; memset(&event_data, 0, sizeof(event_data)); event_data.client = context; DL_FOREACH_SAFE(opts->plugin_callbacks.connect, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_CONNECT, &event_data, cb_base->userdata); } } void plugin__handle_connect(struct mosquitto *context) { /* Global plugins */ plugin__handle_connect_single(&db.config->security_options, context); /* Per listener plugins */ if(context->listener){ plugin__handle_connect_single(context->listener->security_options, context); } } ================================================ FILE: src/plugin_disconnect.c ================================================ /* Copyright (c) 2016-2021 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 "utlist.h" static void plugin__handle_disconnect_single(struct mosquitto__security_options *opts, struct mosquitto *context, int reason) { struct mosquitto_evt_disconnect event_data; struct mosquitto__callback *cb_base, *cb_next; if(context->id == NULL){ return; } memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.reason = reason; DL_FOREACH_SAFE(opts->plugin_callbacks.disconnect, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_DISCONNECT, &event_data, cb_base->userdata); } } void plugin__handle_disconnect(struct mosquitto *context, int reason) { /* Global plugins */ plugin__handle_disconnect_single(&db.config->security_options, context, reason); /* Per listener plugins */ if(context->listener){ plugin__handle_disconnect_single(context->listener->security_options, context, reason); } } ================================================ FILE: src/plugin_extended_auth.c ================================================ /* Copyright (c) 2011-2021 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/broker_plugin.h" #include "lib_load.h" #include "utlist.h" static int plugin__ext_auth_start(struct mosquitto__security_options *opts, struct mosquitto *context, bool reauth, const void *data_in, uint16_t data_in_len, void **data_out, uint16_t *data_out_len) { struct mosquitto_evt_extended_auth event_data; struct mosquitto__callback *cb_base, *cb_next; int rc; int rc_final = MOSQ_ERR_PLUGIN_DEFER; UNUSED(reauth); DL_FOREACH_SAFE(opts->plugin_callbacks.ext_auth_start, cb_base, cb_next){ 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_IGNORE){ /* Do nothing */ }else if(rc == MOSQ_ERR_PLUGIN_DEFER){ rc_final = MOSQ_ERR_PLUGIN_DEFER; }else{ *data_out = event_data.data_out; *data_out_len = event_data.data_out_len; return rc; } } return rc_final; } 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; if(!context || !context->listener || !context->auth_method){ return MOSQ_ERR_INVAL; } if(!data_out || !data_out_len){ return MOSQ_ERR_INVAL; } /* Global plugins */ if(db.config->security_options.plugin_callbacks.ext_auth_start){ rc = plugin__ext_auth_start(&db.config->security_options, context, reauth, data_in, data_in_len, data_out, data_out_len); if(rc == MOSQ_ERR_PLUGIN_IGNORE || rc == MOSQ_ERR_PLUGIN_DEFER){ /* Do nothing */ }else{ return rc; } } /* Per listener plugins */ if(context->listener){ if(context->listener->security_options->plugin_callbacks.ext_auth_start){ rc = plugin__ext_auth_start(context->listener->security_options, context, reauth, data_in, data_in_len, data_out, data_out_len); if(rc == MOSQ_ERR_PLUGIN_IGNORE || rc == MOSQ_ERR_PLUGIN_DEFER){ /* Do nothing */ }else{ return rc; } } }else{ if(db.config->per_listener_settings){ return MOSQ_ERR_AUTH; } } return MOSQ_ERR_NOT_SUPPORTED; } static int plugin__ext_auth_continue(struct mosquitto__security_options *opts, struct mosquitto *context, const void *data_in, uint16_t data_in_len, void **data_out, uint16_t *data_out_len) { int rc; struct mosquitto_evt_extended_auth event_data; struct mosquitto__callback *cb_base, *cb_next; DL_FOREACH_SAFE(opts->plugin_callbacks.ext_auth_continue, cb_base, cb_next){ 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_CONTINUE, &event_data, cb_base->userdata); if(rc == MOSQ_ERR_PLUGIN_IGNORE || rc == MOSQ_ERR_PLUGIN_DEFER){ /* Do nothing */ }else{ *data_out = event_data.data_out; *data_out_len = event_data.data_out_len; return rc; } } return MOSQ_ERR_PLUGIN_DEFER; } 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; if(!context || !context->listener || !context->auth_method){ return MOSQ_ERR_INVAL; } if(!data_out || !data_out_len){ return MOSQ_ERR_INVAL; } /* Global plugins */ if(db.config->security_options.plugin_callbacks.ext_auth_continue){ rc = plugin__ext_auth_continue(&db.config->security_options, context, data_in, data_in_len, data_out, data_out_len); if(rc == MOSQ_ERR_PLUGIN_IGNORE || rc == MOSQ_ERR_PLUGIN_DEFER){ /* Do nothing */ }else{ return rc; } } /* Per listener plugins */ if(context->listener){ if(context->listener->security_options->plugin_callbacks.ext_auth_continue){ rc = plugin__ext_auth_continue(context->listener->security_options, context, data_in, data_in_len, data_out, data_out_len); if(rc == MOSQ_ERR_PLUGIN_IGNORE || rc == MOSQ_ERR_PLUGIN_DEFER){ /* Do nothing */ }else{ return rc; } } }else{ if(db.config->per_listener_settings){ return MOSQ_ERR_AUTH; } } return MOSQ_ERR_NOT_SUPPORTED; } ================================================ FILE: src/plugin_init.c ================================================ /* Copyright (c) 2011-2021 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/broker_plugin.h" #include "lib_load.h" #include "utlist.h" typedef int (*FUNC_auth_plugin_version)(void); typedef int (*FUNC_plugin_version)(int, const int *); 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 plugin__load_single(mosquitto_plugin_id_t *plugin) { void *lib; int (*plugin_version)(int, const int *) = NULL; int (*plugin_auth_version)(void) = NULL; int version; int rc; const int plugin_versions[] = {5, 4, 3, 2}; int plugin_version_count = sizeof(plugin_versions)/sizeof(int); if(plugin->config.security_option_count == 0){ return MOSQ_ERR_SUCCESS; } memset(&plugin->lib, 0, sizeof(struct mosquitto__plugin_lib)); log__printf(NULL, MOSQ_LOG_INFO, "Loading plugin: %s", plugin->config.path); lib = LIB_LOAD(plugin->config.path); if(!lib){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to load plugin \"%s\".", plugin->config.path); LIB_ERROR(); return MOSQ_ERR_UNKNOWN; } plugin->lib.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; } plugin->lib.version = version; if(version == 5){ rc = plugin__load_v5(plugin, lib); if(rc){ return rc; } }else if(version == 4){ rc = plugin__load_v4(plugin, lib); if(rc){ return rc; } }else if(version == 3){ rc = plugin__load_v3(plugin, lib); if(rc){ return rc; } }else if(version == 2){ rc = plugin__load_v2(plugin, 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 plugin__load_all(void) { int rc = MOSQ_ERR_SUCCESS; for(int i=0; ilib.version == 5){ rc = MOSQ_ERR_SUCCESS; }else if(plugin->lib.version == 4){ rc = plugin->lib.security_init_v4( plugin->lib.user_data, plugin->config.options, plugin->config.option_count, reload); }else if(plugin->lib.version == 3){ rc = plugin->lib.security_init_v3( plugin->lib.user_data, plugin->config.options, plugin->config.option_count, reload); }else if(plugin->lib.version == 2){ rc = plugin->lib.security_init_v2( plugin->lib.user_data, (struct mosquitto_auth_opt *)plugin->config.options, plugin->config.option_count, reload); }else{ rc = MOSQ_ERR_INVAL; } return rc; } int mosquitto_security_init(bool reload) { int rc; for(int 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 "mosquitto_broker_internal.h" #include "utlist.h" struct should_free { bool topic; bool payload; bool properties; }; static int plugin__handle_message_single(struct mosquitto__callback *callbacks, enum mosquitto_plugin_event ev_type, struct should_free *to_free, struct mosquitto *context, struct mosquitto_base_msg *stored) { struct mosquitto_evt_message event_data; struct mosquitto__callback *cb_base, *cb_next; int rc = 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_SAFE(callbacks, cb_base, cb_next){ rc = cb_base->cb((int)ev_type, &event_data, cb_base->userdata); if(rc != MOSQ_ERR_SUCCESS){ break; } if(stored->topic != event_data.topic){ if(to_free->topic){ mosquitto_FREE(stored->topic); } stored->topic = event_data.topic; to_free->topic = true; } if(stored->payload != event_data.payload){ if(to_free->payload){ mosquitto_FREE(stored->payload); } stored->payload = event_data.payload; stored->payloadlen = event_data.payloadlen; to_free->payload = true; } if(stored->properties != event_data.properties){ if(to_free->properties){ mosquitto_property_free_all(&stored->properties); } stored->properties = event_data.properties; to_free->properties = true; } } stored->retain = event_data.retain; if(ev_type == MOSQ_EVT_MESSAGE_OUT){ stored->qos = event_data.qos; } return rc; } int plugin__handle_message_out(struct mosquitto *context, struct mosquitto_base_msg *stored) { int rc = MOSQ_ERR_SUCCESS; struct should_free to_free = {false, false, false}; /* in msg_out, original data will be freed later */ /* Global plugins */ rc = plugin__handle_message_single(db.config->security_options.plugin_callbacks.message_out, MOSQ_EVT_MESSAGE_OUT, &to_free, context, stored); if(rc){ return rc; } if(context->listener){ rc = plugin__handle_message_single(context->listener->security_options->plugin_callbacks.message_out, MOSQ_EVT_MESSAGE_OUT, &to_free, context, stored); } return rc; } int plugin__handle_message_in(struct mosquitto *context, struct mosquitto_base_msg *stored) { int rc = MOSQ_ERR_SUCCESS; struct should_free to_free = {true, true, true}; /* in msg_in, original data should be freed */ /* Global plugins */ rc = plugin__handle_message_single(db.config->security_options.plugin_callbacks.message_in, MOSQ_EVT_MESSAGE_IN, &to_free, context, stored); if(rc){ return rc; } if(context->listener){ rc = plugin__handle_message_single(context->listener->security_options->plugin_callbacks.message_in, MOSQ_EVT_MESSAGE_IN, &to_free, context, stored); } return rc; } ================================================ FILE: src/plugin_persist.c ================================================ /* Copyright (c) 2021 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 "mosquitto/mqtt_protocol.h" #include "send_mosq.h" #include "util_mosq.h" #include "utlist.h" #include "lib_load.h" #include "will_mosq.h" #include void plugin_persist__handle_restore(void) { struct mosquitto_evt_persist_restore event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); DL_FOREACH_SAFE(opts->plugin_callbacks.persist_restore, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_RESTORE, &event_data, cb_base->userdata); } } void plugin_persist__handle_client_add(struct mosquitto *context) { struct mosquitto_evt_persist_client event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; if(db.shutdown || context->is_persisted){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); event_data.data.clientid = context->id; event_data.data.username = context->username; event_data.data.auth_method = context->auth_method; event_data.data.will_delay_time = context->will_delay_time; event_data.data.session_expiry_time = context->session_expiry_time; event_data.data.will_delay_interval = context->will_delay_interval; event_data.data.session_expiry_interval = context->session_expiry_interval; if(context->listener){ event_data.data.listener_port = context->listener->port; }else{ event_data.data.listener_port = 0; } event_data.data.max_qos = context->max_qos; event_data.data.retain_available = context->retain_available; event_data.data.max_packet_size = context->maximum_packet_size; DL_FOREACH_SAFE(opts->plugin_callbacks.persist_client_add, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_CLIENT_ADD, &event_data, cb_base->userdata); } if(context->will){ plugin_persist__handle_will_add(context); } context->is_persisted = true; } void plugin_persist__handle_client_update(struct mosquitto *context) { struct mosquitto_evt_persist_client event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; struct mosquitto_message_v5 will; UNUSED(will); /* FIXME */ if(db.shutdown){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); event_data.data.clientid = context->id; event_data.data.username = context->username; event_data.data.auth_method = context->auth_method; event_data.data.will_delay_time = context->will_delay_time; event_data.data.session_expiry_time = context->session_expiry_time; event_data.data.will_delay_interval = context->will_delay_interval; event_data.data.session_expiry_interval = context->session_expiry_interval; if(context->listener){ event_data.data.listener_port = context->listener->port; }else{ event_data.data.listener_port = 0; } event_data.data.max_qos = context->max_qos; event_data.data.retain_available = context->retain_available; event_data.data.max_packet_size = context->maximum_packet_size; DL_FOREACH_SAFE(opts->plugin_callbacks.persist_client_update, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_CLIENT_UPDATE, &event_data, cb_base->userdata); } if(context->will){ plugin_persist__handle_will_add(context); }else{ plugin_persist__handle_will_delete(context); } } void plugin_persist__handle_client_delete(struct mosquitto *context) { struct mosquitto_evt_persist_client event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; if(context->id == NULL || context->state == mosq_cs_duplicate || db.shutdown){ return; } plugin_persist__handle_will_delete(context); if(context->is_persisted == false || context->session_expiry_interval != MQTT_SESSION_EXPIRY_IMMEDIATE){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); event_data.data.clientid = context->id; DL_FOREACH_SAFE(opts->plugin_callbacks.persist_client_delete, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_CLIENT_DELETE, &event_data, cb_base->userdata); } context->is_persisted = false; } void plugin_persist__handle_subscription_add(struct mosquitto *context, const struct mosquitto_subscription *sub) { struct mosquitto_evt_persist_subscription event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; if(db.shutdown || context->is_persisted == false){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); event_data.data.clientid = context->id; event_data.data.topic_filter = sub->topic_filter; event_data.data.identifier = sub->identifier; event_data.data.options = sub->options; DL_FOREACH_SAFE(opts->plugin_callbacks.persist_subscription_add, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_SUBSCRIPTION_ADD, &event_data, cb_base->userdata); } } void plugin_persist__handle_subscription_delete(struct mosquitto *context, char *sub) { struct mosquitto_evt_persist_subscription event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; if(db.shutdown || context->is_persisted == false){ return; } if(!sub){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); event_data.data.clientid = context->id; event_data.data.topic_filter = sub; DL_FOREACH_SAFE(opts->plugin_callbacks.persist_subscription_delete, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_SUBSCRIPTION_DELETE, &event_data, cb_base->userdata); } } static inline void set_client_msg_event_data(struct mosquitto_evt_persist_client_msg *event_data, struct mosquitto *context, const struct mosquitto__client_msg *client_msg) { event_data->data.clientid = context->id; event_data->data.cmsg_id = client_msg->data.cmsg_id; event_data->data.direction = (uint8_t)client_msg->data.direction; event_data->data.dup = client_msg->data.dup; event_data->data.mid = client_msg->data.mid; event_data->data.qos = client_msg->data.qos; event_data->data.retain = client_msg->data.retain; event_data->data.state = (uint8_t)client_msg->data.state; event_data->data.store_id = client_msg->base_msg->data.store_id; event_data->data.subscription_identifier = client_msg->data.subscription_identifier; } void plugin_persist__handle_client_msg_add(struct mosquitto *context, const struct mosquitto__client_msg *client_msg) { struct mosquitto_evt_persist_client_msg event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; if(context->is_persisted == false || (client_msg->data.qos == 0 && db.config->queue_qos0_messages == false) || db.shutdown){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); set_client_msg_event_data(&event_data, context, client_msg); DL_FOREACH_SAFE(opts->plugin_callbacks.persist_client_msg_add, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_CLIENT_MSG_ADD, &event_data, cb_base->userdata); } } void plugin_persist__handle_client_msg_delete(struct mosquitto *context, const struct mosquitto__client_msg *client_msg) { struct mosquitto_evt_persist_client_msg event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; if(context->is_persisted == false || (client_msg->data.qos == 0 && db.config->queue_qos0_messages == false) || db.shutdown){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); set_client_msg_event_data(&event_data, context, client_msg); DL_FOREACH_SAFE(opts->plugin_callbacks.persist_client_msg_delete, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_CLIENT_MSG_DELETE, &event_data, cb_base->userdata); } } void plugin_persist__handle_client_msg_update(struct mosquitto *context, const struct mosquitto__client_msg *client_msg) { struct mosquitto_evt_persist_client_msg event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; if(context->is_persisted == false || (client_msg->data.qos == 0 && db.config->queue_qos0_messages == false) || db.shutdown){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); set_client_msg_event_data(&event_data, context, client_msg); DL_FOREACH_SAFE(opts->plugin_callbacks.persist_client_msg_update, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_CLIENT_MSG_UPDATE, &event_data, cb_base->userdata); } } void plugin_persist__handle_base_msg_add(struct mosquitto__base_msg *base_msg) { struct mosquitto_evt_persist_base_msg event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; if(base_msg->stored || db.shutdown){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); event_data.data.store_id = base_msg->data.store_id; event_data.data.expiry_time = base_msg->data.expiry_time; event_data.data.topic = base_msg->data.topic; event_data.data.payload = base_msg->data.payload; event_data.data.source_id = base_msg->data.source_id; event_data.data.source_username = base_msg->data.source_username; event_data.data.properties = base_msg->data.properties; event_data.data.payloadlen = base_msg->data.payloadlen; event_data.data.source_mid = base_msg->data.source_mid; if(base_msg->source_listener){ event_data.data.source_port = base_msg->source_listener->port; }else{ event_data.data.source_port = 0; } event_data.data.qos = base_msg->data.qos; event_data.data.retain = base_msg->data.retain; DL_FOREACH_SAFE(opts->plugin_callbacks.persist_base_msg_add, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_BASE_MSG_ADD, &event_data, cb_base->userdata); } base_msg->stored = true; } void plugin_persist__handle_base_msg_delete(struct mosquitto__base_msg *base_msg) { struct mosquitto_evt_persist_base_msg event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; if(base_msg->stored == false || db.shutdown){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); event_data.data.store_id = base_msg->data.store_id; DL_FOREACH_SAFE(opts->plugin_callbacks.persist_base_msg_delete, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_BASE_MSG_DELETE, &event_data, cb_base->userdata); } base_msg->stored = false; } void plugin_persist__handle_retain_msg_set(struct mosquitto__base_msg *base_msg) { struct mosquitto_evt_persist_retain_msg event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; if(db.shutdown){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); event_data.store_id = base_msg->data.store_id; event_data.topic = base_msg->data.topic; DL_FOREACH_SAFE(opts->plugin_callbacks.persist_retain_msg_set, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_RETAIN_MSG_SET, &event_data, cb_base->userdata); } } void plugin_persist__handle_retain_msg_delete(struct mosquitto__base_msg *base_msg) { struct mosquitto_evt_persist_retain_msg event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; if(db.shutdown){ return; } opts = &db.config->security_options; memset(&event_data, 0, sizeof(event_data)); event_data.topic = base_msg->data.topic; DL_FOREACH_SAFE(opts->plugin_callbacks.persist_retain_msg_delete, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_RETAIN_MSG_DELETE, &event_data, cb_base->userdata); } } void plugin_persist__handle_will_add(struct mosquitto *context) { struct mosquitto_evt_persist_will_msg event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; struct mosquitto_message *will_msg; if(db.shutdown || !context->will){ return; } opts = &db.config->security_options; will_msg = &context->will->msg; memset(&event_data, 0, sizeof(event_data)); event_data.data.clientid = context->id; event_data.data.topic = will_msg->topic; event_data.data.payload = will_msg->payload; event_data.data.payloadlen = (uint32_t)will_msg->payloadlen; event_data.data.qos = (uint8_t)will_msg->qos; event_data.data.retain = will_msg->retain; event_data.data.properties = context->will->properties; DL_FOREACH_SAFE(opts->plugin_callbacks.persist_will_add, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_WILL_ADD, &event_data, cb_base->userdata); } } void plugin_persist__handle_will_delete(struct mosquitto *context) { struct mosquitto_evt_persist_will_msg event_data; struct mosquitto__callback *cb_base, *cb_next; struct mosquitto__security_options *opts; memset(&event_data, 0, sizeof(event_data)); event_data.data.clientid = context->id; if(db.shutdown){ return; } opts = &db.config->security_options; DL_FOREACH_SAFE(opts->plugin_callbacks.persist_will_delete, cb_base, cb_next){ cb_base->cb(MOSQ_EVT_PERSIST_WILL_ADD, &event_data, cb_base->userdata); } } ================================================ FILE: src/plugin_psk_key.c ================================================ /* Copyright (c) 2011-2021 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/broker_plugin.h" #include "lib_load.h" #include "utlist.h" static int plugin__psk_key_get(struct mosquitto__security_options *opts, struct mosquitto *context, const char *hint, const char *identity, char *key, int max_key_len) { struct mosquitto_evt_psk_key event_data; struct mosquitto__callback *cb_base, *cb_next; int rc; int rc_final = MOSQ_ERR_SUCCESS; DL_FOREACH_SAFE(opts->plugin_callbacks.psk_key, cb_base, cb_next){ 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_IGNORE){ /* Do nothing */ }else if(rc == MOSQ_ERR_PLUGIN_DEFER){ rc_final = MOSQ_ERR_PLUGIN_DEFER; }else{ return rc; } } return rc_final; } int mosquitto_psk_key_get(struct mosquitto *context, const char *hint, const char *identity, char *key, int max_key_len) { int rc; int rc_final = MOSQ_ERR_SUCCESS; /* Global plugins */ if(db.config->security_options.plugin_callbacks.psk_key){ rc = plugin__psk_key_get(&db.config->security_options, context, hint, identity, key, max_key_len); if(rc == MOSQ_ERR_PLUGIN_IGNORE){ /* Do nothing */ }else if(rc == MOSQ_ERR_PLUGIN_DEFER){ rc_final = MOSQ_ERR_PLUGIN_DEFER; }else{ return rc; } } /* Per listener plugins */ if(context->listener){ if(context->listener->security_options->plugin_callbacks.psk_key){ rc = plugin__psk_key_get(context->listener->security_options, context, hint, identity, key, max_key_len); if(rc == MOSQ_ERR_PLUGIN_IGNORE){ /* Do nothing */ }else if(rc == MOSQ_ERR_PLUGIN_DEFER){ rc_final = MOSQ_ERR_PLUGIN_DEFER; }else{ return rc; } } }else{ if(db.config->per_listener_settings){ return MOSQ_ERR_AUTH; } } rc = mosquitto_psk_key_get_default(context, hint, identity, key, max_key_len); if(rc == MOSQ_ERR_PLUGIN_IGNORE){ /* Do nothing */ }else if(rc == MOSQ_ERR_PLUGIN_DEFER){ rc_final = MOSQ_ERR_PLUGIN_DEFER; }else{ return rc; } /* If all plugins deferred, this is a denial. If rc == MOSQ_ERR_SUCCESS * here, then no plugins were configured. */ if(rc_final == MOSQ_ERR_PLUGIN_DEFER){ rc_final = MOSQ_ERR_AUTH; } return rc_final; } ================================================ FILE: src/plugin_public.c ================================================ /* Copyright (c) 2016-2021 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/mqtt_protocol.h" #include "send_mosq.h" #include "util_mosq.h" #include "will_mosq.h" #include "utlist.h" #include "will_mosq.h" #ifdef WITH_TLS # include #endif BROKER_EXPORT int mosquitto_plugin_set_info(mosquitto_plugin_id_t *identifier, const char *plugin_name, const char *plugin_version) { if(identifier == NULL || plugin_name == NULL){ return MOSQ_ERR_INVAL; } identifier->plugin_name = mosquitto_strdup(plugin_name); if(plugin_version){ identifier->plugin_version = mosquitto_strdup(plugin_version); }else{ identifier->plugin_version = NULL; } return MOSQ_ERR_SUCCESS; } BROKER_EXPORT const char *mosquitto_client_address(const struct mosquitto *client) { if(client){ return client->address; }else{ return NULL; } } BROKER_EXPORT struct mosquitto *mosquitto_client(const char *clientid) { size_t len; struct mosquitto *context; if(!clientid){ return NULL; } len = strlen(clientid); if(len == 0){ return NULL; } HASH_FIND(hh_id, db.contexts_by_id, clientid, strlen(clientid), context); return context; } BROKER_EXPORT int mosquitto_client_port(const struct mosquitto *client) { if(client && client->listener){ return client->listener->port; }else{ return 0; } } BROKER_EXPORT bool mosquitto_client_clean_session(const struct mosquitto *client) { if(client){ return client->clean_start; }else{ return true; } } BROKER_EXPORT const char *mosquitto_client_id(const struct mosquitto *client) { if(client){ return client->id; }else{ return NULL; } } BROKER_EXPORT unsigned mosquitto_client_id_hashv(const struct mosquitto *client) { if(client){ return client->id_hashv; }else{ return 0; } } BROKER_EXPORT int mosquitto_client_keepalive(const struct mosquitto *client) { if(client){ return client->keepalive; }else{ return -1; } } BROKER_EXPORT 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 UNUSED(client); return NULL; #endif } BROKER_EXPORT int mosquitto_client_protocol(const struct mosquitto *client) { #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS if(client && client->wsi){ return mp_websockets; }else #elif defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN if(client && client->transport == mosq_t_ws){ return mp_websockets; }else #else UNUSED(client); #endif { return mp_mqtt; } } BROKER_EXPORT 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; } } BROKER_EXPORT int mosquitto_client_sub_count(const struct mosquitto *client) { if(client){ return client->subs_count; }else{ return 0; } } BROKER_EXPORT 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; } } BROKER_EXPORT 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); loop__update_next_event(1); return MOSQ_ERR_SUCCESS; } BROKER_EXPORT 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; int rc; if(topic == NULL || payloadlen < 0 || (payloadlen > 0 && payload == NULL) || qos < 0 || qos > 2){ return MOSQ_ERR_INVAL; } payload_out = mosquitto_calloc(1, (size_t)(payloadlen+1)); if(payload_out == NULL){ return MOSQ_ERR_NOMEM; } memcpy(payload_out, payload, (size_t)payloadlen); rc = mosquitto_broker_publish( clientid, topic, payloadlen, payload_out, qos, retain, properties); if(rc){ mosquitto_FREE(payload_out); } return rc; } BROKER_EXPORT int mosquitto_set_username(struct mosquitto *client, const char *username) { char *u_dup; char *old; if(!client){ return MOSQ_ERR_INVAL; } if(username){ if(mosquitto_validate_utf8(username, (int)strlen(username))){ return MOSQ_ERR_MALFORMED_UTF8; } u_dup = mosquitto_strdup(username); if(!u_dup){ return MOSQ_ERR_NOMEM; } }else{ u_dup = NULL; } old = client->username; client->username = u_dup; mosquitto_FREE(old); return MOSQ_ERR_SUCCESS; } BROKER_EXPORT int mosquitto_set_clientid(struct mosquitto *client, const char *clientid) { struct mosquitto *found_client; char *id_dup; bool in_by_id; int clientid_len; if(!client || !clientid){ return MOSQ_ERR_INVAL; } in_by_id = client->in_by_id; /* If in_by_id is true, then this client has already authenticated and * completed the connection flow. This means it *cannot* take over an * existing session, and we must remove/add it to the by_id hash table. * * If in_by_id is false, then this client is currently going through * authentication and so it is safe to change the client id to any value * because it will be checked after authentication. */ if(in_by_id){ HASH_FIND(hh_id, db.contexts_by_id, clientid, strlen(clientid), found_client); if(found_client){ return MOSQ_ERR_ALREADY_EXISTS; } } clientid_len = (int)strlen(clientid); if(mosquitto_validate_utf8(clientid, clientid_len)){ return MOSQ_ERR_INVAL; } id_dup = mosquitto_strdup(clientid); if(!id_dup){ return MOSQ_ERR_NOMEM; } if(in_by_id){ context__remove_from_by_id(client); } mosquitto_free(client->id); client->id = id_dup; if(in_by_id){ context__add_to_by_id(client); } return MOSQ_ERR_SUCCESS; } /* Check to see whether durable clients still have rights to their subscriptions. */ static void check_subscription_acls(struct mosquitto *context) { int rc; uint8_t reason; for(int i=0; isubs_capacity; i++){ if(context->subs[i] == NULL){ continue; } rc = mosquitto_acl_check(context, context->subs[i]->topic_filter, 0, NULL, 0, /* FIXME */ false, NULL, MOSQ_ACL_SUBSCRIBE); if(rc != MOSQ_ERR_SUCCESS){ sub__remove(context, context->subs[i]->topic_filter, &reason); } } } 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); } if(context->session_expiry_interval != MQTT_SESSION_EXPIRY_IMMEDIATE){ check_subscription_acls(context); } do_disconnect(context, MOSQ_ERR_ADMINISTRATIVE_ACTION); } BROKER_EXPORT 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; } } } BROKER_EXPORT 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; } BROKER_EXPORT int mosquitto_apply_on_all_clients(int (*FUNC_client_functor)(const struct mosquitto *, void *), void *functor_context) { int rc = MOSQ_ERR_SUCCESS; struct mosquitto *ctxt, *ctxt_tmp; HASH_ITER(hh_id, db.contexts_by_id, ctxt, ctxt_tmp){ rc = (*FUNC_client_functor)(ctxt, functor_context); if(rc != MOSQ_ERR_SUCCESS){ break; } } return rc; } BROKER_EXPORT int mosquitto_persist_client_add(struct mosquitto_client *client) { struct mosquitto *context; int rc; if(client == NULL){ return MOSQ_ERR_INVAL; } if(client->clientid == NULL){ rc = MOSQ_ERR_INVAL; goto error; } context = NULL; HASH_FIND(hh_id, db.contexts_by_id, client->clientid, strlen(client->clientid), context); if(context){ rc = MOSQ_ERR_INVAL; goto error; } context = context__init(); if(!context){ rc = MOSQ_ERR_NOMEM; goto error; } context->id = client->clientid; client->clientid = NULL; context->username = client->username; client->username = NULL; context->auth_method = client->auth_method; client->auth_method = NULL; context->clean_start = false; context->will_delay_time = client->will_delay_time; context->session_expiry_time = client->session_expiry_time; context->will_delay_interval = client->will_delay_interval; context->session_expiry_interval = client->session_expiry_interval; context->max_qos = client->max_qos; context->maximum_packet_size = client->max_packet_size; context->retain_available = client->retain_available; context->is_persisted = true; /* in per_listener_settings mode, try to find the listener by persisted port */ if(db.config->per_listener_settings && client->listener_port > 0){ for(int i=0; i < db.config->listener_count; i++){ if(db.config->listeners[i].port == client->listener_port){ context->listener = &db.config->listeners[i]; break; } } } context__add_to_by_id(context); session_expiry__add_from_persistence(context, context->session_expiry_time); return MOSQ_ERR_SUCCESS; error: SAFE_FREE(client->clientid); SAFE_FREE(client->username); SAFE_FREE(client->auth_method); return rc; } BROKER_EXPORT int mosquitto_persist_client_update(struct mosquitto_client *client) { struct mosquitto *context; int rc; if(client == NULL){ return MOSQ_ERR_INVAL; } if(client->clientid == NULL){ rc = MOSQ_ERR_INVAL; goto error; } context = NULL; HASH_FIND(hh_id, db.contexts_by_id, client->clientid, strlen(client->clientid), context); if(context == NULL){ rc = MOSQ_ERR_NOT_FOUND; goto error; } mosquitto_free(context->username); context->username = client->username; client->username = NULL; context->clean_start = false; context->will_delay_time = client->will_delay_time; context->session_expiry_time = client->session_expiry_time; context->will_delay_interval = client->will_delay_interval; context->session_expiry_interval = client->session_expiry_interval; context->max_qos = client->max_qos; context->maximum_packet_size = client->max_packet_size; context->retain_available = client->retain_available; /* in per_listener_settings mode, try to find the listener by persisted port */ if(db.config->per_listener_settings && client->listener_port > 0){ for(int i=0; i < db.config->listener_count; i++){ if(db.config->listeners[i].port == client->listener_port){ context->listener = &db.config->listeners[i]; break; } } } return MOSQ_ERR_SUCCESS; error: SAFE_FREE(client->username); return rc; } BROKER_EXPORT int mosquitto_persist_client_delete(const char *clientid) { struct mosquitto *context; if(clientid == NULL){ return MOSQ_ERR_INVAL; } context = NULL; HASH_FIND(hh_id, db.contexts_by_id, clientid, strlen(clientid), context); if(context == NULL){ return MOSQ_ERR_SUCCESS; } session_expiry__remove(context); will_delay__remove(context); will__clear(context); context->clean_start = true; context->session_expiry_interval = MQTT_SESSION_EXPIRY_IMMEDIATE; context->is_persisted = false; mosquitto__set_state(context, mosq_cs_duplicate); do_disconnect(context, MOSQ_ERR_SUCCESS); return MOSQ_ERR_SUCCESS; } static struct mosquitto__base_msg *find_store_msg(uint64_t store_id) { struct mosquitto__base_msg *base_msg; HASH_FIND(hh, db.msg_store, &store_id, sizeof(store_id), base_msg); return base_msg; } BROKER_EXPORT int mosquitto_persist_client_msg_add(struct mosquitto_client_msg *client_msg) { struct mosquitto *context; struct mosquitto__base_msg *base_msg; if(client_msg == NULL || client_msg->clientid == NULL){ return MOSQ_ERR_INVAL; } HASH_FIND(hh_id, db.contexts_by_id, client_msg->clientid, strlen(client_msg->clientid), context); if(context == NULL){ return MOSQ_ERR_NOT_FOUND; } base_msg = find_store_msg(client_msg->store_id); if(base_msg == NULL){ return MOSQ_ERR_NOT_FOUND; } if(client_msg->direction == mosq_md_out){ if(client_msg->qos > 0){ context->last_mid = client_msg->mid; } return db__message_insert_outgoing(context, client_msg->cmsg_id, client_msg->mid, client_msg->qos, client_msg->retain, base_msg, client_msg->subscription_identifier, false, false); }else if(client_msg->direction == mosq_md_in){ return db__message_insert_incoming(context, client_msg->cmsg_id, base_msg, false); }else{ return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } BROKER_EXPORT int mosquitto_persist_client_msg_delete(struct mosquitto_client_msg *client_msg) { struct mosquitto *context; if(client_msg == NULL || client_msg->clientid == NULL){ return MOSQ_ERR_INVAL; } HASH_FIND(hh_id, db.contexts_by_id, client_msg->clientid, strlen(client_msg->clientid), context); if(context == NULL){ return MOSQ_ERR_NOT_FOUND; } int rc = MOSQ_ERR_INVAL; if(client_msg->direction == mosq_md_out){ rc = db__message_delete_outgoing(context, client_msg->mid, mosq_ms_any, client_msg->qos); }else if(client_msg->direction == mosq_md_in){ rc = db__message_remove_incoming(context, client_msg->mid); } return rc; } BROKER_EXPORT int mosquitto_persist_client_msg_update(struct mosquitto_client_msg *client_msg) { struct mosquitto *context; if(client_msg == NULL || client_msg->clientid == NULL){ return MOSQ_ERR_INVAL; } HASH_FIND(hh_id, db.contexts_by_id, client_msg->clientid, strlen(client_msg->clientid), context); if(context == NULL){ return MOSQ_ERR_NOT_FOUND; } if(client_msg->direction == mosq_md_out){ db__message_update_outgoing(context, client_msg->mid, client_msg->state, client_msg->qos, false); }else if(client_msg->direction == mosq_md_in){ // FIXME db__message_update_incoming(context, client_msg->mid, client_msg->state, client_msg->qos, false); }else{ return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } BROKER_EXPORT int mosquitto_persist_client_msg_clear(struct mosquitto_client_msg *client_msg) { struct mosquitto *context; if(client_msg == NULL || client_msg->clientid == NULL){ return MOSQ_ERR_INVAL; } HASH_FIND(hh_id, db.contexts_by_id, client_msg->clientid, strlen(client_msg->clientid), context); if(context == NULL){ return MOSQ_ERR_NOT_FOUND; } if(client_msg->direction == mosq_bmd_in || client_msg->direction == mosq_bmd_all){ db__messages_delete_incoming(context); }else if(client_msg->direction == mosq_bmd_out || client_msg->direction == mosq_bmd_all){ db__messages_delete_outgoing(context); } return MOSQ_ERR_SUCCESS; } BROKER_EXPORT int mosquitto_subscription_add(const struct mosquitto_subscription *sub) { struct mosquitto *context; if(sub == NULL || sub->clientid == NULL || sub->topic_filter == NULL || sub->clientid[0] == '\0' || sub->topic_filter[0] == '\0'){ return MOSQ_ERR_INVAL; } HASH_FIND(hh_id, db.contexts_by_id, sub->clientid, strlen(sub->clientid), context); if(context){ return sub__add(context, sub); }else{ return MOSQ_ERR_NOT_FOUND; } } BROKER_EXPORT int mosquitto_subscription_delete(const char *clientid, const char *topic) { struct mosquitto *context; uint8_t reason; if(clientid == NULL || topic == NULL || clientid[0] == '\0' || topic[0] == '\0'){ return MOSQ_ERR_INVAL; } HASH_FIND(hh_id, db.contexts_by_id, clientid, strlen(clientid), context); if(context){ return sub__remove(context, topic, &reason); }else{ return MOSQ_ERR_NOT_FOUND; } } BROKER_EXPORT int mosquitto_persist_base_msg_add(struct mosquitto_base_msg *msg_add) { struct mosquitto context; struct mosquitto__base_msg *base_msg; int rc; memset(&context, 0, sizeof(context)); if(msg_add->payloadlen > MQTT_MAX_PAYLOAD){ return MOSQ_ERR_INVAL; } /* db__message_store only takes a copy of .id and .username, so it is reasonably safe * to cast the const char * to char * */ context.id = (char *)msg_add->source_id; context.username = (char *)msg_add->source_username; base_msg = mosquitto_calloc(1, sizeof(struct mosquitto__base_msg)); if(base_msg == NULL){ goto error; } base_msg->data.store_id = msg_add->store_id; base_msg->data.expiry_time = msg_add->expiry_time; base_msg->data.payloadlen = msg_add->payloadlen; base_msg->data.source_mid = msg_add->source_mid; base_msg->data.qos = msg_add->qos; base_msg->data.retain = msg_add->retain; base_msg->data.payload = msg_add->payload; msg_add->payload = NULL; base_msg->data.topic = msg_add->topic; msg_add->topic = NULL; base_msg->data.properties = msg_add->properties; msg_add->properties = NULL; if(msg_add->source_port){ for(int i=0; ilistener_count; i++){ if(db.config->listeners[i].port == msg_add->source_port){ base_msg->source_listener = &db.config->listeners[i]; break; } } } base_msg->stored = true; rc = db__message_store(&context, base_msg, NULL, mosq_mo_broker); return rc; error: mosquitto_property_free_all(&msg_add->properties); mosquitto_free(msg_add->topic); mosquitto_free(msg_add->payload); mosquitto_free(base_msg); return MOSQ_ERR_NOMEM; } BROKER_EXPORT int mosquitto_persist_base_msg_delete(uint64_t store_id) { struct mosquitto__base_msg *base_msg; base_msg = find_store_msg(store_id); if(base_msg && base_msg->ref_count == 0){ /* If ref count is zero, then we should delete this. It might seem * surprising that the ref count is zero already, but it can be. If ref * count is greater than zero then there may be e.g. a retained message * still referring to this and the retained message persist update is * coming later. If we delete the message now in that case, then when * the retain changes there will be use after free errors. All messages * will eventually hit ref count 0 and be removed in some way or other. */ db__msg_store_remove(base_msg, false); } return MOSQ_ERR_SUCCESS; } BROKER_EXPORT void mosquitto_complete_basic_auth(const char *clientid, int result) { struct mosquitto *context; if(clientid == NULL){ return; } HASH_FIND(hh_id, db.contexts_by_id_delayed_auth, clientid, strlen(clientid), context); if(context){ HASH_DELETE(hh_id, db.contexts_by_id_delayed_auth, context); if(result == MOSQ_ERR_SUCCESS){ connect__on_authorised(context, NULL, 0); }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); } context->clean_start = true; context->session_expiry_interval = MQTT_SESSION_EXPIRY_IMMEDIATE; will__clear(context); do_disconnect(context, MOSQ_ERR_AUTH); } } } BROKER_EXPORT int mosquitto_broker_node_id_set(uint16_t id) { if(id > 1023){ return MOSQ_ERR_INVAL; }else{ db.node_id = id; db.node_id_shifted = ((uint64_t)id) << 54; return MOSQ_ERR_SUCCESS; } } BROKER_EXPORT const char *mosquitto_persistence_location(void) { return db.config->persistence_location; } BROKER_EXPORT int mosquitto_client_will_set(const char *clientid, const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties) { struct mosquitto *mosq = mosquitto_client(clientid); if(!mosq){ return MOSQ_ERR_NOT_FOUND; } if(properties && mosq->protocol != mosq_p_mqtt5){ if(net__is_connected(mosq)){ return MOSQ_ERR_NOT_SUPPORTED; } mosq->protocol = mosq_p_mqtt5; } return will__set(mosq, topic, payloadlen, payload, qos, retain, properties); } ================================================ FILE: src/plugin_reload.c ================================================ /* Copyright (c) 2016-2025 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 "mosquitto/broker.h" #include "utlist.h" static int plugin__handle_reload_single(struct mosquitto__security_options *opts) { struct mosquitto_evt_reload event_data; struct mosquitto__callback *cb_base, *cb_next; memset(&event_data, 0, sizeof(event_data)); // Using DL_FOREACH_SAFE here, as reload callbacks might unregister themself DL_FOREACH_SAFE(opts->plugin_callbacks.reload, cb_base, cb_next){ int rc = cb_base->cb(MOSQ_EVT_RELOAD, &event_data, cb_base->userdata); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Plugin %s produced error on reload: %s", cb_base->identifier->plugin_name?cb_base->identifier->plugin_name:"", mosquitto_strerror(rc)); return rc; } } return MOSQ_ERR_SUCCESS; } int plugin__handle_reload(void) { struct mosquitto__security_options *opts; int rc; /* Global plugins */ rc = plugin__handle_reload_single(&db.config->security_options); if(rc){ return rc; } for(int i=0; ilistener_count; i++){ opts = db.config->listeners[i].security_options; if(opts && opts->plugin_callbacks.reload){ rc = plugin__handle_reload_single(opts); if(rc){ return rc; } } } return MOSQ_ERR_SUCCESS; } ================================================ FILE: src/plugin_subscribe.c ================================================ /* Copyright (c) 2016-2022 Roger Light Copyright (c) 2022 Cedalo GmbH 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 "utlist.h" static int plugin__handle_subscribe_single(struct mosquitto__security_options *opts, struct mosquitto *context, struct mosquitto_subscription *sub) { struct mosquitto_evt_subscribe event_data; struct mosquitto__callback *cb_base, *cb_next; int rc = MOSQ_ERR_SUCCESS; memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.data.topic_filter = sub->topic_filter; event_data.data.options = sub->options; event_data.data.identifier = sub->identifier; event_data.data.properties = sub->properties; DL_FOREACH_SAFE(opts->plugin_callbacks.subscribe, cb_base, cb_next){ rc = cb_base->cb(MOSQ_EVT_SUBSCRIBE, &event_data, cb_base->userdata); if(rc != MOSQ_ERR_SUCCESS){ break; } if(sub->topic_filter != event_data.data.topic_filter){ mosquitto_free(sub->topic_filter); sub->topic_filter = event_data.data.topic_filter; } } sub->options = event_data.data.options; return rc; } int plugin__handle_subscribe(struct mosquitto *context, struct mosquitto_subscription *sub) { int rc = MOSQ_ERR_SUCCESS; /* Global plugins */ rc = plugin__handle_subscribe_single(&db.config->security_options, context, sub); if(rc){ return rc; } if(context->listener){ rc = plugin__handle_subscribe_single(context->listener->security_options, context, sub); } return rc; } ================================================ FILE: src/plugin_tick.c ================================================ /* Copyright (c) 2016-2021 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 "mosquitto/broker.h" #include "utlist.h" static void plugin__handle_tick_single(struct mosquitto__security_options *opts) { struct mosquitto_evt_tick event_data; struct mosquitto__callback *cb_base, *cb_next; memset(&event_data, 0, sizeof(event_data)); // Using DL_FOREACH_SAFE here, as tick callbacks might unregister themself DL_FOREACH_SAFE(opts->plugin_callbacks.tick, cb_base, cb_next){ mosquitto_time_ns(&event_data.now_s, &event_data.now_ns); if(mosquitto_time_cmp(event_data.now_s, event_data.now_ns, cb_base->data.next_tick.tv_sec, cb_base->data.next_tick.tv_nsec) > 0){ event_data.next_s = 0; event_data.next_ms = 0; cb_base->cb(MOSQ_EVT_TICK, &event_data, cb_base->userdata); loop__update_next_event(event_data.next_s * 1000 + event_data.next_ms); cb_base->data.next_tick.tv_sec = event_data.now_s + event_data.next_s; cb_base->data.next_tick.tv_nsec = event_data.now_ns + 1000000*event_data.next_ms; if(cb_base->data.next_tick.tv_nsec > 1000000000){ cb_base->data.next_tick.tv_nsec -= 1000000000; cb_base->data.next_tick.tv_sec += 1; } } } } void plugin__handle_tick(void) { struct mosquitto__security_options *opts; /* Global plugins */ plugin__handle_tick_single(&db.config->security_options); for(int i=0; ilistener_count; i++){ opts = db.config->listeners[i].security_options; if(opts && opts->plugin_callbacks.tick){ plugin__handle_tick_single(opts); } } } ================================================ FILE: src/plugin_unsubscribe.c ================================================ /* Copyright (c) 2016-2022 Roger Light Copyright (c) 2022 Cedalo GmbH 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 "utlist.h" static int plugin__handle_unsubscribe_single(struct mosquitto__security_options *opts, struct mosquitto *context, struct mosquitto_subscription *sub) { struct mosquitto_evt_unsubscribe event_data; struct mosquitto__callback *cb_base, *cb_next; int rc = MOSQ_ERR_SUCCESS; memset(&event_data, 0, sizeof(event_data)); event_data.client = context; event_data.data.topic_filter = sub->topic_filter; event_data.data.properties = sub->properties; DL_FOREACH_SAFE(opts->plugin_callbacks.unsubscribe, cb_base, cb_next){ rc = cb_base->cb(MOSQ_EVT_UNSUBSCRIBE, &event_data, cb_base->userdata); if(rc != MOSQ_ERR_SUCCESS){ break; } if(sub->topic_filter != event_data.data.topic_filter){ mosquitto_free(sub->topic_filter); sub->topic_filter = event_data.data.topic_filter; } } return rc; } int plugin__handle_unsubscribe(struct mosquitto *context, struct mosquitto_subscription *sub) { int rc = MOSQ_ERR_SUCCESS; /* Global plugins */ rc = plugin__handle_unsubscribe_single(&db.config->security_options, context, sub); if(rc){ return rc; } if(context->listener){ rc = plugin__handle_unsubscribe_single(context->listener->security_options, context, sub); } return rc; } ================================================ FILE: src/plugin_v2.c ================================================ /* Copyright (c) 2011-2021 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 loads v2 plugins in a v5 wrapper to make the core code cleaner */ #include "config.h" #include #include #include "mosquitto/broker.h" #include "mosquitto_broker_internal.h" #include "mosquitto/broker_plugin.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 plugin_v2_basic_auth(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; struct mosquitto_evt_basic_auth *ed = event_data; UNUSED(event); if(plugin->lib.unpwd_check_v2 == NULL){ return MOSQ_ERR_INVAL; } return plugin->lib.unpwd_check_v2( plugin->lib.user_data, ed->username, ed->password); } static int plugin_v2_acl_check(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; struct mosquitto_evt_acl_check *ed = event_data; int rc; UNUSED(event); if(plugin->lib.acl_check_v2 == NULL){ return MOSQ_ERR_INVAL; } rc = acl__pre_check(plugin, ed->client, ed->access); if(rc == MOSQ_ERR_PLUGIN_DEFER){ return plugin->lib.acl_check_v2( plugin->lib.user_data, ed->client->id, ed->client->username, ed->topic, ed->access); }else{ return rc; } } static int plugin_v2_psk_key_get(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; struct mosquitto_evt_psk_key *ed = event_data; UNUSED(event); if(plugin->lib.psk_key_get_v2 == NULL){ return MOSQ_ERR_INVAL; } return plugin->lib.psk_key_get_v2( plugin->lib.user_data, ed->hint, ed->identity, ed->key, ed->max_key_len); } static int plugin_v2_reload(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; int rc; UNUSED(event); UNUSED(event_data); rc = plugin->lib.security_cleanup_v2( plugin->lib.user_data, (struct mosquitto_auth_opt *)plugin->config.options, plugin->config.option_count, true); if(rc){ return rc; } rc = plugin->lib.security_init_v2( plugin->lib.user_data, (struct mosquitto_auth_opt *)plugin->config.options, plugin->config.option_count, true); return rc; } int plugin__load_v2(mosquitto_plugin_id_t *plugin, void *lib) { int rc; if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } plugin->lib.lib = lib; plugin->lib.user_data = NULL; plugin->lib.identifier = plugin; if(plugin->lib.plugin_init_v2){ rc = plugin->lib.plugin_init_v2( &plugin->lib.user_data, (struct mosquitto_auth_opt *)plugin->config.options, plugin->config.option_count); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Authentication plugin returned %d when initialising.", rc); return rc; } } mosquitto_callback_register(plugin, MOSQ_EVT_RELOAD, plugin_v2_reload, NULL, plugin); if(plugin->lib.unpwd_check_v2){ mosquitto_callback_register(plugin, MOSQ_EVT_BASIC_AUTH, plugin_v2_basic_auth, NULL, plugin); } if(plugin->lib.acl_check_v2){ mosquitto_callback_register(plugin, MOSQ_EVT_ACL_CHECK, plugin_v2_acl_check, NULL, plugin); } if(plugin->lib.psk_key_get_v2){ mosquitto_callback_register(plugin, MOSQ_EVT_PSK_KEY, plugin_v2_psk_key_get, NULL, plugin); } return 0; } ================================================ FILE: src/plugin_v3.c ================================================ /* Copyright (c) 2011-2021 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 loads v3 plugins in a v5 wrapper to make the core code cleaner */ #include "config.h" #include #include #include "mosquitto/broker.h" #include "mosquitto_broker_internal.h" #include "mosquitto/broker_plugin.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 plugin_v3_basic_auth(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; struct mosquitto_evt_basic_auth *ed = event_data; UNUSED(event); if(plugin->lib.unpwd_check_v3 == NULL){ return MOSQ_ERR_INVAL; } return plugin->lib.unpwd_check_v3( plugin->lib.user_data, ed->client, ed->username, ed->password); } static int plugin_v3_acl_check(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; struct mosquitto_evt_acl_check *ed = event_data; struct mosquitto_acl_msg msg; int rc; UNUSED(event); if(plugin->lib.acl_check_v3 == NULL){ return MOSQ_ERR_INVAL; } memset(&msg, 0, sizeof(msg)); msg.topic = ed->topic; msg.payloadlen = ed->payloadlen; msg.payload = ed->payload; msg.qos = ed->qos; msg.retain = ed->retain; rc = acl__pre_check(plugin, ed->client, ed->access); if(rc == MOSQ_ERR_PLUGIN_DEFER){ return plugin->lib.acl_check_v3( plugin->lib.user_data, ed->access, ed->client, &msg); }else{ return rc; } } static int plugin_v3_psk_key_get(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; struct mosquitto_evt_psk_key *ed = event_data; UNUSED(event); if(plugin->lib.psk_key_get_v3 == NULL){ return MOSQ_ERR_INVAL; } return plugin->lib.psk_key_get_v3( plugin->lib.user_data, ed->client, ed->hint, ed->identity, ed->key, ed->max_key_len); } static int plugin_v3_reload(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; int rc; UNUSED(event); UNUSED(event_data); rc = plugin->lib.security_cleanup_v3( plugin->lib.user_data, plugin->config.options, plugin->config.option_count, true); if(rc){ return rc; } rc = plugin->lib.security_init_v3( plugin->lib.user_data, plugin->config.options, plugin->config.option_count, true); return rc; } int plugin__load_v3(mosquitto_plugin_id_t *plugin, void *lib) { int rc; if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } plugin->lib.lib = lib; plugin->lib.user_data = NULL; plugin->lib.identifier = plugin; if(plugin->lib.plugin_init_v3){ rc = plugin->lib.plugin_init_v3(&plugin->lib.user_data, plugin->config.options, plugin->config.option_count); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Authentication plugin returned %d when initialising.", rc); return rc; } } mosquitto_callback_register(plugin, MOSQ_EVT_RELOAD, plugin_v3_reload, NULL, plugin); if(plugin->lib.unpwd_check_v3){ mosquitto_callback_register(plugin, MOSQ_EVT_BASIC_AUTH, plugin_v3_basic_auth, NULL, plugin); } if(plugin->lib.acl_check_v3){ mosquitto_callback_register(plugin, MOSQ_EVT_ACL_CHECK, plugin_v3_acl_check, NULL, plugin); } if(plugin->lib.psk_key_get_v3){ mosquitto_callback_register(plugin, MOSQ_EVT_PSK_KEY, plugin_v3_psk_key_get, NULL, plugin); } return 0; } ================================================ FILE: src/plugin_v4.c ================================================ /* Copyright (c) 2011-2021 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 loads v4 plugins in a v5 wrapper to make the core code cleaner */ #include "config.h" #include #include #include "mosquitto/broker.h" #include "mosquitto_broker_internal.h" #include "mosquitto/broker_plugin.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 plugin_v4_basic_auth(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; struct mosquitto_evt_basic_auth *ed = event_data; UNUSED(event); if(plugin->lib.unpwd_check_v4 == NULL){ return MOSQ_ERR_PLUGIN_DEFER; } return plugin->lib.unpwd_check_v4( plugin->lib.user_data, ed->client, ed->username, ed->password); } static int plugin_v4_acl_check(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; struct mosquitto_evt_acl_check *ed = event_data; struct mosquitto_acl_msg msg; int rc; UNUSED(event); if(plugin->lib.acl_check_v4 == NULL){ return MOSQ_ERR_PLUGIN_DEFER; } memset(&msg, 0, sizeof(msg)); msg.topic = ed->topic; msg.payloadlen = ed->payloadlen; msg.payload = ed->payload; msg.qos = ed->qos; msg.retain = ed->retain; rc = acl__pre_check(plugin, ed->client, ed->access); if(rc == MOSQ_ERR_PLUGIN_DEFER){ return plugin->lib.acl_check_v4( plugin->lib.user_data, ed->access, ed->client, &msg); }else{ return rc; } } static int plugin_v4_auth_start(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; struct mosquitto_evt_extended_auth *ed = event_data; UNUSED(event); if(plugin->lib.auth_start_v4 == NULL){ return MOSQ_ERR_PLUGIN_DEFER; } return plugin->lib.auth_start_v4( plugin->lib.user_data, ed->client, ed->client->auth_method, false, ed->data_in, ed->data_in_len, &ed->data_out, &ed->data_out_len); } static int plugin_v4_auth_continue(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; struct mosquitto_evt_extended_auth *ed = event_data; UNUSED(event); if(plugin->lib.auth_continue_v4 == NULL){ return MOSQ_ERR_PLUGIN_DEFER; } return plugin->lib.auth_continue_v4( plugin->lib.user_data, ed->client, ed->client->auth_method, ed->data_in, ed->data_in_len, &ed->data_out, &ed->data_out_len); } static int plugin_v4_psk_key_get(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; struct mosquitto_evt_psk_key *ed = event_data; UNUSED(event); if(plugin->lib.psk_key_get_v4 == NULL){ return MOSQ_ERR_PLUGIN_DEFER; } return plugin->lib.psk_key_get_v4( plugin->lib.user_data, ed->client, ed->hint, ed->identity, ed->key, ed->max_key_len); } static int plugin_v4_reload(int event, void *event_data, void *userdata) { mosquitto_plugin_id_t *plugin = userdata; int rc; UNUSED(event); UNUSED(event_data); rc = plugin->lib.security_cleanup_v4( plugin->lib.user_data, plugin->config.options, plugin->config.option_count, true); if(rc){ return rc; } rc = plugin->lib.security_init_v4( plugin->lib.user_data, plugin->config.options, plugin->config.option_count, true); return rc; } int plugin__load_v4(mosquitto_plugin_id_t *plugin, void *lib) { int rc; if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } if(!(plugin->lib.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(); return MOSQ_ERR_UNKNOWN; } plugin->lib.unpwd_check_v4 = (FUNC_auth_plugin_unpwd_check_v4)LIB_SYM(lib, "mosquitto_auth_unpwd_check"); if(plugin->lib.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->lib.psk_key_get_v4 = (FUNC_auth_plugin_psk_key_get_v4)LIB_SYM(lib, "mosquitto_auth_psk_key_get"); if(plugin->lib.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->lib.auth_start_v4 = (FUNC_auth_plugin_auth_start_v4)LIB_SYM(lib, "mosquitto_auth_start"); plugin->lib.auth_continue_v4 = (FUNC_auth_plugin_auth_continue_v4)LIB_SYM(lib, "mosquitto_auth_continue"); if(plugin->lib.auth_start_v4){ if(plugin->lib.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."); return MOSQ_ERR_UNKNOWN; } }else{ log__printf(NULL, MOSQ_LOG_INFO, " └── Extended authentication not enabled."); } plugin->lib.lib = lib; plugin->lib.user_data = NULL; plugin->lib.identifier = plugin; if(plugin->lib.plugin_init_v4){ rc = plugin->lib.plugin_init_v4(&plugin->lib.user_data, plugin->config.options, plugin->config.option_count); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Authentication plugin returned %d when initialising.", rc); return rc; } } mosquitto_callback_register(plugin, MOSQ_EVT_RELOAD, plugin_v4_reload, NULL, plugin); if(plugin->lib.unpwd_check_v4){ mosquitto_callback_register(plugin, MOSQ_EVT_BASIC_AUTH, plugin_v4_basic_auth, NULL, plugin); } if(plugin->lib.acl_check_v4){ mosquitto_callback_register(plugin, MOSQ_EVT_ACL_CHECK, plugin_v4_acl_check, NULL, plugin); } if(plugin->lib.auth_start_v4){ mosquitto_callback_register(plugin, MOSQ_EVT_EXT_AUTH_START, plugin_v4_auth_start, NULL, plugin); } if(plugin->lib.auth_continue_v4){ mosquitto_callback_register(plugin, MOSQ_EVT_EXT_AUTH_CONTINUE, plugin_v4_auth_continue, NULL, plugin); } if(plugin->lib.psk_key_get_v4){ mosquitto_callback_register(plugin, MOSQ_EVT_PSK_KEY, plugin_v4_psk_key_get, NULL, plugin); } return 0; } ================================================ FILE: src/plugin_v5.c ================================================ /* Copyright (c) 2016-2021 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 "utlist.h" #include "lib_load.h" int plugin__load_v5(mosquitto_plugin_id_t *plugin, void *lib) { int rc; if(!(plugin->lib.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; } /* Optional function */ plugin->lib.plugin_cleanup_v5 = (FUNC_plugin_cleanup_v5)LIB_SYM(lib, "mosquitto_plugin_cleanup"); plugin->lib.lib = lib; plugin->lib.user_data = NULL; plugin->lib.identifier = plugin; if(plugin->lib.plugin_init_v5){ rc = plugin->lib.plugin_init_v5(plugin, &plugin->lib.user_data, plugin->config.options, plugin->config.option_count); if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Plugin returned %d when initialising.", rc); return rc; } } if(plugin->plugin_name && plugin->plugin_version){ log__printf(NULL, MOSQ_LOG_INFO, "Plugin %s version %s loaded.", plugin->plugin_name, plugin->plugin_version); }else if(plugin->plugin_name){ log__printf(NULL, MOSQ_LOG_INFO, "Plugin %s loaded.", plugin->plugin_name); } return 0; } ================================================ FILE: src/property_broker.c ================================================ /* Copyright (c) 2018-2021 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 "mosquitto/mqtt_protocol.h" #include "property_mosq.h" #include "property_common.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){ switch(mosquitto_property_identifier(p)){ case MQTT_PROP_SESSION_EXPIRY_INTERVAL: context->session_expiry_interval = mosquitto_property_int32_value(p); break; case MQTT_PROP_RECEIVE_MAXIMUM: context->msgs_out.inflight_maximum = mosquitto_property_int16_value(p); if(context->msgs_out.inflight_maximum == 0){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: CONNECT packet with receive-maximum = 0.", context->id); return MOSQ_ERR_PROTOCOL; } context->msgs_out.inflight_quota = context->msgs_out.inflight_maximum; break; case MQTT_PROP_MAXIMUM_PACKET_SIZE: context->maximum_packet_size = mosquitto_property_int32_value(p); if(context->maximum_packet_size == 0){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: CONNECT packet with maximum-packet-size = 0.", context->id); return MOSQ_ERR_PROTOCOL; } break; case MQTT_PROP_TOPIC_ALIAS_MAXIMUM: context->alias_max_l2r = mosquitto_property_int16_value(p); if(context->alias_max_l2r > context->listener->max_topic_alias_broker){ context->alias_max_l2r = context->listener->max_topic_alias_broker; } break; default: break; } p = mosquitto_property_next(p); } 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; msg->expiry_interval = MSG_EXPIRY_INFINITE; while(p){ switch(mosquitto_property_identifier(p)){ 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: /* We save these properties for transmission with the PUBLISH */ /* Add this property to the end of the list */ if(msg_properties){ msg_properties_last->next = p; msg_properties_last = p; }else{ msg_properties = p; msg_properties_last = p; } /* And remove it from *props */ if(p_prev){ p_prev->next = mosquitto_property_next(p); p = mosquitto_property_next(p_prev); }else{ *props = mosquitto_property_next(p); p = *props; } msg_properties_last->next = NULL; break; case MQTT_PROP_WILL_DELAY_INTERVAL: /* Leave this in *props, to be freed */ context->will_delay_interval = mosquitto_property_int32_value(p); p_prev = p; p = mosquitto_property_next(p); break; case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: /* Leave this in *props, to be freed */ msg->expiry_interval = mosquitto_property_int32_value(p); p_prev = p; p = mosquitto_property_next(p); break; default: msg->properties = msg_properties; log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: CONNECT packet invalid property (%d).", context->id, p->identifier); return MOSQ_ERR_PROTOCOL; break; } } msg->properties = msg_properties; return MOSQ_ERR_SUCCESS; } int property__process_publish(struct mosquitto__base_msg *base_msg, mosquitto_property **props, int *topic_alias, uint32_t *message_expiry_interval, bool is_bridge) { mosquitto_property *p, *p_prev; mosquitto_property *msg_properties_last; p = *props; p_prev = NULL; base_msg->data.properties = NULL; msg_properties_last = NULL; while(p){ switch(mosquitto_property_identifier(p)){ 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(base_msg->data.properties){ msg_properties_last->next = p; msg_properties_last = p; }else{ base_msg->data.properties = p; msg_properties_last = p; } if(p_prev){ p_prev->next = mosquitto_property_next(p); p = mosquitto_property_next(p_prev); }else{ *props = mosquitto_property_next(p); p = *props; } msg_properties_last->next = NULL; break; case MQTT_PROP_TOPIC_ALIAS: *topic_alias = mosquitto_property_int16_value(p); p_prev = p; p = mosquitto_property_next(p); break; case MQTT_PROP_MESSAGE_EXPIRY_INTERVAL: *message_expiry_interval = mosquitto_property_int32_value(p); p_prev = p; p = mosquitto_property_next(p); break; case MQTT_PROP_SUBSCRIPTION_IDENTIFIER: if(!is_bridge || mosquitto_property_varint_value(p) == 0){ return MOSQ_ERR_PROTOCOL; } p_prev = p; p = mosquitto_property_next(p); break; default: p = mosquitto_property_next(p); break; } } 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(mosquitto_property_identifier(p) == MQTT_PROP_SESSION_EXPIRY_INTERVAL){ uint32_t session_expiry_interval = mosquitto_property_int32_value(p); if(context->session_expiry_interval == MQTT_SESSION_EXPIRY_IMMEDIATE && session_expiry_interval != MQTT_SESSION_EXPIRY_IMMEDIATE){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: DISCONNECT packet with mismatched session-expiry-interval (%d:%d).", context->id, context->session_expiry_interval, p->value.i32); return MOSQ_ERR_PROTOCOL; } context->session_expiry_interval = session_expiry_interval; } p = mosquitto_property_next(p); } return MOSQ_ERR_SUCCESS; } ================================================ FILE: src/proxy_v1.c ================================================ #ifdef WIN32 # include # include #else # include # include #endif #include #include "mosquitto_broker_internal.h" #include "mosquitto_internal.h" #include "net_mosq.h" #if !defined(WITH_WEBSOCKETS) || WITH_WEBSOCKETS == WS_IS_BUILTIN #define PROXY_V1_PACKET_LIMIT 108 const uint8_t signature4[11] = {'P', 'R', 'O', 'X', 'Y', ' ', 'T', 'C', 'P', '4', ' '}; const uint8_t signature6[11] = {'P', 'R', 'O', 'X', 'Y', ' ', 'T', 'C', 'P', '6', ' '}; const uint8_t signatureU[14] = {'P', 'R', 'O', 'X', 'Y', ' ', 'U', 'N', 'K', 'N', 'O', 'W', 'N', ' '}; static void proxy_cleanup(struct mosquitto *context) { mosquitto_FREE(context->proxy.buf); } static int update_transport(struct mosquitto *context) { #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN if(context->listener->protocol == mp_websockets){ return http__context_init(context); }else #endif { context->transport = mosq_t_tcp; } return MOSQ_ERR_SUCCESS; } static int get_address_for_unknown(struct mosquitto *context) { char address[1024]; proxy_cleanup(context); if(!net__socket_get_address(context->sock, address, sizeof(address), &context->remote_port)){ context->address = mosquitto_strdup(address); } if(!context->address){ return MOSQ_ERR_NOMEM; } return update_transport(context); } static int proxy_v1__decode(struct mosquitto *context) { char *saddr_s, *daddr_s, *sport_s, *dport_s; char *saveptr = NULL; int sport, dport; struct in6_addr addr; if(context->proxy.pos >= sizeof(signatureU) && !memcmp(context->proxy.buf, signatureU, sizeof(signatureU))){ return get_address_for_unknown(context); }else if(context->proxy.pos >= sizeof(signature4) && !memcmp(context->proxy.buf, signature4, sizeof(signature4))){ context->proxy.fam = AF_INET; }else if(context->proxy.pos >= sizeof(signature6) && !memcmp(context->proxy.buf, signature6, sizeof(signature6))){ context->proxy.fam = AF_INET6; }else{ log__printf(NULL, MOSQ_LOG_NOTICE, "Connection rejected, corrupt PROXY header."); proxy_cleanup(context); return MOSQ_ERR_INVAL; } context->proxy.buf[context->proxy.pos-1] = '\0'; context->proxy.buf[context->proxy.pos-2] = '\0'; saddr_s = strtok_r((char *)&context->proxy.buf[sizeof(signature4)], " ", &saveptr); daddr_s = strtok_r(NULL, " ", &saveptr); sport_s = strtok_r(NULL, " ", &saveptr); dport_s = strtok_r(NULL, " ", &saveptr); if(!saddr_s || !daddr_s || !sport_s || !dport_s || (saveptr && strlen(saveptr) > 0)){ log__printf(NULL, MOSQ_LOG_NOTICE, "Connection rejected, corrupt PROXY header."); proxy_cleanup(context); return MOSQ_ERR_INVAL; } /* Verify ports */ sport = atoi(sport_s); dport = atoi(dport_s); if(sport < 1 || sport > 65535 || dport < 1 || dport > 65535){ log__printf(NULL, MOSQ_LOG_NOTICE, "Connection rejected, corrupt PROXY header."); proxy_cleanup(context); return MOSQ_ERR_INVAL; } /* Verify addresses */ if(context->proxy.fam == AF_INET){ if(inet_pton(AF_INET, saddr_s, &addr) != 1 || inet_pton(AF_INET, daddr_s, &addr) != 1){ log__printf(NULL, MOSQ_LOG_NOTICE, "Connection rejected, corrupt PROXY header."); proxy_cleanup(context); return MOSQ_ERR_INVAL; } }else if(context->proxy.fam == AF_INET6){ if(inet_pton(AF_INET6, saddr_s, &addr) != 1 || inet_pton(AF_INET6, daddr_s, &addr) != 1){ log__printf(NULL, MOSQ_LOG_NOTICE, "Connection rejected, corrupt PROXY header."); proxy_cleanup(context); return MOSQ_ERR_INVAL; } } context->address = mosquitto_strdup(saddr_s); if(!context->address){ proxy_cleanup(context); return MOSQ_ERR_NOMEM; } context->remote_port = (uint16_t )sport; proxy_cleanup(context); return update_transport(context); } int proxy_v1__read(struct mosquitto *context) { if(context->proxy.buf == NULL){ context->proxy.buf = mosquitto_calloc(1, PROXY_V1_PACKET_LIMIT); if(!context->proxy.buf){ return MOSQ_ERR_NOMEM; } context->proxy.pos = 0; } while(context->proxy.pos < PROXY_V1_PACKET_LIMIT){ if(net__read(context, &(context->proxy.buf[context->proxy.pos]), 1) != 1){ proxy_cleanup(context); return MOSQ_ERR_CONN_LOST; } context->proxy.pos++; if(context->proxy.pos > 2){ /* FIXME: Figure out better limit */ if(context->proxy.buf[context->proxy.pos-1] == '\n' && context->proxy.buf[context->proxy.pos-2] == '\r'){ /* Line received, now decode */ return proxy_v1__decode(context); } } } if(context->proxy.pos == PROXY_V1_PACKET_LIMIT){ log__printf(NULL, MOSQ_LOG_NOTICE, "Connection rejected, corrupt PROXY header."); proxy_cleanup(context); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } #endif ================================================ FILE: src/proxy_v2.c ================================================ #ifdef WIN32 # include # include #else # include # include #endif #include #include "mosquitto_broker_internal.h" #include "mosquitto_internal.h" #include "net_mosq.h" #if !defined(WITH_WEBSOCKETS) || WITH_WEBSOCKETS == WS_IS_BUILTIN #define PROXY_CMD_LOCAL 0x00 #define PROXY_CMD_PROXY 0x01 #define PROXY_TCP_IPV4 0x11 #define PROXY_TCP_IPV6 0x21 #define PROXY_TCP_UNIX 0x31 #define PP2_TYPE_ALPN 0x01 #define PP2_TYPE_AUTHORITY 0x02 #define PP2_TYPE_CRC32C 0x03 #define PP2_TYPE_NOOP 0x04 #define PP2_TYPE_UNIQUE_ID 0x05 #define PP2_TYPE_SSL 0x20 #define PP2_SUBTYPE_SSL_VERSION 0x21 #define PP2_SUBTYPE_SSL_CN 0x22 #define PP2_SUBTYPE_SSL_CIPHER 0x23 #define PP2_SUBTYPE_SSL_SIG_ALG 0x24 #define PP2_SUBTYPE_SSL_KEY_ALG 0x25 #define PP2_TYPE_NETNS 0x30 #define PP2_CLIENT_SSL 0x01 #define PP2_CLIENT_CERT_CONN 0x02 #define PP2_CLIENT_CERT_SESS 0x04 #define PROXY_PACKET_LIMIT 500 struct proxy_hdr_v2 { uint8_t sig[12]; /* hex 0D 0A 0D 0A 00 0D 0A 51 55 49 54 0A */ uint8_t ver_cmd; /* protocol version and command */ uint8_t fam; /* protocol family and address */ uint16_t len; /* number of following bytes part of the header */ }; union proxy_addr { struct { /* for TCP/UDP over IPv4, len = 12 */ uint32_t src_addr; uint32_t dst_addr; uint16_t src_port; uint16_t dst_port; } ipv4_addr; struct { /* for TCP/UDP over IPv6, len = 36 */ uint8_t src_addr[16]; uint8_t dst_addr[16]; uint16_t src_port; uint16_t dst_port; } ipv6_addr; struct { /* for AF_UNIX sockets, len = 216 */ uint8_t src_addr[108]; uint8_t dst_addr[108]; } unix_addr; }; struct pp2_tlv { uint8_t type; uint8_t length_h; uint8_t length_l; }; struct pp2_tlv_ssl { uint8_t client; uint32_t verify; }; const uint8_t signature[12] = {0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A}; static void proxy_cleanup(struct mosquitto *context) { mosquitto_FREE(context->proxy.buf); mosquitto_FREE(context->proxy.tls_version); mosquitto_FREE(context->proxy.cipher); } static int read_tlv_ssl(struct mosquitto *context, uint16_t len, bool *have_certificate) { struct pp2_tlv_ssl ssl = {0}; if(len < sizeof(uint8_t) + sizeof(uint32_t)){ return MOSQ_ERR_INVAL; } ssl.client = context->proxy.buf[context->proxy.pos]; ssl.verify = ntohl(*(uint32_t *)(&context->proxy.buf[context->proxy.pos + sizeof(uint8_t)])); context->proxy.pos = (uint16_t)(context->proxy.pos + sizeof(uint8_t) + sizeof(uint32_t)); len = (uint16_t)(len - (sizeof(uint8_t) + sizeof(uint32_t))); if(ssl.client & PP2_CLIENT_SSL && ssl.client & PP2_CLIENT_CERT_SESS && !ssl.verify){ *have_certificate = true; } while(len > 0){ if(context->proxy.len - context->proxy.pos < (int)sizeof(struct pp2_tlv)){ return MOSQ_ERR_INVAL; } struct pp2_tlv *tlv = (struct pp2_tlv *)(&context->proxy.buf[context->proxy.pos]); uint16_t tlv_len = (uint16_t)((tlv->length_h<<8) + tlv->length_l); context->proxy.pos = (uint16_t)(context->proxy.pos + sizeof(struct pp2_tlv)); if(tlv_len > context->proxy.len - context->proxy.pos){ return MOSQ_ERR_INVAL; } switch(tlv->type){ case PP2_SUBTYPE_SSL_VERSION: #ifdef WITH_TLS mosquitto_free(context->proxy.tls_version); context->proxy.tls_version = mosquitto_strndup((const char *)&context->proxy.buf[context->proxy.pos], tlv_len); #else return MOSQ_ERR_NOT_SUPPORTED; #endif break; case PP2_SUBTYPE_SSL_CIPHER: #ifdef WITH_TLS mosquitto_free(context->proxy.cipher); context->proxy.cipher = mosquitto_strndup((const char *)&context->proxy.buf[context->proxy.pos], tlv_len); #else return MOSQ_ERR_NOT_SUPPORTED; #endif break; case PP2_SUBTYPE_SSL_CN: #ifdef WITH_TLS if(context->listener->use_identity_as_username){ mosquitto_free(context->username); context->username = mosquitto_strndup((const char *)&context->proxy.buf[context->proxy.pos], tlv_len); if(!context->username){ return MOSQ_ERR_NOMEM; } } #else return MOSQ_ERR_NOT_SUPPORTED; #endif break; } len = (uint16_t)(len - (sizeof(uint8_t) + sizeof(uint8_t) + sizeof(uint8_t) + tlv_len)); context->proxy.pos = (uint16_t)(context->proxy.pos + tlv_len); } context->proxy.have_tls = true; return MOSQ_ERR_SUCCESS; } static int read_tlv(struct mosquitto *context, bool *have_certificate) { while(context->proxy.pos < context->proxy.len){ if(context->proxy.len - context->proxy.pos < (int)sizeof(struct pp2_tlv)){ return MOSQ_ERR_INVAL; } struct pp2_tlv *tlv = (struct pp2_tlv *)(&context->proxy.buf[context->proxy.pos]); uint16_t tlv_len = (uint16_t)((tlv->length_h<<8) + tlv->length_l); context->proxy.pos = (uint16_t)(context->proxy.pos + sizeof(struct pp2_tlv)); if(tlv_len > context->proxy.len - context->proxy.pos){ return MOSQ_ERR_INVAL; } switch(tlv->type){ case PP2_TYPE_SSL: { int rc = read_tlv_ssl(context, tlv_len, have_certificate); if(rc){ return rc; } } break; default: context->proxy.pos = (uint16_t)(context->proxy.pos + tlv_len); break; } } return MOSQ_ERR_SUCCESS; } int proxy_v2__read(struct mosquitto *context) { struct proxy_hdr_v2 hdr; if(context->proxy.cmd == -1){ context->proxy.buf = NULL; if(net__read(context, &hdr, sizeof(hdr)) != sizeof(hdr)){ return MOSQ_ERR_CONN_LOST; } if(memcmp(hdr.sig, signature, sizeof(signature))){ return MOSQ_ERR_INVAL; } if((hdr.ver_cmd & 0xF0) != 0x20){ return MOSQ_ERR_INVAL; } context->proxy.cmd = hdr.ver_cmd & 0x0F; if(context->proxy.cmd != 0x00 && context->proxy.cmd != 0x01){ return MOSQ_ERR_INVAL; } context->proxy.fam = hdr.fam; if((hdr.fam != 0x00 || context->proxy.cmd != PROXY_CMD_LOCAL) && hdr.fam != PROXY_TCP_IPV4 && hdr.fam != PROXY_TCP_IPV6 && hdr.fam != PROXY_TCP_UNIX){ return 1; } context->proxy.pos = 0; context->proxy.len = ntohs(hdr.len); if(context->proxy.len > 0){ /* PROXY_PACKET_LIMIT=500 bytes, arbitrary upper limit */ switch(context->proxy.fam){ case PROXY_TCP_IPV4: if(context->proxy.len < 12 || context->proxy.len > PROXY_PACKET_LIMIT){ return MOSQ_ERR_INVAL; } break; case PROXY_TCP_IPV6: if(context->proxy.len < 36 || context->proxy.len > PROXY_PACKET_LIMIT){ return MOSQ_ERR_INVAL; } break; case PROXY_TCP_UNIX: if(context->proxy.len > PROXY_PACKET_LIMIT){ return MOSQ_ERR_INVAL; } break; } context->proxy.buf = mosquitto_calloc(1, (size_t)(context->proxy.len+1)); if(!context->proxy.buf){ return MOSQ_ERR_NOMEM; } }else{ if(context->proxy.cmd != PROXY_CMD_LOCAL || context->proxy.fam != 0x00){ return MOSQ_ERR_PROTOCOL; } } } if(context->proxy.pos < context->proxy.len){ ssize_t rc = net__read(context, context->proxy.buf, (size_t)(context->proxy.len - context->proxy.pos)); if(rc > 0){ context->proxy.pos = (uint16_t)(context->proxy.pos + rc); }else{ proxy_cleanup(context); return MOSQ_ERR_CONN_LOST; } } if(context->proxy.pos == context->proxy.len){ if(context->proxy.fam == PROXY_TCP_IPV4){ char address[100]; union proxy_addr *addr = (union proxy_addr *)context->proxy.buf; inet_ntop(AF_INET, &addr->ipv4_addr.src_addr, address, sizeof(address)); context->address = mosquitto_strdup(address); context->remote_port = ntohs(addr->ipv4_addr.src_port); context->proxy.pos = 4+4+2+2; }else if(context->proxy.fam == PROXY_TCP_IPV6){ char address[100]; union proxy_addr *addr = (union proxy_addr *)context->proxy.buf; inet_ntop(AF_INET6, addr->ipv6_addr.src_addr, address, sizeof(address)); context->address = mosquitto_strdup(address); context->remote_port = ntohs(addr->ipv6_addr.src_port); context->proxy.pos = 16+16+2+2; }else if(context->proxy.fam == PROXY_TCP_UNIX){ union proxy_addr *addr = (union proxy_addr *)context->proxy.buf; context->address = mosquitto_strndup((char *)addr->unix_addr.src_addr, sizeof(addr->unix_addr.src_addr)); context->remote_port = 0; context->proxy.pos = (uint16_t)(sizeof(addr->unix_addr.src_addr) + 1); }else{ /* Must be LOCAL */ /* Ignore address */ context->address = NULL; context->remote_port = 0; proxy_cleanup(context); return MOSQ_ERR_PROXY; } if(!context->address){ proxy_cleanup(context); return MOSQ_ERR_NOMEM; } bool have_certificate = false; int rc = read_tlv(context, &have_certificate); if(rc){ log__printf(NULL, MOSQ_LOG_NOTICE, "Connection from %s:%d rejected, corrupt PROXY header.", context->address, context->remote_port); proxy_cleanup(context); return MOSQ_ERR_PROXY; } mosquitto_FREE(context->proxy.buf); if(context->listener->proxy_protocol_v2_require_tls && !context->proxy.have_tls){ log__printf(NULL, MOSQ_LOG_NOTICE, "Connection from %s:%d rejected, client did not connect using TLS.", context->address, context->remote_port); proxy_cleanup(context); return MOSQ_ERR_PROXY; } #ifdef WITH_TLS if(context->listener->require_certificate){ if(!have_certificate){ log__printf(NULL, MOSQ_LOG_NOTICE, "Connection from %s:%d rejected, client did not provide a certificate.", context->address, context->remote_port); proxy_cleanup(context); return MOSQ_ERR_PROXY; } } if(context->proxy.tls_version && context->proxy.cipher){ log__printf(NULL, MOSQ_LOG_NOTICE, "Connection from %s:%d negotiated %s cipher %s", context->address, context->remote_port, context->proxy.tls_version, context->proxy.cipher); } #endif proxy_cleanup(context); #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_BUILTIN if(context->listener->protocol == mp_websockets){ return http__context_init(context); }else #endif { context->transport = mosq_t_tcp; } } return MOSQ_ERR_SUCCESS; } #endif ================================================ FILE: src/psk_file.c ================================================ /* Copyright (c) 2011-2021 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 "mosquitto/mqtt_protocol.h" #include "send_mosq.h" #include "util_mosq.h" static int psk__cleanup(struct mosquitto__psk **psk); static int psk__file_parse(struct mosquitto__psk **psk_id, const char *psk_file); static void psk__free_item(struct mosquitto__psk *psk) { mosquitto_FREE(psk->username); mosquitto_FREE(psk->password); mosquitto_FREE(psk); } int psk_file__init(void) { int rc; char *pskf = NULL; /* Load psk data if required. */ if(db.config->per_listener_settings){ for(int 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 psk_file__cleanup(void) { int rc; rc = psk__cleanup(&db.config->security_options.psk_id); if(rc != MOSQ_ERR_SUCCESS){ return rc; } for(int i=0; ilistener_count; i++){ if(db.config->listeners[i].security_options->psk_id){ rc = psk__cleanup(&db.config->listeners[i].security_options->psk_id); if(rc != MOSQ_ERR_SUCCESS){ return rc; } } } return MOSQ_ERR_SUCCESS; } static int pwfile__parse(const char *file, struct mosquitto__psk **root) { FILE *pwfile; struct mosquitto__psk *psk; 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", true); 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(mosquitto_fgets(&buf, &buflen, pwfile)){ if(buf[0] == '#'){ continue; } if(!strchr(buf, ':')){ continue; } username = strtok_r(buf, ":", &saveptr); if(username){ username = mosquitto_trimblanks(username); if(strlen(username) > 65535){ log__printf(NULL, MOSQ_LOG_NOTICE, "Warning: Invalid line in password file '%s', username too long.", file); continue; } if(strlen(username) <= 0){ log__printf(NULL, MOSQ_LOG_NOTICE, "Warning: Empty username in password file '%s', ingoring.", file); continue; } HASH_FIND(hh, *root, username, strlen(username), psk); if(psk){ log__printf(NULL, MOSQ_LOG_NOTICE, "Error: Duplicate user '%s' in password file '%s', ignoring.", username, file); continue; } psk = mosquitto_calloc(1, sizeof(struct mosquitto__psk)); if(!psk){ fclose(pwfile); mosquitto_FREE(buf); return MOSQ_ERR_NOMEM; } psk->username = mosquitto_strdup(username); if(!psk->username){ psk__free_item(psk); mosquitto_FREE(buf); fclose(pwfile); return MOSQ_ERR_NOMEM; } password = strtok_r(NULL, ":", &saveptr); if(password){ password = mosquitto_trimblanks(password); if(strlen(password) > 65535){ log__printf(NULL, MOSQ_LOG_NOTICE, "Warning: Invalid line in password file '%s', password too long.", file); psk__free_item(psk); continue; } psk->password = mosquitto_strdup(password); if(!psk->password){ log__printf(NULL, MOSQ_LOG_NOTICE, "Warning: Unable to decode line in password file '%s'.", file); psk__free_item(psk); continue; } HASH_ADD_KEYPTR(hh, *root, psk->username, strlen(psk->username), psk); }else{ log__printf(NULL, MOSQ_LOG_NOTICE, "Warning: Invalid line in psk file '%s': %s", file, buf); psk__free_item(psk); } } } } fclose(pwfile); mosquitto_FREE(buf); return MOSQ_ERR_SUCCESS; } static int psk__file_parse(struct mosquitto__psk **psk_id, const char *psk_file) { int rc; struct mosquitto__psk *psk, *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), psk, tmp){ /* Check for hex only digits */ if(!psk->password){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty psk for identity \"%s\".", psk->username); return MOSQ_ERR_INVAL; } if(strspn(psk->password, "0123456789abcdefABCDEF") < strlen(psk->password)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: psk for identity \"%s\" contains non-hexadecimal characters.", psk->username); return MOSQ_ERR_INVAL; } } return MOSQ_ERR_SUCCESS; } static int psk__cleanup(struct mosquitto__psk **root) { struct mosquitto__psk *psk, *tmp = NULL; if(!root){ return MOSQ_ERR_INVAL; } HASH_ITER(hh, *root, psk, tmp){ HASH_DEL(*root, psk); psk__free_item(psk); } *root = NULL; 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__psk *psk; struct mosquitto__psk *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_IGNORE; } HASH_FIND(hh, psk_id_ref, identity, strlen(identity), psk); if(psk){ strncpy(key, psk->password, (size_t)max_key_len); return MOSQ_ERR_SUCCESS; } return MOSQ_ERR_AUTH; } ================================================ FILE: src/read_handle.c ================================================ /* Copyright (c) 2009-2021 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 "mosquitto/mqtt_protocol.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: metrics__int_inc(mosq_counter_mqtt_pingreq_received, 1); rc = handle__pingreq(context); break; case CMD_PINGRESP: metrics__int_inc(mosq_counter_mqtt_pingresp_received, 1); rc = handle__pingresp(context); break; case CMD_PUBACK: metrics__int_inc(mosq_counter_mqtt_puback_received, 1); rc = handle__pubackcomp(context, "PUBACK"); break; case CMD_PUBCOMP: metrics__int_inc(mosq_counter_mqtt_pubcomp_received, 1); rc = handle__pubackcomp(context, "PUBCOMP"); break; case CMD_PUBLISH: metrics__int_inc(mosq_counter_mqtt_publish_received, 1); rc = handle__publish(context); break; case CMD_PUBREC: metrics__int_inc(mosq_counter_mqtt_pubrec_received, 1); rc = handle__pubrec(context); break; case CMD_PUBREL: metrics__int_inc(mosq_counter_mqtt_pubrel_received, 1); rc = handle__pubrel(context); break; case CMD_CONNECT: metrics__int_inc(mosq_counter_mqtt_connect_received, 1); return handle__connect(context); case CMD_DISCONNECT: metrics__int_inc(mosq_counter_mqtt_disconnect_received, 1); rc = handle__disconnect(context); break; case CMD_SUBSCRIBE: metrics__int_inc(mosq_counter_mqtt_subscribe_received, 1); rc = handle__subscribe(context); break; case CMD_UNSUBSCRIBE: metrics__int_inc(mosq_counter_mqtt_unsubscribe_received, 1); rc = handle__unsubscribe(context); break; #ifdef WITH_BRIDGE case CMD_CONNACK: metrics__int_inc(mosq_counter_mqtt_connack_received, 1); rc = handle__connack(context); break; case CMD_SUBACK: metrics__int_inc(mosq_counter_mqtt_suback_received, 1); rc = handle__suback(context); break; case CMD_UNSUBACK: metrics__int_inc(mosq_counter_mqtt_unsuback_received, 1); rc = handle__unsuback(context); break; #endif case CMD_AUTH: metrics__int_inc(mosq_counter_mqtt_auth_received, 1); rc = handle__auth(context); break; default: rc = MOSQ_ERR_PROTOCOL; } if(context->protocol == mosq_p_mqtt5){ if(rc == MOSQ_ERR_PROTOCOL || rc == MOSQ_ERR_DUPLICATE_PROPERTY){ 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_RECEIVE_MAXIMUM_EXCEEDED){ send__disconnect(context, MQTT_RC_RECEIVE_MAXIMUM_EXCEEDED, NULL); }else if(rc == MOSQ_ERR_UNKNOWN || rc == MOSQ_ERR_NOMEM){ send__disconnect(context, MQTT_RC_UNSPECIFIED, NULL); } } return rc; } ================================================ FILE: src/retain.c ================================================ /* Copyright (c) 2010-2021 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 "mosquitto/mqtt_protocol.h" #include "util_mosq.h" #include "utlist.h" static time_t next_expire_check = 0; 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) + len + 1); if(!child){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return NULL; } child->parent = parent; child->topic_len = len; if(len > 0){ strncpy(child->topic, topic, (size_t)(len+1)); } HASH_ADD(hh, *sibling, 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; } BROKER_EXPORT int mosquitto_persist_retain_msg_set(const char *topic, uint64_t base_msg_id) { struct mosquitto__base_msg *base_msg; int rc = MOSQ_ERR_UNKNOWN; char **split_topics = NULL; char *local_topic = NULL; if(topic == NULL){ return MOSQ_ERR_INVAL; } HASH_FIND(hh, db.msg_store, &base_msg_id, sizeof(base_msg_id), base_msg); if(base_msg){ if(sub__topic_tokenise(topic, &local_topic, &split_topics, NULL)){ return MOSQ_ERR_NOMEM; } rc = retain__store(topic, base_msg, split_topics, false); mosquitto_free(split_topics); mosquitto_free(local_topic); } return rc; } BROKER_EXPORT int mosquitto_persist_retain_msg_delete(const char *topic) { struct mosquitto__base_msg base_msg; int rc = MOSQ_ERR_UNKNOWN; char **split_topics = NULL; char *local_topic = NULL; if(topic == NULL){ return MOSQ_ERR_INVAL; } memset(&base_msg, 0, sizeof(base_msg)); base_msg.ref_count = 10; /* Ensure this isn't freed */ if(sub__topic_tokenise(topic, &local_topic, &split_topics, NULL)){ return MOSQ_ERR_NOMEM; } /* With stored->payloadlen == 0, this means the message will be removed */ rc = retain__store(topic, &base_msg, split_topics, false); mosquitto_FREE(split_topics); mosquitto_FREE(local_topic); return rc; } void retain__clean_empty_hierarchy(struct mosquitto__retainhier *retainhier) { while(retainhier){ if(retainhier->children || retainhier->retained || retainhier->parent == NULL){ /* Entry is being used */ return; }else{ HASH_DELETE(hh, retainhier->parent->children, retainhier); struct mosquitto__retainhier *parent = retainhier->parent; mosquitto_FREE(retainhier); retainhier = parent; } } } int retain__store(const char *topic, struct mosquitto__base_msg *base_msg, char **split_topics, bool persist) { struct mosquitto__retainhier *retainhier; struct mosquitto__retainhier *branch; size_t slen; assert(base_msg); 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(int 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++; } #else UNUSED(topic); #endif if(retainhier->retained){ if(retainhier->retained == base_msg){ /* This may occur if multiple persistence providers are used */ return MOSQ_ERR_SUCCESS; } if(persist && retainhier->retained->data.topic[0] != '$' && base_msg->data.payloadlen == 0){ /* Only delete if another retained message isn't replacing this one */ plugin_persist__handle_retain_msg_delete(retainhier->retained); } db__msg_store_ref_dec(&retainhier->retained); #ifdef WITH_SYS_TREE db.retained_count--; #endif if(base_msg->data.payloadlen == 0){ retainhier->retained = NULL; retain__clean_empty_hierarchy(retainhier); } } if(base_msg->data.payloadlen){ retainhier->retained = base_msg; db__msg_store_ref_inc(retainhier->retained); if(persist && retainhier->retained->data.topic[0] != '$'){ plugin_persist__handle_base_msg_add(retainhier->retained); plugin_persist__handle_retain_msg_set(retainhier->retained); } #ifdef WITH_SYS_TREE db.retained_count++; #endif } return MOSQ_ERR_SUCCESS; } static bool retain__delete_expired_msg(struct mosquitto__retainhier *branch) { if(branch->retained && branch->retained->data.expiry_time > 0 && db.now_real_s >= branch->retained->data.expiry_time){ plugin_persist__handle_retain_msg_delete(branch->retained); db__msg_store_ref_dec(&branch->retained); branch->retained = NULL; #ifdef WITH_SYS_TREE db.retained_count--; #endif return true; } return false; } static int retain__process(struct mosquitto__retainhier *branch, struct mosquitto *context, const struct mosquitto_subscription *sub) { int rc = 0; uint8_t qos, sub_qos; uint16_t mid; struct mosquitto__base_msg *retained; if(retain__delete_expired_msg(branch)){ return MOSQ_ERR_SUCCESS; } retained = branch->retained; rc = mosquitto_acl_check(context, retained->data.topic, retained->data.payloadlen, retained->data.payload, retained->data.qos, retained->data.retain, retained->data.properties, 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->data.source_id){ struct mosquitto retain_ctxt; memset(&retain_ctxt, 0, sizeof(struct mosquitto)); retain_ctxt.id = retained->data.source_id; retain_ctxt.username = retained->data.source_username; retain_ctxt.listener = retained->source_listener; rc = mosquitto_acl_check(&retain_ctxt, retained->data.topic, retained->data.payloadlen, retained->data.payload, retained->data.qos, retained->data.retain, retained->data.properties, MOSQ_ACL_WRITE); if(rc == MOSQ_ERR_ACL_DENIED){ return MOSQ_ERR_SUCCESS; }else if(rc != MOSQ_ERR_SUCCESS){ return rc; } } sub_qos = sub->options & 0x03; if(db.config->upgrade_outgoing_qos){ qos = sub_qos; }else{ qos = retained->data.qos; if(qos > sub_qos){ qos = sub_qos; } } if(qos > 0){ mid = mosquitto__mid_generate(context); }else{ mid = 0; } return db__message_insert_outgoing(context, 0, mid, qos, true, retained, sub->identifier, false, true); } static int retain__search(struct mosquitto__retainhier *retainhier, char **split_topics, struct mosquitto *context, const struct mosquitto_subscription *sub, 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); } if(branch->children){ retain__search(branch, split_topics, context, sub, 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, level+1) == -1 || (split_topics[1] != NULL && !strcmp(split_topics[1], "#") && level>0)){ if(branch->retained){ retain__process(branch, context, sub); } } }else{ if(branch->retained){ retain__process(branch, context, sub); } } } }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, level+1) == -1 || (split_topics[1] != NULL && !strcmp(split_topics[1], "#") && level>0)){ if(branch->retained){ retain__process(branch, context, sub); } } }else{ if(branch->retained){ retain__process(branch, context, sub); } } } } } return flag; } int retain__queue(struct mosquitto *context, const struct mosquitto_subscription *sub) { struct mosquitto__retainhier *retainhier; char *local_sub; char **split_topics; int rc; assert(context); assert(sub); if(!strncmp(sub->topic_filter, "$share/", strlen("$share/"))){ return MOSQ_ERR_SUCCESS; } rc = sub__topic_tokenise(sub->topic_filter, &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, 0); } mosquitto_FREE(local_sub); mosquitto_FREE(split_topics); return MOSQ_ERR_SUCCESS; } void retain__expire(struct mosquitto__retainhier **retainhier) { struct mosquitto__retainhier *peer, *retainhier_tmp; HASH_ITER(hh, *retainhier, peer, retainhier_tmp){ retain__expire(&peer->children); struct mosquitto__retainhier *parent = peer->parent; if(retain__delete_expired_msg(peer)){ retain__clean_empty_hierarchy(parent); } } } 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); HASH_DELETE(hh, *retainhier, peer); mosquitto_FREE(peer); } } void retain__expiry_check(void) { if(db.config->retain_expiry_interval > 0 && db.now_s > next_expire_check){ retain__expire(&db.retains); next_expire_check = db.now_s + db.config->retain_expiry_interval; } } ================================================ FILE: src/security_default.c ================================================ /* Copyright (c) 2011-2021 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 "mosquitto/mqtt_protocol.h" #include "password_file.h" #include "send_mosq.h" #include "util_mosq.h" int mosquitto_security_init_default(void) { int rc; /* Configure plugin identifier */ if(db.config->per_listener_settings){ for(int 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->plugin_name = mosquitto_strdup("builtin-security"); db.config->listeners[i].security_options->pid->listener = &db.config->listeners[i]; config__plugin_add_secopt(db.config->listeners[i].security_options->pid, db.config->listeners[i].security_options); } }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; } db.config->security_options.pid->plugin_name = mosquitto_strdup("builtin-security"); config__plugin_add_secopt(db.config->security_options.pid, &db.config->security_options); } rc = broker_password_file__init(); if(rc){ return rc; } rc = broker_acl_file__init(); if(rc){ return rc; } rc = psk_file__init(); if(rc){ return rc; } return MOSQ_ERR_SUCCESS; } int mosquitto_security_cleanup_default(void) { int rc = 0; broker_password_file__cleanup(); broker_acl_file__cleanup(); rc = psk_file__cleanup(); if(rc != MOSQ_ERR_SUCCESS){ return rc; } if(db.config->per_listener_settings){ for(int i=0; ilistener_count; i++){ if(db.config->listeners[i].security_options->pid){ mosquitto_FREE(db.config->listeners[i].security_options->pid->plugin_name); mosquitto_FREE(db.config->listeners[i].security_options->pid->config.security_options); mosquitto_FREE(db.config->listeners[i].security_options->pid); } } }else{ if(db.config->security_options.pid){ mosquitto_FREE(db.config->security_options.pid->plugin_name); mosquitto_FREE(db.config->security_options.pid->config.security_options); mosquitto_FREE(db.config->security_options.pid); } } 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; bool allow_anonymous; #ifdef WITH_TLS 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(int 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; } if((context->listener && context->listener->security_options->allow_anonymous == true) || (!db.config->per_listener_settings && db.config->security_options.allow_anonymous == true && context->listener && context->listener->security_options->allow_anonymous != false)){ allow_anonymous = true; }else{ allow_anonymous = false; } 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); mosquitto_FREE(context->password); X509 *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); security__disconnect_auth(context); continue; } if(context->listener->use_identity_as_username){ /* use_identity_as_username */ int i = X509_NAME_get_index_by_NID(name, NID_commonName, -1); if(i == -1){ X509_free(client_cert); 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); security__disconnect_auth(context); continue; } const char *username = (const char *)ASN1_STRING_get0_data(name_asn1); if(!username){ X509_free(client_cert); client_cert = NULL; security__disconnect_auth(context); continue; } context->username = mosquitto_strdup(username); if(!context->username){ X509_free(client_cert); 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); 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); 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); security__disconnect_auth(context); continue; } X509_free(client_cert); } }else #endif { /* Username/password check only if the identity/subject check not used */ if(mosquitto_basic_auth(context) != MOSQ_ERR_SUCCESS){ mosquitto__set_state(context, mosq_cs_disconnecting); do_disconnect(context, MOSQ_ERR_AUTH); continue; } } } return MOSQ_ERR_SUCCESS; } ================================================ FILE: src/send_auth.c ================================================ /* Copyright (c) 2019-2021 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/mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "sys_tree.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){ log__printf(NULL, MOSQ_LOG_INFO, "Protocol error from %s: Sending AUTH packet when session not MQTT v5.0.", context->id); 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){ goto error; } 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){ goto error; } } remaining_length += mosquitto_property_get_remaining_length(properties); rc = packet__check_oversize(context, remaining_length); if(rc){ goto error; } rc = packet__alloc(&packet, CMD_AUTH, remaining_length); if(rc){ goto error; } packet__write_byte(packet, reason_code); property__write_all(packet, properties, true); mosquitto_property_free_all(&properties); metrics__int_inc(mosq_counter_mqtt_auth_sent, 1); return packet__queue(context, packet); error: mosquitto_property_free_all(&properties); return rc; } ================================================ FILE: src/send_connack.c ================================================ /* Copyright (c) 2009-2021 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/mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "sys_tree.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 += mosquitto_property_get_remaining_length(connack_props); } if(packet__check_oversize(context, remaining_length)){ mosquitto_property_free_all(&connack_props); return MOSQ_ERR_OVERSIZE_PACKET; } rc = packet__alloc(&packet, CMD_CONNACK, remaining_length); if(rc){ mosquitto_property_free_all(&connack_props); 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); metrics__int_inc(mosq_counter_mqtt_connack_sent, 1); return packet__queue(context, packet); } ================================================ FILE: src/send_suback.c ================================================ /* Copyright (c) 2009-2021 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/mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "sys_tree.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; uint32_t remaining_length; log__printf(NULL, MOSQ_LOG_DEBUG, "Sending SUBACK to %s", context->id); remaining_length = 2+payloadlen; if(context->protocol == mosq_p_mqtt5){ remaining_length += mosquitto_property_get_remaining_length(properties); } rc = packet__alloc(&packet, CMD_SUBACK, remaining_length); if(rc){ 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); } metrics__int_inc(mosq_counter_mqtt_suback_sent, 1); return packet__queue(context, packet); } ================================================ FILE: src/send_unsuback.c ================================================ /* Copyright (c) 2009-2021 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 "mosquitto/mqtt_protocol.h" #include "packet_mosq.h" #include "property_mosq.h" #include "sys_tree.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; uint32_t remaining_length; assert(mosq); remaining_length = 2; if(mosq->protocol == mosq_p_mqtt5){ remaining_length += mosquitto_property_get_remaining_length(properties); remaining_length += (uint32_t)reason_code_count; } rc = packet__alloc(&packet, CMD_UNSUBACK, remaining_length); if(rc){ 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); } metrics__int_inc(mosq_counter_mqtt_unsuback_sent, 1); return packet__queue(mosq, packet); } ================================================ FILE: src/service.c ================================================ /* Copyright (c) 2011-2021 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. */ #if defined(WIN32) || defined(__CYGWIN__) #include "config.h" #include "mosquitto_broker_internal.h" #include extern int g_run; SERVICE_STATUS_HANDLE service_handle = 0; static SERVICE_STATUS service_status; int main(int argc, char *argv[]); static char *fix_name(char *name) { size_t len; if(strrchr(name, '\\')){ name = strrchr(name, '\\') + 1; } len = strlen(name); if(!strcasecmp(&name[len-4], ".exe")){ name[len-4] = '\0'; } return name; } 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); g_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; char *name; char env_name[MAX_PATH]; UNUSED(dwArgc); name = fix_name(lpszArgv[0]); snprintf(env_name, sizeof(env_name), "%s_DIR", name); for(int i=0; i='A' && env_name[i]<='Z'){ /* Keep upper case letter */ }else if(env_name[i]>='0' && env_name[i]<='9'){ /* Keep number */ }else if(env_name[i]>='a' && env_name[i]<='z'){ /* Convert lower case to upper case */ env_name[i] -= 32; }else{ env_name[i] = '_'; } } service_handle = RegisterServiceCtrlHandler(name, service_handler); if(service_handle){ memset(conf_path, 0, sizeof(conf_path)); rc = GetEnvironmentVariable(env_name, 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] = name; 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(char *name) { SC_HANDLE sc_manager, svc_handle; char service_string[MAX_PATH + 20]; char exe_path[MAX_PATH + 1]; char display_name[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); name = fix_name(name); sc_manager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); if(sc_manager){ if(!strcmp(name, "mosquitto")){ snprintf(display_name, sizeof(display_name), "Mosquitto Broker"); }else{ snprintf(display_name, sizeof(display_name), "Mosquitto Broker (%s.exe)", name); } svc_handle = CreateService(sc_manager, name, display_name, 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){ memset(&svc_desc, 0, sizeof(svc_desc)); 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(char *name) { SC_HANDLE sc_manager, svc_handle; SERVICE_STATUS status; name = fix_name(name); sc_manager = OpenSCManager(NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CONNECT); if(sc_manager){ svc_handle = OpenService(sc_manager, name, 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(char *name) { SERVICE_TABLE_ENTRY ste[] = { { name, service_main }, { NULL, NULL } }; name = fix_name(name); ste[0].lpServiceName = name; StartServiceCtrlDispatcher(ste); } #endif ================================================ FILE: src/session_expiry.c ================================================ /* Copyright (c) 2019-2021 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 "sys_tree.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; } } static void set_session_expiry_time(struct mosquitto *context) { context->session_expiry_time = db.now_real_s; if(db.config->persistent_client_expiration == 0){ /* No global expiry, so use the client expiration interval */ context->session_expiry_time += context->session_expiry_interval; }else{ /* We have a global expiry interval */ if(db.config->persistent_client_expiration < context->session_expiry_interval){ /* The client expiry is longer than the global expiry, so use the global */ context->session_expiry_time += db.config->persistent_client_expiration; }else{ /* The global expiry is longer than the client expiry, so use the client */ context->session_expiry_time += context->session_expiry_interval; } } } int session_expiry__add(struct mosquitto *context) { struct session_expiry_list *item; if(context->expiry_list_item){ /* Already added, may happen in cases like a client disconnecting then * being kicked by a plugin. */ return MOSQ_ERR_SUCCESS; } if(db.config->persistent_client_expiration == 0){ if(context->session_expiry_interval == MQTT_SESSION_EXPIRY_NEVER){ /* 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; set_session_expiry_time(item->context); context->expiry_list_item = item; DL_INSERT_INORDER(expiry_list, item, session_expiry__cmp); plugin_persist__handle_client_update(context); return MOSQ_ERR_SUCCESS; } int session_expiry__add_from_persistence(struct mosquitto *context, time_t expiry_time) { struct session_expiry_list *item; if(context->expiry_list_item){ /* Already added, may happen in cases like a client disconnecting then * being kicked by a plugin. */ return MOSQ_ERR_SUCCESS; } if(db.config->persistent_client_expiration == 0){ if(context->session_expiry_interval == MQTT_SESSION_EXPIRY_NEVER){ /* 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; if(expiry_time){ item->context->session_expiry_time = expiry_time; }else{ set_session_expiry_time(item->context); } 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); } } /* 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 = MQTT_SESSION_EXPIRY_IMMEDIATE; context->will_delay_interval = 0; will_delay__remove(context); context__disconnect(context, -1); } } void session_expiry__check(void) { struct session_expiry_list *item, *tmp; struct mosquitto *context; time_t timeout; if(last_check != 0 && db.now_real_s <= last_check){ if(expiry_list){ /* Next event is the first item of the list, we must set the timeout even if we aren't * checking the full list */ timeout = (expiry_list->context->session_expiry_time - db.now_real_s) * 1000; if(timeout <= 0){ timeout = 100; } loop__update_next_event(timeout); } 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); } metrics__int_inc(mosq_counter_clients_expired, 1); /* Session has now expired, so clear interval */ context->session_expiry_interval = MQTT_SESSION_EXPIRY_IMMEDIATE; /* Session has expired, so will delay should be cleared. */ context->will_delay_interval = 0; will_delay__remove(context); context__send_will(context); plugin_persist__handle_client_delete(context); context__add_to_disused(context); }else{ timeout = (item->context->session_expiry_time - db.now_real_s + 1) * 1000; if(timeout <= 0){ timeout = 100; } loop__update_next_event(timeout); return; } } } ================================================ FILE: src/signals.c ================================================ /* Copyright (c) 2016-2021 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" extern int g_run; static bool flag_reload = false; static bool flag_log_rotate = false; #ifdef WITH_PERSISTENCE static bool flag_db_backup = false; #endif static bool flag_tree_print = false; static bool flag_xtreport = false; static void handle_signal(int signal) { UNUSED(signal); if(signal == SIGINT || signal == SIGTERM){ g_run = 0; #ifdef SIGHUP }else if(signal == SIGHUP){ flag_reload = true; #endif #ifdef SIGUSR1 }else if(signal == SIGUSR1){ #ifdef WITH_PERSISTENCE flag_db_backup = true; #endif #endif #ifdef SIGUSR2 }else if(signal == SIGUSR2){ flag_tree_print = true; flag_xtreport = true; #endif #ifdef SIGRTMIN }else if(signal == SIGRTMIN){ flag_log_rotate = true; #endif } } void signal__setup(void) { signal(SIGINT, handle_signal); signal(SIGTERM, handle_signal); #ifdef SIGHUP signal(SIGHUP, handle_signal); #endif #ifndef WIN32 signal(SIGUSR1, handle_signal); signal(SIGUSR2, handle_signal); signal(SIGPIPE, SIG_IGN); #endif #ifdef SIGRTMIN signal(SIGRTMIN, handle_signal); #endif #ifdef WIN32 CreateThread(NULL, 0, SigThreadProc, NULL, 0, NULL); #endif } int signal__flag_check(void) { #ifdef WITH_PERSISTENCE if(flag_db_backup){ persist__backup(false); flag_db_backup = false; } #endif if(flag_log_rotate){ log__close(db.config); log__init(db.config); flag_log_rotate = false; } if(flag_reload){ int rc; log__printf(NULL, MOSQ_LOG_INFO, "Reloading config."); config__read(db.config, true); listeners__reload_all_certificates(); rc = plugin__handle_reload(); if(rc){ return rc; } mosquitto_security_cleanup(true); rc = mosquitto_security_init(true); if(rc){ return rc; } rc = mosquitto_security_apply_default(); if(rc){ return rc; } log__close(db.config); log__init(db.config); keepalive__cleanup(); rc = keepalive__init(); if(rc){ return rc; } broker_control__reload(); #ifdef WITH_BRIDGE bridge__reload(); #endif flag_reload = false; } if(flag_tree_print){ sub__tree_print(db.normal_subs, 0); sub__tree_print(db.shared_subs, 0); flag_tree_print = false; } #ifdef WITH_XTREPORT if(flag_xtreport){ xtreport(); flag_xtreport = false; } #endif return MOSQ_ERR_SUCCESS; } /* * * Signalling mosquitto process on Win32. * * On Windows we can use named events to pass signals to the mosquitto process. * List of events : * * mosqPID_shutdown * mosqPID_reload * mosqPID_backup * mosqPID_log_rotate * mosqPID_tree_print * mosqPID_xtreport * * (where PID is the PID of the mosquitto process). */ #ifdef WIN32 #define MOSQ_MAX_EVTS 6 DWORD WINAPI SigThreadProc(void *data) { TCHAR evt_name[MAX_PATH]; static HANDLE evt[MOSQ_MAX_EVTS]; int pid = GetCurrentProcessId(); const char *evt_names[MOSQ_MAX_EVTS] = { "shutdown", "reload", "backup", "log_rotate", "tree_print", "xtreport" }; UNUSED(data); for(int 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. */ /* 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 "mosquitto/mqtt_protocol.h" #include "util_mosq.h" #include "utlist.h" static struct mosquitto__subhier *sub__add_hier_entry(struct mosquitto__subhier *parent, struct mosquitto__subhier **sibling, const char *topic, uint16_t len); static unsigned int hashv_plus = 0; static unsigned int hashv_hash = 0; static int subs__send(struct mosquitto__subleaf *leaf, const char *topic, uint8_t qos, int retain, struct mosquitto__base_msg *stored) { bool client_retain; uint16_t mid; uint8_t client_qos, msg_qos; int rc2; /* Check for ACL topic access. */ rc2 = mosquitto_acl_check(leaf->context, topic, stored->data.payloadlen, stored->data.payload, stored->data.qos, stored->data.retain, stored->data.properties, MOSQ_ACL_READ); if(rc2 == MOSQ_ERR_ACL_DENIED){ return MOSQ_ERR_SUCCESS; }else if(rc2 == MOSQ_ERR_SUCCESS){ client_qos = MQTT_SUB_OPT_GET_QOS(leaf->subscription_options); 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(MQTT_SUB_OPT_GET_RETAIN_AS_PUBLISHED(leaf->subscription_options)){ client_retain = retain; }else{ client_retain = false; } if(db__message_insert_outgoing(leaf->context, 0, mid, msg_qos, client_retain, stored, leaf->identifier, true, 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__base_msg *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__base_msg *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 || (MQTT_SUB_OPT_GET_NO_LOCAL(leaf->subscription_options) && !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, const struct mosquitto_subscription *sub, 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->identifier = sub->identifier; leaf->subscription_options = sub->options; return MOSQ_ERR_SUB_EXISTS; } leaf = leaf->next; } leaf = mosquitto_calloc(1, sizeof(struct mosquitto__subleaf) + strlen(sub->topic_filter) + 1); if(!leaf){ return MOSQ_ERR_NOMEM; } leaf->context = context; leaf->identifier = sub->identifier; leaf->subscription_options = sub->options; strcpy(leaf->topic_filter, sub->topic_filter); 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); } } static int sub__add_shared(struct mosquitto *context, const struct mosquitto_subscription *sub, struct mosquitto__subhier *subhier, const char *sharename) { struct mosquitto__subleaf *newleaf; struct mosquitto__subshared *shared = NULL; struct mosquitto__subleaf **subs; size_t slen; int rc; unsigned hashv; slen = strlen(sharename); HASH_VALUE(sharename, slen, hashv); HASH_FIND_BYHASHVALUE(hh, subhier->shared, sharename, slen, hashv, shared); if(shared == NULL){ shared = mosquitto_calloc(1, sizeof(struct mosquitto__subshared) + slen + 1); if(!shared){ return MOSQ_ERR_NOMEM; } strncpy(shared->name, sharename, slen+1); HASH_ADD_BYHASHVALUE(hh, subhier->shared, name, slen, hashv, shared); } rc = sub__add_leaf(context, sub, &shared->subs, &newleaf); if(rc > 0){ if(shared->subs == NULL){ HASH_DELETE(hh, subhier->shared, shared); mosquitto_FREE(shared); } return rc; } if(rc != MOSQ_ERR_SUB_EXISTS){ newleaf->hier = subhier; newleaf->shared = shared; bool assigned = false; for(int i=0; isubs_capacity; i++){ if(!context->subs[i]){ context->subs[i] = newleaf; context->subs_count++; assigned = true; break; } } if(assigned == false){ subs = mosquitto_realloc(context->subs, sizeof(struct mosquitto__subleaf *)*(size_t)(context->subs_capacity + 1)); if(!subs){ sub__remove_shared_leaf(subhier, shared, newleaf); mosquitto_FREE(newleaf); return MOSQ_ERR_NOMEM; } context->subs = subs; context->subs_capacity++; context->subs_count++; context->subs[context->subs_capacity-1] = newleaf; } #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, const struct mosquitto_subscription *sub, struct mosquitto__subhier *subhier) { struct mosquitto__subleaf *newleaf = NULL; struct mosquitto__subleaf **subs; int rc; rc = sub__add_leaf(context, sub, &subhier->subs, &newleaf); if(rc > 0){ return rc; } if(rc != MOSQ_ERR_SUB_EXISTS){ newleaf->hier = subhier; newleaf->shared = NULL; bool assigned = false; for(int i=0; isubs_capacity; i++){ if(!context->subs[i]){ context->subs[i] = newleaf; context->subs_count++; assigned = true; break; } } if(assigned == false){ subs = mosquitto_realloc(context->subs, sizeof(struct mosquitto__subleaf *)*(size_t)(context->subs_capacity + 1)); if(!subs){ DL_DELETE(subhier->subs, newleaf); mosquitto_FREE(newleaf); return MOSQ_ERR_NOMEM; } context->subs = subs; context->subs_capacity++; context->subs_count++; context->subs[context->subs_capacity-1] = newleaf; } #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, const struct mosquitto_subscription *sub, 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, sub, subhier, sharename); }else{ return sub__add_normal(context, sub, 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; leaf = subhier->subs; while(leaf){ if(leaf->context==context){ #ifdef WITH_SYS_TREE db.subscription_count--; #endif DL_DELETE(subhier->subs, 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(int i=0; isubs_capacity; i++){ if(context->subs[i] && context->subs[i]->hier == subhier){ context->subs_count--; mosquitto_free(context->subs[i]); 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; HASH_FIND(hh, subhier->shared, sharename, strlen(sharename), shared); if(shared){ struct mosquitto__subleaf *leaf = shared->subs; while(leaf){ if(leaf->context==context){ #ifdef WITH_SYS_TREE db.shared_subscription_count--; #endif DL_DELETE(shared->subs, 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(int i=0; isubs_capacity; i++){ if(context->subs[i] && context->subs[i]->hier == subhier && context->subs[i]->shared == shared){ mosquitto_free(context->subs[i]); context->subs[i] = NULL; context->subs_count--; break; } } if(shared->subs == NULL){ HASH_DELETE(hh, subhier->shared, shared); 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); } } 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__base_msg *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_BYHASHVALUE(hh, subhier->children, "+", 1, hashv_plus, 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_BYHASHVALUE(hh, subhier->children, "#", 1, hashv_hash, 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; } } static 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) + len + 1); if(!child){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return NULL; } child->parent = parent; child->topic_len = len; if(len > 0){ strncpy(child->topic, topic, (size_t)(len+1)); } HASH_ADD(hh, *sibling, topic, child->topic_len, child); return child; } int sub__add(struct mosquitto *context, const struct mosquitto_subscription *sub) { int rc = 0; struct mosquitto__subhier *subhier; const char *sharename = NULL; char *local_sub; char **topics; size_t topiclen; assert(sub); assert(sub->topic_filter); rc = sub__topic_tokenise(sub->topic_filter, &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; } if(sharename){ HASH_FIND(hh, db.shared_subs, topics[0], topiclen, subhier); if(!subhier){ subhier = sub__add_hier_entry(NULL, &db.shared_subs, 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; } } }else{ HASH_FIND(hh, db.normal_subs, topics[0], topiclen, subhier); if(!subhier){ subhier = sub__add_hier_entry(NULL, &db.normal_subs, 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, sub, subhier, topics, sharename); mosquitto_FREE(local_sub); mosquitto_FREE(topics); return rc; } int sub__remove(struct mosquitto *context, const char *sub, uint8_t *reason) { int rc = 0; struct mosquitto__subhier *subhier; const char *sharename = NULL; char *local_sub = NULL; char **topics = NULL; assert(sub); rc = sub__topic_tokenise(sub, &local_sub, &topics, &sharename); if(rc){ return rc; } if(sharename){ HASH_FIND(hh, db.shared_subs, topics[0], strlen(topics[0]), subhier); }else{ HASH_FIND(hh, db.normal_subs, 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__base_msg **stored) { int rc = MOSQ_ERR_SUCCESS, rc2; int rc_normal = MOSQ_ERR_NO_SUBSCRIBERS, rc_shared = MOSQ_ERR_NO_SUBSCRIBERS; struct mosquitto__subhier *subhier; char **split_topics = NULL; char *local_topic = NULL; unsigned hashv; size_t topiclen; 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); topiclen = strlen(split_topics[0]); HASH_VALUE(split_topics[0], topiclen, hashv); HASH_FIND_BYHASHVALUE(hh, db.normal_subs, split_topics[0], topiclen, hashv, subhier); if(subhier){ rc_normal = sub__search(subhier, split_topics, source_id, topic, qos, retain, *stored); if(rc_normal > 0){ rc = rc_normal; goto end; } } HASH_FIND_BYHASHVALUE(hh, db.shared_subs, split_topics[0], topiclen, hashv, subhier); if(subhier){ rc_shared = sub__search(subhier, split_topics, source_id, topic, qos, retain, *stored); if(rc_shared > 0){ rc = rc_shared; goto end; } } if(rc_normal == MOSQ_ERR_NO_SUBSCRIBERS && rc_shared == MOSQ_ERR_NO_SUBSCRIBERS){ rc = MOSQ_ERR_NO_SUBSCRIBERS; } if(retain){ rc2 = retain__store(topic, *stored, split_topics, true); if(rc2){ rc = rc2; } } end: 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); if(parent->subs == NULL && parent->children == NULL && parent->shared == NULL && parent->parent){ return parent; }else{ return NULL; } } /* Remove all subscriptions for a client. */ int sub__clean_session(struct mosquitto *context) { for(int i=0; isubs_capacity; i++){ if(context->subs[i] == NULL || context->subs[i]->hier == NULL){ continue; } struct mosquitto__subhier *hier = context->subs[i]->hier; struct mosquitto__subleaf *leaf; plugin_persist__handle_subscription_delete(context, context->subs[i]->topic_filter); if(context->subs[i]->shared){ leaf = context->subs[i]->shared->subs; while(leaf){ if(leaf->context==context){ #ifdef WITH_SYS_TREE db.shared_subscription_count--; #endif sub__remove_shared_leaf(context->subs[i]->hier, context->subs[i]->shared, leaf); break; } leaf = leaf->next; } }else{ leaf = hier->subs; while(leaf){ if(leaf->context==context){ #ifdef WITH_SYS_TREE db.subscription_count--; #endif DL_DELETE(hier->subs, leaf); break; } leaf = leaf->next; } } mosquitto_FREE(context->subs[i]); if(hier->subs == NULL && hier->children == NULL && hier->shared == NULL && hier->parent){ do{ hier = tmp_remove_subs(hier); }while(hier); } } mosquitto_FREE(context->subs); context->subs_capacity = 0; context->subs_count = 0; return MOSQ_ERR_SUCCESS; } 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, MQTT_SUB_OPT_GET_QOS(leaf->subscription_options)); }else{ printf(" (%s, %d)", "", MQTT_SUB_OPT_GET_QOS(leaf->subscription_options)); } leaf = leaf->next; } printf("\n"); } sub__tree_print(branch->children, level+1); } } int sub__init(void) { HASH_VALUE("+", 1, hashv_plus); HASH_VALUE("#", 1, hashv_hash); if(sub__add_hier_entry(NULL, &db.shared_subs, "", 0) == NULL || sub__add_hier_entry(NULL, &db.normal_subs, "", 0) == NULL || sub__add_hier_entry(NULL, &db.normal_subs, "$SYS", (uint16_t)strlen("$SYS")) == NULL ){ return MOSQ_ERR_NOMEM; }else{ return MOSQ_ERR_SUCCESS; } } ================================================ FILE: src/sys_tree.c ================================================ /* Copyright (c) 2009-2021 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_SYS_TREE #include "config.h" #include #include #include #include #include #include "mosquitto_broker_internal.h" #include "sys_tree.h" #define BUFLEN 100 #define SYS_TREE_QOS 2 #define METRIC_LOAD_1MIN 1 #define METRIC_LOAD_5MIN 2 #define METRIC_LOAD_15MIN 3 struct metric { int64_t current; int64_t next; const char *topic, *topic_alias; bool is_max; }; struct metric_load { double current; const char *topic; int load_ref; uint8_t interval; }; struct metric metrics[mosq_metric_max] = { { 1, 0, "$SYS/broker/clients/total", NULL, false }, /* mosq_gauge_clients_total */ { 1, 0, "$SYS/broker/clients/maximum", NULL, true }, /* metric_clients_maximum */ { 1, 0, "$SYS/broker/clients/disconnected", "$SYS/broker/clients/inactive", false }, /* mosq_gauge_clients_disconnected */ { 1, 0, "$SYS/broker/clients/connected", "$SYS/broker/clients/active", false }, /* mosq_gauge_clients_connected */ { 1, 0, "$SYS/broker/clients/expired", NULL, false }, /* mosq_counter_clients_expired */ { 1, 0, "$SYS/broker/messages/stored", "$SYS/broker/store/messages/count", false }, /* mosq_gauge_message_store_count */ { 1, 0, "$SYS/broker/store/messages/bytes", NULL, false }, /* mosq_gauge_message_store_bytes */ { 1, 0, "$SYS/broker/subscriptions/count", NULL, false }, /* mosq_gauge_subscription_count */ { 1, 0, "$SYS/broker/shared_subscriptions/count", NULL, false }, /* mosq_gauge_shared_subscription_count */ { 1, 0, "$SYS/broker/retained messages/count", NULL, false }, /* mosq_gauge_retained_message_count */ #ifdef WITH_MEMORY_TRACKING { 1, 0, "$SYS/broker/heap/current", NULL, false }, /* mosq_gauge_heap_current */ { 1, 0, "$SYS/broker/heap/maximum", NULL, true }, /* mosq_gauge_heap_maximum */ #else { 1, 0, NULL, NULL, 0 }, /* mosq_gauge_heap_current */ { 1, 0, NULL, NULL, 0 }, /* mosq_gauge_heap_maximum */ #endif { 1, 0, "$SYS/broker/messages/received", NULL, false }, /* mosq_counter_messages_received */ { 1, 0, "$SYS/broker/messages/sent", NULL, false }, /* mosq_counter_messages_sent */ { 1, 0, "$SYS/broker/bytes/received", NULL, false }, /* mosq_counter_bytes_received */ { 1, 0, "$SYS/broker/bytes/sent", NULL, false }, /* mosq_counter_bytes_sent */ { 1, 0, "$SYS/broker/publish/bytes/received", NULL, false }, /* mosq_counter_pub_bytes_received */ { 1, 0, "$SYS/broker/publish/bytes/sent", NULL, false }, /* mosq_counter_pub_bytes_sent */ { 1, 0, "$SYS/broker/packet/out/count", NULL, false }, /* mosq_gauge_out_packet_count */ { 1, 0, "$SYS/broker/packet/out/bytes", NULL, false }, /* mosq_gauge_out_packet_bytes */ { 1, 0, "$SYS/broker/connections/socket/count", NULL, false }, /* mosq_counter_socket_connections */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_connect_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_connect_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_connack_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_connack_sent */ { 1, 0, "$SYS/broker/publish/messages/dropped", NULL, false }, /* mosq_counter_mqtt_publish_dropped */ { 1, 0, "$SYS/broker/publish/messages/received", NULL, false }, /* mosq_counter_mqtt_publish_received */ { 1, 0, "$SYS/broker/publish/messages/sent", NULL, false }, /* mosq_counter_mqtt_publish_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_puback_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_puback_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_pubrec_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_pubrec_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_pubrel_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_pubrel_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_pubcomp_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_pubcomp_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_subscribe_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_subscribe_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_suback_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_suback_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_unsubscribe_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_unsubscribe_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_unsuback_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_unsuback_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_pingreq_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_pingreq_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_pingresp_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_pingresp_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_disconnect_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_disconnect_sent */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_auth_received */ { 1, 0, NULL, NULL, false }, /* mosq_counter_mqtt_auth_sent */ }; struct metric_load metric_loads[mosq_metric_load_max] = { { 0.0, "$SYS/broker/load/messages/received/1min", mosq_counter_messages_received, METRIC_LOAD_1MIN }, /* metric_load_messages_received_1min */ { 0.0, "$SYS/broker/load/messages/received/5min", mosq_counter_messages_received, METRIC_LOAD_5MIN }, /* metric_load_messages_received_5min */ { 0.0, "$SYS/broker/load/messages/received/15min", mosq_counter_messages_received, METRIC_LOAD_15MIN }, /* metric_load_messages_received_15min */ { 0.0, "$SYS/broker/load/messages/sent/1min", mosq_counter_messages_sent, METRIC_LOAD_1MIN }, /* metric_load_messages_sent_1min */ { 0.0, "$SYS/broker/load/messages/sent/5min", mosq_counter_messages_sent, METRIC_LOAD_5MIN }, /* metric_load_messages_sent_5min */ { 0.0, "$SYS/broker/load/messages/sent/15min", mosq_counter_messages_sent, METRIC_LOAD_15MIN }, /* metric_load_messages_sent_15min */ { 0.0, "$SYS/broker/load/publish/dropped/1min", mosq_counter_mqtt_publish_dropped, METRIC_LOAD_1MIN }, /* metric_load_pub_messages_dropped_1min */ { 0.0, "$SYS/broker/load/publish/dropped/5min", mosq_counter_mqtt_publish_dropped, METRIC_LOAD_5MIN }, /* metric_load_pub_messages_dropped_5min */ { 0.0, "$SYS/broker/load/publish/dropped/15min", mosq_counter_mqtt_publish_dropped, METRIC_LOAD_15MIN }, /* metric_load_pub_messages_dropped_15min */ { 0.0, "$SYS/broker/load/publish/received/1min", mosq_counter_mqtt_publish_received, METRIC_LOAD_1MIN }, /* metric_load_pub_messages_received_1min */ { 0.0, "$SYS/broker/load/publish/received/5min", mosq_counter_mqtt_publish_received, METRIC_LOAD_5MIN }, /* metric_load_pub_messages_received_5min */ { 0.0, "$SYS/broker/load/publish/received/15min", mosq_counter_mqtt_publish_received, METRIC_LOAD_15MIN }, /* metric_load_pub_messages_received_15min */ { 0.0, "$SYS/broker/load/publish/sent/1min", mosq_counter_mqtt_publish_sent, METRIC_LOAD_1MIN }, /* metric_load_pub_messages_sent_1min */ { 0.0, "$SYS/broker/load/publish/sent/5min", mosq_counter_mqtt_publish_sent, METRIC_LOAD_5MIN }, /* metric_load_pub_messages_sent_5min */ { 0.0, "$SYS/broker/load/publish/sent/15min", mosq_counter_mqtt_publish_sent, METRIC_LOAD_15MIN }, /* metric_load_pub_messages_sent_15min */ { 0.0, "$SYS/broker/load/bytes/received/1min", mosq_counter_bytes_received, METRIC_LOAD_1MIN }, /* metric_load_bytes_received_1min */ { 0.0, "$SYS/broker/load/bytes/received/5min", mosq_counter_bytes_received, METRIC_LOAD_5MIN }, /* metric_load_bytes_received_5min */ { 0.0, "$SYS/broker/load/bytes/received/15min", mosq_counter_bytes_received, METRIC_LOAD_15MIN }, /* metric_load_bytes_received_15min */ { 0.0, "$SYS/broker/load/bytes/sent/1min", mosq_counter_bytes_sent, METRIC_LOAD_1MIN }, /* metric_load_bytes_sent_1min */ { 0.0, "$SYS/broker/load/bytes/sent/5min", mosq_counter_bytes_sent, METRIC_LOAD_5MIN }, /* metric_load_bytes_sent_5min */ { 0.0, "$SYS/broker/load/bytes/sent/15min", mosq_counter_bytes_sent, METRIC_LOAD_15MIN }, /* metric_load_bytes_sent_15min */ { 0.0, "$SYS/broker/load/sockets/1min", mosq_counter_socket_connections, METRIC_LOAD_1MIN }, /* metric_load_socket_connections_1min */ { 0.0, "$SYS/broker/load/sockets/5min", mosq_counter_socket_connections, METRIC_LOAD_5MIN }, /* metric_load_socket_connections_5min */ { 0.0, "$SYS/broker/load/sockets/15min", mosq_counter_socket_connections, METRIC_LOAD_15MIN }, /* metric_load_socket_connections_15min */ { 0.0, "$SYS/broker/load/connections/1min", mosq_counter_mqtt_connect_received, METRIC_LOAD_1MIN }, /* metric_load_connections_1min */ { 0.0, "$SYS/broker/load/connections/5min", mosq_counter_mqtt_connect_received, METRIC_LOAD_5MIN }, /* metric_load_connections_5min */ { 0.0, "$SYS/broker/load/connections/15min", mosq_counter_mqtt_connect_received, METRIC_LOAD_15MIN }, /* metric_load_connections_15min */ }; static time_t start_time = 0; static time_t last_update = 0; time_t broker_uptime(void) { return db.now_s - start_time; } static void calc_load(char *buf, double exponent, double i_mult, struct metric_load *m, bool force) { double new_value; uint32_t len; double interval; interval = (double)(metrics[m->load_ref].next - metrics[m->load_ref].current)*i_mult; new_value = interval + exponent*(m->current - interval); if(fabs(new_value - (m->current)) >= 0.01 || force){ len = (uint32_t)snprintf(buf, BUFLEN, "%.2f", new_value); db__messages_easy_queue(NULL, m->topic, SYS_TREE_QOS, len, buf, 1, MSG_EXPIRY_INFINITE, NULL); } m->current = new_value; } void sys_tree__init(void) { char buf[BUFLEN]; 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, MSG_EXPIRY_INFINITE, NULL); start_time = mosquitto_time(); last_update = start_time; sys_tree__update(true); /* Force published load values to 0 */ for(int i=0; isys_interval){ next_event = db.config->sys_interval - db.now_real_s % db.config->sys_interval - 1; if(next_event <= 0){ next_event = db.config->sys_interval; } loop__update_next_event(next_event*1000); } if(db.config->sys_interval && ((db.now_real_s % db.config->sys_interval == 0 && last_update_real != db.now_real_s) || force)){ uptime = db.now_s - start_time; len = (uint32_t)snprintf(buf, BUFLEN, "%" PRIu64 " seconds", (uint64_t)uptime); db__messages_easy_queue(NULL, "$SYS/broker/uptime", SYS_TREE_QOS, len, buf, 1, MSG_EXPIRY_INFINITE, NULL); /* Update metrics values where not otherwise updated */ metrics[mosq_gauge_message_store_count].next = db.msg_store_count; metrics[mosq_gauge_message_store_bytes].next = (int64_t)db.msg_store_bytes; metrics[mosq_gauge_subscriptions].next = db.subscription_count; metrics[mosq_gauge_shared_subscriptions].next = db.shared_subscription_count; metrics[mosq_gauge_retained_messages].next = db.retained_count; #ifdef WITH_MEMORY_TRACKING metrics[mosq_gauge_heap_current].next = (int64_t)mosquitto_memory_used(); metrics[mosq_counter_heap_maximum].next = (int64_t)mosquitto_max_memory_used(); #endif metrics[mosq_gauge_clients_total].next = HASH_CNT(hh_id, db.contexts_by_id); metrics[mosq_counter_clients_maximum].next = HASH_CNT(hh_id, db.contexts_by_id); metrics[mosq_gauge_clients_connected].next = HASH_CNT(hh_sock, db.contexts_by_sock); metrics[mosq_gauge_clients_disconnected].next = HASH_CNT(hh_id, db.contexts_by_id) - HASH_CNT(hh_sock, db.contexts_by_sock); /* Handle loads first, because they reference other metrics and need next != current */ if(db.now_s > last_update){ double i_mult = 60.0/(double)(db.now_s-last_update); double exponent_1min = exp(-1.0*(double)(db.now_s-last_update)/60.0); double exponent_5min = exp(-1.0*(double)(db.now_s-last_update)/300.0); double exponent_15min = exp(-1.0*(double)(db.now_s-last_update)/900.0); for(int i=0; i metrics[i].current) || (!metrics[i].is_max && metrics[i].next != metrics[i].current)){ metrics[i].current = metrics[i].next; len = (uint32_t)snprintf(buf, BUFLEN, "%lu", metrics[i].current); if(metrics[i].topic){ db__messages_easy_queue(NULL, metrics[i].topic, SYS_TREE_QOS, len, buf, 1, MSG_EXPIRY_INFINITE, NULL); } if(metrics[i].topic_alias){ db__messages_easy_queue(NULL, metrics[i].topic_alias, SYS_TREE_QOS, len, buf, 1, MSG_EXPIRY_INFINITE, NULL); } } } last_update = db.now_s; last_update_real = db.now_real_s; } } #endif ================================================ FILE: src/sys_tree.h ================================================ /* Copyright (c) 2015-2021 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) /* This ordering *must* match the metrics array in sys_tree.c. */ enum mosq_metric_type { mosq_gauge_clients_total = 0, mosq_counter_clients_maximum = 1, mosq_gauge_clients_disconnected = 2, mosq_gauge_clients_connected = 3, mosq_counter_clients_expired = 4, mosq_gauge_message_store_count = 5, mosq_gauge_message_store_bytes = 6, mosq_gauge_subscriptions = 7, mosq_gauge_shared_subscriptions = 8, mosq_gauge_retained_messages = 9, mosq_gauge_heap_current = 10, mosq_counter_heap_maximum = 11, mosq_counter_messages_received = 12, mosq_counter_messages_sent = 13, mosq_counter_bytes_received = 14, mosq_counter_bytes_sent = 15, mosq_counter_pub_bytes_received = 16, mosq_counter_pub_bytes_sent = 17, mosq_gauge_out_packets = 18, mosq_gauge_out_packet_bytes = 19, mosq_counter_socket_connections = 20, mosq_counter_mqtt_connect_received = 21, mosq_counter_mqtt_connect_sent = 22, mosq_counter_mqtt_connack_received = 23, mosq_counter_mqtt_connack_sent = 24, mosq_counter_mqtt_publish_dropped = 25, mosq_counter_mqtt_publish_received = 26, mosq_counter_mqtt_publish_sent = 27, mosq_counter_mqtt_puback_received = 28, mosq_counter_mqtt_puback_sent = 29, mosq_counter_mqtt_pubrec_received = 30, mosq_counter_mqtt_pubrec_sent = 31, mosq_counter_mqtt_pubrel_received = 32, mosq_counter_mqtt_pubrel_sent = 33, mosq_counter_mqtt_pubcomp_received = 34, mosq_counter_mqtt_pubcomp_sent = 35, mosq_counter_mqtt_subscribe_received = 36, mosq_counter_mqtt_subscribe_sent = 37, mosq_counter_mqtt_suback_received = 38, mosq_counter_mqtt_suback_sent = 39, mosq_counter_mqtt_unsubscribe_received = 40, mosq_counter_mqtt_unsubscribe_sent = 41, mosq_counter_mqtt_unsuback_received = 42, mosq_counter_mqtt_unsuback_sent = 43, mosq_counter_mqtt_pingreq_received = 44, mosq_counter_mqtt_pingreq_sent = 45, mosq_counter_mqtt_pingresp_received = 46, mosq_counter_mqtt_pingresp_sent = 47, mosq_counter_mqtt_disconnect_received = 48, mosq_counter_mqtt_disconnect_sent = 49, mosq_counter_mqtt_auth_received = 50, mosq_counter_mqtt_auth_sent = 51, mosq_metric_max, }; /* This ordering *must* match the metrics_load array in sys_tree.c. */ enum mosq_metric_load_type { mosq_load_messages_received_1min = 0, mosq_load_messages_received_5min = 1, mosq_load_messages_received_15min = 2, mosq_load_messages_sent_1min = 3, mosq_load_messages_sent_5min = 4, mosq_load_messages_sent_15min = 5, mosq_load_pub_messages_dropped_1min = 6, mosq_load_pub_messages_dropped_5min = 7, mosq_load_pub_messages_dropped_15min = 8, mosq_load_pub_messages_received_1min = 9, mosq_load_pub_messages_received_5min = 10, mosq_load_pub_messages_received_15min = 11, mosq_load_pub_messages_sent_1min = 12, mosq_load_pub_messages_sent_5min = 13, mosq_load_pub_messages_sent_15min = 14, mosq_load_bytes_received_1min = 15, mosq_load_bytes_received_5min = 16, mosq_load_bytes_received_15min = 17, mosq_load_bytes_sent_1min = 18, mosq_load_bytes_sent_5min = 19, mosq_load_bytes_sent_15min = 20, mosq_load_sockets_1min = 21, mosq_load_sockets_5min = 22, mosq_load_sockets_15min = 23, mosq_load_connections_1min = 24, mosq_load_connections_5min = 25, mosq_load_connections_15min = 26, mosq_metric_load_max, }; void metrics__int_inc(enum mosq_metric_type m, int64_t value); void metrics__int_dec(enum mosq_metric_type m, int64_t value); #else # define metrics__int_inc(A, B) # define metrics__int_dec(A, B) #endif #endif ================================================ FILE: src/topic_tok.c ================================================ /* Copyright (c) 2010-2021 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 "mosquitto/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; size_t len; if(!subtopic){ return MOSQ_ERR_INVAL; } 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 < 3 || (count == 3 && strlen((*topics)[2]) == 0)){ mosquitto_FREE(*local_sub); mosquitto_FREE(*topics); return MOSQ_ERR_PROTOCOL; } if(sharename){ if(strpbrk((*topics)[1], "+#")){ mosquitto_FREE(*local_sub); mosquitto_FREE(*topics); return MOSQ_ERR_PROTOCOL; } (*sharename) = (*topics)[1]; } for(int 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 "config.h" #include #include #include "mosquitto.h" #ifdef WITH_SYSTEMD # include #endif #ifdef WITH_SYSTEMD static time_t next_ping = 0; static time_t ping_sec = 0; #endif void watchdog__init(void) { #ifdef WITH_SYSTEMD char *watchdog_usec = getenv("WATCHDOG_USEC"); next_ping = mosquitto_time(); ping_sec = 0; if(watchdog_usec){ char *endptr = NULL; long usec = strtol(watchdog_usec, &endptr, 10); if(watchdog_usec[0] != '\0' && endptr[0] == '\0' && usec > 0){ ping_sec = (usec / 1000000) / 2; } next_ping = mosquitto_time(); } #endif } void watchdog__check(void) { #ifdef WITH_SYSTEMD if(ping_sec){ time_t now = mosquitto_time(); if(now > next_ping){ sd_notify(0, "WATCHDOG=1"); next_ping = now + ping_sec; } } #endif } ================================================ FILE: src/websockets.c ================================================ /* Copyright (c) 2014-2021 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" #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS # include #endif #include "mosquitto_internal.h" #include "mosquitto_broker_internal.h" #include "mosquitto/mqtt_protocol.h" #include "packet_mosq.h" #include "sys_tree.h" #include "util_mosq.h" #include #include #include #ifndef WIN32 # include #endif #if defined(WITH_WEBSOCKETS) && WITH_WEBSOCKETS == WS_IS_LWS /* 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; char ip_addr_buff[1024]; switch(reason){ case LWS_CALLBACK_ESTABLISHED: mosq = context__init(); 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; } mosq->listener->client_count++; if((mosq->listener->max_connections > 0 && mosq->listener->client_count > mosq->listener->max_connections) || (db.config->global_max_connections > 0 && HASH_CNT(hh_sock, db.contexts_by_sock) > (unsigned int)db.config->global_max_connections)){ if(db.config->connection_messages == true){ log__printf(NULL, MOSQ_LOG_NOTICE, "Client connection from %s denied: max_connections exceeded.", mosq->address); } mosq->listener->client_count--; 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__new(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; } while(mosq->out_packet && !lws_send_pipe_choked(mosq->wsi)){ packet = mosq->out_packet; 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 metrics__int_inc(mosq_counter_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 metrics__int_inc(mosq_counter_messages_sent, 1); if(((packet->command)&0xF0) == CMD_PUBLISH){ metrics__int_inc(mosq_counter_mqtt_publish_sent, 1); } #endif packet__get_next_out(mosq); 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->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; metrics__int_inc(mosq_counter_bytes_received, (int64_t)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 metrics__int_inc(mosq_counter_messages_received, 1); #endif rc = handle__packet(mosq); /* Free data and reset values */ packet__cleanup(&mosq->in_packet); keepalive__update(mosq); if(rc && mosq->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. */ SAFE_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; int hlen; /* 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){ SAFE_FREE(filename_canonical); lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL); return -1; } if(fstat(fileno(u->fptr), &filestat) < 0){ SAFE_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; SAFE_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; SAFE_FREE(filename_canonical); return -1; } log__printf(NULL, MOSQ_LOG_DEBUG, "http serving file \"%s\".", filename_canonical); SAFE_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; #if LWS_LIBRARY_VERSION_NUMBER >= 3001000 case LWS_CALLBACK_HTTP_CONFIRM_UPGRADE: hack = lws_context_user(lws_get_context(wsi)); if(hack->listener->ws_origin_count){ hlen = lws_hdr_total_length(wsi, WSI_TOKEN_ORIGIN); if(hlen <= 0 || hlen >= (int)sizeof(buf)){ return -1; } for(int i=0; ilistener->ws_origin_count; i++){ lws_hdr_copy(wsi, (char *)buf, sizeof(buf), WSI_TOKEN_ORIGIN); if((!strcmp(hack->listener->ws_origins[i], (char *)buf))){ return 0; } } return -1; }else{ return 0; } #endif 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; /* while still active, extend timeout */ if(wlen){ lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 10); } 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); }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); }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 if(listener->cafile){ info.ssl_ca_filepath = listener->cafile; }else if(listener->capath){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: CA path option is not supported for websockets"); } info.ssl_cert_filepath = listener->certfile; info.ssl_private_key_filepath = listener->keyfile; info.ssl_cipher_list = listener->ciphers; /* HTTP 1 only, due to HTTP 2 issues in Firefox: https://github.com/eclipse-mosquitto/mosquitto/issues/1211 */ info.alpn = "h1"; #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->packet_buffer_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 #endif ================================================ FILE: src/will_delay.c ================================================ /* Copyright (c) 2019-2021 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" 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); loop__update_next_event(item->context->will_delay_interval*1000); plugin_persist__handle_client_update(context); 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){ if(delay_list){ loop__update_next_event(1000); } 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 == MQTT_SESSION_EXPIRY_IMMEDIATE){ context__add_to_disused(item->context); } mosquitto_FREE(item); }else{ loop__update_next_event((item->context->will_delay_time - db.now_real_s)*1000); 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); } } ================================================ FILE: src/xtreport.c ================================================ /* Copyright (c) 2020-2021 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 #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) { long pkt_count, pkt_bytes; long cmsg_count; long cmsg_bytes; long tBytes; pkt_count = 1; pkt_bytes = context->in_packet.packet_length + context->out_packet_bytes; cmsg_count = context->msgs_in.inflight_count + context->msgs_in.queued_count; cmsg_bytes = context->msgs_in.inflight_bytes + context->msgs_in.queued_bytes; cmsg_count += context->msgs_out.inflight_count + context->msgs_out.queued_count; cmsg_bytes += context->msgs_out.inflight_bytes + context->msgs_out.queued_bytes; tBytes = pkt_bytes + cmsg_bytes; if(context->id){ tBytes += (long)strlen(context->id); } fprintf(fptr, "%d %ld %lu %lu %lu %lu %d 0 0 %" PRIu64 " %" PRIu64 " %" PRIu64 "\n", fn_index, tBytes, pkt_count, cmsg_count, pkt_bytes, cmsg_bytes, context->sock == INVALID_SOCKET?0:context->sock, context->stats.messages_sent, context->stats.messages_received, context->stats.messages_dropped ); } static void report_subscriptions(FILE *fptr, struct mosquitto *context, int *fn_index_max) { for(int i=0; isubs_count; i++){ if(context->subs && context->subs[i]){ struct mosquitto__subhier *subhier = context->subs[i]->hier; int topic_count = 0; char *topics[100]; do{ topics[topic_count] = subhier->topic; subhier = subhier->parent; topic_count++; if(topic_count == 100){ break; } }while(subhier); if(topic_count == 100){ continue; } fprintf(fptr, "cfn=(%d) ", *fn_index_max); if(topics[topic_count-2] && topics[topic_count-2][0] == '\0'){ topic_count--; } for(int j=topic_count-2; j>0; j--){ if(topics[j]){ fprintf(fptr, "%s/", topics[j]); } } if(topics[0]){ fprintf(fptr, "%s\n", topics[0]); } fprintf(fptr, "calls=1 %d\n", *fn_index_max); fprintf(fptr, "1 0 0 0 0 0 0 1 0 0 0 0\n"); (*fn_index_max)++; } } } void xtreport(void) { pid_t pid; char filename[40]; FILE *fptr; struct mosquitto *context, *ctxt_tmp; int fn_index = 2, fn_index_max; 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, "event: sock : client socket number\n"); fprintf(fptr, "event: sub : client subscriptions\n"); fprintf(fptr, "event: refc : message store ref counts\n"); fprintf(fptr, "event: msgS : client message sent count\n"); fprintf(fptr, "event: msgR : client message received count\n"); fprintf(fptr, "event: msgD : client message dropped count\n"); fprintf(fptr, "events: tB pkt cmsg pktB cmsgB sock sub refc msgS msgR msgD\n"); fprintf(fptr, "\nfn=(1) clients\n"); fprintf(fptr, "1 0 0 0 0 0 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_max = fn_index; fn_index = 2; HASH_ITER(hh_id, db.contexts_by_id, context, ctxt_tmp){ fprintf(fptr, "\nfn=(%d)\n", fn_index); client_cost(fptr, context, fn_index); fn_index++; report_subscriptions(fptr, context, &fn_index_max); } fprintf(fptr, "\nfn=(%d) messages\n", fn_index_max); fprintf(fptr, "1 0 0 0 0 0 0 0 0 0 0 0\n"); struct mosquitto__base_msg *base_msg, *base_msg_tmp; HASH_ITER(hh, db.msg_store, base_msg, base_msg_tmp){ if(base_msg->ref_count > 1){ fprintf(fptr, "cfn=(%d) %" PRIu64 "\n", fn_index_max, base_msg->data.store_id); fprintf(fptr, "calls=%d %d\n", base_msg->ref_count, fn_index_max); fprintf(fptr, "%d 0 0 0 0 0 0 0 %d 0 0 0\n", fn_index_max, base_msg->ref_count); fn_index_max++; } } fclose(fptr); } #endif ================================================ FILE: test/CMakeLists.txt ================================================ add_subdirectory(mock) add_subdirectory(apps) add_subdirectory(broker) add_subdirectory(client) add_subdirectory(lib) add_subdirectory(unit) add_custom_target(coverage COMMAND lcov --quiet --capture --directory . --output-file ${PROJECT_BINARY_DIR}/coverage.info --no-external COMMAND genhtml --quiet ${PROJECT_BINARY_DIR}/coverage.info --output-directory ${PROJECT_BINARY_DIR}/coverage COMMENT "Generating coverage.info and coverage/index.html in ${PROJECT_BINARY_DIR}" WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} ) ================================================ FILE: test/Makefile ================================================ R=.. include ${R}/config.mk .PHONY: all check test test-compile ptest clean ssl all : test-compile: ifeq ($(WITH_GMOCK),yes) $(MAKE) -C mock test-compile endif $(MAKE) -C broker test-compile $(MAKE) -C client test-compile $(MAKE) -C lib test-compile $(MAKE) -C unit test-compile $(MAKE) -C apps test-compile check : test ssl: ssl/all-ca.crt ssl/all-ca.crt: ssl/gen.sh cd "${ $ $ ) target_compile_definitions(${TEST_NAME} PRIVATE WITH_CTRL_SHELL WITH_EDITLINE ) target_include_directories(${TEST_NAME} PRIVATE ${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/apps/mosquitto_ctrl ${mosquitto_SOURCE_DIR}/common ${mosquitto_SOURCE_DIR}/include ${mosquitto_SOURCE_DIR}/lib ${mosquitto_SOURCE_DIR}/test/mock ${mosquitto_SOURCE_DIR}/test/mock/apps/mosquitto_ctrl ${mosquitto_SOURCE_DIR}/test/mock/lib ) target_link_libraries(${TEST_NAME} PRIVATE GTest::gmock_main editline_mock pthread_mock cjson libmosquitto_common ) gtest_discover_tests(${TEST_NAME}) endfunction() function(add_ctrl_shell_test_real_editline TEST_NAME) if(NOT WITH_CTRL_SHELL OR NOT EDITLINE_FOUND) return() endif() add_executable(${TEST_NAME} ${TEST_NAME}.cpp ${mosquitto_SOURCE_DIR}/common/json_help.c $ $ $ ) target_compile_definitions(${TEST_NAME} PRIVATE WITH_CTRL_SHELL ) target_include_directories(${TEST_NAME} PRIVATE ${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/apps/mosquitto_ctrl ${mosquitto_SOURCE_DIR}/common ${mosquitto_SOURCE_DIR}/include ${mosquitto_SOURCE_DIR}/lib ${mosquitto_SOURCE_DIR}/test/mock ${mosquitto_SOURCE_DIR}/test/mock/apps/mosquitto_ctrl ${mosquitto_SOURCE_DIR}/test/mock/lib ) target_link_libraries(${TEST_NAME} PRIVATE LineEditing::LineEditing GTest::gmock_main pthread_mock cjson libmosquitto_common ) gtest_discover_tests(${TEST_NAME}) endfunction() add_ctrl_shell_test(ctrl_shell_test) add_ctrl_shell_test(ctrl_shell_broker_test) add_ctrl_shell_test_real_editline(ctrl_shell_completion_test) add_ctrl_shell_test(ctrl_shell_dynsec_test) add_ctrl_shell_test(ctrl_shell_help_test) add_ctrl_shell_test(ctrl_shell_options_test) add_ctrl_shell_test(ctrl_shell_pre_connect_test) ================================================ FILE: test/apps/ctrl/Makefile ================================================ R=../../.. include ${R}/config.mk .PHONY: all check test-compile test test-mock test-lib clean LOCAL_CPPFLAGS+= \ -DWITH_THREADING \ -DWITH_TLS \ -I../ \ -I${R}/include \ -I${R} \ -I${R}/apps/mosquitto_ctrl \ -I${R}/lib \ -I${R}/test/mock \ -I${R}/test/mock/apps/mosquitto_ctrl \ -I${R}/test/mock/lib LOCAL_CXXFLAGS+=-std=c++20 -Wall -ggdb -D TEST_SOURCE_DIR='"$(realpath .)"' LOCAL_LDFLAGS+= LOCAL_LIBADD+=-lcjson -lgmock -lgtest_main -lgtest ${R}/libcommon/libmosquitto_common.a CTRL_OBJS = \ ${R}/apps/mosquitto_ctrl/ctrl_shell_broker.o \ ${R}/apps/mosquitto_ctrl/ctrl_shell.o \ ${R}/apps/mosquitto_ctrl/ctrl_shell_client.o \ ${R}/apps/mosquitto_ctrl/ctrl_shell_completion_tree.o \ ${R}/apps/mosquitto_ctrl/ctrl_shell_dynsec.o \ ${R}/apps/mosquitto_ctrl/ctrl_shell_post_connect.o \ ${R}/apps/mosquitto_ctrl/ctrl_shell_pre_connect.o \ ${R}/apps/mosquitto_ctrl/ctrl_shell_printf.o LIBMOSQ_MOCKS = \ ${R}/test/mock/lib/libmosquitto_mock.o \ ${R}/test/mock/lib/actions_publish_mock.o \ ${R}/test/mock/lib/actions_subscribe_mock.o \ ${R}/test/mock/lib/callbacks_mock.o \ ${R}/test/mock/lib/connect_mock.o \ ${R}/test/mock/lib/loop_mock.o \ ${R}/test/mock/lib/options_mock.o \ ${R}/test/mock/lib/thread_mosq_mock.o LIB_OBJS = \ ${CTRL_OBJS} \ ${R}/common/json_help.o \ ${R}/test/mock/apps/mosquitto_ctrl/ctrl_shell_mock.o \ ${R}/test/mock/editline_mock.o \ ${R}/test/mock/pthread_mock.o \ ${LIBMOSQ_MOCKS} COMPLETION_OBJS = \ ${CTRL_OBJS} \ ${R}/common/json_help.o \ ${R}/test/mock/apps/mosquitto_ctrl/ctrl_shell_mock.o \ ${R}/test/mock/pthread_mock.o \ ${LIBMOSQ_MOCKS} TEST_OBJS = \ ctrl_shell_test.o \ ctrl_shell_broker_test.o \ ctrl_shell_completion_test.o \ ctrl_shell_dynsec_test.o \ ctrl_shell_help_test.o \ ctrl_shell_options_test.o \ ctrl_shell_pre_connect_test.o ifeq ($(WITH_GMOCK),yes) ifeq ($(WITH_EDITLINE),yes) LOCAL_CPPFLAGS+=-DWITH_CTRL_SHELL -DWITH_EDITLINE MOCK_TESTS = \ ctrl_shell_test \ ctrl_shell_broker_test \ ctrl_shell_completion_test \ ctrl_shell_dynsec_test \ ctrl_shell_help_test \ ctrl_shell_options_test \ ctrl_shell_pre_connect_test else MOCK_TESTS = endif else MOCK_TESTS = endif all : test-compile check : test # DEPS ${LIBMOSQ_MOCKS}: $(MAKE) -C ${R}/lib ${CTRL_OBJS} : $(MAKE) -C ${R}/apps/mosquitto_ctrl ${R}/common/json_help.o : ${R}/common/json_help.c ${R}/common/json_help.h ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ # MOCKS ${R}/test/mock/apps/mosquitto_ctrl/ctrl_shell_mock.o : ${R}/test/mock/apps/mosquitto_ctrl/ctrl_shell_mock.cpp ${R}/test/mock/apps/mosquitto_ctrl/ctrl_shell_mock.hpp $(MAKE) -C ${R}/test/mock/apps/mosquitto_ctrl test-compile ${R}/test/mock/editline_mock.o : ${R}/test/mock/editline_mock.cpp ${R}/test/mock/editline_mock.hpp $(MAKE) -C ${R}/test/mock test-compile ${R}/test/mock/pthread_mock.o : ${R}/test/mock/pthread_mock.cpp ${R}/test/mock/pthread_mock.hpp $(MAKE) -C ${R}/test/mock test-compile # TESTS ${TEST_OBJS} : %.o: %.cpp $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_CXXFLAGS) -c $< -o $@ ctrl_shell_test : ctrl_shell_test.o ${LIB_OBJS} $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) ctrl_shell_broker_test : ctrl_shell_broker_test.o ${LIB_OBJS} $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) ctrl_shell_completion_test : ctrl_shell_completion_test.o ${COMPLETION_OBJS} $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) -ledit ctrl_shell_dynsec_test : ctrl_shell_dynsec_test.o ${LIB_OBJS} $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) ctrl_shell_help_test : ctrl_shell_help_test.o ${LIB_OBJS} $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) ctrl_shell_options_test : ctrl_shell_options_test.o ${LIB_OBJS} $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) ctrl_shell_pre_connect_test : ctrl_shell_pre_connect_test.o ${LIB_OBJS} $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LIBADD) test-compile : $(MOCK_TESTS) test-mock : $(MOCK_TESTS) ifeq ($(WITH_GMOCK),yes) ifeq ($(WITH_EDITLINE),yes) ./ctrl_shell_broker_test ./ctrl_shell_completion_test ./ctrl_shell_dynsec_test ./ctrl_shell_help_test ./ctrl_shell_options_test ./ctrl_shell_pre_connect_test ./ctrl_shell_test endif endif test : test-mock ./ctrl-args.py ./ctrl-broker.py ./ctrl-dynsec.py ptest: test-mock ./test.py clean : -rm -rf $(MOCK_TESTS) -rm -rf *.o *.gcda *.gcno coverage.info out/ coverage : lcov --capture --directory . --output-file coverage.info genhtml coverage.info --output-directory out install: uninstall: ================================================ FILE: test/apps/ctrl/ctrl-args.py ================================================ #!/usr/bin/env python3 # Test parsing of command line args and errors. Does not test arg functionality. from mosq_test_helper import * def do_test(args, rc_expected, response=None): proc = subprocess.run([mosq_test.get_build_root()+"/apps/mosquitto_ctrl/mosquitto_ctrl"] + args, env=env, capture_output=True, encoding='utf-8', timeout=2) if response is not None: if proc.stderr != response: print(len(proc.stderr)) print(len(response)) raise ValueError(proc.stderr) if proc.returncode != rc_expected: raise ValueError(f"return code {proc.returncode} != expected {rc_expected} while testing args: {args}") env = mosq_test.env_add_ld_library_path() do_test(["-A"], 1, response="Error: -A argument given but no address specified.\n\n") do_test(["--cafile"], 1, response="Error: --cafile argument given but no file specified.\n\n") do_test(["--cafile", "missing", "broker", "listListeners"], 1, "Error: Problem setting TLS options: File not found.\n") do_test(["--capath"], 1, response="Error: --capath argument given but no directory specified.\n\n") do_test(["--cert"], 1, response="Error: --cert argument given but no file specified.\n\n") do_test(["--cert", ssl_dir / "client.crt"], 1, response="Error: Both certfile and keyfile must be provided if one of them is set.\n") do_test(["--help"], 1) # Gives generic help do_test(["--key"], 1, response="Error: --key argument given but no file specified.\n\n") do_test(["--key", ssl_dir / "client.key"], 1, response="Error: Both certfile and keyfile must be provided if one of them is set.\n") do_test(["--ciphers"], 1, response="Error: --ciphers argument given but no ciphers specified.\n\n") do_test(["-f"], 1, response="Error: -f argument given but no data file specified.\n\n") do_test(["--host"], 1, response="Error: -h argument given but no host specified.\n\n") do_test(["-i"], 1, response="Error: -i argument given but no id specified.\n\n") do_test(["--keyform"], 1, response="Error: --keyform argument given but no keyform specified.\n\n") do_test(["--keyform", "key"], 1, response="Error: If keyform is set, keyfile must be also specified.\n") do_test(["--keyform", "key", "--cafile", "file", "--cert", "file", "--key", "file", "broker", "listListeners"], 1, response="Error: Problem setting key form, it must be one of 'pem' or 'engine'.\n") do_test(['-L'], 1, response="Error: -L argument given but no URL specified.\n\n") do_test(['-L', 'invalid://'], 1, response="Error: Unsupported URL scheme.\n\n") do_test(['-L', 'mqtt://localhost'], 1, response="Error: Invalid URL for -L argument specified - topic missing.\n") do_test(['-L', 'mqtts://localhost'], 1, response="Error: Invalid URL for -L argument specified - topic missing.\n") do_test(['-L', 'mqtts://:@localhost/topic'], 1, response="Error: Empty username in URL.\n") do_test(['-L', 'mqtts://localhost:/topic'], 1, response="Error: Empty port in URL.\n") do_test(["-o"], 1, response="Error: -o argument given but no options file specified.\n\n") do_test(["-p"], 1, response="Error: -p argument given but no port specified.\n\n") do_test(["-p", "-1"], 1, response="Error: Invalid port given: -1\n") do_test(["-p", "65536"], 1, response="Error: Invalid port given: 65536\n") do_test(["-P"], 1, response="Error: -P argument given but no password specified.\n\n") do_test(["--proxy"], 1, response="Error: --proxy argument given but no proxy url specified.\n\n") do_test(["--proxy", "mqtt://localhost"], 1, response="Error: Unsupported proxy protocol: mqtt://localhost\n") do_test(["--proxy", "socks5h://"], 1, response="Error: Invalid proxy.\n") do_test(["--proxy", "socks5h://localhost:0"], 1, response="Error: Invalid proxy port 0\n") do_test(["--proxy", "socks5h://localhost:65536"], 1, response="Error: Invalid proxy port 65536\n") do_test(["--proxy", "socks5h://username%@localhost"], 1, response="Error: Invalid URL encoding in username.\n") do_test(["--proxy", "socks5h://username%41@localhost"], 1, response="Error: Invalid URL encoding in username.\n") do_test(["--proxy", "socks5h://username:password%@localhost"], 1, response="Error: Invalid URL encoding in password.\n") do_test(["--proxy", "socks5h://username:password%41@localhost"], 1, response="Error: Invalid URL encoding in password.\n") do_test(["--psk"], 1, response="Error: --psk argument given but no key specified.\n\n") do_test(["--psk", "missing.psk"], 1, response="Error: --psk-identity required if --psk used.\n") do_test(["--psk-identity"], 1, response="Error: --psk-identity argument given but no identity specified.\n\n") do_test(["--cafile", ssl_dir / "all-ca.crt", "--psk", "missing.psk", "--psk-identity", "identity"], 1, response="Error: Only one of --psk or --cafile/--capath may be used at once.\n") do_test(["-q"], 1, response="Error: -q argument given but no QoS specified.\n\n") do_test(["-q", "-1"], 1, response="Error: Invalid QoS given: -1\n") do_test(["-q", "3"], 1, response="Error: Invalid QoS given: 3\n") do_test(["--tls-alpn"], 1, response="Error: --tls-alpn argument given but no protocol specified.\n\n") do_test(["--tls-engine"], 1, response="Error: --tls-engine argument given but no engine_id specified.\n\n") do_test(["--tls-engine-kpass-sha1"], 1, response="Error: --tls-engine-kpass-sha1 argument given but no kpass sha1 specified.\n\n") do_test(["--tls-version"], 1, response="Error: --tls-version argument given but no version specified.\n\n") do_test(["--username"], 1, response="Error: -u argument given but no username specified.\n\n") do_test(["--unix"], 1, response="Error: --unix argument given but no socket path specified.\n\n") do_test(["-V"], 1, response="Error: --protocol-version argument given but no version specified.\n\n") do_test(["-V", "2"], 1, response="Error: Invalid protocol version argument given.\n\n") do_test(["-V", "6"], 1, response="Error: Invalid protocol version argument given.\n\n") do_test(["--unknown"], 1, response="Error: Unknown option '--unknown'.\n") do_test(["--version"], 1) # Gives generic help # Behaviour with incomplete args is now to run the shell, so these tests don't work #do_test([], 1) #do_test(["broker"], 1) #do_test(["-A", "127.0.0.1"], 1) # Gives generic help #do_test(["--cafile", ssl_dir / "all-ca.crt"], 1) # Gives generic help #do_test(["--capath", ssl_dir], 1) # Gives generic help #do_test(["--ciphers", "DEFAULT"], 1) # Gives generic help #do_test(["--debug"], 1) # Gives generic help #do_test(["-f", ssl_dir / "test"], 1) # Gives generic help #do_test(["--host", "127.0.0.1"], 1) # Gives generic help #do_test(["-i", "clientid"], 1) # Gives generic help #do_test(["--insecure"], 1) # Gives generic help #do_test(['-L', 'mqtts://localhost/'], 1) #do_test(['-L', 'mqtts://username:password@localhost:1887/topic'], 1) #do_test(["-o", "file"], 1) # Gives generic help #do_test(["-p", "1887"], 1) # Gives generic help #do_test(["-P", "password"], 1) # Gives generic help #do_test(["--proxy", "socks5h://localhost"], 1) # Gives generic help #do_test(["--proxy", "socks5h://username@localhost@localhost"], 1) # Gives generic help #do_test(["--proxy", "socks5h://username@localhost:localhost:1080"], 1) # Gives generic help #do_test(["--proxy", "socks5h://localhost:1080"], 1) # Gives generic help #do_test(["--proxy", "socks5h://username@localhost"], 1) # Gives generic help #do_test(["--proxy", "socks5h://username:password@localhost"], 1) # Gives generic help #do_test(["--proxy", "socks5h://username:password@localhost:1080"], 1) # Gives generic help #do_test(["--proxy", "socks5h://:"], 1) # Gives generic help #do_test(["--proxy", "socks5h://@"], 1) # Gives generic help #do_test(["--proxy", "socks5h://username%25@localhost"], 1) # Gives generic help #do_test(["--proxy", "socks5h://%25username@localhost"], 1) # Gives generic help #do_test(["--proxy", "socks5h://user%3aname@localhost"], 1) # Gives generic help #do_test(["--proxy", "socks5h://user%40name@localhost"], 1) # Gives generic help #do_test(["--proxy", "socks5h://username:password%25@localhost"], 1) # Gives generic help #do_test(["--proxy", "socks5h://username:%25password@localhost"], 1) # Gives generic help #do_test(["--proxy", "socks5h://username:password%3a@localhost"], 1) # Gives generic help #do_test(["--proxy", "socks5h://username:password%40@localhost"], 1) # Gives generic help #do_test(["-q", "1"], 1) # Gives generic help #do_test(["--quiet"], 1) # Gives generic help #do_test(["--tls-alpn", "protocol"], 1) # Gives generic help #do_test(["--tls-engine", "engine"], 1) # Gives generic help #do_test(["--tls-engine-kpass-sha1", "sha1"], 1) # Gives generic help #do_test(["--tls-version", "tlsv1.3"], 1) # Gives generic help #do_test(["--unix", "sock"], 1) # Gives generic help #do_test(["--username", "username"], 1) # Gives generic help #do_test(["-V", "31"], 1) # Gives generic help #do_test(["-V", "311"], 1) # Gives generic help #do_test(["-V", "5"], 1) # Gives generic help #do_test(["--verbose"], 1) # Gives generic help # Broker do_test(["broker", "unknown"], 13, response="Command 'unknown' not recognised.\n") # Dynsec do_test(["dynsec", "unknown"], 13, response="Command 'unknown' not recognised.\n") do_test(["-f", "file", "dynsec", "setClientPassword", "admin", "admin", "-i"], 3, response="Error: -i argument given, but no iterations provided.\nError: Invalid input.\n") do_test(["-f", "file", "dynsec", "setClientPassword", "admin", "admin", "-c"], 3, response="Error: Unknown argument: -c\nError: Invalid input.\n") do_test(["dynsec", "createClient", "client", "-i"], 3, response="Error: -i argument given, but no clientid provided.\nError: Invalid input.\n") do_test(["dynsec", "createClient", "client", "-p"], 3, response="Error: -p argument given, but no password provided.\nError: Invalid input.\n") # Env modification # Missing file env["HOME"] = "/tmp" do_test(["--cert", ssl_dir / "client.crt"], 1, response="Error: Both certfile and keyfile must be provided if one of them is set.\n") # Invalid file env["XDG_CONFIG_HOME"] = "." with open("mosquitto_ctrl", "w") as f: f.write(f"--cert {ssl_dir}/client.crt\n") f.write(f"--key\n") do_test(["broker"], 1, response="Error: --key argument given but no file specified.\n\n") # Empty file env["XDG_CONFIG_HOME"] = "." with open("mosquitto_ctrl", "w") as f: pass do_test(["--cert", ssl_dir / "client.crt"], 1, response="Error: Both certfile and keyfile must be provided if one of them is set.\n") os.remove("mosquitto_ctrl") exit(0) ================================================ FILE: test/apps/ctrl/ctrl-broker.py ================================================ #!/usr/bin/env python3 # mosquitto_ctrl broker from mosq_test_helper import * import json import shutil def write_config(filename, ports): with open(filename, 'w') as f: f.write("enable_control_api true\n") f.write(f"global_plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write(f"plugin_opt_config_file {ports[0]}/dynamic-security.json\n") f.write("allow_anonymous false\n") f.write(f"listener {ports[0]}\n") f.write(f"listener {ports[1]}\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") def ctrl_cmd(cmd, args, ports, response=None): opts = ["-u", "admin", "-P", "admin", "-V", "5"] if response is None: opts += [ "-p", str(ports[0]), "-q", "1" ] capture_output = False else: opts += ["-p", str(ports[1])] opts += ["--cafile", f"{ssl_dir}/all-ca.crt"] capture_output = True proc = subprocess.run([mosq_test.get_build_root() + "/apps/mosquitto_ctrl/mosquitto_ctrl"] + opts + [cmd] + args, env=env, capture_output=True, encoding='utf-8') if response is not None: if proc.stdout != response: raise ValueError(proc.stdout) if proc.returncode != 0: raise ValueError(args) rc = 0 ports = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, ports) env = mosq_test.env_add_ld_library_path() if not os.path.exists(str(ports[0])): os.mkdir(str(ports[0])) # Generate initial dynsec file ctrl_cmd("dynsec", ["init", f"{ports[0]}/dynamic-security.json", "admin", "admin"], ports) ctrl_cmd("broker", ["help"], ports) # Then start broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=ports[0]) try: ctrl_cmd("dynsec", ["addRoleACL", "admin", "publishClientSend", "$CONTROL/#", "allow"], ports) ctrl_cmd("dynsec", ["addRoleACL", "admin", "publishClientReceive", "$CONTROL/#", "allow"], ports) ctrl_cmd("dynsec", ["addRoleACL", "admin", "subscribePattern", "$CONTROL/#", "allow"], ports) ctrl_cmd("broker", ["listListeners"], ports, response=f"Listener 1:\n Port: {ports[0]}\n Protocol: mqtt\n TLS: false\n\nListener 2:\n Port: {ports[1]}\n Protocol: mqtt\n TLS: true\n\n") ctrl_cmd("broker", ["listPlugins"], ports, response="Plugin: dynamic-security\nControl endpoints: $CONTROL/dynamic-security/v1\n") rc = 0 except mosq_test.TestError: pass except Exception as err: print(err) finally: os.remove(conf_file) try: os.remove(f"{ports[0]}/dynamic-security.json") pass except FileNotFoundError: pass shutil.rmtree(f"{ports[0]}") broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (_, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/apps/ctrl/ctrl-dynsec.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import json import os import shutil def write_config(filename, ports): with open(filename, 'w') as f: f.write(f"global_plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write(f"plugin_opt_config_file {ports[0]}/dynamic-security.json\n") f.write("allow_anonymous false\n") f.write(f"listener {ports[0]}\n") f.write(f"listener {ports[1]}\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") def ctrl_dynsec_cmd(args, ports, response=None, input=None): opts = ["-u", "admin", "-P", "newadmin",] if response is None: opts += [ "-p", str(ports[0]), "-q", "1" ] else: opts += ["-p", str(ports[1])] opts += ["--cafile", f"{ssl_dir}/all-ca.crt"] proc = subprocess.run([mosq_test.get_build_root()+"/apps/mosquitto_ctrl/mosquitto_ctrl"] + opts + ["dynsec"] + args, env=env, capture_output=True, encoding='utf-8', timeout=2, input=input) if response is not None: if proc.stdout != response: print(len(proc.stdout)) print(len(response)) raise ValueError(proc.stdout) if proc.returncode != 0: raise ValueError(args) def ctrl_dynsec_file_cmd(args, ports, response=None): opts = ["-f", f"{ports[0]}/dynamic-security.json"] proc = subprocess.run([mosq_test.get_build_root()+"/apps/mosquitto_ctrl/mosquitto_ctrl"] + opts + ["dynsec"] + args, env=env, capture_output=True, encoding='utf-8') if response is not None: if proc.stdout != response: raise ValueError(proc.stdout) if proc.returncode != 0: raise ValueError(args) ports = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, ports) env = mosq_test.env_add_ld_library_path() if not os.path.exists(str(ports[0])): os.mkdir(str(ports[0])) # Generate initial dynsec file ctrl_dynsec_cmd(["init", f"{ports[0]}/dynamic-security.json", "admin", "admin"], ports) try: # If we're root, set file ownership to "nobody", because that is the user # the broker will change to. os.chown(f"{ports[0]}/dynamic-security.json", 65534, 65534) except PermissionError: pass ctrl_dynsec_file_cmd(["help"], ports) # get the help, don't check the response though ctrl_dynsec_file_cmd(["setClientPassword", "admin", "newadmin", "-i", "10000"], ports) ctrl_dynsec_file_cmd(["setClientPassword", "admin", "newadmin"], ports) # Then start broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=ports[0], nolog=True) try: rc = 1 # Set default access to opposite of normal ctrl_dynsec_cmd(["setDefaultACLAccess", "publishClientSend", "allow"], ports) ctrl_dynsec_cmd(["setDefaultACLAccess", "publishClientReceive", "deny"], ports) ctrl_dynsec_cmd(["setDefaultACLAccess", "subscribe", "allow"], ports) ctrl_dynsec_cmd(["setDefaultACLAccess", "unsubscribe", "deny"], ports) # Verify ctrl_dynsec_cmd(["getDefaultACLAccess"], ports, response="publishClientSend : allow\npublishClientReceive : deny\nsubscribe : allow\nunsubscribe : deny\n") # Create clients ctrl_dynsec_cmd(["createClient", "username1", "-p", "password1"], ports) # password, no client id ctrl_dynsec_cmd(["createClient", "username2", "-p", "password2", "-c", "clientid2"], ports) # password and client id ctrl_dynsec_cmd(["createClient", "username3"], ports, input="pw\npw\n") # password, no client id ctrl_dynsec_cmd(["createClient", "username4"], ports, input="\n\n") # password, no client id ctrl_dynsec_cmd(["createClient", "username5"], ports, input="not\nmatching\n") # List clients ctrl_dynsec_cmd(["listClients"], ports, response="admin\nusername1\nusername2\nusername3\nusername4\n") ctrl_dynsec_cmd(["listClients", "1"], ports, response="admin\n") # with count ctrl_dynsec_cmd(["listClients", "1", "1"], ports, response="username1\n") # with count, offset # Create groups ctrl_dynsec_cmd(["createGroup", "group1"], ports) ctrl_dynsec_cmd(["createGroup", "group2"], ports) ctrl_dynsec_cmd(["createGroup", "group3"], ports) #List groups ctrl_dynsec_cmd(["listGroups"], ports, response="group1\ngroup2\ngroup3\n") ctrl_dynsec_cmd(["listGroups", "1"], ports, response="group1\n") ctrl_dynsec_cmd(["listGroups", "1", "1"], ports, response="group2\n") # Add client to group ctrl_dynsec_cmd(["addGroupClient", "group1", "username1", "10"], ports) # Get anonymous group ctrl_dynsec_cmd(["getAnonymousGroup"], ports, response="\n") # Set anon as anonymous group ctrl_dynsec_cmd(["setAnonymousGroup", "group2"], ports) # Verify ctrl_dynsec_cmd(["getAnonymousGroup"], ports, response="group2\n") # Create roles ctrl_dynsec_cmd(["createRole", "role1"], ports) ctrl_dynsec_cmd(["createRole", "role2"], ports) ctrl_dynsec_cmd(["createRole", "role3"], ports) #Delete a role: deleteRole ctrl_dynsec_cmd(["deleteRole", "role3"], ports) # repeat with count, offset # Add a role to a client ctrl_dynsec_cmd(["addClientRole", "username1", "role1", "20"], ports) # Add a role to a group ctrl_dynsec_cmd(["addGroupRole", "group1", "role2", "15"], ports) ctrl_dynsec_cmd(["getGroup", "group1"], ports) # repeat with count, offset # Add ACLs ctrl_dynsec_cmd(["addRoleACL", "role1", "publishClientSend", "#", "allow", "1"], ports) ctrl_dynsec_cmd(["addRoleACL", "role1", "publishClientReceive", "#", "allow", "2"], ports) ctrl_dynsec_cmd(["addRoleACL", "role1", "subscribeLiteral", "#", "allow", "1"], ports) ctrl_dynsec_cmd(["addRoleACL", "role1", "subscribePattern", "#", "allow", "2"], ports) ctrl_dynsec_cmd(["addRoleACL", "role1", "unsubscribeLiteral", "#", "deny", "1"], ports) ctrl_dynsec_cmd(["addRoleACL", "role1", "unsubscribePattern", "#", "deny", "2"], ports) ctrl_dynsec_cmd(["addRoleACL", "role2", "publishClientSend", "#", "allow", "3"], ports) ctrl_dynsec_cmd(["addRoleACL", "role2", "publishClientReceive", "#", "allow"], ports) # List roles ctrl_dynsec_cmd(["listRoles"], ports, response="admin\nrole1\nrole2\n") ctrl_dynsec_cmd(["listRoles", "1"], ports, response="admin\n") ctrl_dynsec_cmd(["listRoles", "1", "1"], ports, response="role1\n") # Get role ctrl_dynsec_cmd(["getRole", "role1"], ports, response="Rolename: role1\nACLs: publishClientSend : allow : # (priority: 1)\n publishClientReceive : allow : # (priority: 2)\n subscribeLiteral : allow : # (priority: 1)\n subscribePattern : allow : # (priority: 2)\n unsubscribeLiteral : deny : # (priority: 1)\n unsubscribePattern : deny : # (priority: 2)\n") # Get client ctrl_dynsec_cmd(["getClient", "username1"], ports, response="Username: username1\nClientid:\nRoles: role1 (priority: 20)\nGroups: group1 (priority: 10)\n") # Disable client ctrl_dynsec_cmd(["disableClient", "username1"], ports) # Verify client ctrl_dynsec_cmd(["getClient", "username1"], ports, response="Username: username1\nClientid:\nDisabled: true\nRoles: role1 (priority: 20)\nGroups: group1 (priority: 10)\n") # Set clientid ctrl_dynsec_cmd(["setClientID", "username1", "fixed-id"], ports) # Verify client ctrl_dynsec_cmd(["getClient", "username1"], ports, response="Username: username1\nClientid: fixed-id\nDisabled: true\nRoles: role1 (priority: 20)\nGroups: group1 (priority: 10)\n") # Clear clientid ctrl_dynsec_cmd(["setClientID", "username1"], ports) # Enable client ctrl_dynsec_cmd(["enableClient", "username1"], ports) # Verify client ctrl_dynsec_cmd(["getClient", "username1"], ports, response="Username: username1\nClientid:\nRoles: role1 (priority: 20)\nGroups: group1 (priority: 10)\n") # Set client password ctrl_dynsec_cmd(["setClientPassword", "username1", "new-password"], ports) ctrl_dynsec_cmd(["setClientPassword", "username1"], ports, input="not\nmatch\n") # Remove an ACL ctrl_dynsec_cmd(["removeRoleACL", "role1", "publishClientReceive", "#"], ports) ctrl_dynsec_cmd(["getRole", "role1"], ports, response="Rolename: role1\nACLs: publishClientSend : allow : # (priority: 1)\n subscribeLiteral : allow : # (priority: 1)\n subscribePattern : allow : # (priority: 2)\n unsubscribeLiteral : deny : # (priority: 1)\n unsubscribePattern : deny : # (priority: 2)\n") ctrl_dynsec_cmd(["removeRoleACL", "role1", "publishClientSend", "#"], ports) ctrl_dynsec_cmd(["getRole", "role1"], ports, response="Rolename: role1\nACLs: subscribeLiteral : allow : # (priority: 1)\n subscribePattern : allow : # (priority: 2)\n unsubscribeLiteral : deny : # (priority: 1)\n unsubscribePattern : deny : # (priority: 2)\n") ctrl_dynsec_cmd(["removeRoleACL", "role1", "subscribeLiteral", "#"], ports) ctrl_dynsec_cmd(["removeRoleACL", "role1", "subscribePattern", "#"], ports) ctrl_dynsec_cmd(["removeRoleACL", "role1", "unsubscribeLiteral", "#"], ports) ctrl_dynsec_cmd(["removeRoleACL", "role1", "unsubscribePattern", "#"], ports) ctrl_dynsec_cmd(["getRole", "role1"], ports, response="Rolename: role1\n") # Remove a Role ctrl_dynsec_cmd(["deleteRole", "role2"], ports) # Remove client from a group ctrl_dynsec_cmd(["removeGroupClient", "group1", "username1"], ports) # Remove role from a group ctrl_dynsec_cmd(["removeGroupRole", "group1", "role2"], ports) # Delete group ctrl_dynsec_cmd(["deleteGroup", "group1"], ports) ctrl_dynsec_cmd(["removeClientRole", "username1", "role1"], ports) # Delete client ctrl_dynsec_cmd(["deleteClient", "username1"], ports) rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{ports[0]}/dynamic-security.json") pass except FileNotFoundError: pass shutil.rmtree(f"{ports[0]}") broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 exit(rc) ================================================ FILE: test/apps/ctrl/ctrl_shell_broker_test.cpp ================================================ /* Copyright (c) 2022 Cedalo GmbH */ // clang-format off #include "mosquitto_internal.h" // keep this at the top for `#define uthash_free` #include "ctrl_shell.h" #include "ctrl_shell_internal.h" #include "json_help.h" #include "utlist.h" // clang-format on #include #include #include #include "ctrl_shell_mock.hpp" #include "editline_mock.hpp" #include "libmosquitto_mock.hpp" #include "pthread_mock.hpp" namespace t = testing; struct pending_payload { struct pending_payload *next, *prev; char payload[1024]; }; class CtrlShellBrokerTest : public ::t::Test { public: ::t::StrictMock ctrl_shell_mock_{}; ::t::StrictMock editline_mock_{}; ::t::StrictMock libmosquitto_mock_{}; ::t::StrictMock pthread_mock_{}; LIBMOSQ_CB_connect on_connect{}; LIBMOSQ_CB_message on_message{}; LIBMOSQ_CB_subscribe on_subscribe{}; LIBMOSQ_CB_publish_v5 on_publish{}; struct pending_payload *pending_payloads = nullptr; void expect_setup(struct mosq_config *config) { editline_mock_.reset(); EXPECT_CALL(editline_mock_, rl_bind_key(t::Eq('\t'), t::_)); EXPECT_CALL(editline_mock_, add_history(t::_)).WillRepeatedly(t::Return(0)); EXPECT_CALL(editline_mock_, clear_history()).Times(t::AnyNumber()); config->no_colour = true; EXPECT_CALL(ctrl_shell_mock_, ctrl_shell__output(t::StartsWith("mosquitto_ctrl shell v"))); } void expect_connect(struct mosquitto *mosq, const char *host, int port) { EXPECT_CALL(libmosquitto_mock_, mosquitto_new(t::Eq(nullptr), t::Eq(true), t::Eq(nullptr))) .WillOnce(t::Return(mosq)); EXPECT_CALL(libmosquitto_mock_, mosquitto_int_option(t::Eq(mosq), MOSQ_OPT_PROTOCOL_VERSION, 5)); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe_callback_set(t::Eq(mosq), t::A())) .WillRepeatedly(t::SaveArg<1>(&this->on_subscribe)); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish_v5_callback_set(t::Eq(mosq), t::A())) .WillRepeatedly(t::SaveArg<1>(&this->on_publish)); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect(t::Eq(mosq), t::StrEq(host), port, 60)); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_start(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect_callback_set(t::Eq(mosq), t::A())) .WillRepeatedly(t::SaveArg<1>(&this->on_connect)); EXPECT_CALL(libmosquitto_mock_, mosquitto_message_callback_set(t::Eq(mosq), t::A())) .WillOnce(t::SaveArg<1>(&this->on_message)); } void expect_disconnect(struct mosquitto *mosq) { EXPECT_CALL(libmosquitto_mock_, mosquitto_disconnect(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_stop(t::Eq(mosq), false)); EXPECT_CALL(libmosquitto_mock_, mosquitto_destroy(t::Eq(mosq))); } void expect_outputs(const char **outputs, size_t count) { for(size_t i=0; ipayload, sizeof(pp->payload), "%s", respons); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(mosq), nullptr, t::StrEq("$CONTROL/broker/v1"), t::_, t::StrEq(request), 1, false)) .WillOnce(t::Invoke([this, pp](){ DL_APPEND(this->pending_payloads, pp); return 0; })); } void expect_request_response_success(struct mosquitto *mosq, const char *request, const char *command) { char response[100]; snprintf(response, sizeof(response), "{\"responses\":[{\"command\":\"%s\"}]}", command); expect_request_response(mosq, request, response); } void expect_request_response_empty(struct mosquitto *mosq, const char *command) { char request[100]; char response[100]; snprintf(request, sizeof(request), "{\"commands\":[{\"command\":\"%s\"}]}", command); snprintf(response, sizeof(response), "{\"responses\":[{\"command\":\"%s\",\"data\":{}}]}", command); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(mosq), nullptr, t::StrEq("$CONTROL/broker/v1"), t::_, t::StrEq(request), 1, false)) .WillOnce(t::Invoke([this, &command](){ append_empty_response(command); return 0; })); } void append_response(const char *response) { struct pending_payload *pp = (struct pending_payload *)calloc(1, sizeof(struct pending_payload)); snprintf(pp->payload, sizeof(pp->payload), "%s", response); DL_APPEND(this->pending_payloads, pp); } void append_empty_response(const char *command) { struct pending_payload *pp = (struct pending_payload *)calloc(1, sizeof(struct pending_payload)); snprintf(pp->payload, sizeof(pp->payload), "{\"responses\":[{\"command\":\"%s\",\"data\":{}}]}", command); DL_APPEND(this->pending_payloads, pp); } void expect_broker(const char *host, int port) { char buf[200]; snprintf(buf, sizeof(buf), "connect mqtt://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("broker"))); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe(t::_, nullptr, t::StrEq("$CONTROL/broker/v1/response"), 1)) .WillOnce(t::Return(0)); } void expect_connect_and_messages(struct mosquitto *mosq) { /* This is a hacky way of working around the async mqtt send/receive which we don't directly control. * Each send starts a wait which times out after two seconds. We use that call to produce the effect we want. */ EXPECT_CALL(pthread_mock_, pthread_cond_timedwait(t::_, t::_, t::_)) .WillOnce(t::Invoke([this, mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ this->on_connect(mosq, nullptr, 0); data.response_received = true; return 0; })) .WillRepeatedly(t::Invoke([this, mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; struct pending_payload *pp = pending_payloads; if(pp){ DL_DELETE(pending_payloads, pp); msg.payload = pp->payload; msg.payloadlen = (int)strlen((char *)msg.payload); this->on_message(mosq, nullptr, &msg); free(pp); } data.response_received = true; return 0; })); } }; TEST_F(CtrlShellBrokerTest, LineEmpty) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_broker(host, port); expect_connect_and_messages(&mosq); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|broker> "))) .WillOnce(t::Return(strdup(""))) .WillOnce(t::Return(strdup("exit"))); const char *outputs[] = { "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellBrokerTest, SubscribeDenied) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); char buf[200]; snprintf(buf, sizeof(buf), "connect mqtt://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("broker"))); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|broker> "))) .WillOnce(t::Return(strdup("exit"))); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe(t::_, nullptr, t::StrEq("$CONTROL/broker/v1/response"), 1)); EXPECT_CALL(pthread_mock_, pthread_cond_timedwait(t::_, t::_, t::_)) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ this->on_connect(&mosq, nullptr, 0); data.response_received = true; return 0; })) .WillOnce(t::Invoke([this, &mosq](){ int granted_qos[1] = {128}; this->on_subscribe(&mosq, nullptr, 1, 1, granted_qos); data.response_received = true; return 0; })) .WillRepeatedly(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; struct pending_payload *pp = pending_payloads; if(pp){ DL_DELETE(pending_payloads, pp); msg.payload = pp->payload; msg.payloadlen = (int)strlen((char *)msg.payload); this->on_message(&mosq, nullptr, &msg); free(pp); } data.response_received = true; return 0; })); const char *outputs[] = { "Subscribe failed, check you have permission to access this module.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellBrokerTest, PublishDenied) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); char buf[200]; snprintf(buf, sizeof(buf), "connect mqtt://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("broker"))); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|broker> "))) .WillOnce(t::Return(strdup("listListeners"))) .WillOnce(t::Return(strdup("exit"))); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe(t::_, nullptr, t::StrEq("$CONTROL/broker/v1/response"), 1)); EXPECT_CALL(pthread_mock_, pthread_cond_timedwait(t::_, t::_, t::_)) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ this->on_connect(&mosq, nullptr, 0); data.response_received = true; return 0; })) .WillOnce(t::Invoke([this, &mosq](){ int granted_qos[1] = {1}; this->on_subscribe(&mosq, nullptr, 1, 1, granted_qos); data.response_received = true; return 0; })) .WillOnce(t::Invoke([this, &mosq](){ this->on_publish(&mosq, nullptr, 1, 128, nullptr); data.response_received = true; return 0; })); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/broker/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listListeners\"}]}"), 1, false)); const char *outputs[] = { "Publish failed, check you have permission to access this module.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellBrokerTest, ListListeners) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_broker(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|broker> "))) .WillOnce(t::Return(strdup("listListeners"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); const char request[] = "{\"commands\":[{\"command\":\"listListeners\"}]}"; const char response[] = "{\"responses\":[{\"command\":\"listListeners\",\"data\":{" "\"listeners\":[" "{\"port\":1883,\"protocol\":\"mqtt\",\"tls\":false}" "]}}]}"; expect_request_response(&mosq, request, response); const char *outputs[] = { "Listener:", " Port:", " 1883\n", " Protocol:", " mqtt\n", " TLS:", " false\n\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellBrokerTest, ListListenersInvalidResponse) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_broker(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|broker> "))) .WillOnce(t::Return(strdup("listListeners"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); const char request[] = "{\"commands\":[{\"command\":\"listListeners\"}]}"; const char response[] = "{\"responses\":[{\"command\":\"listListeners\",\"data\":{" "\"listeners\":[" "{\"protocol\":\"mqtt\",\"tls\":false}" "]}}]}"; expect_request_response(&mosq, request, response); const char *outputs[] = { "Invalid response from broker.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellBrokerTest, ListPlugins) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_broker(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|broker> "))) .WillOnce(t::Return(strdup("listPlugins"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); const char request[] = "{\"commands\":[{\"command\":\"listPlugins\"}]}"; const char response[] = "{\"responses\":[{\"command\":\"listPlugins\",\"data\":{" "\"plugins\":[" "{\"name\":\"plugin1\",\"control-endpoints\":[\"$CONTROL/plugin1\"]}" "]}}]}"; expect_request_response(&mosq, request, response); const char *outputs[] = { "Plugin:", " plugin1\n", "Control endpoints:", " $CONTROL/plugin1\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellBrokerTest, ListPluginsInvalidResponse) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_broker(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|broker> "))) .WillOnce(t::Return(strdup("listPlugins"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); const char request[] = "{\"commands\":[{\"command\":\"listPlugins\"}]}"; const char response[] = "{\"responses\":[{\"command\":\"listPlugins\",\"data\":{" "\"plugins\":[" "{\"control-endpoints\":[\"$CONTROL/plugin1\"]}" "]}}]}"; expect_request_response(&mosq, request, response); const char *outputs[] = { "Invalid response from broker.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } ================================================ FILE: test/apps/ctrl/ctrl_shell_completion_test.cpp ================================================ /* Copyright (c) 2022 Cedalo GmbH */ // clang-format off #include "mosquitto_internal.h" // keep this at the top for `#define uthash_free` #include "ctrl_shell.h" #include "ctrl_shell_internal.h" #include "json_help.h" #include "utlist.h" // clang-format on #include #include #include #include "ctrl_shell_mock.hpp" #include "libmosquitto_mock.hpp" #include "pthread_mock.hpp" extern "C" { char **completion_matcher(const char *text, int start, int end); char *completion_generator(const char *text, int state); void ctrl_shell__cleanup(void); } namespace t = testing; class CtrlShellCompletionTest : public ::t::Test { public: ::t::StrictMock ctrl_shell_mock_{}; ::t::StrictMock libmosquitto_mock_{}; ::t::StrictMock pthread_mock_{}; void expect_setup() { EXPECT_CALL(pthread_mock_, pthread_cond_timedwait(t::_, t::_, t::_)) .WillRepeatedly(t::Invoke([](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ data.response_received = true; return 0; })); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe(t::_, t::_, t::_, 1)) .WillRepeatedly(t::Return(0)); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::_, nullptr, t::_, t::_, t::_, 1, false)) .WillRepeatedly(t::Return(0)); rl_readline_name = "mosquitto_ctrl"; rl_completion_entry_function = completion_generator; rl_attempted_completion_function = completion_matcher; ctrl_shell__load_module(ctrl_shell__dynsec_init); } void expect_outputs(const char **outputs, size_t count) { for(size_t i=0; i #include #include #include "ctrl_shell_mock.hpp" #include "editline_mock.hpp" #include "libmosquitto_mock.hpp" #include "pthread_mock.hpp" namespace t = testing; struct pending_payload { struct pending_payload *next, *prev; char payload[1024]; }; class CtrlShellDynsecTest : public ::t::Test { public: ::t::StrictMock ctrl_shell_mock_{}; ::t::StrictMock editline_mock_{}; ::t::StrictMock libmosquitto_mock_{}; ::t::StrictMock pthread_mock_{}; LIBMOSQ_CB_connect on_connect{}; LIBMOSQ_CB_message on_message{}; struct pending_payload *pending_payloads = nullptr; void expect_setup(struct mosq_config *config) { editline_mock_.reset(); EXPECT_CALL(editline_mock_, rl_bind_key(t::Eq('\t'), t::_)); EXPECT_CALL(editline_mock_, add_history(t::_)).WillRepeatedly(t::Return(0)); EXPECT_CALL(editline_mock_, clear_history()).Times(t::AnyNumber()); config->no_colour = true; EXPECT_CALL(ctrl_shell_mock_, ctrl_shell__output(t::StartsWith("mosquitto_ctrl shell v"))); } void expect_connect(struct mosquitto *mosq, const char *host, int port) { EXPECT_CALL(libmosquitto_mock_, mosquitto_new(t::Eq(nullptr), t::Eq(true), t::Eq(nullptr))) .WillOnce(t::Return(mosq)); EXPECT_CALL(libmosquitto_mock_, mosquitto_int_option(t::Eq(mosq), MOSQ_OPT_PROTOCOL_VERSION, 5)); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe_callback_set(t::Eq(mosq), t::_)); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish_v5_callback_set(t::Eq(mosq), t::_)); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect(t::Eq(mosq), t::StrEq(host), port, 60)); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_start(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect_callback_set(t::Eq(mosq), t::A())) .WillRepeatedly(t::SaveArg<1>(&this->on_connect)); EXPECT_CALL(libmosquitto_mock_, mosquitto_message_callback_set(t::Eq(mosq), t::A())) .WillOnce(t::SaveArg<1>(&this->on_message)); } void expect_disconnect(struct mosquitto *mosq) { EXPECT_CALL(libmosquitto_mock_, mosquitto_disconnect(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_stop(t::Eq(mosq), false)); EXPECT_CALL(libmosquitto_mock_, mosquitto_destroy(t::Eq(mosq))); } void expect_outputs(const char **outputs, size_t count) { for(size_t i=0; ipayload, sizeof(pp->payload), "%s", respons); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq(request), 1, false)) .WillOnce(t::Invoke([this, pp](){ DL_APPEND(this->pending_payloads, pp); return 0; })); } void expect_request_response_success(struct mosquitto *mosq, const char *request, const char *command) { char response[100]; snprintf(response, sizeof(response), "{\"responses\":[{\"command\":\"%s\"}]}", command); expect_request_response(mosq, request, response); } void expect_request_response_empty(struct mosquitto *mosq, const char *command) { char request[100]; char response[100]; snprintf(request, sizeof(request), "{\"commands\":[{\"command\":\"%s\"}]}", command); snprintf(response, sizeof(response), "{\"responses\":[{\"command\":\"%s\",\"data\":{}}]}", command); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq(request), 1, false)) .WillOnce(t::Invoke([this, command](){ append_empty_response(command); return 0; })); } void append_response(const char *response) { struct pending_payload *pp = (struct pending_payload *)calloc(1, sizeof(struct pending_payload)); snprintf(pp->payload, sizeof(pp->payload), "%s", response); DL_APPEND(this->pending_payloads, pp); } void append_empty_response(const char *command) { struct pending_payload *pp = (struct pending_payload *)calloc(1, sizeof(struct pending_payload)); snprintf(pp->payload, sizeof(pp->payload), "{\"responses\":[{\"command\":\"%s\",\"data\":{}}]}", command); DL_APPEND(this->pending_payloads, pp); } void expect_single_lists(struct mosquitto *mosq) { expect_request_response_empty(mosq, "listClients"); expect_request_response_empty(mosq, "listGroups"); expect_request_response_empty(mosq, "listRoles"); } void expect_dynsec(const char *host, int port) { char buf[200]; snprintf(buf, sizeof(buf), "connect mqtt://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("dynsec"))); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe(t::_, nullptr, t::StrEq("$CONTROL/dynamic-security/v1/response"), 1)) .WillOnce(t::Return(0)); } void expect_connect_and_messages(struct mosquitto *mosq) { /* This is a hacky way of working around the async mqtt send/receive which we don't directly control. * Each send starts a wait which times out after two seconds. We use that call to produce the effect we want. */ EXPECT_CALL(pthread_mock_, pthread_cond_timedwait(t::_, t::_, t::_)) .WillOnce(t::Invoke([this, mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ this->on_connect(mosq, nullptr, 0); data.response_received = true; return 0; })) .WillRepeatedly(t::Invoke([this, mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; struct pending_payload *pp = this->pending_payloads; if(pp){ DL_DELETE(pending_payloads, pp); msg.payload = pp->payload; msg.payloadlen = (int)strlen((char *)msg.payload); this->on_message(mosq, nullptr, &msg); free(pp); } data.response_received = true; return 0; })); } void expect_generic_arg1(const char *command, const char *itemlabel, const char *itemvalue) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; char line[200]; char payload[500]; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); snprintf(line, sizeof(line), "%s %s", command, itemvalue); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup(line))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); snprintf(payload, sizeof(payload), "{\"commands\":[{\"command\":\"%s\",\"%s\":\"%s\"}]}", command, itemlabel, itemvalue); expect_request_response_success(&mosq, payload, command); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } void expect_generic_arg1_with_list_update(const char *command, const char *itemlabel, const char *itemvalue, const char *listcmd) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; char line[200]; char request[500]; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); snprintf(line, sizeof(line), "%s %s", command, itemvalue); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup(line))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); snprintf(request, sizeof(request), "{\"commands\":[{\"command\":\"%s\",\"%s\":\"%s\"}]}", command, itemlabel, itemvalue); expect_request_response_success(&mosq, request, command); expect_request_response_empty(&mosq, listcmd); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } void expect_generic_arg1_with_error(const char *command, const char *itemlabel) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; char line[200]; char error[200]; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); snprintf(line, sizeof(line), "%s", command); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup(line))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); snprintf(error, sizeof(error), "%s %s\n", command, itemlabel); const char *outputs[] = { error, "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } void expect_generic_arg2(const char *command, const char *itemlabel1, const char *itemvalue1, const char *itemlabel2, const char *itemvalue2) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; char line[200]; char payload[500]; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); snprintf(line, sizeof(line), "%s %s %s", command, itemvalue1, itemvalue2); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup(line))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); snprintf(payload, sizeof(payload), "{\"commands\":[{\"command\":\"%s\"," "\"%s\":\"%s\"," "\"%s\":\"%s\"" "}]}", command, itemlabel1, itemvalue1, itemlabel2, itemvalue2); expect_request_response_success(&mosq, payload, command); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } void expect_send_set_acl_default_access(const char *acltype) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; char buf[500]; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); snprintf(buf, sizeof(buf), "setDefaultACLAccess %s allow", acltype); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup(buf))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); snprintf(buf, sizeof(buf), "{\"commands\":[{\"command\":\"setDefaultACLAccess\"," "\"acls\":[" "{" "\"acltype\":\"%s\"," "\"allow\":true}]}]}", acltype); expect_request_response_success(&mosq, buf, "setDefaultACLAccess"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } }; TEST_F(CtrlShellDynsecTest, NoDynsec) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(pthread_mock_, pthread_cond_timedwait(t::_, t::_, t::_)) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ this->on_connect(&mosq, nullptr, 0); data.response_received = true; return 0; })) .WillOnce(t::Invoke([](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ // Subscribe data.response_received = true; return 0; })) .WillOnce(t::Return(ETIMEDOUT)); // First message to dynsec fails EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listClients\"}]}"), 1, false)) .WillOnce(t::Return(0)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(nullptr)); const char *outputs[] = { "Timed out with no response.\n", "Check the dynsec module is configured on the broker.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, CreateClient) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("createClient"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "createClient username [password [clientid]]\n", "createClient username password [clientid]\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, CreateClientWithPassword) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("createClient username password"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listClients\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_empty_response("listClients"); return 0; })) .WillOnce(t::Invoke([this](){ append_empty_response("listClients"); return 0; })); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); expect_request_response_success(&mosq, "{\"commands\":[{\"command\":\"createClient\",\"username\":\"username\",\"password\":\"password\"}]}", "createClient"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, CreateClientWithPasswordAndClientid) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("createClient username1 password1 clientid1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listClients\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_empty_response("listClients"); return 0; })) .WillOnce(t::Invoke([this](){ append_empty_response("listClients"); return 0; })); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); expect_request_response_success(&mosq, "{\"commands\":[{\"command\":\"createClient\",\"username\":\"username1\",\"password\":\"password1\",\"clientid\":\"clientid1\"}]}", "createClient"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, CreateClientPasswordCliMatching) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("createClient username1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listClients\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_empty_response("listClients"); return 0; })) .WillOnce(t::Invoke([this](){ append_empty_response("listClients"); return 0; })); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(ctrl_shell_mock_, ctrl_shell_fgets(t::_, t::_, t::_)) .WillOnce(t::Invoke([](char *s, int size, FILE *){ snprintf(s, (size_t)size, "password1"); return s; })) .WillOnce(t::Invoke([](char *s, int size, FILE *){ snprintf(s, (size_t)size, "password1"); return s; })); expect_request_response_success(&mosq, "{\"commands\":[{\"command\":\"createClient\",\"username\":\"username1\",\"password\":\"password1\"}]}", "createClient"); const char *outputs[] = { "password:", "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, CreateClientPasswordCliNotMatching) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("createClient username"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); EXPECT_CALL(ctrl_shell_mock_, ctrl_shell_fgets(t::_, t::_, t::_)) .WillOnce(t::Invoke([](char *s, int size, FILE *){ snprintf(s, (size_t)size, "mypassword"); return s; })) .WillOnce(t::Invoke([](char *s, int size, FILE *){ snprintf(s, (size_t)size, "nomatch"); return s; })); const char *outputs[] = { "password:", "Passwords do not match.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, CreateClientPasswordCliOneOnly) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("createClient username"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); EXPECT_CALL(ctrl_shell_mock_, ctrl_shell_fgets(t::_, t::_, t::_)) .WillOnce(t::Invoke([](char *s, int size, FILE *){ snprintf(s, (size_t)size, "mypassword"); return s; })) .WillOnce(t::Return(nullptr)); const char *outputs[] = { "password:", "No password.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, EnableClient) { expect_generic_arg1("enableClient", "username", "username1"); } TEST_F(CtrlShellDynsecTest, EnableClientMissing) { expect_generic_arg1_with_error("enableClient", "username"); } /* FIXME - Not found cases */ TEST_F(CtrlShellDynsecTest, DisableClient) { expect_generic_arg1("disableClient", "username", "username1"); } TEST_F(CtrlShellDynsecTest, DisableClientMissing) { expect_generic_arg1_with_error("disableClient", "username"); } TEST_F(CtrlShellDynsecTest, SetAnonGroup) { expect_generic_arg1("setAnonymousGroup", "groupname", "groupname1"); } TEST_F(CtrlShellDynsecTest, SetAnonGroupMissing) { expect_generic_arg1_with_error("setAnonymousGroup", "groupname"); } TEST_F(CtrlShellDynsecTest, AddClientRole) { expect_generic_arg2("addClientRole", "username", "username1", "rolename", "rolename1"); } TEST_F(CtrlShellDynsecTest, AddGroupClient) { expect_generic_arg2("addGroupClient", "groupname", "groupname1", "username", "username1"); } TEST_F(CtrlShellDynsecTest, AddGroupRole) { expect_generic_arg2("addGroupRole", "groupname", "groupname1", "rolename", "rolename1"); } TEST_F(CtrlShellDynsecTest, RemoveClientRole) { expect_generic_arg2("removeClientRole", "username", "username1", "rolename", "rolename1"); } TEST_F(CtrlShellDynsecTest, RemoveGroupClient) { expect_generic_arg2("removeGroupClient", "groupname", "groupname1", "username", "username1"); } TEST_F(CtrlShellDynsecTest, RemoveGroupRole) { expect_generic_arg2("removeGroupRole", "groupname", "groupname1", "rolename", "rolename1"); } TEST_F(CtrlShellDynsecTest, SetClientId) { expect_generic_arg2("setClientId", "username", "username1", "clientid", "clientid1"); } TEST_F(CtrlShellDynsecTest, SetDefaultACLAccessPublishClientReceive) { expect_send_set_acl_default_access("publishClientReceive"); } TEST_F(CtrlShellDynsecTest, SetDefaultACLAccessPublishClientSend) { expect_send_set_acl_default_access("publishClientSend"); } TEST_F(CtrlShellDynsecTest, SetDefaultACLAccessSubscribe) { expect_send_set_acl_default_access("subscribe"); } TEST_F(CtrlShellDynsecTest, SetDefaultACLAccessUnsubscribe) { expect_send_set_acl_default_access("unsubscribe"); } TEST_F(CtrlShellDynsecTest, SetDefaultACLAccessBadType) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("setDefaultACLAccess badtype allow"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "setDefaultACLAccess acltype allow|deny\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, SetDefaultACLAccessBadAllow) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("setDefaultACLAccess subscribe bad"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "setDefaultACLAccess acltype allow|deny\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, SetDefaultACLAccessNoAllow) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("setDefaultACLAccess publishClientSend"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "setDefaultACLAccess acltype allow|deny\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, GetDefaultACLAccess) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("getDefaultACLAccess"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{\"command\":\"getDefaultACLAccess\"}]}"; const char response[] = "{\"responses\":[{\"command\":\"getDefaultACLAccess\",\"data\":{" "\"acls\":[" "{\"acltype\":\"publishClientSend\",\"allow\":false}," "{\"acltype\":\"publishClientReceive\",\"allow\":true}," "{\"acltype\":\"subscribe\",\"allow\":false}," "{\"acltype\":\"unsubscribe\",\"allow\":true}" "]}}]}"; expect_request_response(&mosq, request, response); const char *outputs[] = { "publishClientSend deny\n", "publishClientReceive allow\n", "subscribe deny\n", "unsubscribe allow\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, GetAnonymousGroup) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("getAnonymousGroup"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{\"command\":\"getAnonymousGroup\"}]}"; const char response[] = "{\"responses\":[{\"command\":\"getAnonymousGroup\",\"data\":{" "\"group\":{\"groupname\":\"group1\"}" "}}]}"; expect_request_response(&mosq, request, response); const char *outputs[] = { "group1\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, GetClient) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("getClient username1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{\"command\":\"getClient\",\"username\":\"username1\"}]}"; const char response[] = "{\"responses\":[{\"command\":\"getClient\",\"data\":{" "\"client\":{" "\"username\":\"username1\"," "\"clientid\":\"clientid1\"," "\"disabled\":true," "\"textname\":\"textname1\"," "\"textdescription\":\"textdescription1\"," "\"roles\":[" "{\"rolename\":\"role1\",\"priority\":1}" "]," "\"groups\":[" "{\"groupname\":\"group1\",\"priority\":2}" "]}}}]}"; expect_request_response(&mosq, request, response); const char *outputs[] = { "Username:", " username1\n", "Clientid:", " clientid1\n", "Text name:", " textname1\n", "Text description:", " textdescription1\n", "Disabled:", " true\n", "Roles:", " role1", "Groups:", " group1", " (priority: ", "1", "2", ")", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, GetGroup) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("getGroup groupname1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{\"command\":\"getGroup\",\"groupname\":\"groupname1\"}]}"; const char response[] = "{\"responses\":[{\"command\":\"getGroup\",\"data\":{" "\"group\":{" "\"groupname\":\"groupname1\"," "\"textname\":\"textname1\"," "\"textdescription\":\"textdescription1\"," "\"roles\":[" "{\"rolename\":\"role1\",\"priority\":1}" "]," "\"clients\":[" "{\"username\":\"username1\",\"priority\":2}" "]}}}]}"; expect_request_response(&mosq, request, response); const char *outputs[] = { "Group name:", " groupname1\n", "Text name:", " textname1\n", "Text description:", " textdescription1\n", "Roles:", " role1", "Clients:", " username1", " (priority: ", "1", ")", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellDynsecTest, GetRole) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("getRole rolename1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{\"command\":\"getRole\",\"rolename\":\"rolename1\"}]}"; const char response[] = "{\"responses\":[{\"command\":\"getRole\",\"data\":{" "\"role\":{" "\"rolename\":\"rolename1\"," "\"textname\":\"textname1\"," "\"textdescription\":\"textdescription1\"," "\"allowwildcardsubs\":true," "\"acls\":[" "{\"acltype\":\"subscribeLiteral\",\"topic\":\"topic1\",\"allow\":true,\"priority\":1}" "]}}}]}"; expect_request_response(&mosq, request, response); const char *outputs[] = { "Role name:", " rolename1\n", "Text name:", " textname1\n", "Text description:", " textdescription1\n", "Allow wildcard subscriptions:", " true\n", "ACLs:", " subscribeLiteral allow topic1 (priority 1)\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, SetClientPasswordCliMatching) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("setClientPassword username1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); EXPECT_CALL(ctrl_shell_mock_, ctrl_shell_fgets(t::_, t::_, t::_)) .WillOnce(t::Invoke([](char *s, int size, FILE *){ snprintf(s, (size_t)size, "password1"); return s; })) .WillOnce(t::Invoke([](char *s, int size, FILE *){ snprintf(s, (size_t)size, "password1"); return s; })); expect_request_response_success(&mosq, "{\"commands\":[{\"command\":\"setClientPassword\",\"username\":\"username1\",\"password\":\"password1\"}]}", "setClientPassword"); const char *outputs[] = { "password:", "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, SetClientPasswordCliNotMatching) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("setClientPassword username1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); EXPECT_CALL(ctrl_shell_mock_, ctrl_shell_fgets(t::_, t::_, t::_)) .WillOnce(t::Invoke([](char *s, int size, FILE *){ snprintf(s, (size_t)size, "password1"); return s; })) .WillOnce(t::Invoke([](char *s, int size, FILE *){ snprintf(s, (size_t)size, "password2"); return s; })); const char *outputs[] = { "password:", "Passwords do not match.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, SetClientPasswordCliNoPassword) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("setClientPassword username1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); EXPECT_CALL(ctrl_shell_mock_, ctrl_shell_fgets(t::_, t::_, t::_)) .WillOnce(t::Invoke([](char *, int, FILE *){ return nullptr; })); const char *outputs[] = { "password:", "No password.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, SetClientPasswordCliNoUsername) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("setClientPassword"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "setClientPassword [password]\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, AddRoleACLPublishClientReceive) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("addRoleACL rolename1 publishClientReceive allow topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"addRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"publishClientReceive\"," "\"priority\":-1," "\"topic\":\"topic1\"," "\"allow\":true" "}]}"; expect_request_response_success(&mosq, request, "addRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, AddRoleACLPublishClientSend) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("addRoleACL rolename1 publishClientSend allow topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"addRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"publishClientSend\"," "\"priority\":-1," "\"topic\":\"topic1\"," "\"allow\":true" "}]}"; expect_request_response_success(&mosq, request, "addRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, AddRoleACLPublishClientSendWithPriority) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("addRoleACL rolename1 publishClientSend allow 42 topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"addRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"publishClientSend\"," "\"priority\":42," "\"topic\":\"topic1\"," "\"allow\":true" "}]}"; expect_request_response_success(&mosq, request, "addRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, AddRoleACLSubscribeLiteral) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("addRoleACL rolename1 subscribeLiteral allow topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"addRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"subscribeLiteral\"," "\"priority\":-1," "\"topic\":\"topic1\"," "\"allow\":true" "}]}"; expect_request_response_success(&mosq, request, "addRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, AddRoleACLSubscribePattern) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("addRoleACL rolename1 subscribePattern allow topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"addRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"subscribePattern\"," "\"priority\":-1," "\"topic\":\"topic1\"," "\"allow\":true" "}]}"; expect_request_response_success(&mosq, request, "addRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, AddRoleACLUnsubscribeLiteral) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("addRoleACL rolename1 unsubscribeLiteral allow topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"addRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"unsubscribeLiteral\"," "\"priority\":-1," "\"topic\":\"topic1\"," "\"allow\":true" "}]}"; expect_request_response_success(&mosq, request, "addRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, AddRoleACLUnsubscribePattern) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("addRoleACL rolename1 unsubscribePattern deny topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"addRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"unsubscribePattern\"," "\"priority\":-1," "\"topic\":\"topic1\"," "\"allow\":false" "}]}"; expect_request_response_success(&mosq, request, "addRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, AddRoleACLBadAllow) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("addRoleACL rolename1 unsubscribePattern bad topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "Invalid allow/deny 'bad'\n", "addRoleACL rolename acltype allow|deny [priority] topic\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, AddRoleACLBadACLType) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("addRoleACL rolename1 bad allow topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "Invalid acltype 'bad'\n", "addRoleACL rolename acltype allow|deny [priority] topic\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, AddRoleACLNoTopic) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("addRoleACL rolename1 subscribeLiteral allow"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "addRoleACL rolename acltype allow|deny [priority] topic\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, RemoveRoleACLPublishClientReceive) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("removeRoleACL rolename1 publishClientReceive topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"removeRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"publishClientReceive\"," "\"topic\":\"topic1\"" "}]}"; expect_request_response_success(&mosq, request, "removeRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, RemoveRoleACLPublishClientSend) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("removeRoleACL rolename1 publishClientSend topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"removeRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"publishClientSend\"," "\"topic\":\"topic1\"" "}]}"; expect_request_response_success(&mosq, request, "removeRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, RemoveRoleACLUnsubscribeLiteral) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("removeRoleACL rolename1 unsubscribeLiteral topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"removeRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"unsubscribeLiteral\"," "\"topic\":\"topic1\"" "}]}"; expect_request_response_success(&mosq, request, "removeRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, RemoveRoleACLUnsubscribePattern) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("removeRoleACL rolename1 unsubscribePattern topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"removeRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"unsubscribePattern\"," "\"topic\":\"topic1\"" "}]}"; expect_request_response_success(&mosq, request, "removeRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, RemoveRoleACLSubscribeLiteral) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("removeRoleACL rolename1 subscribeLiteral topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"removeRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"subscribeLiteral\"," "\"topic\":\"topic1\"" "}]}"; expect_request_response_success(&mosq, request, "removeRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, RemoveRoleACLSubscribePattern) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("removeRoleACL rolename1 subscribePattern topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"removeRoleACL\"," "\"rolename\":\"rolename1\"," "\"acltype\":\"subscribePattern\"," "\"topic\":\"topic1\"" "}]}"; expect_request_response_success(&mosq, request, "removeRoleACL"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, RemoveRoleACLBadACLType) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("removeRoleACL rolename1 bad topic1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "Invalid acltype 'bad'\n", "removeRoleACL rolename acltype topic\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, RemoveRoleACLNoTopic) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("removeRoleACL rolename1 subscribeLiteral "))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "removeRoleACL rolename acltype topic\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, CreateGroup) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listGroups\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_empty_response("listGroups"); return 0; })) .WillOnce(t::Invoke([this](){ append_empty_response("listGroups"); return 0; })); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("createGroup group1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); const char request[] = "{\"commands\":[{\"command\":\"createGroup\",\"groupname\":\"group1\"}]}"; expect_request_response_success(&mosq, request, "createGroup"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, CreateRole) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listGroups"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listRoles\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_empty_response("listRoles"); return 0; })) .WillOnce(t::Invoke([this](){ append_empty_response("listRoles"); return 0; })); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("createRole role1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); const char request[] = "{\"commands\":[{\"command\":\"createRole\",\"rolename\":\"role1\"}]}"; expect_request_response_success(&mosq, request, "createRole"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, DeleteClient) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listClients\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_empty_response("listClients"); return 0; })) .WillOnce(t::Invoke([this](){ append_empty_response("listClients"); return 0; })); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("deleteClient user1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); const char request[] = "{\"commands\":[{\"command\":\"deleteClient\",\"username\":\"user1\"}]}"; expect_request_response_success(&mosq, request, "deleteClient"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, DeleteGroup) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listGroups\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_empty_response("listGroups"); return 0; })) .WillOnce(t::Invoke([this](){ append_empty_response("listGroups"); return 0; })); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("deleteGroup group1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); const char request[] = "{\"commands\":[{\"command\":\"deleteGroup\",\"groupname\":\"group1\"}]}"; expect_request_response_success(&mosq, request, "deleteGroup"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, DeleteRole) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listGroups"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listRoles\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_empty_response("listRoles"); return 0; })) .WillOnce(t::Invoke([this](){ append_empty_response("listRoles"); return 0; })); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("deleteRole role1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); const char request[] = "{\"commands\":[{\"command\":\"deleteRole\",\"rolename\":\"role1\"}]}"; expect_request_response_success(&mosq, request, "deleteRole"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ModifyClientTextName) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("modifyClient user1 textName new name"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"modifyClient\"," "\"username\":\"user1\"," "\"textName\":\"new name\"" "}]}"; expect_request_response_success(&mosq, request, "modifyClient"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ModifyClientTextDescription) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("modifyClient user1 textDescription new description"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"modifyClient\"," "\"username\":\"user1\"," "\"textDescription\":\"new description\"" "}]}"; expect_request_response_success(&mosq, request, "modifyClient"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ModifyGroupTextName) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("modifyGroup group1 textName new name"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"modifyGroup\"," "\"groupname\":\"group1\"," "\"textName\":\"new name\"" "}]}"; expect_request_response_success(&mosq, request, "modifyGroup"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ModifyGroupTextDescription) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("modifyGroup group1 textDescription new description"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"modifyGroup\"," "\"groupname\":\"group1\"," "\"textDescription\":\"new description\"" "}]}"; expect_request_response_success(&mosq, request, "modifyGroup"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ModifyRoleTextName) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("modifyRole role1 textName new name"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"modifyRole\"," "\"rolename\":\"role1\"," "\"textName\":\"new name\"" "}]}"; expect_request_response_success(&mosq, request, "modifyRole"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ModifyRoleTextDescription) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("modifyRole role1 textDescription new description"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"modifyRole\"," "\"rolename\":\"role1\"," "\"textDescription\":\"new description\"" "}]}"; expect_request_response_success(&mosq, request, "modifyRole"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ModifyRoleWildcardSubs) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("modifyRole role1 allowWildcardSubs true"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char request[] = "{\"commands\":[{" "\"command\":\"modifyRole\"," "\"rolename\":\"role1\"," "\"allowWildcardSubs\":true" "}]}"; expect_request_response_success(&mosq, request, "modifyRole"); const char *outputs[] = { "OK\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ModifyRoleAllowWildcardSubsBadValue) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("modifyRole role1 allowWildcardSubs bad"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "modifyRole rolename \n", "Invalid value 'bad'\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ModifyRoleBadProp) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("modifyRole role1 badprop new description"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "modifyRole rolename \n", "Unknown property 'badprop'\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ModifyRoleNoProp) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("modifyRole role1"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_single_lists(&mosq); const char *outputs[] = { "modifyRole rolename \n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ListClients) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("listClients"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listClients\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listClients\",\"data\":{" "\"clients\":[\"client1\",\"client2\"]" "}}]}"); return 0; })) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listClients\",\"data\":{" "\"clients\":[\"client1\",\"client2\"]" "}}]}"); return 0; })); const char *outputs[] = { "client1\n", "client2\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ListClientsWithCount) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("listClients 2"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listClients\",\"count\":2}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listClients\",\"data\":{" "\"clients\":[\"client1\",\"client2\"]" "}}]}"); return 0; })); const char *outputs[] = { "client1\n", "client2\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ListClientsWithCountAndOffset) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("listClients 2 3"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listClients\",\"count\":2,\"offset\":3}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listClients\",\"data\":{" "\"clients\":[\"client1\",\"client2\"]" "}}]}"); return 0; })); const char *outputs[] = { "client1\n", "client2\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ListGroups) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("listGroups"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listGroups\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listGroups\",\"data\":{" "\"groups\":[\"group1\",\"group2\"]" "}}]}"); return 0; })) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listGroups\",\"data\":{" "\"groups\":[\"group1\",\"group2\"]" "}}]}"); return 0; })); const char *outputs[] = { "group1\n", "group2\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ListGroupsWithCount) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("listGroups 2"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listGroups\",\"count\":2}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listGroups\",\"data\":{" "\"groups\":[\"group1\",\"group2\"]" "}}]}"); return 0; })); const char *outputs[] = { "group1\n", "group2\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ListGroupsWithCountAndOffset) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("listGroups 2 3"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listGroups\",\"count\":2,\"offset\":3}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listGroups\",\"data\":{" "\"groups\":[\"group1\",\"group2\"]" "}}]}"); return 0; })); const char *outputs[] = { "group1\n", "group2\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ListRoles) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("listRoles"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listGroups"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listRoles\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listRoles\",\"data\":{" "\"roles\":[\"role1\",\"role2\"]" "}}]}"); return 0; })) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listRoles\",\"data\":{" "\"roles\":[\"role1\",\"role2\"]" "}}]}"); return 0; })); const char *outputs[] = { "role1\n", "role2\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ListRolesWithCount) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("listRoles 2"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listRoles\",\"count\":2}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listRoles\",\"data\":{" "\"roles\":[\"role1\",\"role2\"]" "}}]}"); return 0; })); const char *outputs[] = { "role1\n", "role2\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, ListRolesWithCountAndOffset) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("listRoles 2 3"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listRoles\",\"count\":2,\"offset\":3}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"listRoles\",\"data\":{" "\"roles\":[\"role1\",\"role2\"]" "}}]}"); return 0; })); const char *outputs[] = { "role1\n", "role2\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } TEST_F(CtrlShellDynsecTest, GetDetails) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_dynsec(host, port); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("getDetails"))) .WillOnce(t::Return(strdup("exit"))); expect_connect_and_messages(&mosq); expect_request_response_empty(&mosq, "listClients"); expect_request_response_empty(&mosq, "listGroups"); expect_request_response_empty(&mosq, "listRoles"); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"getDetails\"}]}"), 1, false)) .WillOnce(t::Invoke([this](){ append_response("{\"responses\":[{\"command\":\"getDetails\",\"data\":{" "\"clientCount\":1," "\"groupCount\":2," "\"roleCount\":3," "\"changeIndex\":4" "}}]}"); return 0; })); const char *outputs[] = { "Client count:", "Group count:", "Role count:", "Change index:", " 1\n", " 2\n", " 3\n", " 4\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); EXPECT_EQ(pending_payloads, nullptr); } ================================================ FILE: test/apps/ctrl/ctrl_shell_help_test.cpp ================================================ /* Copyright (c) 2022 Cedalo GmbH */ // clang-format off #include "mosquitto_internal.h" // keep this at the top for `#define uthash_free` #include "ctrl_shell.h" #include "ctrl_shell_internal.h" #include "json_help.h" // clang-format on #include #include #include #include "ctrl_shell_mock.hpp" #include "editline_mock.hpp" #include "libmosquitto_mock.hpp" #include "pthread_mock.hpp" namespace t = testing; class CtrlShellHelpTest : public ::t::Test { public: ::t::StrictMock ctrl_shell_mock_{}; ::t::StrictMock editline_mock_{}; ::t::StrictMock libmosquitto_mock_{}; ::t::StrictMock pthread_mock_{}; LIBMOSQ_CB_connect on_connect{}; LIBMOSQ_CB_message on_message{}; void expect_setup(struct mosq_config *config) { editline_mock_.reset(); EXPECT_CALL(editline_mock_, rl_bind_key(t::Eq('\t'), t::_)); EXPECT_CALL(editline_mock_, add_history(t::_)).WillRepeatedly(t::Return(0)); EXPECT_CALL(editline_mock_, clear_history()).Times(t::AnyNumber()); config->no_colour = true; EXPECT_CALL(ctrl_shell_mock_, ctrl_shell__output(t::StartsWith("mosquitto_ctrl shell v"))); } void expect_connect(struct mosquitto *mosq, const char *host, int port) { EXPECT_CALL(libmosquitto_mock_, mosquitto_new(t::Eq(nullptr), t::Eq(true), t::Eq(nullptr))) .WillOnce(t::Return(mosq)); EXPECT_CALL(libmosquitto_mock_, mosquitto_int_option(t::Eq(mosq), MOSQ_OPT_PROTOCOL_VERSION, 5)); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe_callback_set(t::Eq(mosq), t::_)); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish_v5_callback_set(t::Eq(mosq), t::_)); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect(t::Eq(mosq), t::StrEq(host), port, 60)); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_start(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect_callback_set(t::Eq(mosq), t::A())) .WillRepeatedly(t::SaveArg<1>(&this->on_connect)); EXPECT_CALL(libmosquitto_mock_, mosquitto_message_callback_set(t::Eq(mosq), t::A())) .WillOnce(t::SaveArg<1>(&this->on_message)); } void expect_disconnect(struct mosquitto *mosq) { EXPECT_CALL(libmosquitto_mock_, mosquitto_disconnect(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_stop(t::Eq(mosq), false)); EXPECT_CALL(libmosquitto_mock_, mosquitto_destroy(t::Eq(mosq))); } void expect_outputs(const char **outputs, size_t count) { for(size_t i=0; i "))) .WillOnce(t::Return(strdup("help"))) .WillOnce(t::Return(strdup("help auth"))) .WillOnce(t::Return(strdup("help connect"))) .WillOnce(t::Return(strdup("help exit"))) .WillOnce(t::Return(strdup("help help"))) .WillOnce(t::Return(strdup("help unknown"))) .WillOnce(t::Return(strdup("unknown"))) .WillOnce(t::Return(nullptr)); const char *outputs[] = { "This is the mosquitto_ctrl interactive shell, for controlling aspects of a mosquitto broker.\n", "Find help on a command using 'help '\n", "Press tab multiple times to find currently available commands.\n\n", "\n", "Example workflow:\n\n", "> auth\n", "username: admin\n", "password:\n", "> connect mqtt://localhost\n", "mqtt://localhost:1883> dynsec\n", "mqtt://localhost:1883|dynsec> createGroup newgroup\n", "OK\n\n", "auth [username]\n", "\nSet a username and password prior to connecting to a broker.\n", /* help auth */ "connect\n", "connect mqtt://hostname[:port]\n", "connect mqtts://hostname[:port]\n", "connect ws://hostname[:port]\n", "connect wss://hostname[:port]\n", "\nConnect to a broker using the provided transport and port.\n", "If no URL is provided, connects to mqtt://localhost:1883\n", /* help connect */ "exit\n", "\nQuit the program\n", /* help exit */ "help \n", "\nFind help on a command using 'help '\n", "Press tab multiple times to find currently available commands.\n", /* help help */ "Unknown command 'unknown'\n", /* help unknown */ }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellHelpTest, Exit) { mosq_config config{}; expect_setup(&config); char *s = strdup("exit"); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s)); EXPECT_CALL(ctrl_shell_mock_, ctrl_shell__output(t::StrEq("\n"))); ctrl_shell__main(&config); } TEST_F(CtrlShellHelpTest, Connect) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; char buf[200]; expect_setup(&config); expect_connect(&mosq, host, port); snprintf(buf, sizeof(buf), "connect mqtt://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(nullptr)); /* This is a hacky way of working around the async mqtt CONNECT/CONNACK which we don't directly control. */ EXPECT_CALL(pthread_mock_, pthread_cond_timedwait(t::_, t::_, t::_)) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ this->on_connect(&mosq, nullptr, 0); data.response_received = true; return 0; })); EXPECT_CALL(ctrl_shell_mock_, ctrl_shell__output(t::StrEq("\n"))); ctrl_shell__main(&config); } TEST_F(CtrlShellHelpTest, PostConnectHelp) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; char buf[200]; expect_setup(&config); expect_connect(&mosq, host, port); snprintf(buf, sizeof(buf), "connect mqtt://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)) .WillOnce(t::Return(strdup("exit"))); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("help"))) .WillOnce(t::Return(strdup("help dynsec"))) .WillOnce(t::Return(strdup("help broker"))) .WillOnce(t::Return(strdup("help disconnect"))) .WillOnce(t::Return(strdup("help exit"))) .WillOnce(t::Return(strdup("help help"))) .WillOnce(t::Return(strdup("help unknown"))) .WillOnce(t::Return(strdup("unknown"))) .WillOnce(t::Return(strdup("disconnect"))); /* This is a hacky way of working around the async mqtt send/receive which we don't directly control. * Each send starts a wait which times out after two seconds. We use that call to produce the effect we want. */ EXPECT_CALL(pthread_mock_, pthread_cond_timedwait(t::_, t::_, t::_)) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ this->on_connect(&mosq, nullptr, 0); data.response_received = true; return 0; })); const char *outputs[] = { "This is the mosquitto_ctrl interactive shell, for controlling aspects of a mosquitto broker.\n", "Find help on a command using 'help '\n", "Press tab multiple times to find currently available commands.\n\n", "Example workflow:\n\n", "> auth\n", "username: admin\n", "password:\n", "> connect mqtt://localhost\n", "mqtt://localhost:1883> dynsec\n", "mqtt://localhost:1883|dynsec> createGroup newgroup\n", "OK\n\n", "\n", "dynsec\n", "\nStart the dynamic-security control mode.\n", /* help dynsec */ "broker\n", "\nStart the broker control mode.\n", /* help broker */ "disconnect\n", "\nDisconnect from the broker\n", /* help disconnect */ "exit\n", "\nQuit the program\n", /* help exit */ "help \n", "\nFind help on a command using 'help '\n", "Press tab multiple times to find currently available commands.\n", /* help help */ "Unknown command 'unknown'\n", /* help unknown */ }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); expect_disconnect(&mosq); ctrl_shell__main(&config); } TEST_F(CtrlShellHelpTest, BrokerHelp) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; char buf[200]; expect_setup(&config); expect_connect(&mosq, host, port); snprintf(buf, sizeof(buf), "connect mqtt://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)) .WillOnce(t::Return(strdup("exit"))); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("broker"))) .WillOnce(t::Return(strdup("disconnect"))); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|broker> "))) .WillOnce(t::Return(strdup("help "))) // Extra space on end to invoke trim .WillOnce(t::Return(strdup("help listPlugins"))) .WillOnce(t::Return(strdup("help listListeners"))) .WillOnce(t::Return(strdup("help disconnect"))) .WillOnce(t::Return(strdup("help help"))) .WillOnce(t::Return(strdup("help return"))) .WillOnce(t::Return(strdup("help exit"))) .WillOnce(t::Return(strdup("help unknown"))) .WillOnce(t::Return(strdup("unknown"))) .WillOnce(t::Return(strdup("return"))); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe(t::_, nullptr, t::StrEq("$CONTROL/broker/v1/response"), 1)) .WillOnce(t::Return(0)); /* This is a hacky way of working around the async mqtt send/receive which we don't directly control. * Each send starts a wait which times out after two seconds. We use that call to produce the effect we want. */ EXPECT_CALL(pthread_mock_, pthread_cond_timedwait(t::_, t::_, t::_)) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ this->on_connect(&mosq, nullptr, 0); data.response_received = true; return 0; })) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; this->on_message(&mosq, nullptr, &msg); data.response_received = true; return 0; })); const char *outputs[] = { "This is the mosquitto_ctrl interactive shell, for controlling aspects of a mosquitto broker.\n", "You are in broker mode, for controlling some core broker functionality.\n", "Use 'return' to leave this mode.\n", "Find help on a command using 'help '\n", "Press tab multiple times to find currently available commands.\n\n", "\n", "Unknown command 'unknown'\n", "listPlugins\n", "\nLists currently loaded plugins.\n", "listListeners\n", "\nLists current listeners.\n", "disconnect\n", "\nDisconnect from the broker\n", /* help disconnect */ "return\n", "\nLeave broker mode.\n", "exit\n", "\nQuit the program\n", /* help exit */ "help \n", "\nFind help on a command using 'help '\n", "Press tab multiple times to find currently available commands.\n", /* help help */ "Invalid response from broker.\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); expect_disconnect(&mosq); ctrl_shell__main(&config); } TEST_F(CtrlShellHelpTest, DynsecHelp) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; char buf[200]; expect_setup(&config); expect_connect(&mosq, host, port); snprintf(buf, sizeof(buf), "connect mqtt://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("dynsec"))) .WillOnce(t::Return(nullptr)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883|dynsec> "))) .WillOnce(t::Return(strdup("help"))) .WillOnce(t::Return(strdup("help addClientRole"))) .WillOnce(t::Return(strdup("help addGroupClient"))) .WillOnce(t::Return(strdup("help addGroupRole"))) .WillOnce(t::Return(strdup("help addRoleACL"))) .WillOnce(t::Return(strdup("help createClient"))) .WillOnce(t::Return(strdup("help createGroup"))) .WillOnce(t::Return(strdup("help createRole"))) .WillOnce(t::Return(strdup("help deleteClient"))) .WillOnce(t::Return(strdup("help deleteGroup"))) .WillOnce(t::Return(strdup("help deleteRole"))) .WillOnce(t::Return(strdup("help disableClient"))) .WillOnce(t::Return(strdup("help enableClient"))) .WillOnce(t::Return(strdup("help getAnonymousGroup"))) .WillOnce(t::Return(strdup("help getClient"))) .WillOnce(t::Return(strdup("help getDetails"))) .WillOnce(t::Return(strdup("help getDefaultACLAccess"))) .WillOnce(t::Return(strdup("help getGroup"))) .WillOnce(t::Return(strdup("help getRole"))) .WillOnce(t::Return(strdup("help listClients"))) .WillOnce(t::Return(strdup("help listGroups"))) .WillOnce(t::Return(strdup("help listRoles"))) .WillOnce(t::Return(strdup("help removeClientRole"))) .WillOnce(t::Return(strdup("help removeGroupClient"))) .WillOnce(t::Return(strdup("help removeGroupRole"))) .WillOnce(t::Return(strdup("help removeRoleACL"))) .WillOnce(t::Return(strdup("help setAnonymousGroup"))) .WillOnce(t::Return(strdup("help setClientId"))) .WillOnce(t::Return(strdup("help setClientPassword"))) .WillOnce(t::Return(strdup("help setDefaultACLAccess"))) .WillOnce(t::Return(strdup("help modifyClient"))) .WillOnce(t::Return(strdup("help modifyGroup"))) .WillOnce(t::Return(strdup("help modifyRole"))) .WillOnce(t::Return(strdup("help disconnect"))) .WillOnce(t::Return(strdup("help help"))) .WillOnce(t::Return(strdup("help return"))) .WillOnce(t::Return(strdup("help exit"))) .WillOnce(t::Return(strdup("help unknown"))) .WillOnce(t::Return(strdup("unknown"))) .WillOnce(t::Return(strdup("return"))); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe(t::_, nullptr, t::StrEq("$CONTROL/dynamic-security/v1/response"), 1)) .WillOnce(t::Return(0)); /* This is a hacky way of working around the async mqtt send/receive which we don't directly control. * Each send starts a wait which times out after two seconds. We use that call to produce the effect we want. */ EXPECT_CALL(pthread_mock_, pthread_cond_timedwait(t::_, t::_, t::_)) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ this->on_connect(&mosq, nullptr, 0); data.response_received = true; return 0; })) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; this->on_message(&mosq, nullptr, &msg); data.response_received = true; return 0; })) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; this->on_message(&mosq, nullptr, &msg); data.response_received = true; return 0; })) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; this->on_message(&mosq, nullptr, &msg); data.response_received = true; return 0; })) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; this->on_message(&mosq, nullptr, &msg); data.response_received = true; return 0; })) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; this->on_message(&mosq, nullptr, &msg); data.response_received = true; return 0; })) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; this->on_message(&mosq, nullptr, &msg); data.response_received = true; return 0; })) .WillOnce(t::Invoke([this, &mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; this->on_message(&mosq, nullptr, &msg); data.response_received = true; return 0; })); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listClients\"}]}"), 1, false)) .WillOnce(t::Return(0)); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listGroups\"}]}"), 1, false)) .WillOnce(t::Return(0)); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(&mosq), nullptr, t::StrEq("$CONTROL/dynamic-security/v1"), t::_, t::StrEq("{\"commands\":[{\"command\":\"listRoles\"}]}"), 1, false)) .WillOnce(t::Return(0)); const char *outputs[] = { "This is the mosquitto_ctrl interactive shell, for controlling aspects of a mosquitto broker.\n", "You are in dynsec mode, for controlling the dynamic-security clients, groups, and roles used in authentication and authorisation.\n", "Use 'return' to leave dynsec mode.\n", "Find help on a command using 'help '\n", "Press tab multiple times to find currently available commands.\n\n", "\n", "Unknown command 'unknown'\n", "addClientRole \n", "\nAdds a role directly to a client.\n", "addGroupClient \n", "\nAdds a client to a group.\n", "addGroupRole \n", "\nAdds a role to a group.\n", "addRoleACL publishClientReceive allow|deny [priority] \n", "addRoleACL publishClientSend allow|deny [priority] \n", "addRoleACL subscribeLiteral allow|deny [priority] \n", "addRoleACL subscribePattern allow|deny [priority] \n", "addRoleACL unsubscribeLiteral allow|deny [priority] \n", "addRoleACL unsubscribePattern allow|deny [priority] \n", "\nAdds an ACL to a role, with an optional priority.\n", "\nACLs of a specific type within a role are processed in order from highest to lowest priority with the first matching ACL applying.\n", "createClient [password [clientid]]\n", "\nCreate a client with password and optional client id.\n", "createGroup \n", "\nCreate a new group.\n", "createRole \n", "\nCreate a new role.\n", "deleteClient \n", "\nDelete a client\n", "deleteGroup \n", "\nDelete a group\n", "deleteRole \n", "\nDelete a role\n", "disableClient \n", "\nDisable a client. This client will not be able to log in, and will be kicked if it has an existing session.\n", "enableClient \n", "\nEnable a client. Disabled clients are unable to log in.\n", "getAnonymousGroup\n", "\nPrint the group configured as the anonymous group.\n", "getClient \n", "\nPrint details of a client and its groups and direct roles.\n", "getDefaultACLAccess\n", "\nPrint the default allow/deny values for the different classes of ACL.\n", "getDetails\n", "\nPrint details including the client, group, and role count, and the current change index.\n", "getGroup \n", "\nPrint details of a group and its roles.\n", "getRole \n", "\nPrint details of a role and its ACLs.\n", "listClients [count [offset]]\n", "\nPrint a list of clients configured in the dynsec plugin, with an optional total count and list offset.\n", "listGroups [count [offset]]\n", "\nPrint a list of groups configured in the dynsec plugin, with an optional total count and list offset.\n", "listRoles [count [offset]]\n", "\nPrint a list of roles configured in the dynsec plugin, with an optional total count and list offset.\n", "removeClientRole \n", "\nRemoves a role from a client, where the role was directly attached to the client.\n", "removeGroupClient \n", "\nRemoves a client from a group.\n", "removeGroupRole \n", "\nRemoves a role from a group.\n", "removeRoleACL publishClientReceive \n", "removeRoleACL publishClientSend \n", "removeRoleACL subscribeLiteral \n", "removeRoleACL subscribePattern \n", "removeRoleACL unsubscribeLiteral \n", "removeRoleACL unsubscribePattern \n", "\nRemoves an ACL from a role.\n", "setAnonymousGroup \n", "\nSets the anonymous group to a new group.\n", "setClientId \n", "setClientId \n", "\nSets or clears the clientid associated with a client. If a client has a clientid, all three of username, password, and clientid must match for a client to be able to authenticate.\n", "setClientPassword [password]\n", "\nSets a new password for a client.\n", "setDefaultACLAccess publishClientReceive allow|deny\n", "setDefaultACLAccess publishClientSend allow|deny\n", "setDefaultACLAccess subscribe allow|deny\n", "setDefaultACLAccess unsubscribe allow|deny\n", "\nSets the default ACL access to use for an ACL type. The default access will be applied if no other ACL rules match.\n", "Setting a rule to 'allow' means that if no ACLs match, it will be accepted.\n", "Setting a rule to 'deny' means that if no ACLs match, it will be denied.\n", "modifyClient textName \n", "modifyClient textDescription \n", "\nModify the text name or text description for a client.\n", "These are free-text fields for your own use.\n", "modifyGroup textName \n", "modifyGroup textDescription \n", "\nModify the text name or text description for a group.\n", "modifyRole textName \n", "modifyRole textDescription \n", "modifyRole allowWildcardSubs true|false\n", "\nModify the text name or text description for a role.\n", "disconnect\n", "\nDisconnect from the broker\n", /* help disconnect */ "return\n", "\nLeave dynsec mode.\n", "exit\n", "\nQuit the program\n", /* help exit */ "help \n", "\nFind help on a command using 'help '\n", "Press tab multiple times to find currently available commands.\n", /* help help */ "Invalid response from broker.\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } ================================================ FILE: test/apps/ctrl/ctrl_shell_options_test.cpp ================================================ /* Copyright (c) 2022 Cedalo GmbH */ // clang-format off #include "mosquitto_internal.h" // keep this at the top for `#define uthash_free` #include "ctrl_shell.h" #include "ctrl_shell_internal.h" #include "json_help.h" #include "utlist.h" // clang-format on #include #include #include #include "ctrl_shell_mock.hpp" #include "editline_mock.hpp" #include "libmosquitto_mock.hpp" #include "pthread_mock.hpp" namespace t = testing; struct pending_payload { struct pending_payload *next, *prev; char payload[1024]; }; class CtrlShellOptionsTest : public ::t::Test { public: ::t::StrictMock ctrl_shell_mock_{}; ::t::StrictMock editline_mock_{}; ::t::StrictMock libmosquitto_mock_{}; ::t::StrictMock pthread_mock_{}; LIBMOSQ_CB_connect on_connect{}; LIBMOSQ_CB_message on_message{}; struct pending_payload *pending_payloads = nullptr; void expect_setup(struct mosq_config *config) { editline_mock_.reset(); EXPECT_CALL(editline_mock_, rl_bind_key(t::Eq('\t'), t::_)); EXPECT_CALL(editline_mock_, add_history(t::_)).WillRepeatedly(t::Return(0)); EXPECT_CALL(editline_mock_, clear_history()).Times(t::AnyNumber()); config->no_colour = true; config->port = PORT_UNDEFINED; EXPECT_CALL(ctrl_shell_mock_, ctrl_shell__output(t::StartsWith("mosquitto_ctrl shell v"))); } void expect_connect(struct mosquitto *mosq, const char *host, int port) { EXPECT_CALL(libmosquitto_mock_, mosquitto_new(t::Eq(nullptr), t::Eq(true), t::Eq(nullptr))) .WillOnce(t::Return(mosq)); EXPECT_CALL(libmosquitto_mock_, mosquitto_int_option(t::Eq(mosq), MOSQ_OPT_PROTOCOL_VERSION, 5)); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe_callback_set(t::Eq(mosq), t::_)); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish_v5_callback_set(t::Eq(mosq), t::_)); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect(t::Eq(mosq), t::StrEq(host), port, 60)); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_start(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect_callback_set(t::Eq(mosq), t::A())) .WillRepeatedly(t::SaveArg<1>(&this->on_connect)); EXPECT_CALL(libmosquitto_mock_, mosquitto_message_callback_set(t::Eq(mosq), t::A())) .WillOnce(t::SaveArg<1>(&this->on_message)); } void expect_disconnect(struct mosquitto *mosq) { EXPECT_CALL(libmosquitto_mock_, mosquitto_disconnect(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_stop(t::Eq(mosq), false)); EXPECT_CALL(libmosquitto_mock_, mosquitto_destroy(t::Eq(mosq))); } void expect_outputs(const char **outputs, size_t count) { for(size_t i=0; ipayload, sizeof(pp->payload), "%s", respons); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(mosq), nullptr, t::StrEq("$CONTROL/broker/v1"), t::_, t::StrEq(request), 1, false)) .WillOnce(t::Invoke([this, pp](){ DL_APPEND(this->pending_payloads, pp); return 0; })); } void expect_request_response_success(struct mosquitto *mosq, const char *request, const char *command) { char response[100]; snprintf(response, sizeof(response), "{\"responses\":[{\"command\":\"%s\"}]}", command); expect_request_response(mosq, request, response); } void expect_request_response_empty(struct mosquitto *mosq, const char *command) { char request[100]; char response[100]; snprintf(request, sizeof(request), "{\"commands\":[{\"command\":\"%s\"}]}", command); snprintf(response, sizeof(response), "{\"responses\":[{\"command\":\"%s\",\"data\":{}}]}", command); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(mosq), nullptr, t::StrEq("$CONTROL/broker/v1"), t::_, t::StrEq(request), 1, false)) .WillOnce(t::Invoke([this, &command](){ append_empty_response(command); return 0; })); } void append_response(const char *response) { struct pending_payload *pp = (struct pending_payload *)calloc(1, sizeof(struct pending_payload)); snprintf(pp->payload, sizeof(pp->payload), "%s", response); DL_APPEND(this->pending_payloads, pp); } void append_empty_response(const char *command) { struct pending_payload *pp = (struct pending_payload *)calloc(1, sizeof(struct pending_payload)); snprintf(pp->payload, sizeof(pp->payload), "{\"responses\":[{\"command\":\"%s\",\"data\":{}}]}", command); DL_APPEND(this->pending_payloads, pp); } void expect_broker(const char *host, int port) { char buf[200]; snprintf(buf, sizeof(buf), "connect mqtt://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("broker"))); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe(t::_, nullptr, t::StrEq("$CONTROL/broker/v1/response"), 1)) .WillOnce(t::Return(0)); } void expect_connect_and_messages(struct mosquitto *mosq) { /* This is a hacky way of working around the async mqtt send/receive which we don't directly control. * Each send starts a wait which times out after two seconds. We use that call to produce the effect we want. */ EXPECT_CALL(pthread_mock_, pthread_cond_timedwait(t::_, t::_, t::_)) .WillOnce(t::Invoke([this, mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ this->on_connect(mosq, nullptr, 0); data.response_received = true; return 0; })) .WillRepeatedly(t::Invoke([this, mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; struct pending_payload *pp = pending_payloads; if(pp){ DL_DELETE(pending_payloads, pp); msg.payload = pp->payload; msg.payloadlen = (int)strlen((char *)msg.payload); this->on_message(mosq, nullptr, &msg); free(pp); } data.response_received = true; return 0; })); } }; TEST_F(CtrlShellOptionsTest, Empty) { mosq_config config{}; expect_setup(&config); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(strdup(""))) .WillOnce(t::Return(strdup("exit"))); const char *outputs[] = { "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellOptionsTest, ConnectUrlMissingHost) { mosq_config config{}; expect_setup(&config); char buf[200]; snprintf(buf, sizeof(buf), "connect mqtt://"); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)) .WillOnce(t::Return(strdup("exit"))); const char *outputs[] = { "connect mqtt[s]://:port\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellOptionsTest, ConnectTLS) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 8883; expect_setup(&config); expect_connect(&mosq, host, port); expect_connect_and_messages(&mosq); char buf[200]; snprintf(buf, sizeof(buf), "connect mqtts://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(libmosquitto_mock_, mosquitto_int_option(t::_, MOSQ_OPT_TLS_USE_OS_CERTS, 1)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtts://localhost:8883> "))) .WillOnce(t::Return(strdup("exit"))); const char *outputs[] = { "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellOptionsTest, ConnectWebsockets) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 8080; expect_setup(&config); expect_connect(&mosq, host, port); expect_connect_and_messages(&mosq); char buf[200]; snprintf(buf, sizeof(buf), "connect ws://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(libmosquitto_mock_, mosquitto_int_option(t::_, MOSQ_OPT_TRANSPORT, MOSQ_T_WEBSOCKETS)); EXPECT_CALL(editline_mock_, readline(t::StrEq("ws://localhost:8080> "))) .WillOnce(t::Return(strdup("exit"))); const char *outputs[] = { "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellOptionsTest, ConnectWebsocketsTLS) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 8081; expect_setup(&config); expect_connect(&mosq, host, port); expect_connect_and_messages(&mosq); char buf[200]; snprintf(buf, sizeof(buf), "connect wss://%s:%d", host, port); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(libmosquitto_mock_, mosquitto_int_option(t::_, MOSQ_OPT_TLS_USE_OS_CERTS, 1)); EXPECT_CALL(libmosquitto_mock_, mosquitto_int_option(t::_, MOSQ_OPT_TRANSPORT, MOSQ_T_WEBSOCKETS)); EXPECT_CALL(editline_mock_, readline(t::StrEq("wss://localhost:8081> "))) .WillOnce(t::Return(strdup("exit"))); const char *outputs[] = { "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellOptionsTest, ConnectImplicitHostname) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_connect_and_messages(&mosq); char buf[200]; snprintf(buf, sizeof(buf), "connect"); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("exit"))); const char *outputs[] = { "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellOptionsTest, ConnectImplicitPort) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_connect_and_messages(&mosq); char buf[200]; snprintf(buf, sizeof(buf), "connect %s", host); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("exit"))); const char *outputs[] = { "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellOptionsTest, ConnectCertNotFound) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_connect_and_messages(&mosq); config.cafile = strdup("missing cafile"); config.capath = strdup("missing capath"); config.certfile = strdup("missing certfile"); config.keyfile = strdup("missing keyfile"); char buf[200]; snprintf(buf, sizeof(buf), "connect %s", host); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("exit"))); EXPECT_CALL(libmosquitto_mock_, mosquitto_tls_set( t::_, t::StrEq("missing cafile"), t::StrEq("missing capath"), t::StrEq("missing certfile"), t::StrEq("missing keyfile"), nullptr)) .WillOnce(t::Return(MOSQ_ERR_INVAL)); const char *outputs[] = { "Error setting TLS options: File not found.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); free(config.cafile); free(config.capath); free(config.certfile); free(config.keyfile); } TEST_F(CtrlShellOptionsTest, ConnectCertError) { mosq_config config{}; mosquitto mosq{}; const char host[] = "localhost"; int port = 1883; expect_setup(&config); expect_connect(&mosq, host, port); expect_connect_and_messages(&mosq); config.cafile = strdup("cafile"); config.capath = strdup("capath"); config.certfile = strdup("certfile"); config.keyfile = strdup("keyfile"); char buf[200]; snprintf(buf, sizeof(buf), "connect %s", host); char *s_conn = strdup(buf); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(s_conn)); EXPECT_CALL(editline_mock_, readline(t::StrEq("mqtt://localhost:1883> "))) .WillOnce(t::Return(strdup("exit"))); EXPECT_CALL(libmosquitto_mock_, mosquitto_tls_set( t::_, t::StrEq("cafile"), t::StrEq("capath"), t::StrEq("certfile"), t::StrEq("keyfile"), nullptr)) .WillOnce(t::Return(MOSQ_ERR_TLS)); const char *outputs[] = { "Error setting TLS options: A TLS error occurred.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); free(config.cafile); free(config.capath); free(config.certfile); free(config.keyfile); } ================================================ FILE: test/apps/ctrl/ctrl_shell_pre_connect_test.cpp ================================================ /* Copyright (c) 2022 Cedalo GmbH */ // clang-format off #include "mosquitto_internal.h" // keep this at the top for `#define uthash_free` #include "ctrl_shell.h" #include "ctrl_shell_internal.h" #include "json_help.h" // clang-format on #include #include #include #include "ctrl_shell_mock.hpp" #include "editline_mock.hpp" #include "libmosquitto_mock.hpp" #include "pthread_mock.hpp" namespace t = testing; class CtrlShellPreConnectTest : public ::t::Test { public: ::t::StrictMock ctrl_shell_mock_{}; ::t::StrictMock editline_mock_{}; ::t::StrictMock libmosquitto_mock_{}; ::t::StrictMock pthread_mock_{}; LIBMOSQ_CB_connect on_connect{}; LIBMOSQ_CB_message on_message{}; void expect_setup(struct mosq_config *config) { editline_mock_.reset(); EXPECT_CALL(editline_mock_, rl_bind_key(t::Eq('\t'), t::_)); EXPECT_CALL(editline_mock_, add_history(t::_)).WillRepeatedly(t::Return(0)); EXPECT_CALL(editline_mock_, clear_history()).Times(t::AnyNumber()); config->no_colour = true; EXPECT_CALL(ctrl_shell_mock_, ctrl_shell__output(t::StartsWith("mosquitto_ctrl shell v"))); } void expect_connect(struct mosquitto *mosq, const char *host, int port) { EXPECT_CALL(libmosquitto_mock_, mosquitto_new(t::Eq(nullptr), t::Eq(true), t::Eq(nullptr))) .WillOnce(t::Return(mosq)); EXPECT_CALL(libmosquitto_mock_, mosquitto_int_option(t::Eq(mosq), MOSQ_OPT_PROTOCOL_VERSION, 5)); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe_callback_set(t::Eq(mosq), t::_)); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish_v5_callback_set(t::Eq(mosq), t::_)); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect(t::Eq(mosq), t::StrEq(host), port, 60)); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_start(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect_callback_set(t::Eq(mosq), t::A())) .WillRepeatedly(t::SaveArg<1>(&this->on_connect)); EXPECT_CALL(libmosquitto_mock_, mosquitto_message_callback_set(t::Eq(mosq), t::A())) .WillOnce(t::SaveArg<1>(&this->on_message)); } void expect_disconnect(struct mosquitto *mosq) { EXPECT_CALL(libmosquitto_mock_, mosquitto_disconnect(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_stop(t::Eq(mosq), false)); EXPECT_CALL(libmosquitto_mock_, mosquitto_destroy(t::Eq(mosq))); } void expect_outputs(const char **outputs, size_t count) { for(size_t i=0; ion_connect(mosq, nullptr, 0); data.response_received = true; return 0; })) .WillRepeatedly(t::Invoke([this, mosq](pthread_cond_t *, pthread_mutex_t *, const struct timespec *){ mosquitto_message msg{}; this->on_message(mosq, nullptr, &msg); data.response_received = true; return 0; })); } }; TEST_F(CtrlShellPreConnectTest, AuthNoUsername) { mosq_config config{}; expect_setup(&config); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(strdup("auth"))) .WillOnce(t::Return(strdup("exit"))); EXPECT_CALL(editline_mock_, readline(t::StrEq("username: "))) .WillOnce(t::Return(strdup("username1"))); EXPECT_CALL(ctrl_shell_mock_, ctrl_shell_fgets(t::_, t::_, t::_)) .WillOnce(t::Invoke([](char *s, int size, FILE *){ snprintf(s, (size_t)size, "password1"); return s; })); const char *outputs[] = { "password:", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellPreConnectTest, AuthWithUsername) { mosq_config config{}; expect_setup(&config); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(strdup("auth username1"))) .WillOnce(t::Return(strdup("exit"))); EXPECT_CALL(ctrl_shell_mock_, ctrl_shell_fgets(t::_, t::_, t::_)) .WillOnce(t::Invoke([](char *s, int size, FILE *){ snprintf(s, (size_t)size, "password1"); return s; })); const char *outputs[] = { "password:", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } TEST_F(CtrlShellPreConnectTest, AuthNoPassword) { mosq_config config{}; expect_setup(&config); EXPECT_CALL(editline_mock_, readline(t::StrEq("> "))) .WillOnce(t::Return(strdup("auth username1"))) .WillOnce(t::Return(strdup("exit"))); EXPECT_CALL(ctrl_shell_mock_, ctrl_shell_fgets(t::_, t::_, t::_)) .WillOnce(t::Return(nullptr)); const char *outputs[] = { "password:", "No password.\n", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(&config); } ================================================ FILE: test/apps/ctrl/ctrl_shell_test.cpp ================================================ /* Copyright (c) 2022 Cedalo GmbH */ // clang-format off #include "mosquitto_internal.h" // keep this at the top for `#define uthash_free` #include "ctrl_shell.h" #include "ctrl_shell_internal.h" #include "json_help.h" #include "utlist.h" // clang-format on #include #include #include #include "ctrl_shell_mock.hpp" #include "editline_mock.hpp" #include "libmosquitto_mock.hpp" #include "pthread_mock.hpp" namespace t = testing; struct pending_payload { struct pending_payload *next, *prev; char payload[1024]; }; class CtrlShellTest : public ::t::Test { public: ::t::StrictMock ctrl_shell_mock_{}; ::t::StrictMock editline_mock_{}; ::t::StrictMock libmosquitto_mock_{}; ::t::StrictMock pthread_mock_{}; LIBMOSQ_CB_connect on_connect{}; LIBMOSQ_CB_message on_message{}; struct pending_payload *pending_payloads = nullptr; void expect_setup(struct mosq_config *config) { editline_mock_.reset(); EXPECT_CALL(editline_mock_, rl_bind_key(t::Eq('\t'), t::_)); EXPECT_CALL(editline_mock_, add_history(t::_)).WillRepeatedly(t::Return(0)); EXPECT_CALL(editline_mock_, clear_history()).Times(t::AnyNumber()); config->no_colour = true; EXPECT_CALL(ctrl_shell_mock_, ctrl_shell__output(t::StartsWith("mosquitto_ctrl shell v"))); } void expect_connect(struct mosquitto *mosq, const char *host, int port) { EXPECT_CALL(libmosquitto_mock_, mosquitto_new(t::Eq(nullptr), t::Eq(true), t::Eq(nullptr))) .WillOnce(t::Return(mosq)); EXPECT_CALL(libmosquitto_mock_, mosquitto_int_option(t::Eq(mosq), MOSQ_OPT_PROTOCOL_VERSION, 5)); EXPECT_CALL(libmosquitto_mock_, mosquitto_subscribe_callback_set(t::Eq(mosq), t::_)); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish_v5_callback_set(t::Eq(mosq), t::_)); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect(t::Eq(mosq), t::StrEq(host), port, 60)); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_start(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_connect_callback_set(t::Eq(mosq), t::A())) .WillRepeatedly(t::SaveArg<1>(&this->on_connect)); EXPECT_CALL(libmosquitto_mock_, mosquitto_message_callback_set(t::Eq(mosq), t::A())) .WillOnce(t::SaveArg<1>(&this->on_message)); } void expect_disconnect(struct mosquitto *mosq) { EXPECT_CALL(libmosquitto_mock_, mosquitto_disconnect(t::Eq(mosq))); EXPECT_CALL(libmosquitto_mock_, mosquitto_loop_stop(t::Eq(mosq), false)); EXPECT_CALL(libmosquitto_mock_, mosquitto_destroy(t::Eq(mosq))); } void expect_outputs(const char **outputs, size_t count) { for(size_t i=0; ipayload, sizeof(pp->payload), "%s", respons); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(mosq), nullptr, t::StrEq("$CONTROL/broker/v1"), t::_, t::StrEq(request), 1, false)) .WillOnce(t::Invoke([this, pp](){ DL_APPEND(this->pending_payloads, pp); return 0; })); } void expect_request_response_success(struct mosquitto *mosq, const char *request, const char *command) { char response[100]; snprintf(response, sizeof(response), "{\"responses\":[{\"command\":\"%s\"}]}", command); expect_request_response(mosq, request, response); } void expect_request_response_empty(struct mosquitto *mosq, const char *command) { char request[100]; char response[100]; snprintf(request, sizeof(request), "{\"commands\":[{\"command\":\"%s\"}]}", command); snprintf(response, sizeof(response), "{\"responses\":[{\"command\":\"%s\",\"data\":{}}]}", command); EXPECT_CALL(libmosquitto_mock_, mosquitto_publish(t::Eq(mosq), nullptr, t::StrEq("$CONTROL/broker/v1"), t::_, t::StrEq(request), 1, false)) .WillOnce(t::Invoke([this, &command](){ append_empty_response(command); return 0; })); } void append_response(const char *response) { struct pending_payload *pp = (struct pending_payload *)calloc(1, sizeof(struct pending_payload)); snprintf(pp->payload, sizeof(pp->payload), "%s", response); DL_APPEND(this->pending_payloads, pp); } void append_empty_response(const char *command) { struct pending_payload *pp = (struct pending_payload *)calloc(1, sizeof(struct pending_payload)); snprintf(pp->payload, sizeof(pp->payload), "{\"responses\":[{\"command\":\"%s\",\"data\":{}}]}", command); DL_APPEND(this->pending_payloads, pp); } }; #if 0 /* Hangs on CI, presumably due to blocking read() */ TEST_F(CtrlShellTest, NoConfig) { /* No config means we have colour mode enabled */ mosq_config config{}; expect_setup(&config); EXPECT_CALL(editline_mock_, readline(t::StrEq("\x1\x1B[38;5;80m\x2>\x1\x1B[0m\x2 "))) .WillOnce(t::Return(strdup("exit"))); const char *outputs[] = { "\x1B]10;?\a\x1B]11;?\a", "\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); ctrl_shell__main(nullptr); } #endif extern "C" { void set_no_colour(void); } TEST_F(CtrlShellTest, PrintLabelValue) { const char *outputs[] = { "My Label:", " 10\n", }; expect_outputs(outputs, sizeof(outputs)/sizeof(char *)); set_no_colour(); ctrl_shell_print_label_value(0, "My Label:", 10, "%u\n", 10); } ================================================ FILE: test/apps/ctrl/mosq_test_helper.py ================================================ import logging import sys from pathlib import Path logging.basicConfig( level=logging.INFO, format="%(levelname)s %(asctime)s.%(msecs)03d %(module)s: %(message)s", datefmt="%H:%M:%S", ) current_source_dir = Path(__file__).resolve().parent test_dir = current_source_dir.parents[1] if test_dir not in sys.path: sys.path.insert(0, str(test_dir)) ssl_dir = test_dir / "ssl" import mosq_test import subprocess import os ================================================ FILE: test/apps/ctrl/test.py ================================================ #!/usr/bin/env python3 import sys sys.path.insert(0, "../..") import ptest tests = [ #(ports, 'path'), (1, './ctrl-args.py'), (2, './ctrl-broker.py'), (2, './ctrl-dynsec.py'), ] if __name__ == "__main__": test = ptest.PTest() test.run_tests(tests) ================================================ FILE: test/apps/db_dump/CMakeLists.txt ================================================ file(GLOB PY_TEST_FILES db-dump-*.py) set(EXCLUDE_LIST # none ) foreach(PY_TEST_FILE ${PY_TEST_FILES}) get_filename_component(PY_TEST_NAME ${PY_TEST_FILE} NAME_WE) if(${PY_TEST_NAME} IN_LIST EXCLUDE_LIST) continue() endif() add_test(NAME apps-${PY_TEST_NAME} COMMAND ${PY_TEST_FILE} ) set_tests_properties(apps-${PY_TEST_NAME} PROPERTIES ENVIRONMENT "BUILD_ROOT=${CMAKE_BINARY_DIR}" ) endforeach() ================================================ FILE: test/apps/db_dump/Makefile ================================================ .PHONY: all check test test-compile ptest clean all : check : test test-compile: test: ./db-dump-client-stats.py ./db-dump-corrupt.py ./db-dump-json-v6-mqtt-v5-props.py ./db-dump-print-empty.py ./db-dump-print-v6-all.py ./db-dump-print-v6-mqtt-v5-props.py ./db-dump-stats.py ./db-dump-stats-current.py ptest: ./test.py clean : ================================================ FILE: test/apps/db_dump/data/bad-magic.test-db ================================================ This is a text file, not a persistence file. ================================================ FILE: test/apps/db_dump/db-dump-client-stats.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(file, counts): stdout = f"SC: {counts[0]} " + \ f"SS: {counts[1]} " + \ f"MC: {counts[2]} " + \ f"MS: {counts[3]} " + \ f" {counts[4]}\n" cmd = [ mosq_test.get_build_root()+'/apps/db_dump/mosquitto_db_dump', '--client-stats', f'{test_dir}/apps/db_dump/data/{file}' ] res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1, encoding='utf-8') if res.stdout != stdout: print(res.stdout) print(stdout) raise mosq_test.TestError do_test('v6-single-all.test-db', [1,27,1,111,'single-all']) ================================================ FILE: test/apps/db_dump/db-dump-corrupt.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(file, stderr, rc_expected): cmd = [ mosq_test.get_build_root()+'/apps/db_dump/mosquitto_db_dump', f'{test_dir}/apps/db_dump/data/{file}' ] res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1, encoding='utf-8') if res.stderr != stderr: print(res.stderr) raise mosq_test.TestError if res.returncode != rc_expected: print(file) print(res.returncode) raise mosq_test.TestError do_test('missing.test-db', f"Error: Unable to open {test_dir}/apps/db_dump/data/missing.test-db\n", 0) do_test('bad-magic.test-db', "Error: Unrecognised file format.\n", 1) do_test('short.test-db', "", 1) do_test('bad-dbid-size.test-db', "Error: Incompatible database configuration (dbid size is 5 bytes, expected 8)", 1) do_test('bad-chunk.test-db', 'Warning: Unsupported chunk "2816" of length 65696 in persistent database file at position 29. Ignoring.\n', 0) do_test('v3-corrupt.test-db', "Error: Corrupt persistent database.\n", 1) do_test('v4-corrupt.test-db', "Error: Corrupt persistent database.\n", 1) do_test('v5-corrupt.test-db', "Error: Corrupt persistent database.\n", 1) do_test('v6-corrupt.test-db', "Error: Corrupt persistent database.\n", 1) do_test('v6-corrupt-client.test-db', "Error: Corrupt persistent database.\n", 1) do_test('v6-corrupt-cmsg.test-db', "Error: Corrupt persistent database.\n", 1) do_test('v6-corrupt-retain.test-db', "Error: Corrupt persistent database.\n", 1) do_test('v6-corrupt-sub.test-db', "Error: Corrupt persistent database.\n", 1) ================================================ FILE: test/apps/db_dump/db-dump-json-v6-mqtt-v5-props.py ================================================ #!/usr/bin/env python3 import json from mosq_test_helper import * def do_test(file, json_expected): cmd = [ mosq_test.get_build_root() + '/apps/db_dump/mosquitto_db_dump', '--json', f'{test_dir}/apps/db_dump/data/{file}' ] res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=3, encoding='utf-8') json_result = json.loads(res.stdout) if json.dumps(json_result) != json.dumps(json_expected): print(json.dumps(json_result)) print(json.dumps(json_expected)) raise mosq_test.TestError json_expected = { "base-messages": [{ "storeid": 273732462748327, "expiry-time": 1669799825, "source-mid": 1, "source-port": 1883, "qos": 1, "retain": 0, "topic": "test-topic", "clientid": "auto-1F56F09A-97D3-2395-8B77-185E54E0A83C", "payload": "bWVzc2FnZQ==", # "message" "properties": [{ "identifier": "content-type", "value": "text/plain" }, { "identifier": "correlation-data", "value": "35636638653064652D356666612D346131302D393036622D346535623266393038363162" }, { "identifier": "payload-format-indicator", "value": 1 }, { "identifier": "response-topic", "value": "pub-response-topic" }, { "identifier": "user-property", "name": "pub-key", "value": "pub-value" }] },{ "storeid": 273732472648936, "expiry-time": 1669799786, "source-mid": 0, "source-port": 0, "qos": 2, "retain": 1, "topic": "will-topic", "clientid": "clientid", "payload": "d2lsbC1wYXlsb2Fk", "properties": [{ "identifier": "content-type", "value": "text/plain" }, { "identifier": "correlation-data", "value": "636F7272656C6174696F6E2D64617461" }, { "identifier": "payload-format-indicator", "value": 1 }, { "identifier": "response-topic", "value": "will-response-topic" }, { "identifier": "user-property", "name": "key", "value": "value" }] }], "clients": [{ "clientid": "clientid", "session-expiry-time": 1669799784, "session-expiry-interval": 60, "last-mid": 1, "listener-port": 0 }], "client-messages": [{ "clientid": "clientid", "storeid": 42, "mid": 1, "qos": 1, "state": 11, "retain-dup": 0, "direction": 1, "subscription-identifier": 42 }], "retained-messages": [{ "storeid": 273732472648936 }], "subscriptions": [{ "clientid": "clientid", "topic": "test-topic", "qos": 1, "options": 0, "identifier": 42 }] } do_test('v6-mqtt-v5-props.test-db', json_expected) ================================================ FILE: test/apps/db_dump/db-dump-print-empty.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(file, stdout): cmd = [ mosq_test.get_build_root()+'/apps/db_dump/mosquitto_db_dump', f'{test_dir}/apps/db_dump/data/{file}' ] res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1, encoding='utf-8') if res.stdout != stdout: raise mosq_test.TestError v3_empty = """Mosquitto DB dump CRC: 0 DB version: 3 DB_CHUNK_CFG: Length: 10 Shutdown: 1 DB ID size: 8 Last DB ID: 51 """ do_test('v3-empty.test-db', v3_empty) v4_empty = """Mosquitto DB dump CRC: 0 DB version: 4 DB_CHUNK_CFG: Length: 10 Shutdown: 1 DB ID size: 8 Last DB ID: 102 """ do_test('v4-empty.test-db', v4_empty) v5_empty = """Mosquitto DB dump CRC: 0 DB version: 5 DB_CHUNK_CFG: Length: 16 Shutdown: 1 DB ID size: 8 Last DB ID: 52 """ do_test('v5-empty.test-db', v5_empty) v6_empty = """Mosquitto DB dump CRC: 0 DB version: 6 DB_CHUNK_CFG: Length: 16 Shutdown: 1 DB ID size: 8 Last DB ID: 208485212291791 """ do_test('v6-empty.test-db', v6_empty) ================================================ FILE: test/apps/db_dump/db-dump-print-v6-all.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(file, stdout): cmd = [ mosq_test.get_build_root()+'/apps/db_dump/mosquitto_db_dump', f'{test_dir}/apps/db_dump/data/{file}' ] res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1, encoding='utf-8') if res.stdout != stdout: read_lines = res.stdout.splitlines() expected_lines = stdout.splitlines() for (read,expected) in zip(read_lines,expected_lines): if read != expected: print(f"- {expected}") print(f"+ {read}") else: print(f" {read}") raise mosq_test.TestError stdout = """Mosquitto DB dump CRC: 0 DB version: 6 DB_CHUNK_CFG: Length: 16 Shutdown: 1 DB ID size: 8 Last DB ID: 208508774941868 DB_CHUNK_BASE_MSG: Length: 85 Store ID: 208508774941868 Source Port: 1883 Source MID: 1 Topic: topic QoS: 1 Retain: 1 Payload Length: 7 Expiry Time: 0 Payload: message DB_CHUNK_CLIENT: Length: 34 Client ID: single-all Last MID: 1 Session expiry time: 0 Session expiry interval: 4294967295 DB_CHUNK_CLIENT_MSG: Length: 26 Client ID: single-all Store ID: 208508774941868 MID: 1 QoS: 1 Retain: 0 Direction: 1 State: 11 Dup: 0 DB_CHUNK_SUB: Length: 27 Client ID: single-all Topic: topic QoS: 1 Subscription ID: 0 Options: 0x00 DB_CHUNK_RETAIN: Length: 8 Store ID: 208508774941868 """ do_test('v6-single-all.test-db', stdout) ================================================ FILE: test/apps/db_dump/db-dump-print-v6-mqtt-v5-props.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(file, stdout): cmd = [ mosq_test.get_build_root() + '/apps/db_dump/mosquitto_db_dump', f'{test_dir}/apps/db_dump/data/{file}' ] res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=3, encoding='utf-8') if res.stdout != stdout: print(res.stdout) raise mosq_test.TestError stdout = """Mosquitto DB dump CRC: 0 DB version: 6 DB_CHUNK_CFG: Length: 16 Shutdown: 1 DB ID size: 8 Last DB ID: 273732472648936 DB_CHUNK_BASE_MSG: Length: 187 Store ID: 273732462748327 Source Port: 1883 Source MID: 1 Topic: test-topic QoS: 1 Retain: 0 Payload Length: 7 Expiry Time: 1669799825 Payload: message Properties: Content type: text/plain Correlation data: 35636638653064652D356666612D346131302D393036622D346535623266393038363162 Payload format indicator: 1 Response topic: pub-response-topic User property: pub-key , pub-value DB_CHUNK_BASE_MSG: Length: 132 Store ID: 273732472648936 Source Port: 0 Source MID: 0 Topic: will-topic QoS: 2 Retain: 1 Payload Length: 12 Expiry Time: 1669799786 Payload: will-payload Properties: Content type: text/plain Correlation data: 636F7272656C6174696F6E2D64617461 Payload format indicator: 1 Response topic: will-response-topic User property: key , value DB_CHUNK_CLIENT: Length: 32 Client ID: clientid Last MID: 1 Session expiry time: 1669799784 Session expiry interval: 60 DB_CHUNK_CLIENT_MSG: Length: 27 Client ID: clientid Store ID: 273732462748327 MID: 1 QoS: 1 Retain: 0 Direction: 1 State: 11 Dup: 0 Subscription identifier: 42 DB_CHUNK_SUB: Length: 30 Client ID: clientid Topic: test-topic QoS: 1 Subscription ID: 42 Options: 0x00 DB_CHUNK_RETAIN: Length: 8 Store ID: 273732472648936 """ do_test('v6-mqtt-v5-props.test-db', stdout) ================================================ FILE: test/apps/db_dump/db-dump-stats-current.py ================================================ #!/usr/bin/env python3 # Check whether output from the current broker can be read by the current db_dump. from mosq_test_helper import * import shutil def write_config(conf_file, port): with open(conf_file, 'w') as f: f.write(f"listener {port}\n") f.write("allow_anonymous true\n") f.write("persistence true\n") f.write(f"persistence_location {port}\n") def check_db(port, counts): stdout = f"DB_CHUNK_CFG: {counts[0]}\n" + \ f"DB_CHUNK_BASE_MSG: {counts[1]}\n" + \ f"DB_CHUNK_CLIENT_MSG: {counts[2]}\n" + \ f"DB_CHUNK_RETAIN: {counts[3]}\n" + \ f"DB_CHUNK_SUB: {counts[4]}\n" + \ f"DB_CHUNK_CLIENT: {counts[5]}\n" cmd = [ mosq_test.get_build_root()+'/apps/db_dump/mosquitto_db_dump', '--stats', f'{port}/mosquitto.db' ] res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1, encoding='utf-8') if res.stdout != stdout: print(res.stdout) raise mosq_test.TestError def do_test(counts): rc = 1 port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') try: if not os.path.exists(str(port)): os.mkdir(str(port)) except FileExistsError: pass write_config(conf_file, port) try: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port, use_conf=True) env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) # Set up persistent client session, including a subscription cmd = [ mosq_test.get_build_root()+'/client/mosquitto_sub', '-c', '-i', 'client-id', '-p', str(port), '-q', '1', '-t', 'sub-topic', '-E' ] subprocess.run(cmd, timeout=1, env=env) # Publish a retained message which is also queued for the subscriber cmd = [ mosq_test.get_build_root()+'/client/mosquitto_pub', '-p', str(port), '-q', '1', '-t', 'sub-topic', '-m', 'message', '-r' ] subprocess.run(cmd, timeout=1, env=env) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") raise mosq_test.TestError check_db(port, counts) rc = 0 except Exception as e: print(e) finally: os.remove(conf_file) os.remove(f"{port}/mosquitto.db") shutil.rmtree(str(port)) if broker is not None: broker.terminate() exit(rc) do_test([1,1,1,1,1,1]) ================================================ FILE: test/apps/db_dump/db-dump-stats.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(file, counts): stdout = f"DB_CHUNK_CFG: {counts[0]}\n" + \ f"DB_CHUNK_BASE_MSG: {counts[1]}\n" + \ f"DB_CHUNK_CLIENT_MSG: {counts[2]}\n" + \ f"DB_CHUNK_RETAIN: {counts[3]}\n" + \ f"DB_CHUNK_SUB: {counts[4]}\n" + \ f"DB_CHUNK_CLIENT: {counts[5]}\n" cmd = [ mosq_test.get_build_root()+'/apps/db_dump/mosquitto_db_dump', '--stats', f'{test_dir}/apps/db_dump/data/{file}' ] res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1, encoding='utf-8') if res.stdout != stdout: print(res.stdout) raise mosq_test.TestError do_test('v3-empty.test-db', [1,0,0,0,0,0]) do_test('v4-empty.test-db', [1,0,0,0,0,0]) do_test('v5-empty.test-db', [1,0,0,0,0,0]) do_test('v6-empty.test-db', [1,0,0,0,0,0]) do_test('v4-single-client.test-db', [1,0,0,0,0,1]) do_test('v6-single-client.test-db', [1,0,0,0,0,1]) do_test('v4-single-retain.test-db', [1,1,0,1,0,0]) do_test('v6-single-retain.test-db', [1,1,0,1,0,0]) do_test('v4-single-sub.test-db', [1,0,0,0,1,1]) do_test('v6-single-sub.test-db', [1,0,0,0,1,1]) do_test('v4-single-cmsg.test-db', [1,1,1,0,1,1]) do_test('v6-single-cmsg.test-db', [1,1,1,0,1,1]) do_test('v6-single-all.test-db', [1,1,1,1,1,1]) ================================================ FILE: test/apps/db_dump/mosq_test_helper.py ================================================ import logging import sys from pathlib import Path logging.basicConfig( level=logging.INFO, format="%(levelname)s %(asctime)s.%(msecs)03d %(module)s: %(message)s", datefmt="%H:%M:%S", ) current_source_dir = Path(__file__).resolve().parent test_dir = current_source_dir.parents[1] if test_dir not in sys.path: sys.path.insert(0, str(test_dir)) ssl_dir = test_dir / "ssl" import mosq_test import subprocess import os ================================================ FILE: test/apps/db_dump/test.py ================================================ #!/usr/bin/env python3 import os import pathlib import sys sys.path.insert(0, "../..") import ptest tests = [] for test_file in pathlib.Path(os.path.abspath(os.path.dirname(__file__))).glob('db-dump-*.py'): tests.append((1, test_file.resolve())) if __name__ == "__main__": test = ptest.PTest() test.run_tests(tests) ================================================ FILE: test/apps/mosq_test_helper.py ================================================ import 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 ================================================ FILE: test/apps/passwd/CMakeLists.txt ================================================ file(GLOB PY_TEST_FILES passwd-*.py) set(EXCLUDE_LIST # none ) foreach(PY_TEST_FILE ${PY_TEST_FILES}) get_filename_component(PY_TEST_NAME ${PY_TEST_FILE} NAME_WE) if(${PY_TEST_NAME} IN_LIST EXCLUDE_LIST) continue() endif() add_test(NAME apps-${PY_TEST_NAME} COMMAND ${PY_TEST_FILE} ) set_tests_properties(apps-${PY_TEST_NAME} PROPERTIES ENVIRONMENT "BUILD_ROOT=${CMAKE_BINARY_DIR}" ) endforeach() ================================================ FILE: test/apps/passwd/Makefile ================================================ R=../../.. include ${R}/config.mk .PHONY: all check test ptest clean .NOTPARALLEL: all : check : test test : ./passwd-args.py ./passwd-changes.py ./passwd-stdout.py ptest : ./test.py clean: ================================================ FILE: test/apps/passwd/mosq_test_helper.py ================================================ import logging import sys from pathlib import Path logging.basicConfig( level=logging.INFO, format="%(levelname)s %(asctime)s.%(msecs)03d %(module)s: %(message)s", datefmt="%H:%M:%S", ) current_source_dir = Path(__file__).resolve().parent test_dir = current_source_dir.parents[1] if test_dir not in sys.path: sys.path.insert(0, str(test_dir)) ssl_dir = test_dir / "ssl" import mosq_test import subprocess import os ================================================ FILE: test/apps/passwd/passwd-args.py ================================================ #!/usr/bin/env python3 # Test parsing of command line args and errors. Does not test arg functionality. from mosq_test_helper import * def do_test(args, rc_expected, response=None, input=None): proc = subprocess.run([mosq_test.get_build_root()+"/apps/mosquitto_passwd/mosquitto_passwd"] + args, capture_output=True, encoding='utf-8', timeout=2, input=input) if response is not None: if proc.stderr != response: print(len(proc.stderr)) print(len(response)) raise ValueError(proc.stderr) if proc.returncode != rc_expected: print(proc.returncode) raise ValueError(args) do_test([], 1) # For the usage message do_test(["-H"], 1, response="Error: -H argument given but not enough other arguments.\n") do_test(["-H", "nohash"], 1, response="Error: Unknown hash type 'nohash'\n") do_test(["-I"], 1, response="Error: -I argument given but not enough other arguments.\n") do_test(["-I", "0"], 1, response="Error: Number of iterations must be > 0.\n") do_test(["-c", "-D"], 1, response="Error: -c and -D cannot be used together.\n") do_test(["-c", "-U"], 1, response="Error: -c and -U cannot be used together.\n") do_test(["-U", "-D"], 1, response="Error: -D and -U cannot be used together.\n") do_test(["-b", "-D"], 1, response="Error: -b and -D cannot be used together.\n") do_test(["-c", "-b"], 1, response="Error: -c argument given but password file, username, or password missing.\n") do_test(["-c"], 1, response="Error: -c argument given but password file or username missing.\n") do_test(["-D"], 1, response="Error: -D argument given but password file or username missing.\n") do_test(["-U"], 1, response="Error: -U argument given but password file missing.\n") do_test(["-D", "pwfile", "bad-username:"], 1, response="Error: Username must not contain the ':' character.\n") do_test(["-D", "pwfile", "bad-username\n"], 1, response="Error: Username must not contain control characters.\n") do_test(["-D", "pwfile", "a"*65536], 1, response="Error: Username must be less than 65536 characters long.\n") do_test(["-c", "file", "username"], 2, response="Error: Passwords do not match.\n", input="not\nmatching\n") exit(0) ================================================ FILE: test/apps/passwd/passwd-changes.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import json import shutil import signal def write_config(filename, pw_file, port): with open(filename, 'w') as f: f.write(f"listener {port}\n") f.write("allow_anonymous false\n") f.write(f"password_file {pw_file}\n") def client_check(port, username, password, rc): connect_packet = mosq_test.gen_connect("pwd-test", username=username, password=password) connack_packet = mosq_test.gen_connack(rc=rc) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() def passwd_cmd(args, response=None, input=None, expected_rc=0): proc = subprocess.run([mosq_test.get_build_root()+"/apps/mosquitto_passwd/mosquitto_passwd"] + args, capture_output=True, encoding='utf-8', timeout=2, input=input) if response is not None: if proc.stdout != response and proc.stderr != response: print(f"stdout: {proc.stdout}") print(f"stderr: {proc.stderr}") print(f"expected: {response}") raise ValueError(proc.stdout) if proc.returncode != expected_rc: print(proc.returncode) print(expected_rc) raise ValueError(args) 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) # Generate initial password file passwd_cmd(["-H", "sha512", "-c", "-b", pw_file, "user1", "pass1"]) passwd_cmd(["-H", "sha512-pbkdf2", pw_file, "user2"], input="cmd\ncmd\n") passwd_cmd(["-H", "sha512-pbkdf2", pw_file, "user3"], input="pass3\npass3\n") #passwd_cmd(["-H", "argon2id", pw_file, "user3"], input="pass3\npass3\n") try: # If we're root, set file ownership to "nobody", because that is the user # the broker will change to. os.chown(pw_file, 65534, 65534) except PermissionError: pass # Then start broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port, nolog=True) try: rc = 1 client_check(port, "user1", "badpass", 5) client_check(port, "user1", "pass1", 0) client_check(port, "user2", "badpass", 5) client_check(port, "user2", "cmd", 0) client_check(port, "user3", "badpass", 5) client_check(port, "user3", "pass3", 0) client_check(port, "baduser", "badpass", 5) client_check(port, "baduser", "goodpass", 5) # Update password passwd_cmd(["-H", "sha512-pbkdf2", "-b", pw_file, "user1", "newpass"]) broker.send_signal(signal.SIGHUP) client_check(port, "user1", "badpass", 5) client_check(port, "user1", "newpass", 0) client_check(port, "user2", "badpass", 5) client_check(port, "user2", "cmd", 0) client_check(port, "user3", "badpass", 5) client_check(port, "user3", "pass3", 0) client_check(port, "baduser", "badpass", 5) client_check(port, "baduser", "goodpass", 5) # New user passwd_cmd(["-b", pw_file, "newuser", "goodpass"]) broker.send_signal(signal.SIGHUP) client_check(port, "user1", "badpass", 5) client_check(port, "user1", "newpass", 0) client_check(port, "user2", "badpass", 5) client_check(port, "user2", "cmd", 0) client_check(port, "user3", "badpass", 5) client_check(port, "user3", "pass3", 0) client_check(port, "newuser", "badpass", 5) client_check(port, "newuser", "goodpass", 0) # Delete user passwd_cmd(["-D", pw_file, "user2"]) passwd_cmd(["-D", pw_file, "user2"], response="Warning: User user2 not found in password file.\n", expected_rc=1) broker.send_signal(signal.SIGHUP) client_check(port, "user1", "badpass", 5) client_check(port, "user1", "newpass", 0) client_check(port, "user2", "badpass", 5) client_check(port, "user2", "cmd", 5) client_check(port, "user3", "badpass", 5) client_check(port, "user3", "pass3", 0) client_check(port, "newuser", "badpass", 5) client_check(port, "newuser", "goodpass", 0) rc = 0 except mosq_test.TestError: pass except Exception as err: print(err) finally: os.remove(conf_file) os.remove(pw_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 exit(rc) ================================================ FILE: test/apps/passwd/passwd-stdout.py ================================================ #!/usr/bin/env python3 # Test parsing of command line args and errors. Does not test arg functionality. from mosq_test_helper import * def do_test(args, rc_expected, response=None, input=None): proc = subprocess.run([mosq_test.get_build_root()+"/apps/mosquitto_passwd/mosquitto_passwd"] + args, capture_output=True, encoding='utf-8', timeout=2, input=input) if response is not None: if proc.stdout[0:len(response)] != response: print(len(proc.stdout)) print(len(response)) print(proc.stdout[0:len(response)]) print(response) raise ValueError(proc.stdout) if proc.returncode != rc_expected: print(proc.returncode) raise ValueError(args) resp = "Password: \nReenter password: \nstdout:$7$1000$" do_test(["-c", "-", "stdout"], 0, response=resp, input="pw\npw\n") resp = "stdout:$7$1000$" do_test(["-b", "-c", "-", "stdout", "pw"], 0, response=resp) exit(0) ================================================ FILE: test/apps/passwd/test.py ================================================ #!/usr/bin/env python3 import os import pathlib import sys sys.path.insert(0, "../..") import ptest tests = [] for test_file in pathlib.Path(os.path.abspath(os.path.dirname(__file__))).glob('passwd-*.py'): tests.append((1, test_file.resolve())) if __name__ == "__main__": test = ptest.PTest() test.run_tests(tests) ================================================ FILE: test/apps/signal/CMakeLists.txt ================================================ file(GLOB PY_TEST_FILES signal-*.py) set(EXCLUDE_LIST # none ) foreach(PY_TEST_FILE ${PY_TEST_FILES}) get_filename_component(PY_TEST_NAME ${PY_TEST_FILE} NAME_WE) if(${PY_TEST_NAME} IN_LIST EXCLUDE_LIST) continue() endif() add_test(NAME apps-${PY_TEST_NAME} COMMAND ${PY_TEST_FILE} ) set_tests_properties(apps-${PY_TEST_NAME} PROPERTIES ENVIRONMENT "BUILD_ROOT=${CMAKE_BINARY_DIR}" ) endforeach() ================================================ FILE: test/apps/signal/Makefile ================================================ R=../../.. include ${R}/config.mk .PHONY: all check test ptest clean .NOTPARALLEL: all : check : test test : ./signal-args.py ptest : ./test.py clean: ================================================ FILE: test/apps/signal/mosq_test_helper.py ================================================ import logging import sys from pathlib import Path logging.basicConfig( level=logging.INFO, format="%(levelname)s %(asctime)s.%(msecs)03d %(module)s: %(message)s", datefmt="%H:%M:%S", ) current_source_dir = Path(__file__).resolve().parent test_dir = current_source_dir.parents[1] if test_dir not in sys.path: sys.path.insert(0, str(test_dir)) ssl_dir = test_dir / "ssl" import mosq_test import subprocess import os ================================================ FILE: test/apps/signal/signal-args.py ================================================ #!/usr/bin/env python3 # Test parsing of command line args and errors. Does not test arg functionality. from mosq_test_helper import * def do_test(args, rc_expected, response=None, input=None): proc = subprocess.run([mosq_test.get_build_root()+"/apps/mosquitto_signal/mosquitto_signal"] + args, capture_output=True, encoding='utf-8', timeout=2, input=input) if response is not None: if proc.stderr != response: print(len(proc.stderr)) print(len(response)) raise ValueError(proc.stderr) if proc.returncode != rc_expected: print(proc.returncode) raise ValueError(args) do_test([], 1) # For the usage message do_test(["--help"], 1) do_test(["--invalid"], 1, response="Error: One of -a or -p must be used.\n") do_test(["-p"], 1, response="Error: -p argument given but process ID missing.\n") do_test(["-p", "0"], 1, response="Error: Process ID must be >0.\n") do_test(["-p", "1"], 1, response="Error: No signal given.\n") do_test(["-a"], 1, response="Error: No signal given.\n") do_test(["-p", "1", "invalid"], 1, response="Error: Unknown signal 'invalid'.\n") do_test(["-p", "1", "config-reload"], 0) do_test(["-p", "1", "log-rotate"], 0) do_test(["-p", "1", "shutdown"], 0) do_test(["-p", "1", "tree-print"], 0) do_test(["-p", "1", "xtreport"], 0) do_test(["-a", "config-reload"], 0) exit(0) ================================================ FILE: test/apps/signal/test.py ================================================ #!/usr/bin/env python3 import os import pathlib import sys sys.path.insert(0, "../..") import ptest tests = [] for test_file in pathlib.Path(os.path.abspath(os.path.dirname(__file__))).glob('signal-*.py'): tests.append((1, test_file.resolve())) if __name__ == "__main__": test = ptest.PTest() test.run_tests(tests) ================================================ FILE: test/broker/01-bad-initial-packets.py ================================================ #!/usr/bin/env python3 # Test whether non-CONNECT packets as an initial packet can cause excess memory use from mosq_test_helper import * try: import psutil except ModuleNotFoundError: print("WARNING: Test not running due to missing psutil module") exit(0) def write_config(filename, port): with open(filename, 'w') as f: f.write(f"listener {port}\n") f.write("allow_anonymous true\n") f.write("sys_interval 1\n") def do_send(port, socks, payload): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socks.append(sock) sock.connect(("127.0.0.1", port)) try: sock.send(payload) except (ConnectionResetError, BrokenPipeError): pass def do_test(port): rc = 1 conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port, use_conf=True) # Get the base memory useage before any connection attempt has happen base_mem = psutil.Process(broker.pid).memory_info().vms try: socks = [] do_send(port, socks, b"\x20\x80\x80\x80t" + b"\01"*100000000) # CONNACK do_send(port, socks, b"\x30\x80\x80\x80t" + b"\01"*100000000) # PUBLISH do_send(port, socks, b"\x40\x80\x80\x80t" + b"\01"*100000000) # PUBACK do_send(port, socks, b"\x50\x80\x80\x80t" + b"\01"*100000000) # PUBREC do_send(port, socks, b"\x60\x80\x80\x80t" + b"\01"*100000000) # PUBREL do_send(port, socks, b"\x70\x80\x80\x80t" + b"\01"*100000000) # PUBCOMP do_send(port, socks, b"\x80\x80\x80\x80t" + b"\01"*100000000) # SUBSCRIBE do_send(port, socks, b"\x90\x80\x80\x80t" + b"\01"*100000000) # SUBACK do_send(port, socks, b"\xA0\x80\x80\x80t" + b"\01"*100000000) # UNSUBSCRIBE do_send(port, socks, b"\xB0\x80\x80\x80t" + b"\01"*100000000) # UNSUBACK do_send(port, socks, b"\xC0\x80\x80\x80t" + b"\01"*100000000) # PINGREQ do_send(port, socks, b"\xD0\x80\x80\x80t" + b"\01"*100000000) # PINGRESP do_send(port, socks, b"\xE0\x80\x80\x80t" + b"\01"*100000000) # DISCONNECT do_send(port, socks, b"\xF0\x80\x80\x80t" + b"\01"*100000000) # AUTH mem = psutil.Process(broker.pid).memory_info().vms - base_mem for s in socks: s.close() limit = 20000000 if mem > limit: raise mosq_test.TestError(f"Process memory {mem} greater than limit of {limit}") rc = 0 except MemoryError: print("Memory error!") except Exception as e: print(e) 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) port = mosq_test.get_port() do_test(port) exit(0) ================================================ FILE: test/broker/01-connect-575314.py ================================================ #!/usr/bin/env python3 # Check for performance of processing user-property on CONNECT from mosq_test_helper import * def do_test(): rc = 1 props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key", "value") for i in range(0, 5000): props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key", "value") connect_packet_slow = mosq_test.gen_connect("connect-user-property", proto_ver=5, properties=props) connect_packet_fast = mosq_test.gen_connect("a"*65000, 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: t_start = time.monotonic() sock = mosq_test.do_client_connect(connect_packet_slow, connack_packet, port=port) t_stop = time.monotonic() sock.close() t_diff_slow = t_stop - t_start t_start = time.monotonic() sock = mosq_test.do_client_connect(connect_packet_fast, connack_packet, port=port) t_stop = time.monotonic() sock.close() t_diff_fast = t_stop - t_start # 20 is chosen as a factor that works in plain mode and running under # valgrind. The slow performance manifests as a factor of >100. Fast is <10. if t_diff_slow / t_diff_fast < 20: rc = 0 except mosq_test.TestError: pass finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() exit(0) ================================================ FILE: test/broker/01-connect-accept-protocol.py ================================================ #!/usr/bin/env python3 # Test accept_protocol_version option from mosq_test_helper import * def write_config(filename, port, accept): with open(filename, 'w') as f: f.write("listener %s\n" % (port)) f.write("allow_anonymous true\n") f.write("accept_protocol_versions %s\n" % (accept)) def do_test(accept, expect_success): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, accept) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: for proto_ver in [3, 4, 5]: rc = 1 connect_packet = mosq_test.gen_connect("accept-protocol-test-%d" % (proto_ver), proto_ver=proto_ver) if proto_ver == 5: if proto_ver in expect_success: connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) else: connack_packet = mosq_test.gen_connack(rc=mqtt5_rc.UNSUPPORTED_PROTOCOL_VERSION, proto_ver=proto_ver, properties=None) else: if proto_ver in expect_success: connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) else: connack_packet = mosq_test.gen_connack(rc=1, 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(accept="3,4,5", expect_success=[3, 4, 5]) do_test(accept="5,4,3", expect_success=[3, 4, 5]) do_test(accept="3 ,4, 5", expect_success=[3, 4, 5]) do_test(accept=" , 3 , 4 , 5 ", expect_success=[3, 4, 5]) do_test(accept="3", expect_success=[3]) do_test(accept="4", expect_success=[4]) do_test(accept="5", expect_success=[5]) do_test(accept="3,4", expect_success=[3, 4]) do_test(accept="3,5", expect_success=[3, 5]) do_test(accept="4,3", expect_success=[3, 4]) do_test(accept="4,5", expect_success=[4, 5]) do_test(accept="5,3", expect_success=[3, 5]) ================================================ FILE: test/broker/01-connect-allow-anonymous.py ================================================ #!/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 write_config6(filename, port): with open(filename, 'w') as f: f.write("allow_anonymous false\n") def write_config7(filename, port): with open(filename, 'w') as f: f.write("allow_anonymous true\n") def write_config8(filename, port): with open(filename, 'w') as f: f.write("allow_anonymous false\n") f.write("listener %d\n" % (port)) f.write("listener_allow_anonymous true\n") def write_config9(filename, port): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write("listener %d\n" % (port)) f.write("listener_allow_anonymous false\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 connect_packet = mosq_test.gen_connect("connect-anon-test-%d" % (proto_ver), 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.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) pass broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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 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) # Config file without "listener" - allow_anonymous explicitly false do_test(use_conf=True, write_config=write_config6, expect_success=False) # Config file without "listener" - allow_anonymous explicitly true do_test(use_conf=True, write_config=write_config7, expect_success=True) # Config file with "listener" - allow_anonymous explicitly false and listener_allow_anonymous explicitly true do_test(use_conf=True, write_config=write_config8, expect_success=True) # Config file with "listener" - allow_anonymous explicitly true and listener_allow_anonymous explicitly false do_test(use_conf=True, write_config=write_config9, expect_success=False) exit(0) ================================================ FILE: test/broker/01-connect-auto-id.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def write_config1(filename, port1, port2): with open(filename, 'w') as f: f.write(f"listener {port2}\n") f.write("allow_anonymous true\n") f.write(f"listener {port1}\n") f.write("allow_anonymous true\n") def write_config2(filename, port1, port2): with open(filename, 'w') as f: f.write("auto_id_prefix new-\n") f.write(f"listener {port2}\n") f.write("allow_anonymous true\n") f.write(f"listener {port1}\n") f.write("allow_anonymous true\n") def write_config3(filename, port1, port2): with open(filename, 'w') as f: f.write(f"listener {port2}\n") f.write("listener_auto_id_prefix port2-\n") f.write("allow_anonymous true\n") f.write(f"listener {port1}\n") f.write("allow_anonymous true\n") def write_config4(filename, port1, port2): with open(filename, 'w') as f: f.write(f"listener {port2}\n") f.write("listener_auto_id_prefix port2-\n") f.write("allow_anonymous true\n") f.write(f"listener {port1}\n") f.write("listener_auto_id_prefix port1-\n") f.write("allow_anonymous true\n") def write_config5(filename, port1, port2): with open(filename, 'w') as f: f.write("auto_id_prefix global-\n") f.write(f"listener {port2}\n") f.write("listener_auto_id_prefix port2-\n") f.write("allow_anonymous true\n") f.write(f"listener {port1}\n") f.write("listener_auto_id_prefix port1-\n") f.write("allow_anonymous true\n") def write_config6(filename, port1, port2): with open(filename, 'w') as f: f.write("auto_id_prefix global-\n") f.write(f"listener {port2}\n") f.write("allow_anonymous true\n") f.write(f"listener {port1}\n") f.write("listener_auto_id_prefix port1-\n") f.write("allow_anonymous true\n") def do_test(config_func, client_port, auto_id): conf_file = os.path.basename(__file__).replace('.py', '.conf') config_func(conf_file, port1, port2) rc = 1 connect_packet = mosq_test.gen_connect("", proto_ver=5) props = mqtt5_props.gen_string_prop(mqtt5_props.ASSIGNED_CLIENT_IDENTIFIER, f"{auto_id}xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, 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[:-44] 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() os.remove(conf_file) if rc: print(stde.decode('utf-8')) exit(rc) (port1, port2) = mosq_test.get_port(2) do_test(config_func=write_config1, client_port=port1, auto_id="auto-") do_test(config_func=write_config1, client_port=port2, auto_id="auto-") do_test(config_func=write_config2, client_port=port1, auto_id="new-") do_test(config_func=write_config2, client_port=port2, auto_id="new-") do_test(config_func=write_config3, client_port=port1, auto_id="auto-") do_test(config_func=write_config3, client_port=port2, auto_id="port2-") do_test(config_func=write_config4, client_port=port1, auto_id="port1-") do_test(config_func=write_config4, client_port=port2, auto_id="port2-") do_test(config_func=write_config5, client_port=port1, auto_id="port1-") do_test(config_func=write_config5, client_port=port2, auto_id="port2-") do_test(config_func=write_config6, client_port=port1, auto_id="port1-") do_test(config_func=write_config6, client_port=port2, auto_id="global-") exit(0) ================================================ FILE: test/broker/01-connect-disconnect-v5.py ================================================ #!/usr/bin/env python3 # loop through the different v5 DISCONNECT reason_code/properties options. from mosq_test_helper import * rc = 0 port = mosq_test.get_port() def disco_test(test, disconnect_packet): global rc connect1_packet = mosq_test.gen_connect("sub", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid, "failure", 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, will_topic="failure", will_payload=b"failure") connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) 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 def do_test(start_broker): global rc rc = 4 if start_broker: 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.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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/01-connect-global-max-clients.py ================================================ #!/usr/bin/env python3 # Test whether global_max_clients works 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("global_max_clients 10\n") def do_test(): rc = 1 connect_packets_ok = [] connack_packets_ok = [] connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 60) for i in range(0, 10): connect_packets_ok.append(mosq_test.gen_connect("max-conn-%d"%i, proto_ver=5, properties=connect_props)) connack_packets_ok.append(mosq_test.gen_connack(rc=0, proto_ver=5)) connect_packet_bad = mosq_test.gen_connect("max-conn-bad", proto_ver=5) connack_packet_bad = mosq_test.gen_connack(rc=mqtt5_rc.SERVER_BUSY, proto_ver=5, property_helper=False) 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) socks = [] try: # Open all allowed connections, a limit of 10 for i in range(0, 10): socks.append(mosq_test.do_client_connect(connect_packets_ok[i], connack_packets_ok[i], port=port)) # Try to open an 11th connection try: sock_bad = mosq_test.do_client_connect(connect_packet_bad, connack_packet_bad, port=port) except (ConnectionResetError, BrokenPipeError): # Expected behaviour pass # Close all allowed connections for i in range(0, 10): socks[i].close() ## Session expiry means those clients sessions are still active # Try to open an 11th connection try: sock_bad = mosq_test.do_client_connect(connect_packet_bad, connack_packet_bad, port=port) except (ConnectionResetError, BrokenPipeError): # Expected behaviour pass rc = 0 except mosq_test.TestError: pass except Exception as err: print(err) finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) return rc sys.exit(do_test()) ================================================ FILE: test/broker/01-connect-global-max-connections.py ================================================ #!/usr/bin/env python3 # Test whether global_max_connections works 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("global_max_connections 10\n") def do_test(): rc = 1 connect_packets_ok = [] connack_packets_ok = [] for i in range(0, 10): connect_packets_ok.append(mosq_test.gen_connect("max-conn-%d"%i, proto_ver=5)) connack_packets_ok.append(mosq_test.gen_connack(rc=0, proto_ver=5)) connect_packet_bad = mosq_test.gen_connect("max-conn-bad", proto_ver=5) connack_packet_bad = b"" 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) socks = [] try: # Open all allowed connections, a limit of 10 for i in range(0, 10): socks.append(mosq_test.do_client_connect(connect_packets_ok[i], connack_packets_ok[i], port=port)) # Try to open an 11th connection try: mosq_test.do_client_connect(connect_packet_bad, connack_packet_bad, port=port) print("did not throw when trying to open 11th connection (first time)") return rc except (ConnectionResetError, BrokenPipeError, OSError): # Expected behaviour pass finally: # Close all allowed connections for sock in socks: sock.close() socks.clear() ## Now repeat - check it works as before if os.environ.get('MOSQ_USE_VALGRIND') is not None: time.sleep(0.5) # Open all allowed connections, a limit of 10 for i in range(0, 10): socks.append(mosq_test.do_client_connect(connect_packets_ok[i], connack_packets_ok[i], port=port)) # Try to open an 11th connection try: mosq_test.do_client_connect(connect_packet_bad, connack_packet_bad, port=port) print("did not throw when trying to open 11th connection (second time)") return rc except (ConnectionResetError, BrokenPipeError, OSError): # Expected behaviour pass finally: # Close all allowed connections for sock in socks: sock.close() socks.clear() rc = 0 except Exception as err: raise err finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (_, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) return rc sys.exit(do_test()) ================================================ FILE: test/broker/01-connect-listener-allow-anonymous.py ================================================ #!/usr/bin/env python3 # Test whether an anonymous connection is correctly denied. from mosq_test_helper import * def write_config1(filename, port1, port2): with open(filename, 'w') as f: f.write("listener %d\n" % (port1)) f.write("listener_allow_anonymous false\n") f.write("listener %d\n" % (port2)) f.write("listener_allow_anonymous false\n") def write_config2(filename, port1, port2): with open(filename, 'w') as f: f.write("listener %d\n" % (port1)) f.write("listener_allow_anonymous true\n") f.write("listener %d\n" % (port2)) f.write("listener_allow_anonymous false\n") def write_config3(filename, port1, port2): with open(filename, 'w') as f: f.write("listener %d\n" % (port1)) f.write("listener_allow_anonymous false\n") f.write("listener %d\n" % (port2)) f.write("listener_allow_anonymous true\n") def write_config4(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write("listener %d\n" % (port1)) f.write("listener_allow_anonymous false\n") f.write("listener %d\n" % (port2)) f.write("listener_allow_anonymous false\n") def write_config5(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write("listener %d\n" % (port1)) f.write("listener_allow_anonymous true\n") f.write("listener %d\n" % (port2)) f.write("listener_allow_anonymous false\n") def write_config6(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write("listener %d\n" % (port1)) f.write("listener_allow_anonymous false\n") f.write("listener %d\n" % (port2)) f.write("listener_allow_anonymous true\n") def write_config7(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous false\n") f.write("listener %d\n" % (port1)) f.write("listener_allow_anonymous false\n") f.write("listener %d\n" % (port2)) f.write("listener_allow_anonymous false\n") def write_config8(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous false\n") f.write("listener %d\n" % (port1)) f.write("listener_allow_anonymous true\n") f.write("listener %d\n" % (port2)) f.write("listener_allow_anonymous false\n") def write_config9(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous false\n") f.write("listener %d\n" % (port1)) f.write("listener_allow_anonymous false\n") f.write("listener %d\n" % (port2)) f.write("listener_allow_anonymous true\n") def do_test(write_config, expect_success1, expect_success2): port1, port2 = mosq_test.get_port(2) if write_config is not None: conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port1, port2) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port1) try: for proto_ver in [4, 5]: rc = 1 connect_packet = mosq_test.gen_connect(f"connect-anon-test-{proto_ver}-{expect_success1}-{expect_success2}", proto_ver=proto_ver) if proto_ver == 5: connack_packet_success = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet_rejected = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=proto_ver, properties=None) else: connack_packet_success = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet_rejected = mosq_test.gen_connack(rc=5, proto_ver=proto_ver) if expect_success1: sock = mosq_test.do_client_connect(connect_packet, connack_packet_success, port=port1) else: sock = mosq_test.do_client_connect(connect_packet, connack_packet_rejected, port=port1) sock.close() if expect_success2: sock = mosq_test.do_client_connect(connect_packet, connack_packet_success, port=port2) else: sock = mosq_test.do_client_connect(connect_packet, connack_packet_rejected, port=port2) sock.close() rc = 0 except mosq_test.TestError: pass finally: if write_config is not None: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(write_config=write_config1, expect_success1=False, expect_success2=False) do_test(write_config=write_config2, expect_success1=True, expect_success2=False) do_test(write_config=write_config3, expect_success1=False, expect_success2=True) do_test(write_config=write_config4, expect_success1=False, expect_success2=False) do_test(write_config=write_config5, expect_success1=True, expect_success2=False) do_test(write_config=write_config6, expect_success1=False, expect_success2=True) do_test(write_config=write_config7, expect_success1=False, expect_success2=False) do_test(write_config=write_config8, expect_success1=True, expect_success2=False) do_test(write_config=write_config9, expect_success1=False, expect_success2=True) exit(0) ================================================ FILE: test/broker/01-connect-max-connections.py ================================================ #!/usr/bin/env python3 # Test whether max_connections works with repeated connections 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_connections 10\n") def test_iteration(port, connect_packets_ok, connack_packets_ok, connect_packet_bad, connack_packet_bad): socks = [] # Open all allowed connections, a limit of 10 for i in range(0, 10): socks.append(mosq_test.do_client_connect(connect_packets_ok[i], connack_packets_ok[i], port=port)) # Try to open an 11th connection try: sock_bad = mosq_test.do_client_connect(connect_packet_bad, connack_packet_bad, port=port) except (ConnectionResetError, BrokenPipeError): # Expected behaviour pass except OSError as e: if e.errno == errno.ENOTCONN: pass else: raise e # Close all allowed connections for i in range(0, 10): socks[i].close() def do_test(): rc = 1 connect_packets_ok = [] connack_packets_ok = [] for i in range(0, 10): connect_packets_ok.append(mosq_test.gen_connect("max-conn-%d"%i, proto_ver=5)) connack_packets_ok.append(mosq_test.gen_connack(rc=0, proto_ver=5)) connect_packet_bad = mosq_test.gen_connect("max-conn-bad", proto_ver=5) connack_packet_bad = b"" 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: test_iteration(port, connect_packets_ok, connack_packets_ok, connect_packet_bad, connack_packet_bad) ## Now repeat - check it works as before if os.environ.get('MOSQ_USE_VALGRIND') is not None: time.sleep(0.5) test_iteration(port, connect_packets_ok, connack_packets_ok, connect_packet_bad, connack_packet_bad) rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) return rc sys.exit(do_test()) ================================================ FILE: test/broker/01-connect-max-keepalive.py ================================================ #!/usr/bin/env python3 # Test whether max_keepalive violations are rejected for MQTT < 5.0. 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_keepalive 100\n") def do_test(proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("max-keepalive", keepalive=101, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=2, 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) socks = [] try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 except mosq_test.TestError: pass except Exception as err: print(err) finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(3) do_test(4) exit(0) ================================================ FILE: test/broker/01-connect-take-over.py ================================================ #!/usr/bin/env python3 # MQTT v5 session takeover test from mosq_test_helper import * port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: rc = 1 connect_packet = mosq_test.gen_connect("take-over", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(reason_code=mqtt5_rc.SESSION_TAKEN_OVER, proto_ver=5) sock1 = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock2 = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.expect_packet(sock1, "disconnect", disconnect_packet) mosq_test.do_ping(sock2) sock2.close() sock1.close() rc = 0 except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/01-connect-uname-no-password-denied.pwfile ================================================ user:$6$Ut1cUS9PG8+gC3vn$tOjCfSJJDe1Alu9HktxxyyzwN4+6mAMSWGRAF9gmMN8pzcGTPVEYYMAZpCEp96Oz2ZRRz5YKM6lPMf1tUbb6zA== ================================================ FILE: test/broker/01-connect-uname-no-password-denied.py ================================================ #!/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("listener %d\n" % (port)) f.write("password_file %s/%s\n" % (Path(__file__).resolve().parent, 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 connect_packet = mosq_test.gen_connect("connect-uname-test", username="user", proto_ver=proto_ver) if proto_ver == 5: connack_packet = mosq_test.gen_connack(rc=mqtt5_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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/01-connect-uname-or-anon.pwfile ================================================ user:$6$Ut1cUS9PG8+gC3vn$tOjCfSJJDe1Alu9HktxxyyzwN4+6mAMSWGRAF9gmMN8pzcGTPVEYYMAZpCEp96Oz2ZRRz5YKM6lPMf1tUbb6zA== ================================================ FILE: test/broker/01-connect-uname-or-anon.py ================================================ #!/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/%s\n" % (Path(__file__).resolve().parent, 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 [3, 4, 5]: rc = 1 if username: connect_packet = mosq_test.gen_connect("connect-test-%d" % (proto_ver), proto_ver=proto_ver, username="user", password="password") else: connect_packet = mosq_test.gen_connect("connect-test-%d" % (proto_ver), 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.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/01-connect-uname-password-denied-no-will.py ================================================ #!/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("listener %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 connect1_packet = mosq_test.gen_connect("connect-uname-pwd-test", 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", username="user", password="password9", proto_ver=proto_ver) if proto_ver == 5: connack2_packet = mosq_test.gen_connack(rc=mqtt5_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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/01-connect-uname-password-denied.pwfile ================================================ user:$6$vZY4TS+/HBxHw38S$vvjVFECzb8dyuu/mruD2QKTfdFn0WmKxbc+1TsdB0L8EdHk3v9JRmfjHd56+VaTnUcSZOZ/hzkdvWCtxlX7AUQ== ================================================ FILE: test/broker/01-connect-uname-password-denied.py ================================================ #!/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("listener %d\n" % (port)) f.write("password_file %s/%s\n" % (Path(__file__).resolve().parent, 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 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", username="user", password="password9", proto_ver=proto_ver) if proto_ver == 5: connack_packet = mosq_test.gen_connack(rc=mqtt5_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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/01-connect-uname-password-success-no-tls.pwfile ================================================ user:password ================================================ FILE: test/broker/01-connect-uname-password-success-no-tls.py ================================================ #!/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("listener %d\n" % (port)) f.write("password_file %s/%s\n" % (Path(__file__).resolve().parent, 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 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/01-connect-unix-socket.py ================================================ #!/usr/bin/env python3 # Test whether connections to a unix socket work from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("listener 0 %d.sock\n" % (port)) f.write("allow_anonymous true\n") def do_test(): rc = 1 connect_packet = mosq_test.gen_connect("unix-socket") connack_packet = mosq_test.gen_connack(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=conf_file, check_port=False) try: if os.environ.get('MOSQ_USE_VALGRIND') is None: time.sleep(0.1) else: time.sleep(2) sock = mosq_test.do_client_connect_unix(connect_packet, connack_packet, path=f"{port}.sock") sock.close() rc = 0 except mosq_test.TestError: pass except Exception as err: print(err) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 os.remove(conf_file) try: os.remove(f"{port}.sock") except FileNotFoundError: pass (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() exit(0) ================================================ FILE: test/broker/01-connect-windows-line-endings.py ================================================ #!/usr/bin/env python3 # Test whether config files with windows line endings are accepted. # This just connects anonymously - if the config file causes a failure, the # broker won't start so the connection would fail. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\r\n" % (port)) f.write("allow_anonymous true\r\n") def do_test(): 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: for proto_ver in [4, 5]: rc = 1 connect_packet = mosq_test.gen_connect("connect-anon-test-%d" % (proto_ver), proto_ver=proto_ver) if proto_ver == 5: connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) else: 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() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test() exit(0) ================================================ FILE: test/broker/01-connect-zero-length-id.py ================================================ #!/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 connect_packet = mosq_test.gen_connect("", 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.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[:-44] 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/01-plugin-connect-uname-password-denied.pwfile ================================================ user:$6$vZY4TS+/HBxHw38S$vvjVFECzb8dyuu/mruD2QKTfdFn0WmKxbc+1TsdB0L8EdHk3v9JRmfjHd56+VaTnUcSZOZ/hzkdvWCtxlX7AUQ== ================================================ FILE: test/broker/01-plugin-connect-uname-password-denied.py ================================================ #!/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("listener %d\n" % (port)) f.write(f"plugin {mosq_test.get_build_root()}/plugins/password-file/mosquitto_password_file.so\n") f.write("plugin_opt_password_file %s/%s\n" % (Path(__file__).resolve().parent, 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 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", username="user", password="password9", proto_ver=proto_ver) if proto_ver == 5: connack_packet = mosq_test.gen_connack(rc=mqtt5_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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/02-shared-nolocal.py ================================================ #!/usr/bin/env python3 # No local option is not allowed on shared subscriptions from mosq_test_helper import * def do_test(start_broker): rc = 1 mid = 1 connect1_packet = mosq_test.gen_connect("02-shared-nolocal-client1", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "$share/sharename/subpub/qos1", 1 | mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(reason_code=mqtt5_rc.PROTOCOL_ERROR, proto_ver=5) port = mosq_test.get_port() if start_broker: broker = mosq_test.start_broker(filename=os.path.basename(__file__), 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, disconnect_packet, "disconnect") rc = 0 sock.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-shared-qos0-v5.py ================================================ #!/usr/bin/env python3 # Test whether shared subscriptions work # Client 1 subscribes to 02/#, non shared. Should receive everything. # Client 2 subscribes to $share/one/02/share/test # Client 3 subscribes to $share/one/02/share/test and $share/two/02/share/test # Client 4 subscribes to $share/two/02/share/test # Client 5 subscribes to $share/one/02/share/test # A publish to "02/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 * def do_test(start_broker): rc = 1 mid = 1 connect1_packet = mosq_test.gen_connect("02-shared-client1", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect2_packet = mosq_test.gen_connect("02-shared-client2", proto_ver=5) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect3_packet = mosq_test.gen_connect("02-shared-client3", proto_ver=5) connack3_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect4_packet = mosq_test.gen_connect("02-shared-client4", proto_ver=5) connack4_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect5_packet = mosq_test.gen_connect("02-shared-client5", proto_ver=5) connack5_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe1_packet = mosq_test.gen_subscribe(mid, "02A/#", 0, proto_ver=5) suback1_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) subscribe2_packet = mosq_test.gen_subscribe(mid, "$share/one/02A/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/02A/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/02A/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/02A/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/02A/share/test", 0, proto_ver=5) suback5_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish1_packet = mosq_test.gen_publish("02A/share/test", qos=0, payload="message1", proto_ver=5) publish2_packet = mosq_test.gen_publish("02A/share/test", qos=0, payload="message2", proto_ver=5) publish3_packet = mosq_test.gen_publish("02A/share/test", qos=0, payload="message3", proto_ver=5) mid = 2 unsubscribe1_packet = mosq_test.gen_unsubscribe(mid, "02A/#", proto_ver=5) unsuback1_packet = mosq_test.gen_unsuback(mid, proto_ver=5) unsubscribe2_packet = mosq_test.gen_unsubscribe(mid, "$share/one/02A/share/test", proto_ver=5) unsuback2_packet = mosq_test.gen_unsuback(mid, proto_ver=5) unsubscribe3a_packet = mosq_test.gen_unsubscribe(mid, "$share/one/02A/share/test", proto_ver=5) unsuback3a_packet = mosq_test.gen_unsuback(mid, proto_ver=5) unsubscribe3b_packet = mosq_test.gen_unsubscribe(mid, "$share/two/02A/share/test", proto_ver=5) unsuback3b_packet = mosq_test.gen_unsuback(mid, proto_ver=5) unsubscribe4_packet = mosq_test.gen_unsubscribe(mid, "$share/two/02A/share/test", proto_ver=5) unsuback4_packet = mosq_test.gen_unsuback(mid, proto_ver=5) unsubscribe5_packet = mosq_test.gen_unsubscribe(mid, "$share/one/02A/share/test", proto_ver=5) unsuback5_packet = mosq_test.gen_unsuback(mid, proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subhier-crash.py ================================================ #!/usr/bin/env python3 # Test related to https://github.com/eclipse/mosquitto/issues/505 from mosq_test_helper import * def test(port): connect_packet = mosq_test.gen_connect("subhier-crash") 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() 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() def do_test(start_broker=True): rc = 1 port = mosq_test.get_port() if start_broker: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: test(port) # Repeat test to check broker is still there test(port) rc = 0 except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-b2c-topic-alias.py ================================================ #!/usr/bin/env python3 # Test whether "topic alias" works from the broker # MQTT v5 from mosq_test_helper import * def do_test(start_broker): rc = 1 props = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 65535) connect_packet = mosq_test.gen_connect("02-b2c-topic-alias", proto_ver=5, properties=props) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(topic="02/b2c/topic/alias/#", qos=0, mid=1, proto_ver=5) suback_packet = mosq_test.gen_suback(qos=0, mid=1, proto_ver=5) connect_packet_helper = mosq_test.gen_connect("02-b2c-topic-alias-helper", proto_ver=5) connack_packet_helper = mosq_test.gen_connack(rc=0, proto_ver=5) port = mosq_test.get_port() if start_broker: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port, nolog=True) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) helper = mosq_test.do_client_connect(connect_packet_helper, connack_packet_helper, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet) # This test allows us to test up to the 65535 aliases, but the default # max_topic_alias_broker setting is 10, so use that. max_alias = 10 # Send messages so the broker configures topic aliases publish_packet_s = b"" publish_packet_r = b"" for i in range(1, max_alias): # This doesn't make sense in the max_alias=10 case, but for higher values it speeds up the test if i % 50 == 0: sock.send(publish_packet_s) mosq_test.expect_packet(sock, "publish %da"%(i), publish_packet_r) publish_packet_s = b"" publish_packet_r = b"" publish_packet_s += mosq_test.gen_publish("02/b2c/topic/alias/%d"%(i), qos=0, payload="message", proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS, i) publish_packet_r += mosq_test.gen_publish("02/b2c/topic/alias/%d"%(i), qos=0, payload="message", proto_ver=5, properties=props) if len(publish_packet_s) > 0: sock.send(publish_packet_s) mosq_test.expect_packet(sock, "publish %da"%(i), publish_packet_r) # Re-send now aliases have been configured by the broker publish_packet_s = b"" publish_packet_r = b"" for i in range(1, max_alias): if i % 50 == 0: sock.send(publish_packet_s) mosq_test.expect_packet(sock, "publish %db"%(i), publish_packet_r) publish_packet_s = b"" publish_packet_r = b"" publish_packet_s += mosq_test.gen_publish("02/b2c/topic/alias/%d"%(i), qos=0, payload="message", proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS, i) publish_packet_r += mosq_test.gen_publish("", qos=0, payload="message", proto_ver=5, properties=props) if len(publish_packet_s) > 0: sock.send(publish_packet_s) mosq_test.expect_packet(sock, "publish %db"%(i), publish_packet_r) rc = 0 sock.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-qos0-long-topic.py ================================================ #!/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(start_broker, topic, succeeds): rc = 1 mid = 53 connect_packet = mosq_test.gen_connect("02-subpub-qos0-long-topic") 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 = None if start_broker: 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: mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.do_send_receive(sock, publish_packet, publish_packet, "publish") else: try: mosq_test.do_send_receive(sock, subscribe_packet, b"", "suback") return 1 except BrokenPipeError: pass rc = 0 sock.close() finally: if broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) return rc def all_tests(start_broker=False): rc = do_test(start_broker, "/"*200, True) # 200 max hierarchy limit if rc: return rc rc = do_test(start_broker, "abc/"*199+"d", True) # 200 max hierarchy limit, longer overall string than 200 if rc: return rc rc = do_test(start_broker, "/"*201, False) # Exceeds 200 max hierarchy limit if rc: return rc rc = do_test(start_broker, "abc/"*201+"d", False) # Exceeds 200 max hierarchy limit, longer overall string than 200 if rc: return rc return 0 if __name__ == '__main__': sys.exit(all_tests(True)) ================================================ FILE: test/broker/02-subpub-qos0-oversize-payload.py ================================================ #!/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 connect_packet = mosq_test.gen_connect("02-subpub-qos0-oversize", 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/oversize", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) connect2_packet = mosq_test.gen_connect("02-subpub-qos0-oversize-helper", 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/oversize", qos=0, payload="A", proto_ver=proto_ver) publish_packet_bad = mosq_test.gen_publish("subpub/qos0/oversize", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/02-subpub-qos0-queued-bytes.py ================================================ #!/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 connect_packet = mosq_test.gen_connect("subpub-qos0-bytes", 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", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/02-subpub-qos0-retain-as-publish.py ================================================ #!/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(start_broker): rc = 1 connect_packet = mosq_test.gen_connect("02-subpub-qos0-rap", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 530 subscribe1_packet = mosq_test.gen_subscribe(mid, "02/subpub/rap/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, "02/subpub/rap/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("02/subpub/rap/normal", qos=0, retain=True, payload="message", proto_ver=5) publish2_packet = mosq_test.gen_publish("02/subpub/rap/rap", qos=0, retain=True, payload="message", proto_ver=5) publish1r_packet = mosq_test.gen_publish("02/subpub/rap/normal", qos=0, retain=False, payload="message", proto_ver=5) publish2r_packet = mosq_test.gen_publish("02/subpub/rap/rap", qos=0, retain=True, payload="message", proto_ver=5) mid = 1 publish3_packet = mosq_test.gen_publish("02/subpub/rap/receive", qos=1, mid=mid, payload="success", proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-qos0-send-retain.py ================================================ #!/usr/bin/env python3 # Test whether "send retain" subscribe options work # MQTT v5 from mosq_test_helper import * def do_test(start_broker): rc = 1 connect_packet = mosq_test.gen_connect("02-subpub-qos0-send-retain", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 530 subscribe1_packet = mosq_test.gen_subscribe(mid, "02/subpub/send-retain/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, "02/subpub/send-retain/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, "02/subpub/send-retain/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("02/subpub/send-retain/always", qos=0, retain=True, payload="message", proto_ver=5) publish2_packet = mosq_test.gen_publish("02/subpub/send-retain/new", qos=0, retain=True, payload="message", proto_ver=5) publish3_packet = mosq_test.gen_publish("02/subpub/send-retain/never", qos=0, retain=True, payload="message", proto_ver=5) publish1r1_packet = mosq_test.gen_publish("02/subpub/send-retain/always", qos=0, retain=True, payload="message", proto_ver=5) publish1r2_packet = mosq_test.gen_publish("02/subpub/send-retain/always", qos=0, retain=True, payload="message", proto_ver=5) publish2r1_packet = mosq_test.gen_publish("02/subpub/send-retain/new", qos=0, retain=True, payload="message", proto_ver=5) publish2r2_packet = mosq_test.gen_publish("02/subpub/send-retain/new", qos=0, retain=False, payload="message", proto_ver=5) publish3r1_packet = mosq_test.gen_publish("02/subpub/send-retain/never", qos=0, retain=False, payload="message", proto_ver=5) publish3r2_packet = mosq_test.gen_publish("02/subpub/send-retain/never", qos=0, retain=False, payload="message", proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-qos0-subscription-id.py ================================================ #!/usr/bin/env python3 # Does setting and updating subscription identifiers work as expected? # MQTT v5 from mosq_test_helper import * def do_test(start_broker, proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("02-subpub-subid", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 props = mqtt5_props.gen_varint_prop(mqtt5_props.SUBSCRIPTION_IDENTIFIER, 1) subscribe1_packet = mosq_test.gen_subscribe(mid, "02/subpub/subid/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.SUBSCRIPTION_IDENTIFIER, 14) subscribe2_packet = mosq_test.gen_subscribe(mid, "02/subpub/subid/+/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, "02/subpub/subid/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, "02/subpub/subid/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.SUBSCRIPTION_IDENTIFIER, 19) subscribe2u_packet = mosq_test.gen_subscribe(mid, "02/subpub/subid/+/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.SUBSCRIPTION_IDENTIFIER, 21) subscribe3u_packet = mosq_test.gen_subscribe(mid, "02/subpub/subid/noid", 0, proto_ver=5, properties=props) suback3u_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish1_packet = mosq_test.gen_publish("02/subpub/subid/id1", qos=0, payload="message1", proto_ver=5) props = mqtt5_props.gen_varint_prop(mqtt5_props.SUBSCRIPTION_IDENTIFIER, 1) publish1r_packet = mosq_test.gen_publish("02/subpub/subid/id1", qos=0, payload="message1", proto_ver=5, properties=props) publish2_packet = mosq_test.gen_publish("02/subpub/subid/test/id2", qos=0, payload="message2", proto_ver=5) props = mqtt5_props.gen_varint_prop(mqtt5_props.SUBSCRIPTION_IDENTIFIER, 14) publish2r_packet = mosq_test.gen_publish("02/subpub/subid/test/id2", qos=0, payload="message2", proto_ver=5, properties=props) publish3_packet = mosq_test.gen_publish("02/subpub/subid/noid", qos=0, payload="message3", proto_ver=5) # Updated version of publish1r, now with no id publish1ru_packet = mosq_test.gen_publish("02/subpub/subid/id1", qos=0, payload="message1", proto_ver=5) # Updated verison of publish2r, with updated id props = mqtt5_props.gen_varint_prop(mqtt5_props.SUBSCRIPTION_IDENTIFIER, 19) publish2ru_packet = mosq_test.gen_publish("02/subpub/subid/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.SUBSCRIPTION_IDENTIFIER, 21) publish3ru_packet = mosq_test.gen_publish("02/subpub/subid/noid", qos=0, payload="message3", proto_ver=5, properties=props) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker, proto_ver=5) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-qos0-topic-alias-unknown.py ================================================ #!/usr/bin/env python3 # Test whether "topic alias" works to the broker # MQTT v5 from mosq_test_helper import * def do_test(start_broker): rc = 1 connect_packet = mosq_test.gen_connect("02-subpub-alias-unknown", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.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.PROTOCOL_ERROR, proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-qos0-topic-alias.py ================================================ #!/usr/bin/env python3 # Test whether "topic alias" works to the broker # MQTT v5 from mosq_test_helper import * def do_test(start_broker): rc = 1 connect1_packet = mosq_test.gen_connect("02-subpub-qos0-topic-alias", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect2_packet = mosq_test.gen_connect("02-subpub-qos0-topic-alias-helper", proto_ver=5) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "02/subpub/topic-alias/alias", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS, 3) publish1_packet = mosq_test.gen_publish("02/subpub/topic-alias/alias", qos=0, payload="message", proto_ver=5, properties=props) props = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS, 3) publish2s_packet = mosq_test.gen_publish("", qos=0, payload="message", proto_ver=5, properties=props) publish2r_packet = mosq_test.gen_publish("02/subpub/topic-alias/alias", qos=0, payload="message", proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-qos1-message-expiry-retain.py ================================================ #!/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(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("subpub", 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, "subpub/expired", 1, proto_ver=proto_ver) suback1_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) mid = 2 subscribe2_packet = mosq_test.gen_subscribe(mid, "subpub/kept", 1, proto_ver=proto_ver) suback2_packet = mosq_test.gen_suback(mid, 1, proto_ver=proto_ver) helper_connect = mosq_test.gen_connect("helper", proto_ver=proto_ver) helper_connack = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid=1 props = mqtt5_props.gen_uint32_prop(mqtt5_props.MESSAGE_EXPIRY_INTERVAL, 2) publish1_packet = mosq_test.gen_publish("subpub/expired", mid=mid, qos=1, retain=True, payload="message1", proto_ver=proto_ver, properties=props) puback1_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver, reason_code=mqtt5_rc.NO_MATCHING_SUBSCRIBERS) mid=2 publish2s_packet = mosq_test.gen_publish("subpub/kept", mid=mid, qos=1, retain=True, payload="message2", proto_ver=proto_ver) puback2s_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver, reason_code=mqtt5_rc.NO_MATCHING_SUBSCRIBERS) mid=1 publish2r_packet = mosq_test.gen_publish("subpub/kept", mid=mid, qos=1, retain=True, payload="message2", proto_ver=proto_ver) puback2r_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver, reason_code=mqtt5_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(3) 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/02-subpub-qos1-message-expiry-will.py ================================================ #!/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(proto_ver): rc = 1 mid = 53 keepalive = 60 props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 60) connect_packet = mosq_test.gen_connect("subpub-qos1-test", keepalive=keepalive, proto_ver=proto_ver, clean_session=False, properties=props) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver, flags=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) props = mqtt5_props.gen_uint32_prop(mqtt5_props.MESSAGE_EXPIRY_INTERVAL, 10) helper_connect = mosq_test.gen_connect("helper", proto_ver=proto_ver, 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=proto_ver) #mid=2 props = mqtt5_props.gen_uint32_prop(mqtt5_props.MESSAGE_EXPIRY_INTERVAL, 10) publish2s_packet = mosq_test.gen_publish("subpub/qos1", mid=mid, qos=1, payload="message2", proto_ver=proto_ver, 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.MESSAGE_EXPIRY_INTERVAL, i) publish2r_packet = mosq_test.gen_publish("subpub/qos1", mid=1, qos=1, payload="message", proto_ver=proto_ver, properties=props) if packet == publish2r_packet: rc = 0 break sock.close() except mosq_test.TestError: pass finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/02-subpub-qos1-message-expiry.py ================================================ #!/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(proto_ver): rc = 1 mid = 53 keepalive = 60 props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 60) connect_packet = mosq_test.gen_connect("subpub-qos0-test", keepalive=keepalive, proto_ver=proto_ver, clean_session=False, properties=props) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver, flags=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) helper_connect = mosq_test.gen_connect("helper", proto_ver=proto_ver) helper_connack = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid=1 props = mqtt5_props.gen_uint32_prop(mqtt5_props.MESSAGE_EXPIRY_INTERVAL, 1) publish1s_packet = mosq_test.gen_publish("subpub/qos1", mid=mid, qos=1, payload="message1", proto_ver=proto_ver, properties=props) puback1s_packet = mosq_test.gen_puback(mid) mid=2 props = mqtt5_props.gen_uint32_prop(mqtt5_props.MESSAGE_EXPIRY_INTERVAL, 10) publish2s_packet = mosq_test.gen_publish("subpub/qos1", mid=mid, qos=1, payload="message2", proto_ver=proto_ver, 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.MESSAGE_EXPIRY_INTERVAL, i) publish2r_packet = mosq_test.gen_publish("subpub/qos1", mid=2, qos=1, payload="message2", proto_ver=proto_ver, properties=props) if packet == publish2r_packet: rc = 0 break sock.close() except mosq_test.TestError: pass finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/02-subpub-qos1-nolocal.py ================================================ #!/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(start_broker): rc = 1 connect_packet = mosq_test.gen_connect("02-subpub-qos1-nolocal", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 530 subscribe_packet = mosq_test.gen_subscribe(mid, "02/subpub/qos1/nolocal/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, "02/subpub/qos1/nolocal/receive", 1, proto_ver=5) suback2_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 300 publish_packet = mosq_test.gen_publish("02/subpub/qos1/nolocal/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("02/subpub/qos1/nolocal/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("02/subpub/qos1/nolocal/receive", qos=1, mid=mid, payload="success", proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-qos1-oversize-payload.py ================================================ #!/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 connect_packet = mosq_test.gen_connect("subpub-qos1-oversize", 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/oversize", 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-oversize-helper", 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/oversize", 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/oversize", 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.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/02-subpub-qos1.py ================================================ #!/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(start_broker, proto_ver): rc = 1 mid = 530 connect_packet = mosq_test.gen_connect("subpub-qos1-test", 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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-qos2-1322.py ================================================ #!/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(start_broker, proto_ver): rc = 1 pub_connect_packet = mosq_test.gen_connect("02-subpub-qos2-1322-pub", 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) pub_connect_packet_clear = mosq_test.gen_connect("02-subpub-qos2-1322-pub", proto_ver=proto_ver) sub1_connect_packet = mosq_test.gen_connect("02-subpub-qos2-1322-sub1", proto_ver=proto_ver) sub1_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) sub2_connect_packet = mosq_test.gen_connect("02-subpub-qos2-1322-sub2", 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, "02/subpub/qos2/1322/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, "02/subpub/qos2/1322/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("02/subpub/qos2/1322/topic1", qos=2, mid=mid, payload="message1", proto_ver=proto_ver) publish2s_packet = mosq_test.gen_publish("02/subpub/qos2/1322/topic2", qos=2, mid=mid, payload="message2", proto_ver=proto_ver) publish3s_packet = mosq_test.gen_publish("02/subpub/qos2/1322/topic1", qos=2, mid=mid, payload="message3", proto_ver=proto_ver) publish4s_packet = mosq_test.gen_publish("02/subpub/qos2/1322/topic1", qos=2, mid=mid, payload="message4", proto_ver=proto_ver) publish5s_packet = mosq_test.gen_publish("02/subpub/qos2/1322/topic1", qos=2, mid=mid, payload="message5", proto_ver=proto_ver) publish1r_packet = mosq_test.gen_publish("02/subpub/qos2/1322/topic1", qos=0, payload="message1", proto_ver=proto_ver) publish2r_packet = mosq_test.gen_publish("02/subpub/qos2/1322/topic2", qos=0, payload="message2", proto_ver=proto_ver) publish3r_packet = mosq_test.gen_publish("02/subpub/qos2/1322/topic1", qos=0, payload="message3", proto_ver=proto_ver) publish4r_packet = mosq_test.gen_publish("02/subpub/qos2/1322/topic1", qos=0, payload="message4", proto_ver=proto_ver) publish5r_packet = mosq_test.gen_publish("02/subpub/qos2/1322/topic1", qos=0, payload="message5", proto_ver=proto_ver) port = mosq_test.get_port() if start_broker: 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() # Clear session pub = mosq_test.do_client_connect(pub_connect_packet_clear, pub_connack1_packet, timeout=10, port=port) pub.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-qos2-max-inflight-bytes.py ================================================ #!/usr/bin/env python3 # Does the broker respect max_inflight_bytes? # Also check whether the send quota is dealt with properly when both # RECEIVE-MAXIMUM and max_inflight_bytes are set. # MQTT v5 from mosq_test_helper import * def helper(port): rc = 1 connect_packet = mosq_test.gen_connect("subpub-qos2-recv-max1-helper", 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) 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") sock.close() 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_bytes 16\n") def send_small(port): rc = 1 connect_packet = mosq_test.gen_connect("subpub-qos2-test-helper") connack_packet = mosq_test.gen_connack(rc=0) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) for i in range(0, 10): mid = 1+i publish_packet = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload=str(i+1)) pubrec_packet = mosq_test.gen_pubrec(mid) pubrel_packet = mosq_test.gen_pubrel(mid) pubcomp_packet = mosq_test.gen_pubcomp(mid) mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") def do_test(proto_ver): if proto_ver == 4: exit(0) rc = 1 props = mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 5) connect_packet = mosq_test.gen_connect("subpub-qos2-test", 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) 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__), port=port, use_conf=True) 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") # Repeat many times to stress the send quota mid = 0 for i in range(0, 12): helper(port) #pub = subprocess.Popen(['./02-subpub-qos2-receive-maximum-helper.py', str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) #if mosq_test.wait_for_subprocess(pub): # print("pub not terminated") # if rc == 0: rc=1 #(stdo, stde) = pub.communicate() 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 += 1 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 += 1 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) 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) # send messages where count will exceed max_inflight_messages, but the # payload bytes won't exceed max_inflight_bytes send_small(port) mid += 1 publish_packet1 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="1", 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 += 1 publish_packet2 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="2", 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 += 1 publish_packet3 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="3", 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) mid += 1 publish_packet4 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="4", proto_ver=5) pubrec_packet4 = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet4 = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet4 = mosq_test.gen_pubcomp(mid, proto_ver=5) mid += 1 publish_packet5 = mosq_test.gen_publish("subpub/qos2", qos=2, mid=mid, payload="5", proto_ver=5) pubrec_packet5 = mosq_test.gen_pubrec(mid, proto_ver=5) pubrel_packet5 = mosq_test.gen_pubrel(mid, proto_ver=5) pubcomp_packet5 = mosq_test.gen_pubcomp(mid, proto_ver=5) mosq_test.expect_packet(sock, "publish1s", publish_packet1) mosq_test.expect_packet(sock, "publish2s", publish_packet2) mosq_test.expect_packet(sock, "publish3s", publish_packet3) mosq_test.expect_packet(sock, "publish4s", publish_packet4) mosq_test.expect_packet(sock, "publish5s", publish_packet5) mosq_test.do_send_receive(sock, pubrec_packet1, pubrel_packet1, "pubrel1s") mosq_test.do_send_receive(sock, pubrec_packet2, pubrel_packet2, "pubrel2s") mosq_test.do_send_receive(sock, pubrec_packet3, pubrel_packet3, "pubrel3s") mosq_test.do_send_receive(sock, pubrec_packet4, pubrel_packet4, "pubrel4s") mosq_test.do_send_receive(sock, pubrec_packet5, pubrel_packet5, "pubrel5s") rc = 0 sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/02-subpub-qos2-pubrec-error.py ================================================ #!/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("helper") 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(proto_ver): rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("pub-qo2-timeout-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/pubrec/+", 2, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 1 publish_1_packet = mosq_test.gen_publish("qos2/pubrec/rejected", qos=2, mid=mid, payload="rejected-message", proto_ver=proto_ver) pubrec_1_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver, reason_code=0x80) mid = 2 publish_2_packet = mosq_test.gen_publish("qos2/pubrec/accepted", qos=2, mid=mid, payload="accepted-message", proto_ver=proto_ver) pubrec_2_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) pubrel_2_packet = mosq_test.gen_pubrel(mid, proto_ver=proto_ver) pubcomp_2_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, 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/02-subpub-qos2-receive-maximum-1.py ================================================ #!/usr/bin/env python3 # Does the broker respect receive maximum==1? # MQTT v5 from mosq_test_helper import * def helper(port): rc = 1 connect_packet = mosq_test.gen_connect("subpub-qos2-recv-max1-helper", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 publish_packet = mosq_test.gen_publish("subpub/qos2/receive/maximum1", 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/receive/maximum1", 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/receive/maximum1", 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) 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") sock.close() def do_test(start_broker): rc = 1 props = mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 1) connect_packet = mosq_test.gen_connect("subpub-qos2-receive-max1", 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/receive/maximum1", 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/receive/maximum1", 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/receive/maximum1", 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/receive/maximum1", 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() if start_broker: 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) 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-qos2-receive-maximum-2.py ================================================ #!/usr/bin/env python3 # Does the broker respect receive maximum==2? # MQTT v5 from mosq_test_helper import * def helper(port): rc = 1 connect_packet = mosq_test.gen_connect("subpub-qos2-recv-max2-helper", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 publish_packet = mosq_test.gen_publish("subpub/qos2/receive/maximum2", 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/receive/maximum2", 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/receive/maximum2", 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) 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") sock.close() def do_test(start_broker, proto_ver): if proto_ver == 4: exit(0) rc = 1 props = mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 2) connect_packet = mosq_test.gen_connect("subpub-qos2-recv-max2", 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/receive/maximum2", 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/receive/maximum2", 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/receive/maximum2", 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/receive/maximum2", 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() if start_broker: 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) 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker, proto_ver=5) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-qos2.py ================================================ #!/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(start_broker, proto_ver): rc = 1 mid = 530 connect_packet = mosq_test.gen_connect("subpub-qos2-test", 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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subpub-recover-subscriptions.py ================================================ #!/usr/bin/env python3 # Check whether a durable client keeps its subscriptions on reconnecting. from mosq_test_helper import * def publish_helper(port): connect_packet = mosq_test.gen_connect("subpub-sub-helper") connack_packet = mosq_test.gen_connack(rc=0) publish1_packet = mosq_test.gen_publish("not-shared/sub", qos=0, payload="message1") publish2_packet = mosq_test.gen_publish("shared/sub", qos=0, payload="message2") sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) sock.send(publish1_packet) sock.send(publish2_packet) sock.close() def do_test(proto_ver): rc = 1 if proto_ver == 5: props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 60) connect_packet = mosq_test.gen_connect("subpub-sub-test", proto_ver=proto_ver, clean_session=False, properties=props) else: connect_packet = mosq_test.gen_connect("subpub-sub-test", proto_ver=proto_ver, clean_session=False) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver, flags=1) mid = 1 subscribe1_packet = mosq_test.gen_subscribe(mid, "not-shared/sub", 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/name/shared/sub", 0, proto_ver=proto_ver) suback2_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) publish1_packet = mosq_test.gen_publish("not-shared/sub", qos=0, payload="message1", proto_ver=proto_ver) publish2_packet = mosq_test.gen_publish("shared/sub", qos=0, payload="message2", 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, timeout=2, port=port, connack_error="connack 1") mosq_test.do_send_receive(sock, subscribe1_packet, suback1_packet, "suback1") mosq_test.do_send_receive(sock, subscribe2_packet, suback2_packet, "suback2") publish_helper(port) mosq_test.expect_packet(sock, "publish1", publish1_packet) if proto_ver == 5: mosq_test.expect_packet(sock, "publish2", publish2_packet) sock.close() # Reconnect, but don't resubscribe sock = mosq_test.do_client_connect(connect_packet, connack2_packet, timeout=2, port=port, connack_error="connack 2") publish_helper(port) mosq_test.expect_packet(sock, "publish1", publish1_packet) if proto_ver == 5: mosq_test.expect_packet(sock, "publish2", publish2_packet) sock.close() rc = 0 sock.close() except mosq_test.TestError: pass except Exception as err: print(err) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(proto_ver=4) do_test(proto_ver=5) exit(0) ================================================ FILE: test/broker/02-subscribe-dollar-v5.py ================================================ #!/usr/bin/env python3 # Test whether a SUBSCRIBE to $SYS or $share succeeds from mosq_test_helper import * def do_test(start_broker, proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("subscribe-test", 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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/02-subscribe-invalid-utf8.py ================================================ #!/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(start_broker, proto_ver): rc = 1 mid = 53 connect_packet = mosq_test.gen_connect("subscribe-invalid-utf8", 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) port = mosq_test.get_port() broker = None if start_broker: 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: try: mosq_test.do_send_receive(sock, subscribe_packet, b"", "suback") except BrokenPipeError: rc = 0 else: disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code = mqtt5_rc.MALFORMED_PACKET) mosq_test.do_send_receive(sock, subscribe_packet, disconnect_packet, "suback") rc = 0 sock.close() finally: if broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc rc = do_test(start_broker, proto_ver=5) if rc: return rc return 0 if __name__ == '__main__': sys.exit(all_tests(True)) ================================================ FILE: test/broker/02-subscribe-long-topic.py ================================================ #!/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(start_broker, proto_ver): rc = 1 mid = 1 connect_packet = mosq_test.gen_connect("subscribe-long-test", 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) port = mosq_test.get_port() broker = None if start_broker: 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: try: mosq_test.do_send_receive(sock, subscribe_packet, b"", "suback") except BrokenPipeError: rc = 0 else: disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code = mqtt5_rc.MALFORMED_PACKET) mosq_test.do_send_receive(sock, subscribe_packet, disconnect_packet, "suback") rc = 0 sock.close() finally: if broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc rc = do_test(start_broker, proto_ver=5) if rc: return rc return 0 if __name__ == '__main__': sys.exit(all_tests(True)) ================================================ FILE: test/broker/02-subscribe-persistence-flipflop.py ================================================ #!/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(start_broker, proto_ver): rc = 1 connect_packet_sub_persistent = mosq_test.gen_connect("flipflop-test", clean_session=False, proto_ver=proto_ver) connect_packet_sub_clean = mosq_test.gen_connect("flipflop-test", 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", 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() if start_broker: 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() sub_sock = mosq_test.do_client_connect(connect_packet_sub_clean, connack_packet_sub, port=port) sub_sock.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/03-pattern-matching.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def helper(port, pub_topic): connect_packet = mosq_test.gen_connect("test-helper") 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 connect_packet = mosq_test.gen_connect("pattern-sub-test") 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/03-publish-b2c-disconnect-qos1.py ================================================ #!/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("03-b2c-disco-qos1-helper") connack_packet = mosq_test.gen_connack(rc=0) mid = 128 publish_packet = mosq_test.gen_publish("03/b2c/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(start_broker, proto_ver): port = mosq_test.get_port() rc = 1 mid = 3265 connect_packet = mosq_test.gen_connect("03-b2c-disco-qos1", 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) connect_packet_clear = mosq_test.gen_connect("03-b2c-disco-qos1", proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "03/b2c/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("03/b2c/qos1/disconnect/test", qos=1, mid=mid, payload="disconnect-message", proto_ver=proto_ver) publish_dup_packet = mosq_test.gen_publish("03/b2c/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("03/b2c/qos1/outgoing", qos=1, mid=mid, payload="outgoing-message", proto_ver=proto_ver) puback2_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) if start_broker: 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) sock.send(puback_packet) rc = 0 sock.close() # clear session sock = mosq_test.do_client_connect(connect_packet_clear, connack1_packet, port=port) sock.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/03-publish-b2c-disconnect-qos2.py ================================================ #!/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("03-bc2-disco-qos2-helper") connack_packet = mosq_test.gen_connack(rc=0) mid = 312 publish_packet = mosq_test.gen_publish("03/b2c/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(start_broker, proto_ver): rc = 1 mid = 3265 connect_packet = mosq_test.gen_connect("03-b2c-disco-qos2-test", 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) connect_packet_clear = mosq_test.gen_connect("03-b2c-disco-qos2-test", proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "03/b2c/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("03/b2c/qos2/disconnect/test", qos=2, mid=mid, payload="disconnect-message", proto_ver=proto_ver) publish_dup_packet = mosq_test.gen_publish("03/b2c/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("03/b2c/qos2/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() if start_broker: 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() # Clear session sock = mosq_test.do_client_connect(connect_packet_clear, connack1_packet, port=port) sock.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/03-publish-b2c-qos1-len.py ================================================ #!/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("03-b2c-qos1-len-helper") connack_packet = mosq_test.gen_connack(rc=0) mid = 1 publish_packet = mosq_test.gen_publish("03/b2c/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 do_test(start_broker, test, puback_packet): rc = 1 mid = 3265 connect_packet = mosq_test.gen_connect("03-b2c-qos1-len", 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, "03/b2c/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("03/b2c/qos1/len/test", qos=1, mid=mid, payload="len-message", proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print(test) exit(rc) else: return rc def all_tests(start_broker=False): # No reason code, no properties puback_packet = mosq_test.gen_puback(1) rc = do_test(start_broker, "qos1 len 2", puback_packet) if rc: return rc # Reason code, no properties puback_packet = mosq_test.gen_puback(1, proto_ver=5, reason_code=0x00) rc = do_test(start_broker, "qos1 len 3", puback_packet) if rc: return rc # Reason code, empty properties puback_packet = mosq_test.gen_puback(1, proto_ver=5, reason_code=0x00, properties="") rc = do_test(start_broker, "qos1 len 4", puback_packet) if rc: return rc # Reason code, one property props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key", "value") puback_packet = mosq_test.gen_puback(1, proto_ver=5, reason_code=0x00, properties=props) rc = do_test(start_broker, "qos1 len >5", puback_packet) if rc: return rc return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/03-publish-b2c-qos2-len.py ================================================ #!/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("03-b2c-qos2-len-helper") connack_packet = mosq_test.gen_connack(rc=0) mid = 1 publish_packet = mosq_test.gen_publish("03/b2c/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 do_test(start_broker, test, pubrec_packet, pubcomp_packet): rc = 1 mid = 3265 connect_packet = mosq_test.gen_connect("03-b2c-qos2-len-test", 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, "03/b2c/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("03/b2c/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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print(test) exit(rc) else: return rc def all_tests(start_broker=False): # No reason code, no properties pubrec_packet = mosq_test.gen_pubrec(1) pubcomp_packet = mosq_test.gen_pubcomp(1) rc = do_test(start_broker, "qos2 len 2", pubrec_packet, pubcomp_packet) if rc: return rc # 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) rc = do_test(start_broker, "qos2 len 3", pubrec_packet, pubcomp_packet) if rc: return rc # 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="") rc = do_test(start_broker, "qos2 len 4", pubrec_packet, pubcomp_packet) if rc: return rc # Reason code, one property props = mqtt5_props.gen_string_pair_prop(mqtt5_props.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.USER_PROPERTY, "key", "value") pubcomp_packet = mosq_test.gen_pubcomp(1, proto_ver=5, reason_code=0x00, properties=props) rc = do_test(start_broker, "qos2 len >5", pubrec_packet, pubcomp_packet) if rc: return rc return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/03-publish-bad-flags.py ================================================ #!/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 connect_packet = mosq_test.gen_connect("13-malformed-publish-v5", proto_ver=5) connack_props = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) connack_props += mqtt5_props.gen_byte_prop(mqtt5_props.RETAIN_AVAILABLE, 0) connack_props += mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 2000000) connack_props += mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) connack_props += mqtt5_props.gen_byte_prop(mqtt5_props.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: # 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.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.RETAIN_NOT_SUPPORTED, "retain not supported") except mosq_test.TestError: pass finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() os.remove(conf_file) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/03-publish-c2b-disconnect-qos2.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(start_broker, proto_ver): rc = 1 mid = 3265 connect_packet = mosq_test.gen_connect("03-c2b-qos2-disco-test", clean_session=False, proto_ver=proto_ver, session_expiry=60) connack1_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=proto_ver) connect_packet_clear = mosq_test.gen_connect("03-c2b-qos2-disco-test", 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("03-c2b-qos2-disco-helper", 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, "03/c2b/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("03/c2b/qos2/disconnect/test", qos=2, mid=mid, payload="disconnect-message", proto_ver=proto_ver) publish_dup_packet = mosq_test.gen_publish("03/c2b/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() if start_broker: 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() # Clear session sock = mosq_test.do_client_connect(connect_packet_clear, connack1_packet, port=port, connack_error="connack clear") sock.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=3) if rc: return rc; rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/03-publish-c2b-qos2-len.py ================================================ #!/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 do_test(start_broker, test, pubrel_packet): rc = 1 mid = 3265 connect_packet = mosq_test.gen_connect("03-c2b-qos2-len", 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("03/c2b/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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print(test) exit(rc) else: return rc def all_tests(start_broker=False): # No reason code, no properties pubrel_packet = mosq_test.gen_pubrel(1) rc = do_test(start_broker, "qos2 len 2", pubrel_packet) if rc: return rc # Reason code, no properties pubrel_packet = mosq_test.gen_pubrel(1, proto_ver=5, reason_code=0x00) rc = do_test(start_broker, "qos2 len 3", pubrel_packet) if rc: return rc # Reason code, empty properties pubrel_packet = mosq_test.gen_pubrel(1, proto_ver=5, reason_code=0x00, properties="") rc = do_test(start_broker, "qos2 len 4", pubrel_packet) if rc: return rc # Reason code, one property props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key", "value") pubrel_packet = mosq_test.gen_pubrel(1, proto_ver=5, reason_code=0x00, properties=props) rc = do_test(start_broker, "qos2 len >5", pubrel_packet) if rc: return rc return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/03-publish-dollar-v5.py ================================================ #!/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(port, topic, reason_code): global mid connect_packet = mosq_test.gen_connect("03-publish-dollar-v5", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) 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)) mid += 1 def do_test(start_broker): rc = 1 port = mosq_test.get_port() if start_broker: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: helper(port, "$SYS/broker/uptime", mqtt5_rc.NOT_AUTHORIZED) helper(port, "$SYS/broker/connection/me", mqtt5_rc.NOT_AUTHORIZED) helper(port, "$SYS/broker/connection/me/state", mqtt5_rc.NO_MATCHING_SUBSCRIBERS) helper(port, "$share/share/03/publish/dollar/v5/topic", mqtt5_rc.NOT_AUTHORIZED) rc = 0 except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/03-publish-dollar.py ================================================ #!/usr/bin/env python3 # Test whether a PUBLISH to a topic starting with $ succeeds from mosq_test_helper import * def do_test(start_broker): rc = 1 mid = 19 connect_packet = mosq_test.gen_connect("pub-dollar-test") 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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/03-publish-invalid-utf8.py ================================================ #!/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(start_broker, proto_ver): rc = 1 mid = 53 connect_packet = mosq_test.gen_connect("03-publish-invalid-utf8", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("03/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) port = mosq_test.get_port() broker = None if start_broker: 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: try: mosq_test.do_send_receive(sock, publish_packet, b"", "puback") except BrokenPipeError: rc = 0 else: disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=mqtt5_rc.MALFORMED_PACKET) mosq_test.do_send_receive(sock, publish_packet, disconnect_packet, "puback") rc = 0 sock.close() finally: if broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc rc = do_test(start_broker, proto_ver=5) if rc: return rc return 0 if __name__ == '__main__': sys.exit(all_tests(True)) ================================================ FILE: test/broker/03-publish-long-topic.py ================================================ #!/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(start_broker, proto_ver): rc = 1 mid = 19 connect_packet = mosq_test.gen_connect("03-pub-long-test", 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) port = mosq_test.get_port() broker = None if start_broker: 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: try: mosq_test.do_send_receive(sock, publish_packet, b"", "puback") except BrokenPipeError: rc = 0 else: disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, reason_code=mqtt5_rc.MALFORMED_PACKET) mosq_test.do_send_receive(sock, publish_packet, disconnect_packet, "puback") rc = 0 sock.close() finally: if broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc rc = do_test(start_broker, proto_ver=5) if rc: return rc return 0 if __name__ == '__main__': sys.exit(all_tests(True)) ================================================ FILE: test/broker/03-publish-qos1-max-inflight-expire.py ================================================ #!/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("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("max_inflight_messages 1\n") def do_test(proto_ver): rc = 1 properties = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 1000) sub_connect_packet = mosq_test.gen_connect("sub", properties=properties, proto_ver=proto_ver, clean_session=False) properties = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) \ + mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 2000000) \ + mqtt5_props.gen_uint16_prop(mqtt5_props.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", proto_ver=proto_ver) properties = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) \ + mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 2000000) \ + mqtt5_props.gen_uint16_prop(mqtt5_props.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.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/03-publish-qos1-max-inflight.py ================================================ #!/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("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("max_inflight_messages 1\n") def do_test(proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("pub-qos1-test", proto_ver=proto_ver) properties = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) \ + mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 2000000) \ + mqtt5_props.gen_uint16_prop(mqtt5_props.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.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/03-publish-qos1-no-subscribers-v5.py ================================================ #!/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 * def do_test(start_broker): rc = 1 connect_packet = mosq_test.gen_connect("03-pub-qos1-no-subs", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 publish1_packet = mosq_test.gen_publish("03B/no/subs/pub", qos=1, mid=mid, payload="message", proto_ver=5) puback1_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.NO_MATCHING_SUBSCRIBERS) mid = 2 publish2_packet = mosq_test.gen_publish("03B/no/subs/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.NO_MATCHING_SUBSCRIBERS) mid = 3 publish3_packet = mosq_test.gen_publish("03B/no/subs/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.NO_MATCHING_SUBSCRIBERS) mid = 4 publish4_packet = mosq_test.gen_publish("03B/no/subs/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.NO_MATCHING_SUBSCRIBERS) mid = 5 publish1b_packet = mosq_test.gen_publish("03B/no/subs/pub", qos=1, mid=mid, payload="message", proto_ver=5) puback1b_packet = mosq_test.gen_puback(mid, proto_ver=5, reason_code=mqtt5_rc.NO_MATCHING_SUBSCRIBERS) mid = 6 publish2b_packet = mosq_test.gen_publish("03B/no/subs/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.NO_MATCHING_SUBSCRIBERS) mid = 7 publish3b_packet = mosq_test.gen_publish("03B/no/subs/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.NO_MATCHING_SUBSCRIBERS) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/03-publish-qos1-queued-bytes.conf ================================================ sys_interval 1 max_queued_messages 0 max_queued_bytes 400 port 1888 ================================================ FILE: test/broker/03-publish-qos1-queued-bytes.py ================================================ #!/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) ================================================ FILE: test/broker/03-publish-qos1-retain-disabled.py ================================================ #!/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 connect_packet = mosq_test.gen_connect("pub-qos1-test", proto_ver=5) props = mqtt5_props.gen_byte_prop(mqtt5_props.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/03-publish-qos1.py ================================================ #!/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(start_broker, proto_ver): rc = 1 mid = 19 connect_packet = mosq_test.gen_connect("03-pub-qos1-test", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("03/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.NO_MATCHING_SUBSCRIBERS) else: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/03-publish-qos2-dup.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("03-pub-qos2-dup-test", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 publish_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="message", proto_ver=proto_ver, dup=1) pubrec_packet = mosq_test.gen_pubrec(mid, proto_ver=proto_ver) disconnect_packet = mosq_test.gen_disconnect(reason_code=130, 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 1") mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec 2") if proto_ver == 5: mosq_test.do_send_receive(sock, publish_packet, disconnect_packet, "disconnect") rc = 0 else: try: mosq_test.do_send_receive(sock, publish_packet, b"", "disconnect1") rc = 0 except BrokenPipeError: rc = 0 sock.close() except Exception as e: print(e) 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) def all_tests(): rc = do_test(proto_ver=4) if rc: return rc; rc = do_test(proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests() ================================================ FILE: test/broker/03-publish-qos2-max-inflight-exceeded.py ================================================ #!/usr/bin/env python3 # What does the broker do if an MQTT v5 client doesn't respect max_inflight_messages? from mosq_test_helper import * def do_test(proto_ver): port = mosq_test.get_port() rc = 1 connect_packet = mosq_test.gen_connect("pub-qos2-inflight-exceeded", 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__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port, timeout=10) for i in range(1, 21): publish_packet = mosq_test.gen_publish("pub/qos2/max/inflight/exceeded", qos=2, mid=i, payload="message", proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid=i, proto_ver=proto_ver) mosq_test.do_send_receive(sock, publish_packet, pubrec_packet) i = 21 publish_packet = mosq_test.gen_publish("pub/qos2/max/inflight/exceeded", qos=2, mid=i, payload="message", proto_ver=proto_ver) if proto_ver == 5: disconnect_packet = mosq_test.gen_disconnect(reason_code=mqtt5_rc.RECEIVE_MAXIMUM_EXCEEDED, proto_ver=proto_ver) else: disconnect_packet = b"" try: mosq_test.do_send_receive(sock, publish_packet, disconnect_packet, "disconnect") except BrokenPipeError: pass rc = 0 sock.close() finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) return rc def all_test(): rc = do_test(proto_ver=4) if rc: return rc rc = do_test(proto_ver=5) return rc if __name__ == "__main__": sys.exit(all_test()) ================================================ FILE: test/broker/03-publish-qos2-max-inflight.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("pub-qos2-test", proto_ver=proto_ver) properties = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) \ + mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 2000000) \ + mqtt5_props.gen_uint16_prop(mqtt5_props.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/03-publish-qos2-reuse-mid.py ================================================ #!/usr/bin/env python3 # Test what happens if a client reuses an in-use mid with a different message. from mosq_test_helper import * def do_test(proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("pub-qos2-test", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 312 publish_packet1 = 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) mid = 312 publish_packet2 = mosq_test.gen_publish("pub/qos2/reuse", qos=2, mid=mid, payload="message", proto_ver=proto_ver) sub_connect_packet = mosq_test.gen_connect("sub-qos2-test", proto_ver=proto_ver) sub_connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 2, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 1 publish_packet_expected = mosq_test.gen_publish("pub/qos2/reuse", qos=2, 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: ssock = mosq_test.do_client_connect(sub_connect_packet, sub_connack_packet, port=port) mosq_test.do_send_receive(ssock, subscribe_packet, suback_packet, "suback") sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, publish_packet1, pubrec_packet, "pubrec1") mosq_test.do_send_receive(sock, publish_packet2, pubrec_packet, "pubrec2") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") mosq_test.expect_packet(ssock, "publish", publish_packet_expected) rc = 0 sock.close() except mosq_test.TestError: pass finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/03-publish-qos2.py ================================================ #!/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(start_broker, proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("03-pub-qos2-test", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 312 publish_packet = mosq_test.gen_publish("03/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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/04-retain-check-source-persist-diff-port.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("retain-check", 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", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 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") ================================================ FILE: test/broker/04-retain-check-source-persist.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("retain-check", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 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") ================================================ FILE: test/broker/04-retain-check-source.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("retain-check", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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") ================================================ FILE: test/broker/04-retain-clear-multiple.py ================================================ #!/usr/bin/env python3 # Exercise multi-level retain clearing from mosq_test_helper import * def send_retain(port, topic, payload): connect_packet = mosq_test.gen_connect("retain-clear-test") connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish(topic, qos=1, mid=1, payload=payload, retain=True) puback_packet = mosq_test.gen_puback(mid=1) sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=4, port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, f"set retain {topic}") sock.close() def do_test(): rc = 1 connect_packet = mosq_test.gen_connect("retain-clear-test") connack_packet = mosq_test.gen_connack(rc=0) subscribe_packet = mosq_test.gen_subscribe(1, "#", 0) suback_packet = mosq_test.gen_suback(1, 0) retain1_packet = mosq_test.gen_publish("1/2/3/4/5/6/7", qos=0, payload="retained message", retain=True) retain2_packet = mosq_test.gen_publish("1/2/3/4", qos=0, payload="retained message", retain=True) retain3_packet = mosq_test.gen_publish("1", qos=0, payload="retained message", retain=True) port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: send_retain(port, "1/2/3/4/5/6/7", "retained message") send_retain(port, "1/2/3/4", "retained message") send_retain(port, "1", "retained message") sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.expect_packet(sock, "retain3", retain3_packet) mosq_test.expect_packet(sock, "retain2", retain2_packet) mosq_test.expect_packet(sock, "retain1", retain1_packet) sock.close() send_retain(port, "1/2/3/4", None) 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.expect_packet(sock, "retain3", retain3_packet) mosq_test.expect_packet(sock, "retain1", retain1_packet) sock.close() send_retain(port, "1/2/3/4/5/6/7", None) 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.expect_packet(sock, "retain3", retain3_packet) sock.close() send_retain(port, "1", None) 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_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')) exit(rc) do_test() exit(0) ================================================ FILE: test/broker/04-retain-qos0-clear.py ================================================ #!/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(start_broker, proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("retain-qos0-clear-test", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("retain/qos0/clear/test", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) retain_clear_packet = mosq_test.gen_publish("retain/qos0/clear/test", qos=0, payload=None, retain=True, proto_ver=proto_ver) mid_sub = 592 subscribe_packet = mosq_test.gen_subscribe(mid_sub, "retain/qos0/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/qos0/clear/test", proto_ver=proto_ver) unsuback_packet = mosq_test.gen_unsuback(mid_unsub, proto_ver=proto_ver) port = mosq_test.get_port() if start_broker: 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") # 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/04-retain-qos0-fresh.py ================================================ #!/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(start_broker, proto_ver): rc = 1 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-fresh", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("retain/qos0/fresh", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) publish_fresh_packet = mosq_test.gen_publish("retain/qos0/fresh", qos=0, payload="retained message", proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos0/fresh", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) publish_packet_clear = mosq_test.gen_publish("retain/qos0/fresh", qos=0, payload=None, retain=True, proto_ver=proto_ver) port = mosq_test.get_port() if start_broker: 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") sock.send(publish_packet_clear) rc = 0 sock.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/04-retain-qos0-repeated.py ================================================ #!/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(start_broker, proto_ver): rc = 1 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-rep-test", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("retain/qos0/repeated", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid, "retain/qos0/repeated", 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/repeated", proto_ver=proto_ver) unsuback_packet = mosq_test.gen_unsuback(unsub_mid, proto_ver=proto_ver) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/04-retain-qos0.py ================================================ #!/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(start_broker, proto_ver): rc = 1 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-test", 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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/04-retain-qos1-qos0.py ================================================ #!/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(start_broker, proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("retain-qos1-qos0-test", 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/qos0/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.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/qos0/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/qos0/test", qos=0, payload="retained message", retain=True, proto_ver=proto_ver) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/04-retain-upgrade-outgoing-qos.py ================================================ #!/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("listener %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 mid = 16 connect_packet = mosq_test.gen_connect("retain-qos0-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/05-clean-session-qos1.py ================================================ #!/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("05-clean-qos1-test-helper") connack_packet = mosq_test.gen_connack(rc=0) mid = 128 publish_packet = mosq_test.gen_publish("qos1/05-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(start_broker, proto_ver): rc = 1 mid = 109 connect_packet = mosq_test.gen_connect("05-clean-session", 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/05-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/05-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) connect_packet_clear = mosq_test.gen_connect("05-clean-session", clean_session=True, proto_ver=proto_ver, session_expiry=0) port = mosq_test.get_port() if start_broker: 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, connack_error="connack 1") 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, connack_error="connack 2") mosq_test.expect_packet(sock, "publish", publish_packet) sock.send(puback_packet) rc = 0 sock.close() # Clear the session sock = mosq_test.do_client_connect(connect_packet_clear, connack1_packet, port=port, connack_error="connack clear") sock.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/05-session-expiry-kick.py ================================================ #!/usr/bin/env python3 # MQTT v5. Test whether session expiry interval works correctly. from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("plugin c/kick_last_client.so\n") f.write("allow_anonymous true\n") f.write("log_type all\n") def do_test(): rc = 1 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) # Test the case of connect with session-expiry>0, kick, expiry for a crash props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 1) connect_packet = mosq_test.gen_connect("05-session-expiry", clean_session=False, proto_ver=5, properties=props) connack_packet = mosq_test.gen_connack(flags=0, rc=0, proto_ver=5) try: sock = mosq_test.client_connect_only(port=port) sock.send(connect_packet) # Immediately disconnect, this should now be queued to expire, but the plugin should kick it first sock.close() time.sleep(2) # This should succeed if the broker is still online # The "session present" flag must *not* be set sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port, connack_error="connack 1") sock.close() rc = 0 except mosq_test.TestError: pass finally: broker.terminate() os.remove(conf_file) if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() ================================================ FILE: test/broker/05-session-expiry-v5.py ================================================ #!/usr/bin/env python3 # MQTT v5. Test whether session expiry interval works correctly. from mosq_test_helper import * def do_test(start_broker): rc = 1 # 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.SESSION_EXPIRY_INTERVAL, 4294967294) connect0_packet = mosq_test.gen_connect("05-session-expiry-overflow", 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.SESSION_EXPIRY_INTERVAL, 1) connect_packet = mosq_test.gen_connect("05-session-expiry", 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.SESSION_EXPIRY_INTERVAL, 3) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5, properties=props) props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 0) disconnect2_packet = mosq_test.gen_disconnect(proto_ver=5, properties=props) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/06-bridge-b2br-disconnect-qos1.py ================================================ #!/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("listener %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 client_id = socket.gethostname()+".bridge_sample" properties = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) properties += mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) connect_packet = mosq_test.gen_connect(client_id, clean_session=False, proto_ver=proto_ver_connect, properties=properties) 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, "2nd 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-b2br-disconnect-qos2.py ================================================ #!/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("listener %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 2\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 client_id = socket.gethostname()+".bridge_sample" properties = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) properties += mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) connect_packet = mosq_test.gen_connect(client_id, clean_session=False, proto_ver=proto_ver_connect, properties=properties) 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-b2br-late-connection-retain.py ================================================ #!/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("listener %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("listener %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("bridge_max_topic_alias 0\n") 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 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, 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", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 # 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-b2br-late-connection.py ================================================ #!/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("listener %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_max_topic_alias 0\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 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, 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", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-b2br-remapping.py ================================================ #!/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("listener %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('topic rmapped in 0 "" remote/mapped/\n') f.write('topic lmapped in 0 local/mapped/ ""\n') f.write('topic "" in 0 local/single remote/single\n') f.write("notifications false\n") f.write("restart_timeout 5\n") f.write("bridge_max_topic_alias 0\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'), ('local/mapped/lmapped', 'lmapped'), ('rmapped', 'remote/mapped/rmapped'), ('local/single', 'remote/single'), ] 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 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, 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", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-br2b-disconnect-qos1.py ================================================ #!/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("listener %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 2\n") f.write("bridge_protocol_version %s\n" % (protocol_version)) f.write("bridge_max_topic_alias 0\n") 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 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, 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", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-br2b-disconnect-qos2.py ================================================ #!/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("listener %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 2\n") f.write("bridge_protocol_version %s\n" % (protocol_version)) f.write("bridge_max_topic_alias 0\n") 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 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, 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", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-br2b-remapping.py ================================================ #!/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("listener %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)) f.write("bridge_max_topic_alias 0\n") 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 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, 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", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-clean-session-core.py ================================================ #!/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 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("listener %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("local_clientid id_local\n") f.write("remote_clientid id_remote\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") # We need to ensure connections break fast enough to keep test times sane f.write("keepalive_interval 5\n") f.write("restart_timeout 2\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)) f.write("bridge_max_topic_alias 0\n") # this is our "B" broker def write_config_core(filename, listen_port, persistence_file): with open(filename, 'w') as f: f.write("listener %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 wait_for_bridge_to_connect(port, clientid): conn = mosq_test.gen_connect("helper", clean_session=True) connack = mosq_test.gen_connack(rc=0) sock = mosq_test.do_client_connect(conn, connack, port=port) sub = mosq_test.gen_subscribe(1, f'$SYS/broker/connection/{clientid}/state', 0) suback = mosq_test.gen_suback(1, 0) mosq_test.do_send_receive(sock, sub, suback) pub_r = mosq_test.gen_publish(topic=f"$SYS/broker/connection/{clientid}/state", payload="1", qos=0, retain=True) pub_nr = mosq_test.gen_publish(topic=f"$SYS/broker/connection/{clientid}/state", payload="1", qos=0) pub_rec = sock.recv(len(pub_r)) if pub_rec != pub_r and pub_rec != pub_nr: raise ValueError(mosq_test.to_string(pub_rec)) sock.close() 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', '%d_a_edge.conf'%(port_a_listen)) persistence_file_a = os.path.basename(__file__).replace('.py', '%d_a_edge.db'%(port_a_listen)) 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', '%d_b_core.conf'%(port_b_listen)) persistence_file_b = os.path.basename(__file__).replace('.py', '%d_b_core.db'%(port_b_listen)) 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 conn = mosq_test.gen_connect(client_id, 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 broker_termination_success = True 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() if mosq_test.wait_for_subprocess(broker_b): print("broker_b not terminated") broker_termination_success = False (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()) wait_for_bridge_to_connect(port_b_listen, "id_remote") # 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() if mosq_test.wait_for_subprocess(broker_a): print("broker_a not terminated") broker_termination_success = False (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()) wait_for_bridge_to_connect(port_a_listen, "id_remote") # should go through client_b.send(pub_b3.p) 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 = broker_termination_success except Exception as e: print(e) except mosq_test.TestError: pass finally: os.remove(conf_file_a) os.remove(conf_file_b) broker_a.terminate() broker_b.terminate() if mosq_test.wait_for_subprocess(broker_a): print("broker_a not terminated") success = False if mosq_test.wait_for_subprocess(broker_b): print("broker_b not terminated") success = False (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) if sys.argv[3] == "True": cs = True elif sys.argv[3] == "False": cs = False else: raise ValueError("cs") if sys.argv[4] == "True": lcs = True elif sys.argv[4] == "False": lcs = False elif sys.argv[4] == "None": lcs = None else: raise ValueError("lcs") 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) ================================================ FILE: test/broker/06-bridge-clean-session-csF-lcsF.py ================================================ #!/usr/bin/env python3 # Test whether a broker handles cleansession and local_cleansession correctly on bridges from collections import namedtuple from mosq_test_helper import * (port_a_listen, port_b_listen) = mosq_test.get_port(2) subprocess.run([f'{Path(__file__).resolve().parent}/06-bridge-clean-session-core.py', str(port_a_listen), str(port_b_listen), "False", "False"]) ================================================ FILE: test/broker/06-bridge-clean-session-csF-lcsN.py ================================================ #!/usr/bin/env python3 # Test whether a broker handles cleansession and local_cleansession correctly on bridges from mosq_test_helper import * from collections import namedtuple (port_a_listen, port_b_listen) = mosq_test.get_port(2) subprocess.run([f'{Path(__file__).resolve().parent}/06-bridge-clean-session-core.py', str(port_a_listen), str(port_b_listen), "False", "None"]) ================================================ FILE: test/broker/06-bridge-clean-session-csF-lcsT.py ================================================ #!/usr/bin/env python3 # Test whether a broker handles cleansession and local_cleansession correctly on bridges from mosq_test_helper import * from collections import namedtuple (port_a_listen, port_b_listen) = mosq_test.get_port(2) subprocess.run([f'{Path(__file__).resolve().parent}/06-bridge-clean-session-core.py', str(port_a_listen), str(port_b_listen), "False", "True"]) ================================================ FILE: test/broker/06-bridge-clean-session-csT-lcsF.py ================================================ #!/usr/bin/env python3 # Test whether a broker handles cleansession and local_cleansession correctly on bridges from mosq_test_helper import * from collections import namedtuple (port_a_listen, port_b_listen) = mosq_test.get_port(2) subprocess.run([f'{Path(__file__).resolve().parent}/06-bridge-clean-session-core.py', str(port_a_listen), str(port_b_listen), "True", "False"]) ================================================ FILE: test/broker/06-bridge-clean-session-csT-lcsN.py ================================================ #!/usr/bin/env python3 # Test whether a broker handles cleansession and local_cleansession correctly on bridges from mosq_test_helper import * from collections import namedtuple (port_a_listen, port_b_listen) = mosq_test.get_port(2) subprocess.run([f'{Path(__file__).resolve().parent}/06-bridge-clean-session-core.py', str(port_a_listen), str(port_b_listen), "True", "None"]) ================================================ FILE: test/broker/06-bridge-clean-session-csT-lcsT.py ================================================ #!/usr/bin/env python3 # Test whether a broker handles cleansession and local_cleansession correctly on bridges from mosq_test_helper import * from collections import namedtuple (port_a_listen, port_b_listen) = mosq_test.get_port(2) subprocess.run([f'{Path(__file__).resolve().parent}/06-bridge-clean-session-core.py', str(port_a_listen), str(port_b_listen), "True", "True"]) ================================================ FILE: test/broker/06-bridge-config-reload.py ================================================ #!/usr/bin/env python3 # tests that bridge configuration is reloaded on signal from mosq_test_helper import * import signal def write_config(filename, port1, port2, subtopic, reload_immediate=False): with open(filename, 'w') as f: f.write("listener %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 # in 0 local/topic/ remote/%s/\n" % (subtopic)) f.write("notifications false\n") f.write("restart_timeout 1\n") if reload_immediate: f.write("bridge_reload_type immediate\n") f.write("bridge_max_topic_alias 0\n") def accept_new_connection(sock): conn, _ = sock.accept() conn.settimeout(20) client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect( client_id, clean_session=False, proto_ver=0x84) connack_packet = mosq_test.gen_connack() mosq_test.expect_packet(conn, "connect", connect_packet) conn.send(connack_packet) return conn def accept_subscription(socket, topic, mid=1, qos=0): subscribe_packet = mosq_test.gen_subscribe(mid, topic, qos) suback_packet = mosq_test.gen_suback(mid, qos) mosq_test.expect_packet(socket, "subscribe", subscribe_packet) socket.send(suback_packet) def start_fake_broker(port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(3) sock.bind(('', port)) sock.listen(5) return sock def expect_no_incoming_connection(sock): try: accept_new_connection(sock) # will timeout if nothing comes in raise mosq_test.TestError # hence, it shouldn't reach this except socket.timeout: pass def do_test(): rc = 1 port1, port2 = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') try: ssock = start_fake_broker(port1) write_config(conf_file, port1, port2, "topic1", True) broker = mosq_test.start_broker( filename=os.path.basename(__file__), port=port2, use_conf=True) bridge = accept_new_connection(ssock) accept_subscription(bridge, "remote/topic1/#") write_config(conf_file, port1, port2, "topic2", True) broker.send_signal(signal.SIGHUP) bridge = accept_new_connection(ssock) # immediate reload forces a reconnection accept_subscription(bridge, "remote/topic2/#") write_config(conf_file, port1, port2, "topic3", False) broker.send_signal(signal.SIGHUP) expect_no_incoming_connection(ssock) # as it was set to lazy reload bridge.close() bridge = accept_new_connection(ssock) accept_subscription(bridge, "remote/topic3/#") rc = 0 except mosq_test.TestError: pass finally: try: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 _, stde = broker.communicate() if rc: print(stde.decode('utf-8')) except NameError: pass try: os.remove(conf_file) except FileNotFoundError: pass try: bridge.close() except NameError: pass try: ssock.close() except NameError: pass return rc exit_code = do_test() exit(exit_code) ================================================ FILE: test/broker/06-bridge-fail-persist-resend-qos1.py ================================================ #!/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("listener %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)) f.write("bridge_max_topic_alias 0\n") 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 connect_packet = mosq_test.gen_connect("bridge-u-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-fail-persist-resend-qos2.py ================================================ #!/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("listener %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)) f.write("bridge_max_topic_alias 0\n") 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 connect_packet = mosq_test.gen_connect("bridge-u-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-no-local.py ================================================ #!/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(start_broker, proto_ver_connect, proto_ver_msgs, sub_opts): rc = 1 connect_packet = mosq_test.gen_connect("bridge-test", 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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, 128+3, 3, 0) if rc: return rc; rc = do_test(start_broker, 128+4, 4, 0) if rc: return rc; rc = do_test(start_broker, 5, 5, mqtt5_opts.MQTT_SUB_OPT_NO_LOCAL) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/06-bridge-outgoing-retain.py ================================================ #!/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("listener %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 with space/#\" 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)) f.write("bridge_max_topic_alias 0\n") 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 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, 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 with space/#", 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 with space/retain/test", qos=0, retain=True, payload="message", proto_ver=proto_ver) else: publish_packet = mosq_test.gen_publish("bridge with space/retain/test", qos=0, retain=False, payload="message", proto_ver=proto_ver) helper_connect_packet = mosq_test.gen_connect("helper", 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 with space/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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-per-listener-settings.py ================================================ #!/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("per_listener_settings true\n") f.write("listener %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)) f.write("bridge_max_topic_alias 0\n") 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 client_id = socket.gethostname()+".bridge_sample" connect_packet = mosq_test.gen_connect(client_id, 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", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/06-bridge-reconnect-local-out.py ================================================ #!/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("listener %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)) f.write("bridge_max_topic_alias 0\n") f.write("cleansession false\n") 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 connect_packet = mosq_test.gen_connect("bridge-reconnect-test", 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 = [mosq_test.get_build_root() + '/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() if mosq_test.wait_for_subprocess(local_broker): print("local_broker not terminated") if rc == 0: rc=1 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", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) local_broker.terminate() if mosq_test.wait_for_subprocess(local_broker): print("local_broker not terminated") if rc == 0: rc=1 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) ================================================ FILE: test/broker/06-bridge-remap-receive-wildcard.py ================================================ #!/usr/bin/env python3 # Does a bridge resend a QoS=1 message correctly after a disconnect? from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write(f"listener {port2}\n") f.write("allow_anonymous true\n") f.write("connection bridge1\n") f.write(f"address 127.0.0.1:{port1}\n") f.write("topic room1/# both 2 sensor/ myhouse/\n") f.write("topic tst/ba both 2\n") f.write("topic # both 2\n") f.write("keepalive_interval 600\n") f.write("remote_clientid mosquitto\n") f.write("bridge_protocol_version mqttv50\n") f.write("notifications false\n") 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 = 600 client_id = "mosquitto" properties = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) properties += mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, clean_session=False, proto_ver=proto_ver, properties=properties) 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, "myhouse/room1/#", 2 | opts, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 2 subscribe_packet2 = mosq_test.gen_subscribe(mid, "tst/ba", 2 | opts, proto_ver=proto_ver) suback_packet2= mosq_test.gen_suback(mid, 2, proto_ver=proto_ver) mid = 3 subscribe_packet3 = mosq_test.gen_subscribe(mid, "#", 2 | opts, proto_ver=proto_ver) suback_packet3 = mosq_test.gen_suback(mid, 2, 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, "subscribe1", subscribe_packet) bridge.send(suback_packet) mosq_test.expect_packet(bridge, "subscribe2", subscribe_packet2) bridge.send(suback_packet2) mosq_test.expect_packet(bridge, "subscribe3", subscribe_packet3) bridge.send(suback_packet3) try: bridge.send(bytes.fromhex("320c00062b2b2b2b2b2b00040033")) #bridge.send(bytes.fromhex("320c00062b2b2b2b2b2b00040033")) #bridge.send(bytes.fromhex("320c00062b2b2b2b2b2b00040033")) bridge.send(bytes.fromhex("C000")) # PING d = bridge.recv(1) if len(d) == 0: rc = 0 except (ConnectionResetError, BrokenPipeError, mosq_test.TestError): #expected behaviour rc = 0 bridge.close() except mosq_test.TestError: pass except Exception as e: print(e) 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=5) exit(0) ================================================ FILE: test/broker/06-bridge-remote-shutdown.py ================================================ #!/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("log_type all\n") f.write("listener %d\n" % (port2)) f.write("plugin c/plugin_evt_persist_client_update.so\n") f.write("allow_anonymous true\n") f.write("persistent_client_expiration 1d\n") f.write("\n") f.write("connection connect_only_bridge\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)) f.write("bridge_max_topic_alias 0\n") f.write("cleansession false\n") f.write("notification_topic bridge_state\n") f.write("restart_timeout 300\n") def do_test(proto_ver): bridge_protocol = "mqttv311" if proto_ver == 4 else "mqttv50" (port1, port2) = mosq_test.get_port(2) conf_file = '06-bridge-remote-shutdown.conf' write_config(conf_file, port1, port2, bridge_protocol) rc = 1 connect_packet = mosq_test.gen_connect("test-client", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 180 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("echo_topic", qos=0, payload="sample-message", proto_ver=proto_ver) bridge_up_packet = mosq_test.gen_publish("bridge_state", qos=0, payload="1", retain=1, proto_ver=proto_ver) bridge_down_packet = mosq_test.gen_publish("bridge_state", qos=0, payload="0", retain=0, proto_ver=proto_ver) remote_broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port1, use_conf=False) local_cmd = [mosq_test.get_build_root() + '/src/mosquitto', '-c', conf_file] local_broker = mosq_test.start_broker(cmd=local_cmd, filename=os.path.basename(__file__)+'_local1', use_conf=False, port=port2) rc1 = None try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port2) sock = mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") mosq_test.expect_packet(sock, "check for bridge up state", bridge_up_packet) rc1, stde1 = mosq_test.terminate_broker(remote_broker) mosq_test.expect_packet(sock, "wait for bridge down state", bridge_down_packet) # If we now get a message published to evt/persist/client/update instead of the expected echo # the bridge connection was most likely added to the expiry list sock = mosq_test.do_send_receive(sock, publish_packet, publish_packet) rc = 0 sock.close() except mosq_test.TestError: pass finally: if rc1 is None: rc1, stde1 = mosq_test.terminate_broker(remote_broker) rc2, stde2 = mosq_test.terminate_broker(local_broker) if rc or rc1 or rc2: print(f"Remote broker first run rc={rc1}") print(stde1.decode('utf-8')) print(f"Local broker rc={rc2}") print(stde2.decode('utf-8')) try: os.remove(conf_file) except OSError: pass return rc == 0 if do_test(proto_ver=4) and do_test(proto_ver=5): exit(0) exit(1) ================================================ FILE: test/broker/07-will-control.py ================================================ #!/usr/bin/env python3 # Test whether a client setting a will with $CONTROL in is denied from mosq_test_helper import * def do_test(start_broker, proto_ver): rc = 1 mid = 1 connect_packet = mosq_test.gen_connect("will", will_topic="$CONTROL/dynamic-security/v1", will_payload=b"will-message", proto_ver=proto_ver) port = mosq_test.get_port() if start_broker: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.client_connect_only(port=port) sock.send(connect_packet) d = sock.recv(1) if d == b"": rc = 0 sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: if start_broker: broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-delay-invalid-573191.py ================================================ #!/usr/bin/env python3 # Test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=573191 # Check under valgrind/asan for leaks. from mosq_test_helper import * def do_test(): rc = 1 props = mqtt5_props.gen_uint32_prop(mqtt5_props.WILL_DELAY_INTERVAL, 3) connect_packet = mosq_test.gen_connect("will-573191-test", proto_ver=5, will_topic="", will_properties=props) connack_packet = mosq_test.gen_connack(rc=mqtt5_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=30, port=port) sock.close() except BrokenPipeError: rc = 0 finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) return rc sys.exit(do_test()) ================================================ FILE: test/broker/07-will-delay-reconnect.py ================================================ #!/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(start_broker): rc = 1 mid = 1 connect1_packet = mosq_test.gen_connect("will-delay-reconnect-test", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 60) will_props = mqtt5_props.gen_uint32_prop(mqtt5_props.WILL_DELAY_INTERVAL, 3) connect2a_packet = mosq_test.gen_connect("will-delay-reconnect-helper", proto_ver=5, will_topic="will/delay/reconnect/test", will_payload=b"will delay", will_properties=will_props, clean_session=False, properties=props) connack2a_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect2b_packet = mosq_test.gen_connect("will-delay-reconnect-helper", proto_ver=5, clean_session=False) connack2b_packet = mosq_test.gen_connack(rc=0, flags=1, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "will/delay/reconnect/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-delay-recover.py ================================================ #!/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(start_broker, clean_session): rc = 1 mid = 1 connect1_packet = mosq_test.gen_connect("will-delay-recovery", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 30) props = mqtt5_props.gen_uint32_prop(mqtt5_props.WILL_DELAY_INTERVAL, 3) connect2_packet = mosq_test.gen_connect("will-delay-recovery-helper", proto_ver=5, will_topic="will/delay/recovery/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/delay/recovery/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) connect2_packet_clear = mosq_test.gen_connect("will-delay-recovery-helper", proto_ver=5) will_packet = mosq_test.gen_publish(topic="will/delay/recovery/test", payload="will delay", qos=0, proto_ver=5) port = mosq_test.get_port() if start_broker: 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. if clean_session: # The old session has ended, so we should receive the will mosq_test.expect_packet(sock1, "will", will_packet) else: # We should not have received the will at this point. mosq_test.do_ping(sock1) rc = 0 sock1.close() sock2.close() sock2 = mosq_test.do_client_connect(connect2_packet_clear, connack1_packet, timeout=30, port=port) sock2.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, clean_session=True) if rc: return rc rc = do_test(start_broker, clean_session=False) if rc: return rc return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-delay-session-expiry-0.py ================================================ #!/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 * def do_test(start_broker): rc = 1 mid = 1 connect1_packet = mosq_test.gen_connect("will-session-exp", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) will_props = mqtt5_props.gen_uint32_prop(mqtt5_props.WILL_DELAY_INTERVAL, 60) connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 0) connect2_packet = mosq_test.gen_connect("will-session-exp-helper", proto_ver=5, properties=connect_props, will_topic="will/session-expiry/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/session-expiry/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet = mosq_test.gen_publish("will/session-expiry/test", qos=0, payload="will delay", proto_ver=5) port = mosq_test.get_port() if start_broker: 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, 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=5, port=port, connack_error="connack2") time.sleep(1) sock2.close() # Will should be sent immediately due to session-expiry-interval=0. If not, the read will timeout mosq_test.expect_packet(sock1, "publish", publish_packet) rc = 0 sock1.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-delay-session-expiry.py ================================================ #!/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 * def do_test(start_broker): rc = 1 mid = 1 connect1_packet = mosq_test.gen_connect("will-session-exp", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) will_props = mqtt5_props.gen_uint32_prop(mqtt5_props.WILL_DELAY_INTERVAL, 4) connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 2) connect2_packet = mosq_test.gen_connect("will-session-exp-helper", proto_ver=5, properties=connect_props, will_topic="will/session-expiry/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/session-expiry/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet = mosq_test.gen_publish("will/session-expiry/test", qos=0, payload="will delay", proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-delay-session-expiry2.py ================================================ #!/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 * def do_test(start_broker): rc = 1 mid = 1 connect1_packet = mosq_test.gen_connect("will-session-exp2", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) will_props = mqtt5_props.gen_uint32_prop(mqtt5_props.WILL_DELAY_INTERVAL, 2) connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 4) connect2_packet = mosq_test.gen_connect("will-session-exp2-helper", proto_ver=5, properties=connect_props, will_topic="will/session/expiry2/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/session/expiry2/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet = mosq_test.gen_publish("will/session/expiry2/test", qos=0, payload="will delay", proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-delay.py ================================================ #!/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(start_broker, clean_session): rc = 1 mid = 1 connect1_packet = mosq_test.gen_connect("will-delay-test", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 60) will_props = mqtt5_props.gen_uint32_prop(mqtt5_props.WILL_DELAY_INTERVAL, 3) connect2_packet = mosq_test.gen_connect("will-delay-helper", proto_ver=5, properties=props, will_topic="will/delay/test", will_payload=b"will delay", will_qos=2, will_properties=will_props, clean_session=clean_session) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "will/delay/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet = mosq_test.gen_publish("will/delay/test", qos=0, payload="will delay", proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, clean_session=True) if rc: return rc rc = do_test(start_broker, clean_session=False) if rc: return rc return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-disconnect-with-will.py ================================================ #!/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(start_broker): rc = 1 mid = 1 connect1_packet = mosq_test.gen_connect("will-with-disconnect-test", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) connect2_packet = mosq_test.gen_connect("will-with-disconnect-helper", proto_ver=5, will_topic="will/with/disconnect/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/with/disconnect/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet = mosq_test.gen_publish("will/with/disconnect/test", qos=0, payload="will delay", proto_ver=5) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-invalid-utf8.py ================================================ #!/usr/bin/env python3 # Test whether a will topic with invalid UTF-8 fails from mosq_test_helper import * def do_test(start_broker, proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("will-invalid-utf8", will_topic="will/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 = None if start_broker: 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) sock.close() except BrokenPipeError: rc = 0 finally: if broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc return do_test(start_broker, proto_ver=5) if __name__ == '__main__': sys.exit(all_tests(True)) ================================================ FILE: test/broker/07-will-no-flag.py ================================================ #!/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(start_broker, proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("will-no-payload", 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) connack_packet = mosq_test.gen_connack(mqtt5_rc.PROTOCOL_ERROR, proto_ver=5) port = mosq_test.get_port() broker = None if start_broker: 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() except BrokenPipeError: rc = 0 finally: if broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc return do_test(start_broker, proto_ver=5) if __name__ == '__main__': sys.exit(all_tests(True)) ================================================ FILE: test/broker/07-will-null-topic.py ================================================ #!/usr/bin/env python3 import struct from mosq_test_helper import * def do_test(start_broker, proto_ver): rc = 1 connect_packet = mosq_test.gen_connect("will-null-topic", will_topic="", will_payload=struct.pack("!4sB7s", b"will", 0, b"message"), proto_ver=proto_ver) if proto_ver == 5: connack_packet = mosq_test.gen_connack(rc=mqtt5_rc.PROTOCOL_ERROR, proto_ver=5) else: connack_packet = b"" port = mosq_test.get_port() broker = None if start_broker: 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) sock.close() except BrokenPipeError: rc = 0 finally: if broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc rc = do_test(start_broker, proto_ver=5) if rc: return rc return 0 if __name__ == '__main__': sys.exit(all_tests(True)) ================================================ FILE: test/broker/07-will-null.py ================================================ #!/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("07-will-null-helper", 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(start_broker, proto_ver): rc = 1 mid = 53 connect_packet = mosq_test.gen_connect("07-will-null-test", 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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-oversize-payload.py ================================================ #!/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 connect_packet = mosq_test.gen_connect("will-test", 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", 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", 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.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/07-will-per-listener.py ================================================ #!/usr/bin/env python3 # Test whether a client will is transmitted correctly, with per_listener_settings enabled from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("per_listener_settings true\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") def do_test(proto_ver, clean_session): rc = 1 mid = 53 connect1_packet = mosq_test.gen_connect("will-qos0-test", proto_ver=proto_ver) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connect2_packet = mosq_test.gen_connect("test-helper", 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() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port, use_conf=True) 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: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/07-will-properties.py ================================================ #!/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(start_broker, will_props, recvd_props): rc = 1 mid = 1 connect1_packet = mosq_test.gen_connect("07-will-properties-helper", proto_ver=5) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe1_packet = mosq_test.gen_subscribe(mid, "07/will/properties/will/test", 0, proto_ver=5) suback1_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) connect2_packet = mosq_test.gen_connect("07-will-properties", proto_ver=5, will_topic="07/will/properties/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("07/will/properties/will/test", qos=0, payload="will payload", proto_ver=5, properties=recvd_props) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): # Single test property will_props = mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "response/topic") rc = do_test(start_broker, will_props, will_props) if rc: return rc; # Multiple test properties will_props = mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "response/topic") will_props += mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 0) rc = do_test(start_broker, will_props, will_props) if rc: return rc; # Multiple test properties, with property that is removed will_props = mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "response/topic") will_props += mqtt5_props.gen_uint32_prop(mqtt5_props.WILL_DELAY_INTERVAL, 0) will_props += mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 0) recv_props = mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "response/topic") recv_props += mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 0) rc = do_test(start_broker, will_props, recv_props) if rc: return rc; # Multiple test properties, with property that is removed *first* will_props = mqtt5_props.gen_uint32_prop(mqtt5_props.WILL_DELAY_INTERVAL, 0) will_props += mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "response/topic") will_props += mqtt5_props.gen_string_prop(mqtt5_props.CORRELATION_DATA, "data") recv_props = mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "response/topic") recv_props += mqtt5_props.gen_string_prop(mqtt5_props.CORRELATION_DATA, "data") rc = do_test(start_broker, will_props, recv_props) if rc: return rc; # 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.USER_PROPERTY, "key1", "value1") will_props += mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "response/topic") will_props += mqtt5_props.gen_string_prop(mqtt5_props.CORRELATION_DATA, "data") will_props += mqtt5_props.gen_uint32_prop(mqtt5_props.WILL_DELAY_INTERVAL, 0) will_props += mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 1) will_props += mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "application/test") will_props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key2", "value2") recv_props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key1", "value1") recv_props += mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "response/topic") recv_props += mqtt5_props.gen_string_prop(mqtt5_props.CORRELATION_DATA, "data") recv_props += mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 1) recv_props += mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "application/test") recv_props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key2", "value2") rc = do_test(start_broker, will_props, recv_props) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-qos0.py ================================================ #!/usr/bin/env python3 # Test whether a client will is transmitted correctly. from mosq_test_helper import * def do_test(start_broker, proto_ver, clean_session): rc = 1 mid = 53 connect1_packet = mosq_test.gen_connect("will-qos0-test", proto_ver=proto_ver) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connect2_packet = mosq_test.gen_connect("will-qos0-helper", 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) connect2_packet_clear = mosq_test.gen_connect("will-qos0-helper", proto_ver=proto_ver) port = mosq_test.get_port() if start_broker: 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() sock = mosq_test.do_client_connect(connect2_packet_clear, connack1_packet, timeout=5, port=port) sock.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4, clean_session=True) if rc: return rc; rc = do_test(start_broker, proto_ver=4, clean_session=False) if rc: return rc; rc = do_test(start_broker, proto_ver=5, clean_session=True) if rc: return rc; rc = do_test(start_broker, proto_ver=5, clean_session=False) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-reconnect-1273.py ================================================ #!/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(start_broker, proto_ver): rc = 1 connect1_packet = mosq_test.gen_connect("will-reconnect-helper", 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/reconnect/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", will_topic="will/reconnect/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/reconnect/test", qos=0, payload="alive", proto_ver=proto_ver) connect2_packet_clear = mosq_test.gen_connect("will-1273", proto_ver=proto_ver) port = mosq_test.get_port() if start_broker: 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() sock2 = mosq_test.do_client_connect(connect2_packet_clear, connack1_packet, timeout=30, port=port, connack_error="connack clear") sock2.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4) if rc: return rc; rc = do_test(start_broker, proto_ver=5) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/07-will-takeover.py ================================================ #!/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(start_broker, proto_ver, clean_session1, clean_session2): rc = 1 mid = 1 connect1_packet = mosq_test.gen_connect("will-takeover-helper", 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.SESSION_EXPIRY_INTERVAL, 60) else: connect_props1 = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 0) if clean_session2 == False: connect_props2 = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 60) else: connect_props2 = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 0) else: connect_props1 = b"" connect_props2 = b"" connect2_packet = mosq_test.gen_connect("will-takeover-test", proto_ver=proto_ver, will_topic="will/takeover/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-takeover-test", 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/takeover/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/takeover/test", qos=0, payload="Client ready", proto_ver=proto_ver) publish_lwt_packet = mosq_test.gen_publish(topic="will/takeover/test", qos=0, payload="LWT", proto_ver=proto_ver) connect2_packet_clear = mosq_test.gen_connect("will-takeover-test", proto_ver=proto_ver) port = mosq_test.get_port() if start_broker: 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() sock2 = mosq_test.do_client_connect(connect2_packet_clear, connack2_packet, timeout=5, port=port) sock2.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, proto_ver=4, clean_session1=True, clean_session2=True) if rc: print("1") return rc; rc = do_test(start_broker, proto_ver=4, clean_session1=False, clean_session2=True) if rc: print("2") return rc; rc = do_test(start_broker, proto_ver=4, clean_session1=True, clean_session2=False) if rc: print("3") return rc; rc = do_test(start_broker, proto_ver=4, clean_session1=False, clean_session2=False) if rc: print("4") return rc; rc = do_test(start_broker, proto_ver=5, clean_session1=True, clean_session2=True) if rc: print("5") return rc; rc = do_test(start_broker, proto_ver=5, clean_session1=False, clean_session2=True) if rc: print("6") return rc; rc = do_test(start_broker, proto_ver=5, clean_session1=True, clean_session2=False) if rc: print("7") return rc; rc = do_test(start_broker, proto_ver=5, clean_session1=False, clean_session2=False) if rc: print("8") return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/08-ssl-bridge-helper.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * port = mosq_test.get_port() rc = 1 connect_packet = mosq_test.gen_connect("test-helper") 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) ================================================ FILE: test/broker/08-ssl-bridge.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * source_dir = Path(__file__).resolve().parent ssl_dir = source_dir.parent / "ssl" def write_config(filename, address, port1, port2): with open(filename, 'w') as f: f.write(f"listener {port2}\n") f.write("allow_anonymous true\n") f.write("\n") f.write("connection bridge_test\n") f.write(f"address {address}:{port1}\n") f.write("topic bridge/# both 0\n") f.write("notifications false\n") f.write("restart_timeout 2\n") f.write("\n") f.write(f"bridge_cafile {ssl_dir}/all-ca.crt\n") f.write("bridge_insecure true\n") def do_test(address): (port1, port2) = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, address, port1, port2) rc = 1 client_id = socket.gethostname()+".bridge_test" connect_packet = mosq_test.gen_connect(client_id, 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) context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=f"{ssl_dir}/all-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 context.load_cert_chain(certfile=f"{ssl_dir}/server-san.crt", keyfile=f"{ssl_dir}/server-san.key") ssock = context.wrap_socket(sock, 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([f'{source_dir}/08-ssl-bridge-helper.py', str(port2)], stdout=subprocess.PIPE, stderr=subprocess.PIPE) pub_terminated = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminated = 1 (stdo, stde) = pub.communicate() mosq_test.expect_packet(bridge, "publish", publish_packet) rc = pub_terminated bridge.close() except mosq_test.TestError: pass finally: os.remove(conf_file) try: bridge.close() except NameError: pass broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() ssock.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test("127.0.0.1") do_test(mosq_test.get_non_loopback_ip()) # tests non-matching certificate hostname with bridge_insecure ================================================ FILE: test/broker/08-ssl-connect-cert-auth-crl.py ================================================ #!/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("listener %d\n" % (port2)) f.write("allow_anonymous true\n") f.write("listener %d\n" % (port1)) f.write("allow_anonymous true\n") f.write(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") f.write("require_certificate true\n") f.write(f"crlfile {ssl_dir}/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 connect_packet = mosq_test.gen_connect("connect-success-test") 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) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=f"{ssl_dir}/test-root-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 context.load_cert_chain(certfile=f"{ssl_dir}/client.crt", keyfile=f"{ssl_dir}/client.key") ssock = context.wrap_socket(sock, server_hostname="localhost") 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/08-ssl-connect-cert-auth-expired-allowed.py ================================================ #!/usr/bin/env python3 # Check the `disable_client_cert_date_checks` option. 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("listener %d\n" % (port2)) f.write("\n") f.write("listener %d\n" % (port1)) f.write(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") f.write("require_certificate true\n") f.write("disable_client_cert_date_checks true\n") f.write("allow_anonymous 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 connect_packet = mosq_test.gen_connect("connect-success-test") 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) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=f"{ssl_dir}/test-root-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 context.load_cert_chain(certfile=f"{ssl_dir}/client-expired.crt", keyfile=f"{ssl_dir}/client-expired.key") ssock = context.wrap_socket(sock, server_hostname="localhost") ssock.settimeout(20) ssock.connect(("localhost", port1)) mosq_test.do_send_receive(ssock, connect_packet, connack_packet, "connack") rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) time.sleep(0.5) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/08-ssl-connect-cert-auth-expired.py ================================================ #!/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("listener %d\n" % (port2)) f.write("\n") f.write("listener %d\n" % (port1)) f.write(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/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 broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) ssl_eof = False try: context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=f"{ssl_dir}/test-root-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 context.load_cert_chain(certfile=f"{ssl_dir}/client-expired.crt", keyfile=f"{ssl_dir}/client-expired.key") with socket.create_connection(("localhost", port1)) as sock: ssock = context.wrap_socket(sock, server_hostname="localhost", suppress_ragged_eofs=True) ssock.settimeout(None) try: ssock.read(1) except ssl.SSLEOFError: # Under load, sometimes the broker closes the connection after the # handshake has failed, but before we have chance to send our # payload and so we get an EOF. ssl_eof = True except ssl.SSLError as err: if err.reason == "SSLV3_ALERT_CERTIFICATE_EXPIRED": rc = 0 elif err.errno == 8 and "EOF occurred" in err.strerror: rc = 0 else: broker.terminate() print(err.strerror) raise ValueError(err.errno) from err except mosq_test.TestError: pass finally: os.remove(conf_file) time.sleep(0.5) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if ssl_eof: if "certificate verify failed" in stde.decode('utf-8'): rc = 0 if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/08-ssl-connect-cert-auth-revoked.py ================================================ #!/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("listener %d\n" % (port2)) f.write("allow_anonymous true\n") f.write("listener %d\n" % (port1)) f.write("allow_anonymous true\n") f.write(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") f.write("require_certificate true\n") f.write(f"crlfile {ssl_dir}/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 broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) ssl_eof = False try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=f"{ssl_dir}/test-root-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 context.load_cert_chain(certfile=f"{ssl_dir}/client-revoked.crt", keyfile=f"{ssl_dir}/client-revoked.key") ssock = context.wrap_socket(sock, server_hostname="localhost") ssock.settimeout(20) try: ssock.connect(("localhost", port1)) try: ssock.read(1) except ssl.SSLEOFError: # Under load, sometimes the broker closes the connection after the # handshake has failed, but before we have chance to send our # payload and so we get an EOF. ssl_eof = True except ssl.SSLError as err: if err.reason == "SSLV3_ALERT_CERTIFICATE_REVOKED": rc = 0 elif err.errno == 8 and "EOF occurred" in err.strerror: rc = 0 else: broker.terminate() print(err.strerror) raise ValueError(err.errno) from err except ssl.SSLError as err: if err.errno == 1 and "certificate revoked" in err.strerror: rc = 0 elif err.errno == 8 and "EOF occurred" 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if ssl_eof: if "certificate verify failed" in stde.decode('utf-8'): rc = 0 if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/08-ssl-connect-cert-auth-without.py ================================================ #!/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("listener %d\n" % (port2)) f.write("listener %d\n" % (port1)) f.write(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/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 connect_packet = mosq_test.gen_connect("connect-cert-test") broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, use_conf=True) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) context.minimum_version = ssl.TLSVersion.TLSv1_2 ssock = context.wrap_socket(sock, server_hostname="localhost") ssock.settimeout(20) try: ssock.connect(("localhost", port1)) mosq_test.do_send_receive(ssock, connect_packet, "", "connack") except ssl.SSLEOFError as err: rc = 0 except ssl.SSLError as err: if err.errno == 1: rc = 0 else: print("unexpected SSLError occurred", err) except socket.error as err: if err.errno == errno.ECONNRESET: rc = 0 else: print("unexpected socket.error occurred", err) except mosq_test.TestError as err: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/08-ssl-connect-cert-auth.py ================================================ #!/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("listener %d\n" % (port2)) f.write("allow_anonymous true\n") f.write("listener %d\n" % (port1)) f.write("allow_anonymous true\n") f.write(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/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 connect_packet = mosq_test.gen_connect("connect-success-test") 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) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=f"{ssl_dir}/test-root-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 context.load_cert_chain(certfile=f"{ssl_dir}/client.crt", keyfile=f"{ssl_dir}/client.key") ssock = context.wrap_socket(sock, server_hostname="localhost") 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/08-ssl-connect-dhparam.py ================================================ #!/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("listener %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(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") f.write(f"dhparamfile {ssl_dir}/dhparam\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 connect_packet = mosq_test.gen_connect("connect-success-test") 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) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=f"{ssl_dir}/test-root-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 ssock = context.wrap_socket(sock, server_hostname="localhost") 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/08-ssl-connect-identity.py ================================================ #!/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("listener %d\n" % (port2)) f.write("\n") f.write("listener %d\n" %(port1)) f.write(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/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 connect_packet = mosq_test.gen_connect("connect-identity-test") 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) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=f"{ssl_dir}/test-root-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 context.load_cert_chain(certfile=f"{ssl_dir}/client.crt", keyfile=f"{ssl_dir}/client.key") ssock = context.wrap_socket(sock, server_hostname="localhost") 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/08-ssl-connect-no-auth-wrong-ca.py ================================================ #!/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("listener %d\n" % (port2)) f.write("\n") f.write("listener %d\n" % (port1)) f.write(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/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 connect_packet = mosq_test.gen_connect("connect-success-test") 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) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=f"{ssl_dir}/test-alt-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 ssock = context.wrap_socket(sock, server_hostname="localhost") 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/08-ssl-connect-no-auth.py ================================================ #!/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("listener %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(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/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 connect_packet = mosq_test.gen_connect("connect-success-test") 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) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=f"{ssl_dir}/test-root-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 ssock = context.wrap_socket(sock, server_hostname="localhost") 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/08-ssl-connect-no-identity.py ================================================ #!/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("listener %d\n" % (port2)) f.write("\n") f.write("listener %d\n" % (port1)) f.write(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/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 connect_packet = mosq_test.gen_connect("connect-no-identity-test") 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) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=f"{ssl_dir}/test-root-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 ssock = context.wrap_socket(sock, server_hostname="localhost") 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/08-ssl-hup-disconnect.py ================================================ #!/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(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/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 connect_packet = mosq_test.gen_connect("connect-success-test") 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) context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=f"{ssl_dir}/test-root-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 context.load_cert_chain(certfile=f"{ssl_dir}/client.crt", keyfile=f"{ssl_dir}/client.key") ssock = context.wrap_socket(sock, server_hostname="localhost") 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/08-tls-psk-bridge.psk ================================================ psk-test:deadbeef ================================================ FILE: test/broker/08-tls-psk-bridge.py ================================================ #!/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(f"psk_file {str(source_dir/'08-tls-psk-bridge.psk')}\n") f.write("\n") f.write("listener %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("listener %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 = mosq_test.env_add_ld_library_path() rc = 1 connect_packet = mosq_test.gen_connect("no-psk-test-client") 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 = [mosq_test.get_build_root() + '/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.run(['./c/08-tls-psk-bridge.test', str(port3)], env=env, capture_output=True, encoding='utf-8') if pub.returncode != 0: print("d") print(pub.returncode) raise ValueError mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub.returncode sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file1) os.remove(conf_file2) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 bridge.terminate() if mosq_test.wait_for_subprocess(bridge): print("bridge not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) (stdo, stde) = bridge.communicate() print(stde.decode('utf-8')) if pub: print(pub.stdout) print(pub.stderr) exit(rc) ================================================ FILE: test/broker/08-tls-psk-pub.psk ================================================ psk-id:deadbeef ================================================ FILE: test/broker/08-tls-psk-pub.py ================================================ #!/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(f"psk_file {str(source_dir/'08-tls-psk-pub.psk')}\n") f.write("\n") f.write("listener %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 = mosq_test.env_add_ld_library_path() rc = 1 connect_packet = mosq_test.gen_connect("no-psk-test-client") 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) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 if pub.returncode != 0: raise ValueError (stdo, stde) = pub.communicate() mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-acl-access-variants.py ================================================ #!/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("listener %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): connect_packet = mosq_test.gen_connect("acl-check", 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() def acl_test(port, per_listener, global_en, user_en, pattern_en): acl_file = os.path.basename(__file__).replace('.py', '.acl') conf_file = os.path.basename(__file__).replace('.py', '.conf') write_acl(acl_file, global_en=global_en, user_en=user_en, pattern_en=pattern_en) write_config(conf_file, port, per_listener) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) rc = 0 try: 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) except mosq_test.TestError: rc = 1 finally: os.remove(conf_file) os.remove(acl_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) def do_test(port, per_listener): 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) port = mosq_test.get_port() do_test(port, "true") do_test(port, "false") ================================================ FILE: test/broker/09-acl-change.py ================================================ #!/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("listener %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') username = "username" connect1_packet = mosq_test.gen_connect("acl-check", 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", 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: # 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) port = mosq_test.get_port() ================================================ FILE: test/broker/09-acl-empty-file.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("acl-check") 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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") ================================================ FILE: test/broker/09-auth-bad-method.py ================================================ #!/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 * def do_test(start_broker): rc = 1 props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "basic") connect_packet = mosq_test.gen_connect("connect-test", proto_ver=5, properties=props) connack_packet = mosq_test.gen_connack(rc=mqtt5_rc.BAD_AUTHENTICATION_METHOD, proto_ver=5, properties=None) port = mosq_test.get_port() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/09-extended-auth-change-username.py ================================================ #!/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("listener %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", 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.NOT_AUTHORIZED) # Connect without a username, but have the plugin change it props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "change") connect2_packet = mosq_test.gen_connect("client-params-test2", proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test("true") do_test("false") exit(0) ================================================ FILE: test/broker/09-extended-auth-multistep-reauth.py ================================================ #!/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("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.AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "step1") connect1_packet = mosq_test.gen_connect("client-params-test", proto_ver=5, properties=props) # Server to client props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "1pets") auth1_1_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.CONTINUE_AUTHENTICATION, properties=props) # Client to server props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "supercalifragilisticexpialidocious") auth1_2_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.CONTINUE_AUTHENTICATION, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.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.AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "step1") reauth2_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.REAUTHENTICATE, properties=props) # Server to client props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "1pets") auth2_1_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.CONTINUE_AUTHENTICATION, properties=props) # Client to server props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "supercalifragilisticexpialidocious") auth2_2_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.CONTINUE_AUTHENTICATION, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.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.AUTHENTICATION_METHOD, "badmethod") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "step1") reauth3_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.REAUTHENTICATE, properties=props) # Server to client disconnect3_packet = mosq_test.gen_disconnect(reason_code=mqtt5_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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-extended-auth-multistep.py ================================================ #!/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("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.AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "step1") connect_packet = mosq_test.gen_connect("client-params-test", proto_ver=5, properties=props) # Server to client props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "1pets") auth1_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.CONTINUE_AUTHENTICATION, properties=props) # Client to server props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "supercalifragilisticexpialidocious") auth2_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.CONTINUE_AUTHENTICATION, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-extended-auth-reauth.py ================================================ #!/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_reauth.so\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 # First authentication succeeds props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "repeat") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "repeat") connect_packet = mosq_test.gen_connect("client-params-test", proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "repeat") connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) # Reauthentication fails props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "repeat") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "repeat") auth_packet = mosq_test.gen_auth(reason_code=mqtt5_rc.REAUTHENTICATE, properties=props) disconnect_packet = mosq_test.gen_disconnect(reason_code=mqtt5_rc.NOT_AUTHORIZED, 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, timeout=20, port=port) mosq_test.do_send_receive(sock, auth_packet, disconnect_packet) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-extended-auth-single.py ================================================ #!/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("listener %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.AUTHENTICATION_METHOD, "error") connect1_packet = mosq_test.gen_connect("client-params-test1", proto_ver=5, properties=props) # Single, no matching authentication method props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "non-matching") connect2_packet = mosq_test.gen_connect("client-params-test2", proto_ver=5, properties=props) connack2_packet = mosq_test.gen_connack(rc=mqtt5_rc.BAD_AUTHENTICATION_METHOD, proto_ver=5, properties=None) # Single step, matching method, failure props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "single") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "baddata") connect3_packet = mosq_test.gen_connect("client-params-test3", proto_ver=5, properties=props) connack3_packet = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5, properties=None) # Single step, matching method, success props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "single") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "data") connect4_packet = mosq_test.gen_connect("client-params-test5", proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.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.AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "somedata") connect5_packet = mosq_test.gen_connect("client-params-test6", proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "mirror") props += mqtt5_props.gen_string_prop(mqtt5_props.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 = None try: sock = mosq_test.do_client_connect(connect1_packet, b"", timeout=20, port=port) sock.close() rc = 2 except BrokenPipeError: pass sock = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect3_packet, connack3_packet, timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect4_packet, connack4_packet, timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect5_packet, connack5_packet, timeout=20, port=port) sock.close() rc = 0 finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) sys.exit(rc) ================================================ FILE: test/broker/09-extended-auth-single2.py ================================================ #!/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("listener %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.AUTHENTICATION_METHOD, "error%s" % (suffix)) connect1_packet = mosq_test.gen_connect("client-params-test1", proto_ver=5, properties=props) # Single, no matching authentication method props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "non-matching%s" % (suffix)) connect2_packet = mosq_test.gen_connect("client-params-test2", proto_ver=5, properties=props) connack2_packet = mosq_test.gen_connack(rc=mqtt5_rc.BAD_AUTHENTICATION_METHOD, proto_ver=5, properties=None) # Single step, matching method, failure props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "single%s" % (suffix)) props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "baddata") connect3_packet = mosq_test.gen_connect("client-params-test3", proto_ver=5, properties=props) connack3_packet = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5, properties=None) # Single step, matching method, success props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "single%s" % (suffix)) props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "data") connect4_packet = mosq_test.gen_connect("client-params-test5", proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.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.AUTHENTICATION_METHOD, "mirror%s" % (suffix)) props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "somedata") connect5_packet = mosq_test.gen_connect("client-params-test6", proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "mirror%s" % (suffix)) props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "atademos") connack5_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props) broker = mosq_test.start_broker(filename=conf_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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test("") do_test("2") exit(0) ================================================ FILE: test/broker/09-plugin-acl-access-variants.py ================================================ #!/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("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write(f"plugin {mosq_test.get_build_root()}/plugins/acl-file/mosquitto_acl_file.so\n") f.write("plugin_opt_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): connect_packet = mosq_test.gen_connect("acl-check", 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() def acl_test(port, per_listener, global_en, user_en, pattern_en): acl_file = os.path.basename(__file__).replace('.py', '.acl') conf_file = os.path.basename(__file__).replace('.py', '.conf') write_acl(acl_file, global_en=global_en, user_en=user_en, pattern_en=pattern_en) write_config(conf_file, port, per_listener) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) rc = 0 try: 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) except mosq_test.TestError: rc = 1 finally: os.remove(conf_file) os.remove(acl_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) def do_test(port, per_listener): 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) port = mosq_test.get_port() do_test(port, "true") do_test(port, "false") ================================================ FILE: test/broker/09-plugin-acl-change.py ================================================ #!/usr/bin/env python3 # A clean start=False client connects, and publishes to a topic it has access # to with QoS 2 - but does not send a PUBREL. It closes the connection. The # access to the topic is revoked, the client reconnects and it attempts to # complete the flow. Is the publish allowed? It should not be. from mosq_test_helper import * def write_config(filename, port, plugin_ver): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("auth_plugin c/auth_plugin_acl_change.so\n") f.write("allow_anonymous true\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 connect1_packet = mosq_test.gen_connect("acl-change-test", clean_session=False) connack1_packet = mosq_test.gen_connack(rc=0) connect2_packet = mosq_test.gen_connect("acl-change-test", clean_session=False) connack2_packet = mosq_test.gen_connack(rc=0,flags=1) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 0) suback_packet = mosq_test.gen_suback(mid, 0) mid = 2 publish1_packet = mosq_test.gen_publish("publish/topic", 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) 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, "suback 1") mosq_test.do_send_receive(sock, publish1_packet, pubrec1_packet, "pubrec") sock.close() # ACL has changed sock = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=20, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback 2") mosq_test.do_send_receive(sock, pubrel1_packet, pubcomp1_packet, "pubcomp") mosq_test.do_ping(sock) rc = 0 sock.close() except mosq_test.TestError: pass except Exception as err: print(err) finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) ================================================ FILE: test/broker/09-plugin-auth-acl-pub-prop.py ================================================ #!/usr/bin/env python3 # Bug specific test - if a QoS2 publish is denied, then we publish again with # the same mid to a topic that is allowed, does it work properly? from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("plugin c/auth_plugin_v5.so\n") f.write("allow_anonymous false\n") def do_test(): 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("connect-uname-pwd-test", username="test-username", password="cnwTICONIURW", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "custom-name", "custom-value") publish_allowed_packet = mosq_test.gen_publish("bad-topic", qos=1, mid=mid, payload="message", properties=props, proto_ver=5) puback_allowed_packet = mosq_test.gen_puback(mid, reason_code=mqtt5_rc.NO_MATCHING_SUBSCRIBERS, proto_ver=5) mid = 2 publish_denied_packet = mosq_test.gen_publish("bad-topic", qos=1, mid=mid, payload="message", proto_ver=5) puback_denied_packet = mosq_test.gen_puback(mid, reason_code=mqtt5_rc.NOT_AUTHORIZED, 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_allowed_packet, puback_allowed_packet, "puback allowed") mosq_test.do_send_receive(sock, publish_denied_packet, puback_denied_packet, "puback denied") sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() ================================================ FILE: test/broker/09-plugin-auth-acl-pub.py ================================================ #!/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("listener %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 connect1_packet = mosq_test.gen_connect("connect-uname-pwd-test", username="readwrite", clean_session=False) connack1_packet = mosq_test.gen_connack(rc=0) connect2_packet = mosq_test.gen_connect("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(2) do_test(3) do_test(4) do_test(5) ================================================ FILE: test/broker/09-plugin-auth-acl-sub-denied.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("sub-denied-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-auth-acl-sub.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", 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) if plugin_ver == 2: suback_packet_fail = mosq_test.gen_suback(mid_fail, 0) else: 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(2) do_test(3) do_test(4) do_test(5) ================================================ FILE: test/broker/09-plugin-auth-context-params.py ================================================ #!/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("listener %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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-auth-defer-unpwd-fail.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) ================================================ FILE: test/broker/09-plugin-auth-defer-unpwd-success.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) ================================================ FILE: test/broker/09-plugin-auth-msg-params.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("msg-param-test") 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-auth-unpwd-fail.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", username="test-username", password="wrong") connack_packet = mosq_test.gen_connack(rc=5) connect_packet_binary_pw1 = mosq_test.gen_connect("connect-uname-pwd-test", username="binary-password", password="\x00\x01\x02\x03\x04\x05\x06\x08") connect_packet_binary_pw2 = mosq_test.gen_connect("connect-uname-pwd-test", username="binary-password", password="\x00\x01\x02\x03\x04\x05\x06") 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) sock.close() if plugin_ver == 5: sock = mosq_test.do_client_connect(connect_packet_binary_pw1, connack_packet, port=port) sock.close() sock = mosq_test.do_client_connect(connect_packet_binary_pw2, connack_packet, port=port) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) ================================================ FILE: test/broker/09-plugin-auth-unpwd-success.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", username="test-username", password="cnwTICONIURW") connack_packet = mosq_test.gen_connack(rc=0) connect_packet_binary_pw = mosq_test.gen_connect("connect-uname-pwd-test", username="binary-password", password="\x00\x01\x02\x03\x04\x05\x06\x07") 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) sock.close() if plugin_ver == 5: sock = mosq_test.do_client_connect(connect_packet_binary_pw, connack_packet, port=port) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) ================================================ FILE: test/broker/09-plugin-auth-v2-unpwd-fail.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-auth-v2-unpwd-success.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-auth-v3-unpwd-fail.py ================================================ #!/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("listener %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v3.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("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-auth-v3-unpwd-success.py ================================================ #!/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("listener %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v3.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("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-auth-v4-unpwd-fail.py ================================================ #!/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("listener %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v4.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("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-auth-v4-unpwd-success.py ================================================ #!/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("listener %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v4.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("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-auth-v5-unpwd-fail.py ================================================ #!/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("listener %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v5.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("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-auth-v5-unpwd-success.py ================================================ #!/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("listener %d\n" % (port)) f.write("auth_plugin c/auth_plugin_v5.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("connect-uname-pwd-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-bad.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * # Check whether incomplete plugins are handled ok def write_config(filename, port, plugver, num): with open(filename, 'w') as f: f.write(f"listener {port}\n") f.write(f"auth_plugin c/bad_v{plugver}_{num}.so\n") f.write("allow_anonymous false\n") def do_test(plugver, num): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, plugver, num) try: rc = 1 broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port, check_port=False) broker.wait(5) broker.terminate() if broker.returncode == 13: rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test("none", 1) for i in range(1,8): do_test(2, i) for i in range(1,8): do_test(3, i) for i in range(1,5): do_test(4, i) do_test(5, 1) ================================================ FILE: test/broker/09-plugin-change-id.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def write_config(filename, port, plugin_ver): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write("auth_plugin c/auth_plugin_id_change.so\n") f.write("allow_anonymous true\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 connect1_packet = mosq_test.gen_connect("already-exists") connack1_packet = mosq_test.gen_connack(rc=0) connect2_packet = mosq_test.gen_connect("id-change-test") connack2_packet = mosq_test.gen_connack(rc=0) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 0) # Only subs by client id == allowed is allowed suback_packet_denied = mosq_test.gen_suback(mid, 128) suback_packet_ok = mosq_test.gen_suback(mid, 0) mid = 2 publish1_packet = mosq_test.gen_publish("publish/topic", 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) 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, timeout=20, port=port) sock2 = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=20, port=port) mosq_test.do_send_receive(sock1, subscribe_packet, suback_packet_denied, "suback denied") mosq_test.do_send_receive(sock2, subscribe_packet, suback_packet_ok, "suback ok") mosq_test.do_ping(sock1) mosq_test.do_ping(sock2) sock1.close() sock2.close() rc = 0 except mosq_test.TestError: pass except Exception as err: print(err) finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) ================================================ FILE: test/broker/09-plugin-delayed-auth.py ================================================ #!/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("listener %d\n" % (port)) f.write("auth_plugin c/auth_plugin_delayed.so\n") 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 connect_packet = mosq_test.gen_connect("delayed-auth-test", username="delayed-username", password="good", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connect_packet2 = mosq_test.gen_connect("delayed-auth-test", username="delayed-username", password="bad", proto_ver=proto_ver) if proto_ver == 5: connack_packet2 = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=proto_ver, property_helper=False) else: connack_packet2 = 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, timeout=20, port=port) sock.close() sock = mosq_test.do_client_connect(connect_packet2, connack_packet2, timeout=20, port=port) sock.close() # Connect, disconnect, reconnect - try to trigger #3388 print(broker.returncode) for i in range(0, 10): try: sock = mosq_test.client_connect_only() except ConnectionRefusedError: time.sleep(0.5) sock.send(connect_packet) sock.close() # Give the tick time to trigger time.sleep(0.5) sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=20, port=port) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(4) do_test(5) ================================================ FILE: test/broker/09-plugin-evt-client-offline.py ================================================ #!/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("plugin c/plugin_evt_client_offline.so\n") f.write("allow_anonymous true\n") def do_test(): rc = 1 connect_packet = mosq_test.gen_connect("plugin-evt-subscribe", proto_ver=4, clean_session=False) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=4) publish_packet = mosq_test.gen_publish("evt/client/offline", qos=0, payload="plugin-evt-subscribe") 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__), port=port, use_conf=True) try: sub_sock = mosq_test.sub_helper(port, '#') sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() mosq_test.expect_packet(sub_sock, "publish", publish_packet) rc = 0 sub_sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() ================================================ FILE: test/broker/09-plugin-evt-message-in.py ================================================ #!/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("plugin c/plugin_evt_message_in.so\n") f.write("allow_anonymous true\n") def do_test(): rc = 1 connect_packet = mosq_test.gen_connect("plugin-evt-message-in", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "fixed-topic", 2, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=5) props = mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "response/topic") publish_packet1 = mosq_test.gen_publish("subpub/qos2/receive/maximum1", qos=0, payload="message1", proto_ver=5, properties=props) props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key", "value") publish_packet2 = mosq_test.gen_publish("fixed-topic", qos=0, payload="new-message", proto_ver=5, properties=props) 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__), port=port, use_conf=True) 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_packet1) mosq_test.expect_packet(sock, "publish2", publish_packet2) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() ================================================ FILE: test/broker/09-plugin-evt-message-out.py ================================================ #!/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("plugin c/plugin_evt_message_out.so\n") f.write("allow_anonymous true\n") def do_test(): rc = 1 connect_packet = mosq_test.gen_connect("plugin-evt-message-out", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 2, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 2, proto_ver=5) publish_packet_deny = mosq_test.gen_publish("deny", qos=0, payload="message1", proto_ver=5) props = mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "response/topic") publish_packet1 = mosq_test.gen_publish("out-topic", qos=0, payload="message1", proto_ver=5, properties=props) props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key", "value") publish_packet2 = mosq_test.gen_publish("new-topic", qos=0, payload="new-message", proto_ver=5, properties=props) 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__), port=port, use_conf=True) 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_deny) mosq_test.do_ping(sock) sock.send(publish_packet1) mosq_test.expect_packet(sock, "publish2", publish_packet2) mosq_test.do_ping(sock) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() ================================================ FILE: test/broker/09-plugin-evt-psk-key.py ================================================ #!/usr/bin/env python3 # Test whether a plugin can subscribe to the tick event from mosq_test_helper import * def write_config(filename, port, per_listener_settings="false"): with open(filename, "w") as f: f.write("per_listener_settings %s\n" % (per_listener_settings)) f.write("listener %d\n" % (port)) f.write("plugin c/plugin_evt_psk_key.so\n") f.write("psk_hint myhint\n") f.write("allow_anonymous true\n") def do_test(per_listener_settings): rc = 1 proto_ver = 5 port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace(".py", ".conf") write_config(conf_file, port, per_listener_settings) broker = mosq_test.start_broker( filename=os.path.basename(__file__), use_conf=True, port=port, ) try: pub_client_args = [ mosq_test.get_build_root() + "/client/mosquitto_pub", "-t", "plugin/psk/test", "-m", "psk-test-pub-client", "--psk", "297A49", "--psk-identity", "pubidentity", "-p", str(port), "-r", ] pub_client = mosq_test.start_client( filename=sys.argv[0].replace("/", "-"), cmd=pub_client_args ) pub_client.wait() bad_client_args = [ mosq_test.get_build_root() + "/client/mosquitto_pub", "-t", "plugin/psk/test", "-m", "psk-test-bad-client", "--psk", "159445", "--psk-identity", "badidentity", "-p", str(port), "-r", ] bad_client = mosq_test.start_client( filename=sys.argv[0].replace("/", "-"), cmd=bad_client_args ) bad_client.wait() if bad_client.returncode == 0: raise ValueError("bad client should have failed") sub_client_args = [ mosq_test.get_build_root() + "/client/mosquitto_sub", "-t", "plugin/psk/test", "-C", "1", "-W", "2", "--psk", "159445", "--psk-identity", "subidentity", "-v", "-N", "-p", str(port), ] sub_client = mosq_test.start_client( filename=sys.argv[0].replace("/", "-"), cmd=sub_client_args ) sub_client.wait() if pub_client.returncode == 0 and sub_client.returncode == 0: (stdo, _) = sub_client.communicate() if stdo.decode("utf-8") != "plugin/psk/test psk-test-pub-client": raise ValueError(stdo.decode("utf-8")) else: raise ValueError( f"pub_client returned {pub_client.returncode}, sub_client returned {sub_client.returncode}" ) rc = 0 except mosq_test.TestError: pass except Exception as err: print(err) finally: os.remove(conf_file) broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode("utf-8")) exit(rc) do_test("false") do_test("true") ================================================ FILE: test/broker/09-plugin-evt-reload.py ================================================ #!/usr/bin/env python3 # Test whether a plugin can subscribe to the reload event from mosq_test_helper import * import signal def write_config(filename, port, per_listener_settings="false"): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener_settings)) f.write("listener %d\n" % (port)) f.write("plugin c/plugin_evt_reload.so\n") f.write("allow_anonymous true\n") def do_test(per_listener_settings): proto_ver = 5 port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, per_listener_settings) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("plugin-reload-test", keepalive=keepalive, username="readwrite", clean_session=False, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) reload_packet = mosq_test.gen_publish("topic/reload", qos=0, payload="test-message", proto_ver=proto_ver) print("1") 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=10, port=port) broker.send_signal(signal.SIGHUP) mosq_test.expect_packet(sock, "reload message", reload_packet) #mosq_test.expect_packet(sock, "reload message", reload_packet) #mosq_test.expect_packet(sock, "reload message", reload_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) do_test("false") do_test("true") ================================================ FILE: test/broker/09-plugin-evt-subscribe.py ================================================ #!/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("plugin c/plugin_evt_subscribe.so\n") f.write("allow_anonymous true\n") def do_test(): rc = 1 connect_packet = mosq_test.gen_connect("plugin-evt-subscribe", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "subscribe-topic", 1, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 2 publish_packet1 = mosq_test.gen_publish("new-topic", mid=mid, qos=1, payload="message1", proto_ver=5) puback_packet1 = mosq_test.gen_puback(mid, proto_ver=5) publish_packet2 = mosq_test.gen_publish("new-topic", qos=0, payload="message1", proto_ver=5) 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__), port=port, use_conf=True) 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_packet1) mosq_test.receive_unordered(sock, puback_packet1, publish_packet2, "puback / publish2") rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() ================================================ FILE: test/broker/09-plugin-evt-tick.py ================================================ #!/usr/bin/env python3 # Test whether a plugin can subscribe to the tick event from mosq_test_helper import * def write_config(filename, port, per_listener_settings="false"): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener_settings)) f.write("listener %d\n" % (port)) f.write("plugin c/plugin_evt_tick.so\n") f.write("allow_anonymous true\n") def do_test(per_listener_settings): proto_ver = 5 port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, per_listener_settings) rc = 1 keepalive = 10 connect_packet = mosq_test.gen_connect("plugin-tick-test", keepalive=keepalive, username="readwrite", clean_session=False, proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) tick_packet = mosq_test.gen_publish("topic/tick", qos=0, payload="test-message", 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, timeout=10, port=port) mosq_test.expect_packet(sock, "tick message", tick_packet) mosq_test.expect_packet(sock, "tick message", tick_packet) mosq_test.expect_packet(sock, "tick message", tick_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) do_test("false") do_test("true") ================================================ FILE: test/broker/09-plugin-evt-unsubscribe.py ================================================ #!/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("plugin c/plugin_evt_unsubscribe.so\n") f.write("allow_anonymous true\n") def do_test(): rc = 1 connect_packet = mosq_test.gen_connect("plugin-evt-unsubscribe", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "unsubscribe-topic", 1, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 2 unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "unsubscribe-topic", proto_ver=5) unsuback_packet = mosq_test.gen_unsuback(mid, mqtt5_rc.NO_SUBSCRIPTION_EXISTED, proto_ver=5) publish_packet = mosq_test.gen_publish("unsubscribe-topic", qos=0, payload="message1", proto_ver=5) 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__), port=port, use_conf=True) 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, unsubscribe_packet, unsuback_packet, "unsuback") mosq_test.do_send_receive(sock, publish_packet, publish_packet, "publish") rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() ================================================ FILE: test/broker/09-plugin-load-acl.py ================================================ #!/usr/bin/env python3 # Test whether a plugin can subscribe to the tick event from mosq_test_helper import * import signal def write_config(filename, ports, per_listener_settings): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener_settings)) f.write("plugin_load acl c/plugin_load_acl.so\n") f.write("listener %d\n" % (ports[0])) f.write("listener_allow_anonymous true\n") f.write("plugin_use acl\n") f.write("listener %d\n" % (ports[1])) f.write("listener_allow_anonymous true\n") def client_check(topic, rc, port): connect_packet = mosq_test.gen_connect(client_id="id", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) publish_packet = mosq_test.gen_publish(topic=topic, qos=1, mid=1, payload="message", proto_ver=5) puback_packet = mosq_test.gen_puback(mid=1, reason_code=rc, proto_ver=5) mosq_test.do_send_receive(sock, publish_packet, puback_packet, f"puback {topic}") sock.close() def do_test(per_listener_settings): proto_ver = 5 ports = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, ports, per_listener_settings) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=ports[0]) rc = 1 try: # Plugin loaded client_check("denied-topic", mqtt5_rc.NOT_AUTHORIZED, ports[0]) # Should fail client_check("allowed-topic", mqtt5_rc.NO_MATCHING_SUBSCRIBERS, ports[0]) # Should succeed # No plugin client_check("denied-topic", mqtt5_rc.NO_MATCHING_SUBSCRIBERS, ports[1]) # Should succeed client_check("allowed-topic", mqtt5_rc.NO_MATCHING_SUBSCRIBERS, ports[1]) # Should succeed rc = 0 except Exception as err: print(err) finally: os.remove(conf_file) broker.terminate() broker.wait() if rc: print(f"per_listener_settings:{per_listener_settings}") (stdo, stde) = broker.communicate() print(stde.decode('utf-8')) exit(rc) do_test("false") do_test("true") ================================================ FILE: test/broker/09-plugin-load-basic-auth.py ================================================ #!/usr/bin/env python3 # Test whether a plugin can subscribe to the tick event from mosq_test_helper import * import signal def write_config1(filename, ports, per_listener_settings, plugver): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener_settings)) f.write("plugin_load auth c/auth_plugin_v%d.so\n" % (plugver)) f.write("listener %d\n" % (ports[0])) f.write("plugin_use auth\n") f.write("listener %d\n" % (ports[1])) f.write("allow_anonymous false\n") f.write("listener %d\n" % (ports[2])) f.write("plugin_use auth\n") def write_config2(filename, ports, per_listener_settings, plugver): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener_settings)) f.write("plugin_load auth c/auth_plugin_v%d.so\n" % (plugver)) f.write("listener %d\n" % (ports[0])) f.write("listener %d\n" % (ports[1])) f.write("plugin_use auth\n") f.write("listener %d\n" % (ports[2])) f.write("plugin_use auth\n") def client_check(username, password, rc, port): connect_packet = mosq_test.gen_connect(client_id="id", username=username, password=password) connack_packet = mosq_test.gen_connack(rc=rc) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() def do_test(per_listener_settings, plugver): proto_ver = 5 ports = mosq_test.get_port(3) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config1(conf_file, ports, per_listener_settings, plugver) plugin_reload_fixed = False # FIXME - set to true then remove once plugin reloading is working broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=ports[0]) rc = 1 try: client_check("test-username", "cnwTICONIURW", 0, ports[0]) # Should succeed client_check("test-username", "cnwTICONIURW", 5, ports[1]) # Should fail client_check("test-username", "cnwTICONIURW", 0, ports[2]) # Should succeed client_check("bad-actor", "nope", 5, ports[0]) # Should fail client_check("bad-actor", "nope", 5, ports[1]) # Should fail client_check("bad-actor", "nope", 5, ports[2]) # Should fail client_check(None, None, 5, ports[0]) # Should fail client_check(None, None, 5, ports[1]) # Should fail client_check(None, None, 5, ports[2]) # Should fail if plugin_reload_fixed: # Now swap auth around so ports[0] has no plugin but ports[1] does write_config2(conf_file, ports, per_listener_settings, plugver) broker.send_signal(signal.SIGHUP) client_check("test-username", "cnwTICONIURW", 5, ports[0]) # Should fail client_check("test-username", "cnwTICONIURW", 0, ports[1]) # Should succeed client_check("test-username", "cnwTICONIURW", 0, ports[2]) # Should succeed client_check("bad-actor", "nope", 5, ports[0]) # Should fail client_check("bad-actor", "nope", 5, ports[1]) # Should fail client_check("bad-actor", "nope", 5, ports[2]) # Should fail client_check(None, None, 5, ports[0]) # Should fail client_check(None, None, 5, ports[1]) # Should fail client_check(None, None, 5, ports[2]) # Should fail else: # Now swap auth around so ports[0] has no plugin but ports[1] does write_config2(conf_file, ports, per_listener_settings, plugver) # Check config works as before - plugin reloading disabled broker.send_signal(signal.SIGHUP) client_check("test-username", "cnwTICONIURW", 0, ports[0]) # Should succeed client_check("test-username", "cnwTICONIURW", 5, ports[1]) # Should fail client_check("test-username", "cnwTICONIURW", 0, ports[2]) # Should succeed client_check("bad-actor", "nope", 5, ports[0]) # Should fail client_check("bad-actor", "nope", 5, ports[1]) # Should fail client_check("bad-actor", "nope", 5, ports[2]) # Should fail client_check(None, None, 5, ports[0]) # Should fail client_check(None, None, 5, ports[1]) # Should fail client_check(None, None, 5, ports[2]) # Should fail rc = 0 except Exception as err: print(err) finally: os.remove(conf_file) broker.terminate() broker.wait() if rc: print(f"per_listener_settings:{per_listener_settings} plugver:{plugver}") (stdo, stde) = broker.communicate() print(stde.decode('utf-8')) exit(rc) print("T1") do_test("false", 2) print("T2") do_test("true", 2) print("T3") do_test("false", 3) print("T4") do_test("true", 3) print("T5") do_test("false", 4) print("T6") do_test("true", 4) print("T7") do_test("false", 5) print("T8") do_test("true", 5) ================================================ FILE: test/broker/09-plugin-load-extended-auth.py ================================================ #!/usr/bin/env python3 # Test whether a plugin can subscribe to the tick event from mosq_test_helper import * import signal def write_config(filename, ports, per_listener_settings): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener_settings)) f.write("plugin_load auth c/plugin_load_extended_auth.so\n") f.write("listener %d\n" % (ports[0])) f.write("plugin_use auth\n") f.write("listener %d\n" % (ports[1])) def client_check_start_denied(start_data, rc, port): props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "test") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, start_data) connect_packet = mosq_test.gen_connect(client_id="id", proto_ver=5, properties=props) connack_packet = mosq_test.gen_connack(rc=rc, proto_ver=5) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() except BrokenPipeError: if rc == mqtt5_rc.NOT_AUTHORIZED or rc == mqtt5_rc.BAD_AUTHENTICATION_METHOD: return else: raise return def client_check_start_allowed(start_data, cont_data, rc, port): props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "test") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, start_data) connect_packet = mosq_test.gen_connect(client_id="id", proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "test") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "start-ok") auth_packet_recv = mosq_test.gen_auth(reason_code=mqtt5_rc.CONTINUE_AUTHENTICATION, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "test") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, cont_data) auth_packet_send = mosq_test.gen_auth(reason_code=mqtt5_rc.CONTINUE_AUTHENTICATION, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "test") connack_packet = mosq_test.gen_connack(rc=rc, proto_ver=5, properties=props) sock = mosq_test.do_client_connect(connect_packet, auth_packet_recv, port=port) try: mosq_test.do_send_receive(sock, auth_packet_send, connack_packet, f"connack {cont_data}") sock.close() except BrokenPipeError: if rc == mqtt5_rc.NOT_AUTHORIZED: return else: raise def do_test(per_listener_settings): proto_ver = 5 ports = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, ports, per_listener_settings) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=ports[0]) rc = 1 try: # Plugin loaded client_check_start_denied("denied-start", mqtt5_rc.NOT_AUTHORIZED, ports[0]) # Should fail client_check_start_allowed("allowed-start", "denied-continue", mqtt5_rc.NOT_AUTHORIZED, ports[0]) # Should fail client_check_start_allowed("allowed-start", "allowed-continue", mqtt5_rc.SUCCESS, ports[0]) # Should succeed # No plugin client_check_start_denied("denied-topic", mqtt5_rc.BAD_AUTHENTICATION_METHOD, ports[1]) # Should fail client_check_start_denied("allowed-topic", mqtt5_rc.BAD_AUTHENTICATION_METHOD, ports[1]) # Should fail rc = 0 except Exception as err: print(err) finally: os.remove(conf_file) broker.terminate() broker.wait() if rc: print(f"per_listener_settings:{per_listener_settings}") (stdo, stde) = broker.communicate() print(stde.decode('utf-8')) exit(rc) do_test("false") do_test("true") ================================================ FILE: test/broker/09-plugin-publish.py ================================================ #!/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("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 connect1_packet = mosq_test.gen_connect("test-client", 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.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/09-plugin-unsupported.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * # Check whether unsupported plugin versions are handled ok def write_config(filename, port, plugver): with open(filename, 'w') as f: f.write(f"listener {port}\n") f.write(f"auth_plugin c/bad_v{plugver}.so\n") f.write("allow_anonymous false\n") def do_test(plugver): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port, plugver) try: rc = 1 broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port, check_port=False) broker.wait(5) broker.terminate() if broker.returncode == 13: rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(1) do_test(6) ================================================ FILE: test/broker/09-pwfile-parse-invalid.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("username-password-check", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 def expect_broker_fail_test(port, expect_fail_log): broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port, expect_fail=True, expect_fail_log=expect_fail_log) 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) expect_broker_fail_test(port, "Error: Unable to decode line in password file") # Invalid file, first line incomplete, but with "password" write_pwfile(pw_file, bad_line1='bad:bad', bad_line2=None) expect_broker_fail_test(port, "Error: Unable to decode line in password file") # Invalid file, first line incomplete, partial password hash write_pwfile(pw_file, bad_line1='bad:$', bad_line2=None) expect_broker_fail_test(port, "Error: Unable to decode line in password file") # Invalid file, first line incomplete, partial password hash write_pwfile(pw_file, bad_line1='bad:$6', bad_line2=None) expect_broker_fail_test(port, "Error: Unable to decode line in password file") # Invalid file, first line incomplete, partial password hash write_pwfile(pw_file, bad_line1='bad:$6$', bad_line2=None) expect_broker_fail_test(port, "Error: Unable to decode line in password file") # 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) expect_broker_fail_test(port, "Error: Unable to decode line in password file") # 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) expect_broker_fail_test(port, "Error: Unable to decode line in password file") # 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) expect_broker_fail_test(port, "Error: Unable to decode line in password file") # 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) expect_broker_fail_test(port, "Error: Invalid line in password file") # 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) expect_broker_fail_test(port, "Error: Unable to decode line in password file") # 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) expect_broker_fail_test(port, "Error: Unable to decode line in password file") 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) ================================================ FILE: test/broker/10-listener-mount-point.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("listener %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("10-listener-mount-helper", proto_ver=proto_ver) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish("10/listener/mount/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 mid = 1 # Subscriber for listener with mount point connect_packet1 = mosq_test.gen_connect("test1", proto_ver=proto_ver) connack_packet1 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet1 = mosq_test.gen_subscribe(mid, "#", 0, proto_ver=proto_ver) suback_packet1 = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) publish_packet1 = mosq_test.gen_publish("mount/10/listener/mount/test", qos=0, payload="mount point", proto_ver=proto_ver) # Subscriber for listener without mount point connect_packet2 = mosq_test.gen_connect("test2", proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) subscribe_packet2 = mosq_test.gen_subscribe(mid, "#", 0, proto_ver=proto_ver) suback_packet2 = mosq_test.gen_suback(mid, 0, proto_ver=proto_ver) publish_packet2 = mosq_test.gen_publish("10/listener/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: sock1 = mosq_test.do_client_connect(connect_packet1, connack_packet1, timeout=20, port=port1) mosq_test.do_send_receive(sock1, subscribe_packet1, suback_packet1, "suback1") sock2 = mosq_test.do_client_connect(connect_packet2, connack_packet2, timeout=20, port=port2) mosq_test.do_send_receive(sock2, subscribe_packet2, suback_packet2, "suback2") helper(port2, proto_ver) # Should have now received a publish command mosq_test.expect_packet(sock1, "publish1", publish_packet1) mosq_test.expect_packet(sock2, "publish2", publish_packet2) rc = 0 sock1.close() sock2.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/11-message-expiry.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect("subpub-qos0-test", 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.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.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/11-persistence-autosave-changes.py ================================================ #!/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("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("persistence true\n") f.write("persistence_file mosquitto-%d.db\n" % (port)) f.write("autosave_interval 1\n") f.write("autosave_on_changes true\n") def do_test(): 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("persistent-test", clean_session=True) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("subpub/qos1", qos=1, mid=1, payload="message", retain=True) puback_packet = mosq_test.gen_puback(1) 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) try: 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() time.sleep(0.5) if os.path.exists('mosquitto-%d.db' % (port)): rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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')) exit(rc) do_test() exit(0) ================================================ FILE: test/broker/11-persistent-subscription-no-local.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect( "persistent-subscription-test", 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) = (None, None) 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) # Send a ping and wait for the the response to make sure the puback2a_packet was processed by the broker mosq_test.do_ping(sock) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) if rc and stde1: print(stde1.decode('utf-8')) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/11-persistent-subscription.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect( "persistent-subscription-test", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/11-pub-props.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect( "persistent-props-test", 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.PAYLOAD_FORMAT_INDICATOR, 1) props += mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "plain/text") props += mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "/dev/null") props += mqtt5_props.gen_string_prop(mqtt5_props.CORRELATION_DATA, "2357289375902345") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.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.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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/11-subscription-id.py ================================================ #!/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("listener %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 connect_packet = mosq_test.gen_connect( "persistent-subscription-test", 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.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.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", 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/broker/12-prop-assigned-client-identifier.py ================================================ #!/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(start_broker, clean_start): rc = 1 connect_packet = mosq_test.gen_connect(None, proto_ver=5, clean_session=clean_start) props = mqtt5_props.gen_string_prop(mqtt5_props.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.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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): rc = do_test(start_broker, True) if rc: return rc; rc = do_test(start_broker, False) if rc: return rc; return 0 if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/12-prop-maximum-packet-size-broker.py ================================================ #!/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("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("max_packet_size 50\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("12-max-packet-broker", proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) props += mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 50) props += mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props, property_helper=False) publish_packet_ok = mosq_test.gen_publish("12/max/packet/size/broker/test/topic", qos=0, payload="012345678", proto_ver=5) publish_packet_bad = mosq_test.gen_publish("12/max/packet/size/broker/test/topic", qos=0, payload="0123456789", 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) sock.send(publish_packet_ok) mosq_test.do_ping(sock) mosq_test.do_send_receive(sock, publish_packet_bad, disconnect_packet, "disconnect") rc = 0 except mosq_test.TestError: pass finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 os.remove(conf_file) (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/12-prop-maximum-packet-size-publish-qos1.py ================================================ #!/usr/bin/env python3 # Test whether maximum packet size is honoured on a PUBLISH to a client # MQTTv5 from mosq_test_helper import * def do_test(start_broker): rc = 1 props = mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 40) connect_packet = mosq_test.gen_connect("12-max-publish-qos1", 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, "12/max/publish/qos1/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="12/max/publish/qos1/test/topic", mid=mid, qos=1, payload="1234", proto_ver=5) puback1_packet = mosq_test.gen_puback(mid, proto_ver=5) mid=2 props = mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 1) publish2_packet = mosq_test.gen_publish(topic="12/max/publish/qos1/test/topic", mid=mid, qos=1, payload="56", proto_ver=5, properties=props) puback2_packet = mosq_test.gen_puback(mid, proto_ver=5) mid=3 publish3_packet = mosq_test.gen_publish(topic="12/max/publish/qos1/test/topic", mid=mid, qos=1, payload="789", proto_ver=5) puback3_packet = mosq_test.gen_puback(mid, proto_ver=5) port = mosq_test.get_port() if start_broker: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet) mosq_test.do_send_receive(sock, publish1_packet, puback1_packet, "puback 1") # We shouldn't receive the publish here because it is > MAXIMUM_PACKET_SIZE mosq_test.do_ping(sock) mosq_test.do_send_receive(sock, publish2_packet, puback2_packet, "puback 2") # We shouldn't receive the publish here because it is > MAXIMUM_PACKET_SIZE mosq_test.do_ping(sock) sock.send(publish3_packet) mosq_test.receive_unordered(sock, puback3_packet, publish3_packet, "puback 3/publish3") rc = 0 except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc; def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/12-prop-maximum-packet-size-publish-qos2.py ================================================ #!/usr/bin/env python3 # Test whether maximum packet size is honoured on a PUBLISH to a client # MQTTv5 from mosq_test_helper import * def do_test(start_broker): rc = 1 props = mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 40) connect_packet = mosq_test.gen_connect("12-max-publish-qos2", 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, "12/max/publish/qos2/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="12/max/publish/qos2/test/topic", mid=mid, qos=2, payload="1234", 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="12/max/publish/qos2/test/topic", mid=mid, qos=2, payload="789", 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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/12-prop-response-topic-correlation-data.py ================================================ #!/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 * def do_test(start_broker): rc = 1 connect_packet1 = mosq_test.gen_connect("client1", proto_ver=5) connect_packet2 = mosq_test.gen_connect("client2", proto_ver=5) 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.RESPONSE_TOPIC, "response/topic") props = mqtt5_props.gen_string_prop(mqtt5_props.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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/12-prop-response-topic.py ================================================ #!/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 * def do_test(start_broker): rc = 1 connect_packet1 = mosq_test.gen_connect("12-response-topic-client1", proto_ver=5) connect_packet2 = mosq_test.gen_connect("12-response-topic-client2", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet1 = mosq_test.gen_subscribe(mid=1, topic="12/response/topic/normal/topic", qos=0, proto_ver=5) subscribe_packet2 = mosq_test.gen_subscribe(mid=1, topic="12/response/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.RESPONSE_TOPIC, "12/response/topic/response/topic") publish_packet2 = mosq_test.gen_publish(topic="12/response/topic/normal/topic", qos=0, payload="2", proto_ver=5, properties=props) publish_packet1 = mosq_test.gen_publish(topic="12/response/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() if start_broker: 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: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/12-prop-server-keepalive.py ================================================ #!/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("listener %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("12-server-keepalive", proto_ver=5, keepalive=keepalive) props = mqtt5_props.gen_uint16_prop(mqtt5_props.SERVER_KEEP_ALIVE, 60) \ + mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) \ + mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 2000000) \ + mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props, property_helper=False) 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/12-prop-subpub-content-type.py ================================================ #!/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 * def do_test(start_broker): props_out = mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "text") props_out = props_out+mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS, 1) props_in = mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "text") return helper.prop_subpub_helper(start_broker, "12-prop-subpub-content-type", props_out, props_in) def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/12-prop-subpub-payload-format.py ================================================ #!/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 * def do_test(start_broker): props_out = mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 0xed) props_out = props_out+mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS, 1) props_in = mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 0xed) return helper.prop_subpub_helper(start_broker, "12-prop-subpub-payload-format", props_out, props_in, expect_proto_error=True) def all_tests(start_broker=False): return do_test(start_broker) if __name__ == '__main__': all_tests(True) ================================================ FILE: test/broker/13-websocket-bad-origin.py ================================================ #!/usr/bin/env python3 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("protocol websockets\n") f.write("websockets_origin example.org\n") def do_test(publish_packet, reason_code, error_string): global rc rc = 1 connect_packet = mosq_test.gen_connect("13-malformed-publish-v5", proto_ver=5) connack_props = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) connack_props += mqtt5_props.gen_byte_prop(mqtt5_props.RETAIN_AVAILABLE, 0) connack_props += mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) connack_props += mqtt5_props.gen_byte_prop(mqtt5_props.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: websocket_req_bad = b"GET /mqtt HTTP/1.1\r\n" \ + b"Host: localhost\r\n" \ + b"Upgrade: websocket\r\n" \ + b"Connection: Upgrade\r\n" \ + B"Sec-WebSocket-Key: 1JaITHdgDZVd/4OE2AzTTA==\r\n" \ + b"Sec-WebSocket-Protocol: mqtt\r\n" \ + b"Sec-WebSocket-Version: 13\r\n" \ + b"Origin: localhost\r\n" \ + b"\r\n" sock = mosq_test.do_client_connect(websocket_req_bad, b"", port=port) sock.close() except BrokenPipeError: pass try: websocket_req_good = b"GET /mqtt HTTP/1.1\r\n" \ + b"Host: localhost\r\n" \ + b"Upgrade: websocket\r\n" \ + b"Connection: Upgrade\r\n" \ + B"Sec-WebSocket-Key: 1JaITHdgDZVd/4OE2AzTTA==\r\n" \ + b"Sec-WebSocket-Protocol: mqtt\r\n" \ + b"Sec-WebSocket-Version: 13\r\n" \ + b"Origin: example.org\r\n" \ + b"\r\n" websocket_resp_good = b"HTTP/1.1 101 Switching Protocols\r\n" \ + b"Upgrade: WebSocket\r\n" \ + b"Connection: Upgrade\r\n" \ + b"Sec-WebSocket-Accept: Ako91O0lxiq8gN0+b9YCijMx8lk=\r\n" \ + b"Sec-WebSocket-Protocol: mqtt\r\n" \ + b"\r\n" sock = mosq_test.do_client_connect(websocket_req_good, websocket_resp_good, port=port) sock.close() rc = 0 except Exception as err: print(err) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() os.remove(conf_file) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-acl.py ================================================ #!/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 * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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": "addRoleACL", "rolename": "myrole", "acltype": "subscribePattern", "topic": "pattern/#", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "subscribePattern", "topic": "subscribe/pattern/c/%c/allowed", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "subscribePattern", "topic": "subscribe/pattern/c/%c/denied", "allow": False }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "subscribePattern", "topic": "subscribe/pattern/u/%u/allowed", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "subscribePattern", "topic": "subscribe/pattern/u/%u/denied", "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': 'addRoleACL'}, {'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": "publishClientSend", "topic": "pattern/u/%u/topic/#", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientSend", "topic": "pattern/u/%u/denied", "allow": False }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientSend", "topic": "pattern/c/%c/topic/#", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientSend", "topic": "pattern/c/%c/denied", "allow": False }, { "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 }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientReceive", "topic": "pattern/u/%u/topic/#", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientReceive", "topic": "pattern/u/%u/denied", "allow": False }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientReceive", "topic": "pattern/c/%c/topic/#", "allow": True }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "publishClientReceive", "topic": "pattern/c/%c/denied", "allow": False }, ]} add_publish_acl_response = {'responses': [ {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'command': 'addRoleACL'}, {'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 connect_packet_admin = mosq_test.gen_connect("ctrl-test", 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", 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.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.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.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.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.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.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.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.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) mid = 14 subscribe_pattern_packet = mosq_test.gen_subscribe(mid, "pattern/#", 0, proto_ver=5) suback_pattern_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) disconnect_kick_packet = mosq_test.gen_disconnect(reason_code=mqtt5_rc.ADMINISTRATIVE_ACTION, proto_ver=5) mid = 15 publish_u_pattern_packet = mosq_test.gen_publish(mid=mid, topic="pattern/u/user_one/topic", qos=1, proto_ver=5, payload="test") puback_u_packet_success = mosq_test.gen_puback(mid=mid, proto_ver=5) publish_u_pattern_packet_r = mosq_test.gen_publish(topic="pattern/u/user_one/topic", qos=0, proto_ver=5, payload="test") mid = 16 publish_u_pattern_packet_denied = mosq_test.gen_publish(mid=mid, topic="pattern/u/user_one/denied", qos=1, proto_ver=5, payload="test") puback_u_packet_denied = mosq_test.gen_puback(mid=mid, reason_code=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5) mid = 17 publish_c_pattern_packet = mosq_test.gen_publish(mid=mid, topic="pattern/c/cid/topic", qos=1, proto_ver=5, payload="test") puback_c_packet_success = mosq_test.gen_puback(mid=mid, proto_ver=5) publish_c_pattern_packet_r = mosq_test.gen_publish(topic="pattern/c/cid/topic", qos=0, proto_ver=5, payload="test") mid = 18 publish_c_pattern_packet_denied = mosq_test.gen_publish(mid=mid, topic="pattern/c/cid/denied", qos=1, proto_ver=5, payload="test") puback_c_packet_denied = mosq_test.gen_puback(mid=mid, reason_code=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5) mid = 19 subscribe_u_pattern_packet_allowed_success = mosq_test.gen_subscribe(mid, "subscribe/pattern/u/user_one/allowed", qos=1, proto_ver=5) suback_u_pattern_packet_allowed_success = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 20 subscribe_u_pattern_packet_allowed_fail = mosq_test.gen_subscribe(mid, "subscribe/pattern/u/bad/allowed", qos=1, proto_ver=5) suback_u_pattern_packet_allowed_fail = mosq_test.gen_suback(mid, mqtt5_rc.NOT_AUTHORIZED, proto_ver=5) mid = 21 subscribe_u_pattern_packet_denied_success = mosq_test.gen_subscribe(mid, "subscribe/pattern/u/user_one/denied", qos=1, proto_ver=5) suback_u_pattern_packet_denied_success = mosq_test.gen_suback(mid, mqtt5_rc.NOT_AUTHORIZED, proto_ver=5) mid = 22 subscribe_c_pattern_packet_allowed_success = mosq_test.gen_subscribe(mid, "subscribe/pattern/c/cid/allowed", qos=1, proto_ver=5) suback_c_pattern_packet_allowed_success = mosq_test.gen_suback(mid, 1, proto_ver=5) mid = 23 subscribe_c_pattern_packet_allowed_fail = mosq_test.gen_subscribe(mid, "subscribe/pattern/c/bad/allowed", qos=1, proto_ver=5) suback_c_pattern_packet_allowed_fail = mosq_test.gen_suback(mid, mqtt5_rc.NOT_AUTHORIZED, proto_ver=5) mid = 24 subscribe_c_pattern_packet_denied_success = mosq_test.gen_subscribe(mid, "subscribe/pattern/c/cid/denied", qos=1, proto_ver=5) suback_c_pattern_packet_denied_success = mosq_test.gen_suback(mid, mqtt5_rc.NOT_AUTHORIZED, proto_ver=5) try: if not os.path.exists(str(port)): os.mkdir(str(port)) shutil.copyfile(str(Path(__file__).resolve().parent) + "/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") # Subscribe to "pattern/#" - allowed mosq_test.do_send_receive(csock, subscribe_pattern_packet, suback_pattern_packet, "suback") # 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") # Publish to "pattern/u/user_one/topic" - this is allowed csock.send(publish_u_pattern_packet) mosq_test.receive_unordered(csock, publish_u_pattern_packet_r, puback_u_packet_success, "puback pattern 1 / publish r") # Publish to "pattern/u/user_one/denied" - this is not allowed mosq_test.do_send_receive(csock, publish_u_pattern_packet_denied, puback_u_packet_denied, "puback pattern 2") # Publish to "pattern/c/cid/topic" - this is allowed csock.send(publish_c_pattern_packet) mosq_test.receive_unordered(csock, publish_c_pattern_packet_r, puback_c_packet_success, "puback pattern 3 / publish r") # Publish to "pattern/c/cid/denied" - this is not allowed mosq_test.do_send_receive(csock, publish_c_pattern_packet_denied, puback_c_packet_denied, "puback pattern 4") # Subscribe to "subscribe/pattern/u/user_one/allowed" - this is allowed mosq_test.do_send_receive(csock, subscribe_u_pattern_packet_allowed_success, suback_u_pattern_packet_allowed_success, "suback pattern 1") # Subscribe to "subscribe/pattern/u/bad/allowed" - this is not allowed mosq_test.do_send_receive(csock, subscribe_u_pattern_packet_allowed_fail, suback_u_pattern_packet_allowed_fail, "suback pattern 2") # Subscribe to "subscribe/pattern/u/user_one/denied" - this is not allowed mosq_test.do_send_receive(csock, subscribe_u_pattern_packet_denied_success, suback_u_pattern_packet_denied_success, "suback pattern 3") # Subscribe to "subscribe/pattern/c/cid/allowed" - this is allowed mosq_test.do_send_receive(csock, subscribe_c_pattern_packet_allowed_success, suback_c_pattern_packet_allowed_success, "suback pattern 4") # Subscribe to "subscribe/pattern/c/bad/allowed" - this is not allowed mosq_test.do_send_receive(csock, subscribe_c_pattern_packet_allowed_fail, suback_c_pattern_packet_allowed_fail, "suback pattern 5") # Subscribe to "subscribe/pattern/c/cid/denied" - this is not allowed mosq_test.do_send_receive(csock, subscribe_c_pattern_packet_denied_success, suback_c_pattern_packet_denied_success, "suback pattern 6") # 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") check_details(sock, 2, 1, 1, 29) 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 shutil.rmtree(f"{port}") broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-allow-wildcard.py ================================================ #!/usr/bin/env python3 # Test for allowwildcardsubs behaviour from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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", "allowwildcardsubs": True}, { "command": "addGroupRole", "groupname": "mygroup", "rolename": "myrole" }, { "command": "addRoleACL", "rolename": "myrole", "acltype": "subscribePattern", "topic": "multilevel-wildcard/#", "allow": True }, { "command": "addGroupClient", "groupname": "mygroup", "username": "user_one" } ]} add_client_group_role_response = {'responses': [ {'command': 'createGroup'}, {'command': 'createRole'}, {'command': 'addGroupRole'}, {'command': 'addRoleACL'}, {'command': 'addGroupClient'} ]} modify_role_command = {"commands":[ { "command": "modifyRole", "rolename": "myrole", "allowwildcardsubs": False} ]} modify_role_response = {"responses":[ { "command": "modifyRole"} ]} rc = 1 connect_packet_admin = mosq_test.gen_connect("ctrl-test", 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 = mosq_test.gen_connect("cid", username="user_one", password="password", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 4 subscribe_packet = mosq_test.gen_subscribe(mid, "multilevel-wildcard/#", 0, proto_ver=5) suback_packet_success = mosq_test.gen_suback(mid, 0, proto_ver=5) suback_packet_fail = mosq_test.gen_suback(mid, mqtt5_rc.NOT_AUTHORIZED, proto_ver=5) disconnect_kick_packet = mosq_test.gen_disconnect(reason_code=mqtt5_rc.ADMINISTRATIVE_ACTION, proto_ver=5) try: os.mkdir(str(port)) shutil.copyfile(str(Path(__file__).resolve().parent / "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) # Create a group, add a role to the group, add the client to the group command_check(sock, add_client_group_role_command, add_client_group_role_response) # Client with username, password, and client id csock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port, connack_error="connack 1") # Subscribe to "multilevel-wildcard/#" - allowed mosq_test.do_send_receive(csock, subscribe_packet, suback_packet_success, "suback # allowed") # Modify role - this will kick the client and remove the ability to subscribe to wildcards command_check(sock, modify_role_command, modify_role_response) mosq_test.expect_packet(csock, "disconnect kick 1", disconnect_kick_packet) csock.close() # Reconnect csock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port, connack_error="connack 2") # Subscribe to "multilevel-wildcard/#" - not allowed mosq_test.do_send_receive(csock, subscribe_packet, suback_packet_fail, "suback # not allowed") csock.close() check_details(sock, 2, 1, 2, 7) 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 shutil.rmtree(f"{port}") broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-anon-group.py ================================================ #!/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 * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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'} ]} delete_anon_group_command = { "commands": [ { "command": "deleteGroup", "groupname": "anon-clients", "correlationData": "40" } ] } delete_anon_group_response = {'responses': [ {'command': 'deleteGroup', "error":'Deleting the anonymous group is forbidden', 'correlationData': '40'} ]} delete_anon_group_command = { "commands": [ { "command": "deleteGroup", "groupname": "anon-clients", "correlationData": "40" } ] } delete_anon_group_response = {'responses': [ {'command': 'deleteGroup', "error":'Deleting the anonymous group is forbidden', 'correlationData': '40'} ]} rc = 1 # Admin connect_packet_admin = mosq_test.gen_connect("ctrl-test", 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", 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.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.ADMINISTRATIVE_ACTION, proto_ver=5) try: os.mkdir(str(port)) shutil.copyfile(str(Path(__file__).resolve().parent / "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") # Try to delete anon group, this should fail command_check(sock, delete_anon_group_command, delete_anon_group_response) check_details(sock, 1, 1, 2, 5) 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-auth.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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 connect_packet = mosq_test.gen_connect("ctrl-test", 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", 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", username="user_one", password="password", proto_ver=5) connack_packet_with_id2 = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - bad password connect_packet_with_id3 = mosq_test.gen_connect("cid", username="user_one", password="ttt", proto_ver=5) connack_packet_with_id3 = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - no password connect_packet_with_id4 = mosq_test.gen_connect("cid", username="user_one", proto_ver=5) connack_packet_with_id4 = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Success connect_packet_without_id1 = mosq_test.gen_connect("no-cid", 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", username="user_two", password="pass", proto_ver=5) connack_packet_without_id2 = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - no password connect_packet_without_id3 = mosq_test.gen_connect("no-cid", username="user_two", proto_ver=5) connack_packet_without_id3 = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Success connect_packet_set_id1 = mosq_test.gen_connect("new-cid", 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", username="user_two", password="asdfgh", proto_ver=5) connack_packet_set_id2 = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - bad password connect_packet_without_pw1 = mosq_test.gen_connect("cid2", username="user_three", password="pass", proto_ver=5) connack_packet_without_pw1 = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - no password connect_packet_without_pw2 = mosq_test.gen_connect("cid2", username="user_three", proto_ver=5) connack_packet_without_pw2 = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5, property_helper=False) # Fail - no username connect_packet_without_un = mosq_test.gen_connect("cid3", proto_ver=5) connack_packet_without_un = mosq_test.gen_connack(rc=mqtt5_rc.NOT_AUTHORIZED, proto_ver=5, property_helper=False) try: os.mkdir(str(port)) shutil.copyfile(str(Path(__file__).resolve().parent / "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() check_details(sock, 4, 0, 1, 4) 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-client-invalid.py ================================================ #!/usr/bin/env python3 # Check invalid inputs for client commands from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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 connect_packet = mosq_test.gen_connect("ctrl-test", 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(str(Path(__file__).resolve().parent / "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") check_details(sock, 2, 0, 1, 1) 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-client.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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': [], 'connections': [{'address': '127.0.0.1'}]}, {"username":"user_one", "clientid":"cid", "textname":"Name", "textdescription":"Description", "roles":[], "groups":[], 'connections': []}]}, "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': [], 'connections': [], '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 connect_packet = mosq_test.gen_connect("ctrl-test", username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) anon_connect_packet = mosq_test.gen_connect("anon-helper") anon_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(str(Path(__file__).resolve().parent / "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: # The anon user is used to ensure that when the commands are run they are also valid if an anon user is present. anon_sock = mosq_test.do_client_connect(anon_connect_packet, anon_connack_packet, timeout=5, 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 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_terminate_rc = 0 if mosq_test.wait_for_subprocess(broker): print("broker not terminated") broker_terminate_rc = 1 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) # Check number of changes is correct check_details(sock, 1, 0, 1, 3) rc = broker_terminate_rc sock.close() anon_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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-config-init-env.py ================================================ #!/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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) try: os.mkdir(str(port)) except FileExistsError: pass rc = 1 connect_packet = mosq_test.gen_connect("ctrl-test", username="admin", password="adminadminadmin") connack_packet = mosq_test.gen_connack(rc=0) env = os.environ env["MOSQUITTO_DYNSEC_PASSWORD"] = "adminadminadmin" broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port, env=env, timeout=3) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) 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 try: os.remove(f"{port}/dynamic-security.json.pw") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-config-init-file.py ================================================ #!/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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) f.write("plugin_opt_password_init_file %d/init\n" % (port)) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) try: os.mkdir(str(port)) with open(f"{port}/init", "w") as f: f.write("adminadminadmin\n") except FileExistsError: pass rc = 1 connect_packet = mosq_test.gen_connect("ctrl-test", username="admin", password="adminadminadmin") connack_packet = mosq_test.gen_connack(rc=0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port, timeout=3) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) 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 try: os.remove(f"{port}/init") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-config-init-random.py ================================================ #!/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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) try: os.mkdir(str(port)) except FileExistsError: pass rc = 1 broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port, timeout=3) with open(f"{port}/dynamic-security.json.pw", "r") as f: data = f.readlines() admin_pw = data[0].split(" ")[1].strip() user_pw = data[1].split(" ")[1].strip() try: # Admin user connect_packet = mosq_test.gen_connect("ctrl-test", username="admin", password=admin_pw) connack_packet = mosq_test.gen_connack(rc=0) sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Subscribe should be allowed mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet = mosq_test.gen_suback(mid, 1) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "admin suback") sock.close() # Basic user connect_packet = mosq_test.gen_connect("ctrl-test", username="democlient", password=user_pw) connack_packet = mosq_test.gen_connack(rc=0) sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Subscribe should not be allowed mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/dynamic-security/#", 1) suback_packet = mosq_test.gen_suback(mid, 128) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "user suback") sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) try: os.remove(f"{port}/dynamic-security.json") except FileNotFoundError: pass try: os.remove(f"{port}/dynamic-security.json.pw") except FileNotFoundError: pass os.rmdir(f"{port}") broker.terminate() broker.wait() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-default-access.py ================================================ #!/usr/bin/env python3 # This tests the default ACL type access behaviour for when no ACL matches. from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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 connect_packet_admin = mosq_test.gen_connect("ctrl-test", 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", 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.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.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.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(str(Path(__file__).resolve().parent / "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() check_details(sock, 2, 0, 1, 5) 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-disable-client.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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': [], 'connections': []}}}]} get_client_response2 = {'responses':[{'command': 'getClient', 'data': {'client': {'username': 'user_one', 'clientid': 'cid', 'textname': 'Name', 'textdescription': 'Description', 'disabled':True, 'groups': [], 'roles': [], 'connections': []}}}]} 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 connect_packet = mosq_test.gen_connect("ctrl-test", username="admin", password="admin") connack_packet = mosq_test.gen_connack(rc=0) client_connect_packet = mosq_test.gen_connect("cid", 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(str(Path(__file__).resolve().parent / "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() check_details(sock, 2, 0, 1, 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-group-invalid.py ================================================ #!/usr/bin/env python3 # Check invalid inputs for group commands from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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 connect_packet = mosq_test.gen_connect("ctrl-test", 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(str(Path(__file__).resolve().parent / "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") check_details(sock, 2, 1, 2, 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-group.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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', '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'}]} add_role_to_group_command = { "commands": [{'command': 'addGroupRole', 'correlationData': '4', "groupname": "group_one", "rolename": "basic" }]} add_role_to_group_response = {'responses': [{'command': 'addGroupRole', 'correlationData': '4'}]} 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":[{'rolename':'basic'}]}, {'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': [], 'connections': [{'address': '127.0.0.1'}]}, {"username":"user_one", "clientid":"cid", "textname":"Name", "textdescription":"description", "groups":[{"groupname":"group_one"}, {"groupname":"group_two"}], "roles":[], 'connections': []}, {"username":"user_two", "textname":"Name", "textdescription":"description", "groups":[{"groupname":"group_one"}], "roles":[], 'connections': []}, ]}, "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': [{'rolename':'basic'}] }}}]} 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_two", "correlationData":"5678"}]} delete_group_response = {'responses':[{"command":"deleteGroup", "correlationData":"5678"}]} rc = 1 connect_packet = mosq_test.gen_connect("ctrl-test", 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(str(Path(__file__).resolve().parent / "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) # 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) # Add role to group command_check(sock, add_role_to_group_command, add_role_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_terminate_rc = 0 if mosq_test.wait_for_subprocess(broker): print("broker not terminated") broker_terminate_rc = 1 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) check_details(sock, 3, 1, 2, 12) rc = broker_terminate_rc 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-modify-client.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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': [], 'connections': [] }}}]} 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}], 'connections': [] }}}]} 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'}], 'connections': [] }}}]} rc = 1 connect_packet = mosq_test.gen_connect("ctrl-test", 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(str(Path(__file__).resolve().parent / "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_terminate_rc = 0 if mosq_test.wait_for_subprocess(broker): print("broker not terminated") broker_terminate_rc = 1 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") check_details(sock, 2, 2, 4, 8) rc = broker_terminate_rc 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-modify-group.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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 connect_packet = mosq_test.gen_connect("ctrl-test", 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(str(Path(__file__).resolve().parent / "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_terminate_rc = 0 if mosq_test.wait_for_subprocess(broker): print("broker not terminated") broker_terminate_rc = 1 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") check_details(sock, 2, 1, 3, 7) rc = broker_terminate_rc 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-modify-role.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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", 'allowwildcardsubs': False, "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', 'allowwildcardsubs': True, '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', 'allowwildcardsubs': False, 'acls': [ { "acltype": "publishClientReceive", "topic": "topic/#", "allow": True, "priority": 2 }, { "acltype": "publishClientReceive", "topic": "topic/2/#", "allow": True, "priority": 1 } ]}}}]} rc = 1 connect_packet = mosq_test.gen_connect("ctrl-test", 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(str(Path(__file__).resolve().parent / "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_terminate_rc = 0 if mosq_test.wait_for_subprocess(broker): print("broker not terminated") broker_terminate_rc = 1 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) check_details(sock, 1, 0, 2, 2) rc = broker_terminate_rc 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-plugin-invalid.py ================================================ #!/usr/bin/env python3 # Check invalid inputs for plugin commands from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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 connect_packet = mosq_test.gen_connect("ctrl-test", 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(str(Path(__file__).resolve().parent / "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") check_details(sock, 1, 0, 1, 0) 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-role-invalid.py ================================================ #!/usr/bin/env python3 # Check invalid inputs for role commands from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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 connect_packet = mosq_test.gen_connect("ctrl-test", 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(str(Path(__file__).resolve().parent / "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") check_details(sock, 2, 1, 2, 4) 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/14-dynsec-role.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from dynsec_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(f"plugin {mosq_test.get_build_root()}/plugins/dynamic-security/mosquitto_dynamic_security.so\n") f.write("plugin_opt_config_file %d/dynamic-security.json\n" % (port)) 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","allowwildcardsubs": True, "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", "allowwildcardsubs": True, 'acls': [{'acltype':'publishClientSend', 'topic': 'out/#', 'priority': 3, 'allow': True}]}, {'rolename': 'basic2', "textname": "name", "textdescription": "desc", "allowwildcardsubs": True, '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",'allowwildcardsubs': True, "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', 'allowwildcardsubs': True, 'acls': [{'acltype':'publishClientSend', 'topic': 'out/#', 'priority': 3, 'allow': True}, {'acltype':'subscribeLiteral', 'topic': 'basic/out', 'priority': 1, 'allow': True}]}, {'rolename': 'basic2', "textname": "name", "textdescription": "desc", 'allowwildcardsubs': True, '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', 'allowwildcardsubs': True, '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': [], 'connections': [{'address': '127.0.0.1'}]}, {"username":"user_one", "clientid":"cid", "textname":"Name", "textdescription":"Description", "groups":[], "roles":[{'rolename':'basic'}, {'rolename':'basic2'}], 'connections': []}, {"username":"user_two", "textname":"Name", "textdescription":"Description", "groups":[], "roles":[], 'connections': []}]}, "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 connect_packet = mosq_test.gen_connect("ctrl-test", 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(str(Path(__file__).resolve().parent / "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_terminate_rc = 0 if mosq_test.wait_for_subprocess(broker): print("broker not terminated") broker_terminate_rc = 1 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) check_details(sock, 3, 1, 2, 13) rc = broker_terminate_rc 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() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-bridge-queue.py ================================================ #!/usr/bin/env python3 # Start two brokers one bridging forward to the second one (the bridge target). # Once brokers are up and running we stop the bridge target broker, connect # a publisher an publish a number of qos1 messages. # Check all the messages should bestored in the persistence store. # Afterwards start the bridge target broker, connect a client and # add a matching subscription. Then start the bridging broker and check, # if all messages are forwarded from the persistence store to bridge target # and further to the subscriber. # Finally check the persistence store contains zero messages. from mosq_test_helper import * persist_help = persist_module() num_messages = 100 topic = "test/bridge-out" port, bridge_target_port = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace(".py", ".conf") conf_file_bridge_target = os.path.basename(__file__).replace( ".py", "_bridge_target.conf" ) def do_test(test_case_name: str, bridging_add_config: dict, target_add_config: dict): persist_help.write_config( conf_file, port, additional_config_entries=bridging_add_config ) persist_help.write_config( conf_file_bridge_target, bridge_target_port, additional_config_entries=target_add_config, ) rc = 1 persist_help.init(port) persist_help.init(bridge_target_port) client_id = "persist-subscriber" qos = 1 source_id = "persist-bridge-test-publisher" proto_ver = 4 def gen_pub_packets(idx: int, mid_offset: int): payload = f"queued message {idx:3}" publish_packet = mosq_test.gen_publish( topic, mid=mid_offset + idx, qos=qos, payload=payload.encode("UTF-8"), proto_ver=proto_ver, ) puback_packet = mosq_test.gen_puback(mid=mid_offset + idx, proto_ver=proto_ver) return publish_packet, puback_packet connect_packet = mosq_test.gen_connect( client_id, proto_ver=proto_ver, clean_session=False ) connack_packet1 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, topic, qos, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, qos=qos, proto_ver=proto_ver) connect2_packet = mosq_test.gen_connect(source_id, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) num_messages = 100 broker = None try: bridge_target_broker = mosq_test.start_broker( filename=conf_file_bridge_target, use_conf=True, port=bridge_target_port ) # Connect to the bridge target broker and make a qos1 subscription sock_bridge_target = mosq_test.do_client_connect( connect_packet, connack_packet1, timeout=5, port=bridge_target_port ) mosq_test.do_send_receive( sock_bridge_target, subscribe_packet, suback_packet, "suback from bridge target", ) # Now start the broker with the bridge broker = mosq_test.start_broker(filename=conf_file, use_conf=True, port=port) # Connect and send a single message forwarded to the bridge target sock = mosq_test.do_client_connect( connect2_packet, connack2_packet, timeout=5, port=port ) publish_packet, puback_packet = gen_pub_packets(0, mid_offset=3) mosq_test.do_send_receive( sock, publish_packet, puback_packet, "puback for first message" ) # Wait until we have received the message from the bridge target publish_packet, puback_packet = gen_pub_packets(0, mid_offset=1) mosq_test.do_receive_send( sock_bridge_target, publish_packet, puback_packet, "first published message" ) # Wait for a ping response to make sure the target broker has processed the PUBACK mosq_test.do_ping(sock_bridge_target) sock_bridge_target.close() # Make sure the bridging broker processes a ping, which means the PUBACK from the bridge target for the # first message was processed as well mosq_test.do_ping(sock) # Stop the bridge target broker (broker_terminate_rc, stde2) = mosq_test.terminate_broker(bridge_target_broker) bridge_target_broker = None # Publish messages for i in range(num_messages): publish_packet, puback_packet = gen_pub_packets(idx=i, mid_offset=10) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") sock.close() # Terminate the bridging broker (broker_terminate_rc, stde3) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts( port, clients=1, client_msgs_out=num_messages, base_msgs=num_messages, subscriptions=0, ) # Check stored message for i in range(num_messages): payload = f"queued message {i:3}" payload_b = payload.encode("UTF-8") mid = 10 + i store_id = persist_help.check_base_msg( port, 0, topic, payload_b, source_id, None, len(payload_b), mid, port, qos, retain=0, idx=i, ) # Check client msg subscriber_mid = 4 + i cmsg_id = 2 + i persist_help.check_client_msg( port, "upstream-bridge", cmsg_id, store_id, 0, persist_help.dir_out, subscriber_mid, qos, 0, persist_help.ms_queued, ) # Start the bridge target broker bridge_target_broker = mosq_test.start_broker( filename=conf_file_bridge_target, use_conf=True, port=bridge_target_port ) # Reconnect to the bridge target broker sock = mosq_test.do_client_connect( connect_packet, connack_packet2, timeout=5, port=bridge_target_port ) # Restart bridging broker broker = mosq_test.start_broker(filename=conf_file, use_conf=True, port=port) # Check, if all message got forwarded through the bridge for i in range(num_messages): publish_packet, puback_packet = gen_pub_packets(idx=i, mid_offset=1) mosq_test.do_receive_send( sock, publish_packet, puback_packet, f"Receive publish {i} after reconnect", ) # Send ping and wait for the PINGRESP to make sure the broker has processed all sent puback mosq_test.do_ping(sock) sock.close() # Reconnect to the bridging broker and send ping to make sure the broker has process # PUBACK from bridge target before getting shut down sock = mosq_test.do_client_connect( connect2_packet, connack2_packet, timeout=5, port=port ) mosq_test.do_ping(sock) sock.close() # Stop both brokers (broker_terminate_rc, stde2) = mosq_test.terminate_broker(bridge_target_broker) bridge_target_broker = None (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts( port, clients=1, client_msgs_out=0, base_msgs=0, subscriptions=0, ) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): if rc == 0: rc = 1 (_, stde) = broker.communicate() if bridge_target_broker is not None: bridge_target_broker.terminate() if mosq_test.wait_for_subprocess(bridge_target_broker): if rc == 0: rc = 1 (_, stde2) = bridge_target_broker.communicate() os.remove(conf_file_bridge_target) os.remove(conf_file) rc += persist_help.cleanup(bridge_target_port) rc += persist_help.cleanup(port) print(f"{test_case_name}") if rc: if stde2 is not None: print("Bridge target brocker log:") print(stde2.decode("utf-8")) if stde3 is not None: print("Bridging brocker log (first run):") print(stde3.decode("utf-8")) if stde is not None: print("Bridging brocker log:") print(stde.decode("utf-8")) assert rc == 0, f"rc: {rc}" in_bridge_config = { "connection": "in-bridge", "address": f"localhost:{port}", "local_clientid": "bridge-test", "remote_clientid": "upstream-bridge", "topic": f"{topic} in 2", } out_bridge_config = { "connection": "out-bridge", "address": f"localhost:{bridge_target_port}", "local_clientid": "upstream-bridge", "remote_clientid": "bridge-test", "topic": f"{topic} out 2", } memory_queue_config = { "max_queued_messages": num_messages, "max_inflight_messages": num_messages // 20, } do_test( "memory queue out bridge", bridging_add_config=memory_queue_config | out_bridge_config, target_add_config={}, ) # For a test of a push bridge we need to modify the start order # of the brokers... # do_test( # "memory queue in bridge", # bridging_add_config= memory_queue_config, # target_add_config=in_bridge_config # ) exit(0) ================================================ FILE: test/broker/15-persist-client-drop-expired-messages.py ================================================ #!/usr/bin/env python3 # Connect a client, add a subscription, disconnect, send a message with a # different client, restore, reconnect, check it is received. from mosq_test_helper import * from persist_module_helper import * persist_help = persist_module() port = mosq_test.get_port() num_messages = 100 proto_ver = 5 qos = 1 topic = "test-expired-msgs" username = "test-message-expiry" subscriber_id = "test-subscriber" second_subscriber_id = "second-subscriber" publisher_id = "test-publisher" def do_test( test_case_name: str, additional_config_entries: dict, resubscribe: bool, num_messages_two_subscribers: int = 0, num_retain_messages : int = 0, ): print( f"{test_case_name}, resubscribe = {resubscribe}, two_subscribers = {'True' if num_messages_two_subscribers > 0 else 'False'}, num_retain_messages = {num_retain_messages} " ) conf_file = os.path.basename(__file__).replace(".py", f"_{port}.conf") persist_help.write_config( conf_file, port, additional_config_entries=additional_config_entries, ) persist_help.init(port) connect2_packet = mosq_test.gen_connect( publisher_id, username=username, proto_ver=proto_ver ) rc = 1 broker = mosq_test.start_broker(filename=conf_file, use_conf=True, port=port) con = None try: msg_counts = {subscriber_id: num_messages} connect_client( port, subscriber_id, username, proto_ver, session_expiry=60, subscribe_topic=topic, ).close() publisher_sock = connect_client( port, publisher_id, username, proto_ver, session_expiry=0 ) publish_messages( publisher_sock, proto_ver, topic, 0, num_messages - num_messages_two_subscribers, message_expiry=60, retain_end=num_retain_messages, ) if num_messages_two_subscribers > 0: msg_counts[second_subscriber_id] = num_messages_two_subscribers connect_client( port, second_subscriber_id, username, proto_ver, session_expiry=60, subscribe_topic=topic, ).close() publish_messages( publisher_sock, proto_ver, topic, num_messages - num_messages_two_subscribers, num_messages, message_expiry=60, retain_end=num_retain_messages, ) publisher_sock.close() # Terminate the broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None check_db( persist_help, port, username, subscription_topic=topic, client_msg_counts=msg_counts, publisher_id=publisher_id, num_published_msgs=num_messages, retain_end = num_retain_messages, message_expiry=60, ) # Put session expiry_time into the past assert persist_help.modify_base_msgs(port, sub_expiry_time=120) == num_messages # Restart broker broker = mosq_test.start_broker(filename=conf_file, use_conf=True, port=port) # Reconnect client(s), it should have a session, but all queued messages should be dropped for client_id in msg_counts.keys(): subscriber_sock = connect_client( port, client_id, username, proto_ver, session_expiry=60, session_present=True, subscribe_topic=topic if resubscribe else None, ) # Send ping and wait for the PINGRESP to make sure the broker will not send a queued message instead mosq_test.do_ping(subscriber_sock) subscriber_sock.close() (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None for client_id in msg_counts.keys(): # None for subscriber with subscriber_id means no subscription msg_counts[client_id] = 0 check_db( persist_help, port, username, subscription_topic=topic, client_msg_counts=msg_counts, publisher_id=publisher_id, num_published_msgs=num_messages, retain_end = 0, ) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): if rc == 0: rc = 1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode("utf-8")) assert rc == 0, f"rc: {rc}" memory_queue_config = { "log_type": "all", "max_queued_messages": num_messages, } do_test( "memory queue", additional_config_entries=memory_queue_config, resubscribe=False, ) do_test( "memory queue", additional_config_entries=memory_queue_config, resubscribe=True, ) do_test( "memory queue", additional_config_entries=memory_queue_config, resubscribe=False, num_messages_two_subscribers=30, ) do_test( "memory queue", additional_config_entries=memory_queue_config, resubscribe=False, num_retain_messages=40, ) ================================================ FILE: test/broker/15-persist-client-expired-session.py ================================================ #!/usr/bin/env python3 # Connect a client, add a subscription, disconnect, send a message with a # different client, restore, reconnect, check it is received. from mosq_test_helper import * from persist_module_helper import * persist_help = persist_module() port = mosq_test.get_port() num_messages = 100 proto_ver = 5 qos = 1 topic = "test-session-expiry" username = "test-session-expiry" subscriber_id = "test-expired-session-subscriber" second_subscriber_id = "second-subscriber" publisher_id = "test-expired-session-publisher" def do_test( test_case_name: str, additional_config_entries: dict, resubscribe: bool, num_messages_two_subscribers: int = 0, num_retain_messages : int = 0, ): print( f"{test_case_name}, resubscribe = {resubscribe}, two_subscribers = {'True' if num_messages_two_subscribers > 0 else 'False'}, num_retain_messages = {num_retain_messages} " ) conf_file = os.path.basename(__file__).replace(".py", f"_{port}.conf") persist_help.write_config( conf_file, port, additional_config_entries=additional_config_entries, ) persist_help.init(port) connect2_packet = mosq_test.gen_connect( publisher_id, username=username, proto_ver=proto_ver ) rc = 1 broker = mosq_test.start_broker(filename=conf_file, use_conf=True, port=port) con = None try: msg_counts = {subscriber_id: num_messages} connect_client( port, subscriber_id, username, proto_ver, session_expiry=60, subscribe_topic=topic, ).close() publisher_sock = connect_client( port, publisher_id, username, proto_ver, session_expiry=0 ) publish_messages( publisher_sock, proto_ver, topic, 0, num_messages - num_messages_two_subscribers, retain_end=num_retain_messages, ) if num_messages_two_subscribers > 0: msg_counts[second_subscriber_id] = num_messages_two_subscribers connect_client( port, second_subscriber_id, username, proto_ver, session_expiry=60, subscribe_topic=topic, ).close() publish_messages( publisher_sock, proto_ver, topic, num_messages - num_messages_two_subscribers, num_messages, retain_end=num_retain_messages, ) publisher_sock.close() # Terminate the broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None check_db( persist_help, port, username, subscription_topic=topic, client_msg_counts=msg_counts, publisher_id=publisher_id, num_published_msgs=num_messages, retain_end = num_retain_messages, ) # Put session expiry_time into the past assert persist_help.modify_client(port, subscriber_id, sub_expiry_time=120) == 1 # Restart broker broker = mosq_test.start_broker(filename=conf_file, use_conf=True, port=port) # Reconnect client, it should have a session, but all queued messages should be dropped subscriber_sock = connect_client( port, subscriber_id, username, proto_ver, session_expiry=60, subscribe_topic=topic if resubscribe else None, ) # Send ping and wait for the PINGRESP to make sure the broker will not send a queued message instead mosq_test.do_ping(subscriber_sock) subscriber_sock.close() (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # None for subscriber with subscriber_id means no subscription msg_counts[subscriber_id] = 0 if resubscribe else None check_db( persist_help, port, username, subscription_topic=topic, client_msg_counts=msg_counts, publisher_id=publisher_id, num_published_msgs=num_messages, retain_end=num_retain_messages, ) if num_messages_two_subscribers > 0: # Put session expiry_time into the past assert ( persist_help.modify_client( port, second_subscriber_id, sub_expiry_time=120 ) == 1 ) # Restart broker broker = mosq_test.start_broker( filename=conf_file, use_conf=True, port=port ) # Reconnect client, it should have a session, but all queued messages should be dropped subscriber_sock = connect_client( port, second_subscriber_id, username, proto_ver, session_expiry=60, subscribe_topic=topic if resubscribe else None, ) # Send ping and wait for the PINGRESP to make sure the broker will not send a queued message instead mosq_test.do_ping(subscriber_sock) subscriber_sock.close() (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None msg_counts[second_subscriber_id] = 0 if resubscribe else None check_db( persist_help, port, username, subscription_topic=topic, client_msg_counts=msg_counts, publisher_id=publisher_id, num_published_msgs=num_messages, retain_end=num_retain_messages, ) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): if rc == 0: rc = 1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode("utf-8")) assert rc == 0, f"rc: {rc}" memory_queue_config = { "log_type": "all", "max_queued_messages": num_messages, } do_test( "memory queue", additional_config_entries=memory_queue_config, resubscribe=False, ) do_test( "memory queue", additional_config_entries=memory_queue_config, resubscribe=True, ) do_test( "memory queue", additional_config_entries=memory_queue_config, resubscribe=False, num_messages_two_subscribers=20, ) do_test( "memory queue", additional_config_entries=memory_queue_config, resubscribe=True, num_messages_two_subscribers=20, ) do_test( "memory queue", additional_config_entries=memory_queue_config, resubscribe=False, num_retain_messages=30, ) # The following test case is open for discussion as adapting # the check routines will be hard and some observations # are unclear right now # do_test( # "memory queue", # additional_config_entries=memory_queue_config, # resubscribe=False, # num_messages_two_subscribers=40, # num_retain_messages=30, # ) # do_test( # "memory queue", # additional_config_entries=memory_queue_config, # resubscribe=False, # num_messages_two_subscribers=50, # num_retain_messages=60, # ) ================================================ FILE: test/broker/15-persist-client-msg-in-v3-1-1.py ================================================ #!/usr/bin/env python3 # Connect a client, start a QoS 2 flow, disconnect, restore, carry on with the # QoS 2 flow. Is it received? from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() persist_help.init(port) conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 client_id = "persist-client-msg-in-v3-1-1" proto_ver = 4 helper_id = "persist-client-msg-in-v3-1-1-helper" topic = "client-msg-in/2" qos = 2 stde = b"" connect_packet = mosq_test.gen_connect(client_id, proto_ver=proto_ver, clean_session=False) connack_packet1 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) mid = 1 publish1_packet = mosq_test.gen_publish(topic=topic, qos=qos, payload="message1", mid=mid, proto_ver=proto_ver) pubrec1_packet = mosq_test.gen_pubrec(mid=mid, proto_ver=proto_ver) pubrel1_packet = mosq_test.gen_pubrel(mid=mid, proto_ver=proto_ver) pubcomp1_packet = mosq_test.gen_pubcomp(mid=mid, proto_ver=proto_ver) mid = 2 publish2_packet = mosq_test.gen_publish(topic=topic, qos=qos, payload="message2", mid=mid, proto_ver=proto_ver) pubrec2_packet = mosq_test.gen_pubrec(mid=mid, proto_ver=proto_ver) pubrel2_packet = mosq_test.gen_pubrel(mid=mid, proto_ver=proto_ver) pubcomp2_packet = mosq_test.gen_pubcomp(mid=mid, proto_ver=proto_ver) connect_packet_helper = mosq_test.gen_connect(helper_id, proto_ver=proto_ver, clean_session=True) subscribe_packet = mosq_test.gen_subscribe(mid, topic, qos=qos, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid=mid, qos=qos, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) con = None try: # Connect client, start flow, disconnect sock = mosq_test.do_client_connect(connect_packet, connack_packet1, timeout=5, port=port, connack_error="connack 1") mosq_test.do_send_receive(sock, publish1_packet, pubrec1_packet, "pubrec1 send") mosq_test.do_send_receive(sock, publish2_packet, pubrec2_packet, "pubrec2 send") sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1, client_msgs_in=2, base_msgs=2) # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect helper and subscribe helper = mosq_test.do_client_connect(connect_packet_helper, connack_packet1, timeout=5, port=port, connack_error="helper connack") mosq_test.do_send_receive(helper, subscribe_packet, suback_packet, "suback helper") # Complete the flow sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port, connack_error="connack 2") mosq_test.do_send_receive(sock, pubrel1_packet, pubcomp1_packet, "pubrel1 send") mosq_test.do_send_receive(sock, pubrel2_packet, pubcomp2_packet, "pubrel2 send") mosq_test.expect_packet(helper, "publish1 receive", publish1_packet) mosq_test.expect_packet(helper, "publish2 receive", publish2_packet) helper.send(pubrec1_packet) mosq_test.do_receive_send(helper, pubrel1_packet, pubcomp1_packet, "pubcomp1 receive") helper.send(pubrec2_packet) mosq_test.do_receive_send(helper, pubrel2_packet, pubcomp2_packet, "pubcomp2 receive") # Send ping and wait for the PINGRESP to make sure the broker has processed all sent puback mosq_test.do_ping(helper) # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-client-msg-in-v5-0.py ================================================ #!/usr/bin/env python3 # Connect a client, start a QoS 2 flow, disconnect, restore, carry on with the # QoS 2 flow. Is it received? from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) client_id = "persist-client-msg-in-v5-0" proto_ver = 5 helper_id = "persist-client-msg-in-v5-0-helper" topic = "client-msg-in/2" qos = 2 connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 60) connect_packet = mosq_test.gen_connect(client_id, proto_ver=proto_ver, clean_session=False, properties=connect_props) connack_packet1 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) mid = 1 publish1_packet = mosq_test.gen_publish(topic=topic, qos=qos, payload="message1", mid=mid, proto_ver=proto_ver) pubrec1_packet = mosq_test.gen_pubrec(mid=mid, proto_ver=proto_ver) pubrel1_packet = mosq_test.gen_pubrel(mid=mid, proto_ver=proto_ver) pubcomp1_packet = mosq_test.gen_pubcomp(mid=mid, proto_ver=proto_ver) mid = 2 publish2_packet = mosq_test.gen_publish(topic=topic, qos=qos, payload="message2", mid=mid, proto_ver=proto_ver) pubrec2_packet = mosq_test.gen_pubrec(mid=mid, proto_ver=proto_ver) pubrel2_packet = mosq_test.gen_pubrel(mid=mid, proto_ver=proto_ver) pubcomp2_packet = mosq_test.gen_pubcomp(mid=mid, proto_ver=proto_ver) connect_packet_helper = mosq_test.gen_connect(helper_id, proto_ver=proto_ver, clean_session=True) subscribe_packet = mosq_test.gen_subscribe(mid, topic, qos=qos, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid=mid, qos=qos, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) con = None try: # Connect client, start flow, disconnect sock = mosq_test.do_client_connect(connect_packet, connack_packet1, timeout=5, port=port, connack_error="connack 1") mosq_test.do_send_receive(sock, publish1_packet, pubrec1_packet, "pubrec1 send") mosq_test.do_send_receive(sock, publish2_packet, pubrec2_packet, "pubrec2 send") sock.close() # Kill broker broker_terminate_rc = mosq_test.terminate_broker(broker) persist_help.check_counts(port, clients=1, client_msgs_in=2, base_msgs=2) # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect helper and subscribe helper = mosq_test.do_client_connect(connect_packet_helper, connack_packet1, timeout=5, port=port, connack_error="helper connack") mosq_test.do_send_receive(helper, subscribe_packet, suback_packet, "suback helper") # Complete the flow sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port, connack_error="connack 2") mosq_test.do_send_receive(sock, pubrel1_packet, pubcomp1_packet, "pubrel1 send") mosq_test.do_send_receive(sock, pubrel2_packet, pubcomp2_packet, "pubrel2 send") mosq_test.expect_packet(helper, "publish1 receive", publish1_packet) mosq_test.expect_packet(helper, "publish2 receive", publish2_packet) helper.send(pubrec1_packet) mosq_test.do_receive_send(helper, pubrel1_packet, pubcomp1_packet, "pubcomp1 receive") helper.send(pubrec2_packet) mosq_test.do_receive_send(helper, pubrel2_packet, pubcomp2_packet, "pubcomp2 receive") # Send ping and wait for the PINGRESP to make sure the broker has processed all sent puback mosq_test.do_ping(helper) # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-client-msg-modify-acl.py ================================================ #!/usr/bin/env python3 # Connect a client, add a subscription, disconnect, send a message with a # different client, restore, reconnect, check it is received. from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() num_messages = 100 def do_test(test_case_name: str, additional_config_entries: dict): conf_file = os.path.basename(__file__).replace(".py", ".conf") acl_file = os.path.basename(__file__).replace(".py", ".acl") persist_help.write_config( conf_file, port, additional_config_entries={"acl_file": f"{acl_file}"} | additional_config_entries, ) persist_help.init(port) client_id = "test-change-acl-subscriber" username = "test-acl-change" qos = 1 topic = "client-msg/test" source_id = "test-change-acl-publisher" proto_ver = 4 connect_packet = mosq_test.gen_connect( client_id, username=username, proto_ver=proto_ver, clean_session=False ) connack_packet1 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, topic, qos, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, qos=qos, proto_ver=proto_ver) connect2_packet = mosq_test.gen_connect( source_id, proto_ver=proto_ver, username=username ) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) with open(acl_file, "w") as f: f.write(f"user {username}\n") f.write(f"pattern readwrite {topic}\n") os.chmod(f"{acl_file}", 0o644) rc = 1 broker = mosq_test.start_broker(filename=conf_file, use_conf=True, port=port) con = None try: sock = mosq_test.do_client_connect( connect_packet, connack_packet1, timeout=5, port=port ) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") sock.close() sock = mosq_test.do_client_connect( connect2_packet, connack2_packet, timeout=5, port=port ) for i in range(num_messages): payload = f"queued message {i:3}" mid = 10 + i publish_packet = mosq_test.gen_publish( topic, mid=mid, qos=qos, payload=payload.encode("UTF-8"), proto_ver=proto_ver, ) puback_packet = mosq_test.gen_puback(mid=mid, proto_ver=proto_ver) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") sock.close() # Terminate the broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts( port, clients=1, client_msgs_out=num_messages, base_msgs=num_messages, subscriptions=1, ) # Check client persist_help.check_client( port, client_id, username=username, will_delay_time=0, session_expiry_time=0, listener_port=port, max_packet_size=0, max_qos=2, retain_available=1, session_expiry_interval=4294967295, will_delay_interval=0, ) # Check subscription persist_help.check_subscription(port, client_id, topic, qos, 0) # Check stored message for i in range(num_messages): payload = f"queued message {i:3}" payload_b = payload.encode("UTF-8") mid = 10 + i store_id = persist_help.check_base_msg( port, 0, topic, payload_b, source_id, username, len(payload_b), mid, port, qos, retain=0, idx=i, ) # Check client msg subscriber_mid = 1 + i cmsg_id = 1 + i persist_help.check_client_msg( port, client_id, cmsg_id, store_id, 0, persist_help.dir_out, subscriber_mid, qos, 0, persist_help.ms_queued, ) # Remove any permission for the test topic and the test user with open(acl_file, "w") as f: f.write(f"user {username}\n") f.write(f"pattern deny {topic}\n") os.chmod(f"{acl_file}", 0o644) # Restart broker broker = mosq_test.start_broker(filename=conf_file, use_conf=True, port=port) # Connect client again, it should have a session, but all queued messages should be dropped sock = mosq_test.do_client_connect( connect_packet, connack_packet2, timeout=5, port=port ) # Send ping and wait for the PINGRESP to make sure the broker will not send a queued message instead mosq_test.do_ping(sock) sock.close() (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts( port, clients=1, client_msgs_out=0, base_msgs=0, subscriptions=1, ) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): if rc == 0: rc = 1 (_, stde) = broker.communicate() os.remove(acl_file) os.remove(conf_file) rc += persist_help.cleanup(port) print(f"{test_case_name}") if rc: print(stde.decode("utf-8")) assert rc == 0, f"rc: {rc}" do_test( "memory queue", additional_config_entries={ "max_queued_messages": num_messages, "max_inflight_messages": num_messages // 20, }, ) ================================================ FILE: test/broker/15-persist-client-msg-out-clear-v3-1-1.py ================================================ #!/usr/bin/env python3 # Connect a client, add a subscription, disconnect, send a message with a # different client, restore, reconnect with clear start, check it is not received. from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) keepalive = 10 client_id = "persist-client-msg-v3-1-1" proto_ver = 4 helper_id = "persist-client-msg-v3-1-1-helper" topic0 = "client-msg/0" topic1 = "client-msg/1" topic2 = "client-msg/2" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, proto_ver=proto_ver, clean_session=False) connect_packet_clear = mosq_test.gen_connect(client_id, keepalive=keepalive, proto_ver=proto_ver, clean_session=True) connack_packet1 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) mid = 1 subscribe_packet0 = mosq_test.gen_subscribe(mid, topic0, qos=0, proto_ver=proto_ver) suback_packet0 = mosq_test.gen_suback(mid=mid, qos=0, proto_ver=proto_ver) subscribe_packet1 = mosq_test.gen_subscribe(mid, topic1, qos=1, proto_ver=proto_ver) suback_packet1 = mosq_test.gen_suback(mid=mid, qos=1, proto_ver=proto_ver) subscribe_packet2 = mosq_test.gen_subscribe(mid, topic2, qos=2, proto_ver=proto_ver) suback_packet2 = mosq_test.gen_suback(mid=mid, qos=2, proto_ver=proto_ver) connect_packet_helper = mosq_test.gen_connect(helper_id, keepalive=keepalive, proto_ver=proto_ver, clean_session=True) publish_packet0 = mosq_test.gen_publish(topic=topic0, qos=0, payload="message", proto_ver=proto_ver) mid = 1 publish_packet1 = mosq_test.gen_publish(topic=topic1, qos=1, payload="message", mid=mid, proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid=mid, proto_ver=proto_ver) mid = 2 publish_packet2 = mosq_test.gen_publish(topic=topic2, qos=2, payload="message", mid=mid, proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid=mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid=mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid=mid, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) con = None try: # Connect client, subscribe, disconnect sock = mosq_test.do_client_connect(connect_packet, connack_packet1, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet0, suback_packet0, "suback 0") mosq_test.do_send_receive(sock, subscribe_packet1, suback_packet1, "suback 1") mosq_test.do_send_receive(sock, subscribe_packet2, suback_packet2, "suback 2") sock.close() # Connect helper and publish helper = mosq_test.do_client_connect(connect_packet_helper, connack_packet1, timeout=5, port=port) helper.send(publish_packet0) mosq_test.do_send_receive(helper, publish_packet1, puback_packet, "puback helper") mosq_test.do_send_receive(helper, publish_packet2, pubrec_packet, "pubrec helper") mosq_test.do_send_receive(helper, pubrel_packet, pubcomp_packet, "pubcomp helper") helper.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1, client_msgs_out=2, base_msgs=2, subscriptions=3) # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client again, it should have a session sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port) # Does the client get the messages - don't complete the flows mosq_test.expect_packet(sock, "publish 1", publish_packet1) mosq_test.expect_packet(sock, "publish 2", publish_packet2) sock.close() # Connect client again and clear the session sock = mosq_test.do_client_connect(connect_packet_clear, connack_packet1, timeout=5, port=port) # If there are messages, the ping will fail mosq_test.do_ping(sock) # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-client-msg-out-dup-v3-1-1.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 keepalive = 10 persist_help.init(port) client_id = "persist-cmsg-out-dup-v3-1-1" payload = "queued message 1" payload_b = payload.encode("UTF-8") qos = 2 topic = "client-msg/test" source_id = "persist-cmsg-v3-1-1-helper" proto_ver = 4 keepalive = 10 connect1_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, proto_ver=proto_ver, clean_session=False) connack1_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack1_packet2 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver, flags=1) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, topic, qos, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, qos=qos, proto_ver=proto_ver) connect2_packet = mosq_test.gen_connect(source_id, keepalive=keepalive, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) source_mid = 18 publish_packet = mosq_test.gen_publish(topic, mid=source_mid, qos=qos, payload=payload, proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid=source_mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid=source_mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid=source_mid, proto_ver=proto_ver) mid = 1 publish_packet_r1 = mosq_test.gen_publish(topic, mid=mid, qos=qos, payload=payload, proto_ver=proto_ver) publish_packet_r2 = mosq_test.gen_publish(topic, mid=mid, qos=qos, payload=payload, proto_ver=proto_ver, dup=1) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: # Connect and set up subscription, then disconnect 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") sock.close() #persist_help.check_counts(port, clients=1, subscriptions=1) # Helper - send message then disconnect sock = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=5, port=port) mosq_test.do_send_receive(sock, publish_packet, pubrec_packet, "pubrec") mosq_test.do_send_receive(sock, pubrel_packet, pubcomp_packet, "pubcomp") sock.close() #persist_help.check_counts(port, clients=1, client_msgs=1, base_msgs=1, subscriptions=1) # Reconnect, receive publish, disconnect sock = mosq_test.do_client_connect(connect1_packet, connack1_packet2, timeout=5, port=port) mosq_test.expect_packet(sock, "publish 1", publish_packet_r1) #persist_help.check_counts(port, clients=1, client_msgs=1, base_msgs=1, subscriptions=1) # Reconnect, receive publish, disconnect - dup should now be set sock = mosq_test.do_client_connect(connect1_packet, connack1_packet2, timeout=5, port=port) mosq_test.expect_packet(sock, "publish 2", publish_packet_r2) (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1, client_msgs_out=1, base_msgs=1, subscriptions=1) # Check client persist_help.check_client(port, client_id, None, 0, 0, port, 0, 2, 1, 4294967295, 0) # Check subscription persist_help.check_subscription(port, client_id, topic, qos, 0) # Check stored message store_id = persist_help.check_base_msg(port, 0, topic, payload_b, source_id, None, len(payload_b), source_mid, port, qos, 0) # Check client msg persist_help.check_client_msg(port, client_id, 1, store_id, 1, persist_help.dir_out, 1, qos, 0, persist_help.ms_wait_for_pubrec) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated (2)") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-client-msg-out-queue-v3-1-1.py ================================================ #!/usr/bin/env python3 # Connect a client, add a subscription, disconnect, send a message with a # different client, restore, reconnect, check it is received. from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) keepalive = 10 client_id = "persist-client-msg-v3-1-1" proto_ver = 4 helper_id = "persist-client-msg-v3-1-1-helper" topic0 = "client-msg/0" topic1 = "client-msg/1" topic2 = "client-msg/2" connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, proto_ver=proto_ver, clean_session=False) connack_packet1 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) mid = 1 subscribe_packet0 = mosq_test.gen_subscribe(mid, topic0, qos=0, proto_ver=proto_ver) suback_packet0 = mosq_test.gen_suback(mid=mid, qos=0, proto_ver=proto_ver) subscribe_packet1 = mosq_test.gen_subscribe(mid, topic1, qos=1, proto_ver=proto_ver) suback_packet1 = mosq_test.gen_suback(mid=mid, qos=1, proto_ver=proto_ver) subscribe_packet2 = mosq_test.gen_subscribe(mid, topic2, qos=2, proto_ver=proto_ver) suback_packet2 = mosq_test.gen_suback(mid=mid, qos=2, proto_ver=proto_ver) connect_packet_helper = mosq_test.gen_connect(helper_id, keepalive=keepalive, proto_ver=proto_ver, clean_session=True) publish_packet0 = mosq_test.gen_publish(topic=topic0, qos=0, payload="message", proto_ver=proto_ver) mid = 1 publish_packet1 = mosq_test.gen_publish(topic=topic1, qos=1, payload="message", mid=mid, proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid=mid, proto_ver=proto_ver) mid = 2 publish_packet2 = mosq_test.gen_publish(topic=topic2, qos=2, payload="message", mid=mid, proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid=mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid=mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid=mid, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) con = None try: # Connect client, subscribe, disconnect sock = mosq_test.do_client_connect(connect_packet, connack_packet1, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet0, suback_packet0, "suback 0") mosq_test.do_send_receive(sock, subscribe_packet1, suback_packet1, "suback 1") mosq_test.do_send_receive(sock, subscribe_packet2, suback_packet2, "suback 2") sock.close() # Connect helper and publish helper = mosq_test.do_client_connect(connect_packet_helper, connack_packet1, timeout=5, port=port) helper.send(publish_packet0) mosq_test.do_send_receive(helper, publish_packet1, puback_packet, "puback helper") mosq_test.do_send_receive(helper, publish_packet2, pubrec_packet, "pubrec helper") mosq_test.do_send_receive(helper, pubrel_packet, pubcomp_packet, "pubcomp helper") helper.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1, client_msgs_out=2, base_msgs=2, subscriptions=3) # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client again, it should have a session sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port) # Does the client get the messages mosq_test.do_receive_send(sock, publish_packet1, puback_packet, "publish 1") mosq_test.do_receive_send(sock, publish_packet2, pubrec_packet, "publish 2") mosq_test.do_receive_send(sock, pubrel_packet, pubcomp_packet, "pubrel 2") # Send ping and wait for the PINGRESP to make sure the broker has processed all sent pubcomp mosq_test.do_ping(sock) sock.close() # Connect client again, it should have a session sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port) # If there are messages, the ping will fail mosq_test.do_ping(sock) (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1, subscriptions=3) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-client-msg-out-v3-1-1-db.py ================================================ #!/usr/bin/env python3 # Connect a client, add a subscription, disconnect, send a message with a # different client, restore, reconnect, check it is received. from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) client_id = "persist-cmsg-v3-1-1" payload = "queued message 1" payload_b = payload.encode("UTF-8") qos = 1 topic = "client-msg/test" source_id = "persist-cmsg-v3-1-1-helper" proto_ver = 4 connect_packet = mosq_test.gen_connect(client_id, proto_ver=proto_ver, clean_session=False) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, topic, qos, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, qos=qos, proto_ver=proto_ver) connect2_packet = mosq_test.gen_connect(source_id, proto_ver=proto_ver) connack2_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) mid = 18 publish_packet = mosq_test.gen_publish(topic, mid=mid, qos=qos, payload=payload, proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid=mid, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) con = None 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") sock.close() sock = mosq_test.do_client_connect(connect2_packet, connack2_packet, timeout=5, port=port) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") sock.close() (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1, client_msgs_out=1, base_msgs=1, subscriptions=1) # Check client persist_help.check_client(port, client_id, None, 0, 0, port, 0, 2, 1, 4294967295, 0) # Check subscription persist_help.check_subscription(port, client_id, topic, qos, 0) # Check stored message store_id = persist_help.check_base_msg(port, 0, topic, payload_b, source_id, None, len(payload_b), mid, port, qos, 0) # Check client msg persist_help.check_client_msg(port, client_id, 1, store_id, 0, persist_help.dir_out, 1, qos, 0, persist_help.ms_queued) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated (2)") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-client-msg-out-v3-1-1.py ================================================ #!/usr/bin/env python3 # Connect a client, add a subscription, disconnect, send a message with a # different client, restore, reconnect, check it is received. from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) client_id = "persist-client-msg-v3-1-1" proto_ver = 4 helper_id = "persist-client-msg-v3-1-1-helper" topic0 = "client-msg/0" topic1 = "client-msg/1" topic2 = "client-msg/2" connect_packet = mosq_test.gen_connect(client_id, proto_ver=proto_ver, clean_session=False) connack_packet1 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) mid = 1 subscribe_packet0 = mosq_test.gen_subscribe(mid, topic0, qos=0, proto_ver=proto_ver) suback_packet0 = mosq_test.gen_suback(mid=mid, qos=0, proto_ver=proto_ver) subscribe_packet1 = mosq_test.gen_subscribe(mid, topic1, qos=1, proto_ver=proto_ver) suback_packet1 = mosq_test.gen_suback(mid=mid, qos=1, proto_ver=proto_ver) subscribe_packet2 = mosq_test.gen_subscribe(mid, topic2, qos=2, proto_ver=proto_ver) suback_packet2 = mosq_test.gen_suback(mid=mid, qos=2, proto_ver=proto_ver) connect_packet_helper = mosq_test.gen_connect(helper_id, proto_ver=proto_ver, clean_session=True) publish_packet0 = mosq_test.gen_publish(topic=topic0, qos=0, payload="message", proto_ver=proto_ver) mid = 1 publish_packet1 = mosq_test.gen_publish(topic=topic1, qos=1, payload="message", mid=mid, proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid=mid, proto_ver=proto_ver) mid = 2 publish_packet2 = mosq_test.gen_publish(topic=topic2, qos=2, payload="message", mid=mid, proto_ver=proto_ver) pubrec_packet = mosq_test.gen_pubrec(mid=mid, proto_ver=proto_ver) pubrel_packet = mosq_test.gen_pubrel(mid=mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid=mid, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) con = None try: # Connect client, subscribe, disconnect sock = mosq_test.do_client_connect(connect_packet, connack_packet1, timeout=5, port=port) mosq_test.do_send_receive(sock, subscribe_packet0, suback_packet0, "suback 0") mosq_test.do_send_receive(sock, subscribe_packet1, suback_packet1, "suback 1") mosq_test.do_send_receive(sock, subscribe_packet2, suback_packet2, "suback 2") sock.close() # Connect helper and publish helper = mosq_test.do_client_connect(connect_packet_helper, connack_packet1, timeout=5, port=port) helper.send(publish_packet0) mosq_test.do_send_receive(helper, publish_packet1, puback_packet, "puback helper") mosq_test.do_send_receive(helper, publish_packet2, pubrec_packet, "pubrec helper") mosq_test.do_send_receive(helper, pubrel_packet, pubcomp_packet, "pubcomp helper") helper.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client again, it should have a session sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port) # Does the client get the messages mosq_test.do_receive_send(sock, publish_packet1, puback_packet, "publish 1") mosq_test.do_receive_send(sock, publish_packet2, pubrec_packet, "publish 2") mosq_test.do_receive_send(sock, pubrel_packet, pubcomp_packet, "pubrel 2") # Send ping and wait for the PINGRESP to make sure the broker has processed all sent pubcomp mosq_test.do_ping(sock) sock.close() # Connect client again, it should have a session sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port) # If there are messages, the ping will fail mosq_test.do_ping(sock) (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1, subscriptions=3) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated (2)") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-client-msg-out-v5-0.py ================================================ #!/usr/bin/env python3 # Connect a client, add a subscription, disconnect, send a message with a # different client, restore, reconnect, check it is received. from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) client_id = "persist-client-msg-v5-0" proto_ver = 5 helper_id = "persist-client-msg-v5-0-helper" topic0 = "client-msg/0" topic1 = "client-msg/1" topic2 = "client-msg/2" connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 60) connect_packet = mosq_test.gen_connect(client_id, proto_ver=proto_ver, clean_session=False, properties=connect_props) connack_packet1 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) mid = 1 sub_props0 = mqtt5_props.gen_varint_prop(mqtt5_props.SUBSCRIPTION_IDENTIFIER, 1) subscribe_packet0 = mosq_test.gen_subscribe(mid, topic0, qos=0, proto_ver=proto_ver, properties=sub_props0) suback_packet0 = mosq_test.gen_suback(mid=mid, qos=0, proto_ver=proto_ver) sub_props1 = mqtt5_props.gen_varint_prop(mqtt5_props.SUBSCRIPTION_IDENTIFIER, 2) subscribe_packet1 = mosq_test.gen_subscribe(mid, topic1, qos=1, proto_ver=proto_ver, properties=sub_props1) suback_packet1 = mosq_test.gen_suback(mid=mid, qos=1, proto_ver=proto_ver) sub_props2 = mqtt5_props.gen_varint_prop(mqtt5_props.SUBSCRIPTION_IDENTIFIER, 3) subscribe_packet2 = mosq_test.gen_subscribe(mid, topic2, qos=2, proto_ver=proto_ver, properties=sub_props2) suback_packet2 = mosq_test.gen_suback(mid=mid, qos=2, proto_ver=proto_ver) connect_packet_helper = mosq_test.gen_connect(helper_id, proto_ver=proto_ver, clean_session=True) publish_packet0 = mosq_test.gen_publish(topic=topic0, qos=0, payload="message", proto_ver=proto_ver) mid = 1 publish_packet1 = mosq_test.gen_publish(topic=topic1, qos=1, payload="message", mid=mid, proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid=mid, proto_ver=proto_ver) publish_received1 = mosq_test.gen_publish(topic=topic1, qos=1, payload="message", mid=mid, proto_ver=proto_ver, properties=sub_props1) mid = 2 pubrec_packet = mosq_test.gen_pubrec(mid=mid, proto_ver=proto_ver) publish_packet2 = mosq_test.gen_publish(topic=topic2, qos=2, payload="message", mid=mid, proto_ver=proto_ver) publish_received2 = mosq_test.gen_publish(topic=topic2, qos=2, payload="message", mid=mid, proto_ver=proto_ver, properties=sub_props2) pubrel_packet = mosq_test.gen_pubrel(mid=mid, proto_ver=proto_ver) pubcomp_packet = mosq_test.gen_pubcomp(mid=mid, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) con = None try: # Connect client, subscribe, disconnect sock = mosq_test.do_client_connect(connect_packet, connack_packet1, timeout=5, port=port, connack_error="connack 1") mosq_test.do_send_receive(sock, subscribe_packet0, suback_packet0, "suback 0") mosq_test.do_send_receive(sock, subscribe_packet1, suback_packet1, "suback 1") mosq_test.do_send_receive(sock, subscribe_packet2, suback_packet2, "suback 2") sock.close() # Connect helper and publish helper = mosq_test.do_client_connect(connect_packet_helper, connack_packet1, timeout=5, port=port, connack_error="helper connack") helper.send(publish_packet0) mosq_test.do_send_receive(helper, publish_packet1, puback_packet, "puback helper") mosq_test.do_send_receive(helper, publish_packet2, pubrec_packet, "pubrec helper") mosq_test.do_send_receive(helper, pubrel_packet, pubcomp_packet, "pubcomp helper") helper.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client again, it should have a session sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port, connack_error="connack 2") # Does the client get the messages mosq_test.do_receive_send(sock, publish_received1, puback_packet, "publish received 1") mosq_test.do_receive_send(sock, publish_received2, pubrec_packet, "publish received 2") mosq_test.do_receive_send(sock, pubrel_packet, pubcomp_packet, "pubrel 2") # Send ping and wait for the PINGRESP to make sure the broker has processed all sent pubcomp mosq_test.do_ping(sock) sock.close() # Connect client again, it should have a session sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port, connack_error="connack 3") # If there are messages, the ping will fail mosq_test.do_ping(sock) (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1, subscriptions=3) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-client-v3-1-1.py ================================================ #!/usr/bin/env python3 # Connect a client, check it is restored, clear the client, check it is not there. from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) client_id = "persist-client-v3-1-1" proto_ver = 4 connect_packet = mosq_test.gen_connect(client_id, proto_ver=proto_ver, clean_session=False) connack_packet1 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) connect_packet_clean = mosq_test.gen_connect(client_id, proto_ver=proto_ver, clean_session=True) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) con = None try: # Connect client sock = mosq_test.do_client_connect(connect_packet, connack_packet1, timeout=5, port=port, connack_error="connack 1") mosq_test.do_ping(sock) sock.close() # Connect client again, it should have a session sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port, connack_error="connack 2") mosq_test.do_ping(sock) sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client again, it should have a session sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port, connack_error="connack 3") mosq_test.do_ping(sock) sock.close() # Clear the client sock = mosq_test.do_client_connect(connect_packet_clean, connack_packet1, timeout=5, port=port, connack_error="connack 4") mosq_test.do_ping(sock) sock.close() # Connect client, it should not have a session sock = mosq_test.do_client_connect(connect_packet_clean, connack_packet1, timeout=5, port=port, connack_error="connack 5") mosq_test.do_ping(sock) sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client, it should not have a session sock = mosq_test.do_client_connect(connect_packet_clean, connack_packet1, timeout=5, port=port, connack_error="connack 6") mosq_test.do_ping(sock) sock.close() (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated (3)") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-client-v5-0.py ================================================ #!/usr/bin/env python3 # Connect a client, check it is restored, clear the client, check it is not there. from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) keepalive = 10 client_id = "persist-client-v5-0" proto_ver = 5 connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 60) connect_props += mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 10000) connect_packet = mosq_test.gen_connect(client_id, keepalive=keepalive, proto_ver=proto_ver, clean_session=False, properties=connect_props) connack_packet1 = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) connack_packet2 = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) connect_packet_clean = mosq_test.gen_connect(client_id, keepalive=keepalive, proto_ver=proto_ver, clean_session=True) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) con = None try: # Connect client sock = mosq_test.do_client_connect(connect_packet, connack_packet1, timeout=5, port=port, connack_error="connack 1") mosq_test.do_ping(sock) sock.close() # Kill broker broker_terminate_rc = mosq_test.terminate_broker(broker) persist_help.check_counts(port, clients=1) # FIXME - port persist_help.check_client(port, "persist-client-v5-0", None, 0, 1, port, 10000, 2, 1, 60, 0) persist_help.check_client(port, "persist-client-v5-0", None, 0, 1, None, 10000, 2, 1, 60, 0) # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client again, it should have a session sock = mosq_test.do_client_connect(connect_packet, connack_packet2, timeout=5, port=port, connack_error="connack 2") mosq_test.do_ping(sock) sock.close() # Clear the client sock = mosq_test.do_client_connect(connect_packet_clean, connack_packet1, timeout=5, port=port, connack_error="connack 3") mosq_test.do_ping(sock) sock.close() # Connect client, it should not have a session sock = mosq_test.do_client_connect(connect_packet_clean, connack_packet1, timeout=5, port=port, connack_error="connack 4") mosq_test.do_ping(sock) sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port) # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client, it should not have a session sock = mosq_test.do_client_connect(connect_packet_clean, connack_packet1, timeout=5, port=port, connack_error="connack 5") mosq_test.do_ping(sock) sock.close() (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated (2)") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-client-will.py ================================================ #!/usr/bin/env python3 # Connect a client, add a subscription, disconnect, send a message with a # different client, restore, reconnect, check it is received. from mosq_test_helper import * from persist_module_helper import * from typing import Optional import mqtt5_rc import mqtt5_props persist_help = persist_module() port = mosq_test.get_port() proto_ver = 5 qos = 1 topic = "test-will-msg" username = "test-will-msg" subscriber_id = "test-will-subscriber" publisher_id = "test-will-publisher" helper_id = "test-helper" will_properties = mqtt5_props.gen_properties( [ {"identifier": mqtt5_props.PAYLOAD_FORMAT_INDICATOR, "value": 1}, {"identifier": mqtt5_props.CONTENT_TYPE, "value": "text"}, { "identifier": mqtt5_props.USER_PROPERTY, "name": "test-user-property", "value": "nothing important", }, ] ) will_properties_in_db = ( "[" '{"identifier":"payload-format-indicator","value":1}' + ',{"identifier":"content-type","value":"text"}' + ',{"identifier":"user-property","name":"test-user-property","value":"nothing important"}' + "]" ) send_will_disconnect_rc = mqtt5_rc.DISCONNECT_WITH_WILL_MSG normal_disconnect_rc = mqtt5_rc.NORMAL_DISCONNECTION def do_test( session_expiry: int, will_qos: int, will_retain: bool, will_delay: int = 0, disconnect_rc: Optional[int] = None, ): mid = 1 print( f" {'persistent' if session_expiry > 0 else 'non persistent'} client" f" with will qos = {will_qos}" f", will_retain = {will_retain}" f" and will delay = {will_delay}" + (f" and disconnect rc = {disconnect_rc}" if disconnect_rc is not None else "") ) def check_will_received(do_subscribe: bool, expect_will_publish=bool): nonlocal mid # Reconnect client, it should have a session subscriber_sock = connect_client( port, subscriber_id, username, proto_ver, session_expiry=60, session_present=True, subscribe_topic=topic if do_subscribe else None, ) if expect_will_publish: will_publish = mosq_test.gen_publish( topic, will_qos, will_payload, will_retain and do_subscribe, mid=mid, proto_ver=proto_ver, properties=will_properties, ) if will_qos > 0: pub_ack = mosq_test.gen_puback(mid=1, proto_ver=proto_ver) mosq_test.do_receive_send(subscriber_sock, will_publish, pub_ack) else: mosq_test.expect_packet(subscriber_sock, "will message", will_publish) mid += 1 # Always send a ping. Either to make sure a potential puback is processed by the server # or to make sure the server has not send an unexpected publish mosq_test.do_ping(subscriber_sock) subscriber_sock.close() expect_will_received = will_qos > 0 conf_file = os.path.basename(__file__).replace(".py", f"_{port}.conf") persist_help.write_config( conf_file, port, additional_config_entries={"plugin_opt_flush_period": 0, "log_type": "all"}, ) persist_help.init(port) rc = 1 will_payload = b"My simple will message" if will_delay: will_delay_property = mqtt5_props.gen_uint32_prop( mqtt5_props.WILL_DELAY_INTERVAL, will_delay ) else: will_delay_property = b"" will_delayed = will_delay > 0 and session_expiry > 0 broker = mosq_test.start_broker(filename=conf_file, use_conf=True, port=port) stde = None stde2 = None try: subscriber_sock = connect_client( port, subscriber_id, username, proto_ver, session_expiry=60, subscribe_topic=topic, ) # .close() publisher_sock = connect_client( port, publisher_id, username, proto_ver, session_expiry=session_expiry, will_topic=topic, will_qos=will_qos, will_retain=will_retain, will_payload=will_payload, will_properties=will_properties + will_delay_property, ) if disconnect_rc: if disconnect_rc == mqtt5_rc.SESSION_TAKEN_OVER: publisher_sock = connect_client( port, publisher_id, username, proto_ver, session_expiry=session_expiry, session_present=session_expiry > 0, ) # Do a ping to make sure the new connection is functional mosq_test.do_ping(publisher_sock) else: mosq_test.do_send( publisher_sock, mosq_test.gen_disconnect( reason_code=disconnect_rc, proto_ver=proto_ver ), ) will_sent = disconnect_rc != normal_disconnect_rc and not will_delayed else: will_sent = False # Send an additional ping to make sure the commit to the DB has happened helper_sock = connect_client( port, helper_id, username, proto_ver, session_expiry=0 ) mosq_test.do_ping(helper_sock) helper_sock.close() # Kill the broker broker.kill() (_, stde) = broker.communicate() broker = None if will_sent and will_qos > 0: num_client_msgs = 1 else: num_client_msgs = 0 num_retain = 1 if will_retain > 0 and will_sent else 0 num_base_msgs = max(num_client_msgs, num_retain) num_wills = 0 if will_sent else 1 persist_help.check_counts( port, clients=1 if session_expiry == 0 else 2, base_msgs=num_base_msgs, client_msgs_out=num_client_msgs, retain_msgs=num_retain, subscriptions=1, wills=0 if will_sent else 1, ) if not will_sent: persist_help.check_will( port, publisher_id, will_payload, topic, will_qos, will_retain, properties=will_properties_in_db, ) # Restart broker broker = mosq_test.start_broker(filename=conf_file, use_conf=True, port=port) check_will_received( do_subscribe=False, expect_will_publish=will_qos > 0 and not will_delayed ) check_will_received( do_subscribe=True, expect_will_publish=will_retain and not will_delayed ) (broker_terminate_rc, stde2) = mosq_test.terminate_broker(broker) broker = None rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): if rc == 0: rc = 1 (_, stde3) = broker.communicate() if not stde: stde = stde3 else: stde2 = stde3 os.remove(conf_file) rc += persist_help.cleanup(port) if rc: if stde: print(stde.decode("utf-8")) if stde2: print("Broker after restart") print(stde2.decode("utf-8")) # assert rc == 0, f"rc: {rc}" # Run test with different parameters: # If disconnect_rc is not set the client will not disconnect # session_expiry, will qos, will retain, disconnect_rc send_will_disconnect_rc = mqtt5_rc.DISCONNECT_WITH_WILL_MSG # non persistent client connected during crash do_test(0, 0, 0) do_test(0, 1, 0) do_test(0, 0, 1) do_test(0, 1, 1) # non persistent client connected during crash, will delay does not matter do_test(0, 0, 0, will_delay=30) do_test(0, 1, 0, will_delay=30) do_test(0, 0, 1, will_delay=30) do_test(0, 1, 1, will_delay=30) # non persistent client disconnecting with will sent before crash do_test(0, 0, 0, disconnect_rc=send_will_disconnect_rc) do_test(0, 1, 0, disconnect_rc=send_will_disconnect_rc) do_test(0, 0, 1, disconnect_rc=send_will_disconnect_rc) do_test(0, 1, 1, disconnect_rc=send_will_disconnect_rc) # non persistent client disconnecting without will sent before crash do_test(0, 0, 0, disconnect_rc=normal_disconnect_rc) do_test(0, 1, 0, disconnect_rc=normal_disconnect_rc) do_test(0, 0, 1, disconnect_rc=normal_disconnect_rc) do_test(0, 1, 1, disconnect_rc=normal_disconnect_rc) # persistent client connected during crash do_test(60, 0, 0) do_test(60, 1, 0) do_test(60, 0, 1) do_test(60, 1, 1) # persistent client connected during crash with a will delay of 30 seconds do_test(60, 0, 0, will_delay=30) do_test(60, 1, 0, will_delay=30) do_test(60, 0, 1, will_delay=30) do_test(60, 1, 1, will_delay=30) # persistent client disconnecting with will sent before crash do_test(60, 0, 0, disconnect_rc=send_will_disconnect_rc) do_test(60, 1, 0, disconnect_rc=send_will_disconnect_rc) do_test(60, 0, 1, disconnect_rc=send_will_disconnect_rc) do_test(60, 1, 1, disconnect_rc=send_will_disconnect_rc) # persistent client disconnecting without will sent before crash do_test(60, 0, 0, disconnect_rc=normal_disconnect_rc) do_test(60, 1, 0, disconnect_rc=normal_disconnect_rc) do_test(60, 0, 1, disconnect_rc=normal_disconnect_rc) do_test(60, 1, 1, disconnect_rc=normal_disconnect_rc) # persistent client disconnecting with will sent, but will delay do_test(60, 0, 0, will_delay=30, disconnect_rc=send_will_disconnect_rc) do_test(60, 1, 0, will_delay=30, disconnect_rc=send_will_disconnect_rc) do_test(60, 0, 1, will_delay=30, disconnect_rc=send_will_disconnect_rc) do_test(60, 1, 1, will_delay=30, disconnect_rc=send_will_disconnect_rc) # Remove will msg by session takeover through reconnect do_test(0, 1, 1, disconnect_rc=mqtt5_rc.SESSION_TAKEN_OVER) # do_test(60, 1, 1, disconnect_rc=mqtt5_rc.SESSION_TAKEN_OVER) ================================================ FILE: test/broker/15-persist-migrate-db.py ================================================ #!/usr/bin/env python3 # Connect a client, start a QoS 2 flow, disconnect, restore, carry on with the # QoS 2 flow. Is it received? from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace(".py", ".conf") persist_help.write_config(conf_file, port) def do_success_test(create_db_of_version: list[int]): print(f"db migration success test from db {create_db_of_version}") persist_help.init(port, create_db_of_version=create_db_of_version) rc = 1 broker = mosq_test.start_broker( filename=os.path.basename(__file__), use_conf=True, port=port ) try: # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_version_infos( port, database_schema_version=[ 1, 1, create_db_of_version[2] if create_db_of_version else 0, ], ) rc = 0 except Exception as err: print(f"{err}") finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc = 1 (_, stde) = broker.communicate() rc += persist_help.cleanup(port) if rc: print(stde.decode("utf-8")) exit(rc) def do_failure_test(create_db_of_version: list[int]): print(f"db migration failure test for db {create_db_of_version}") persist_help.init(port, create_db_of_version=create_db_of_version) rc = 1 try: rc = do_test_broker_failure( conf_file=conf_file, config=[], port=port, rc_expected=3, error_log_entry=f"Unknown database_schema version {'.'.join([str(i) for i in create_db_of_version])}", with_test_config=False, ) except Exception as exc: print(f"Exception: {str(exc)}") finally: rc += persist_help.cleanup(port) if rc: exit(rc) do_success_test(create_db_of_version=None) do_success_test(create_db_of_version=[0, 9, 0]) do_success_test(create_db_of_version=[1, 0, 0]) do_success_test(create_db_of_version=[1, 1, 0]) do_success_test(create_db_of_version=[1, 1, 2]) do_failure_test(create_db_of_version=[1, 2, 0]) do_failure_test(create_db_of_version=[2, 0, 0]) os.remove(conf_file) ================================================ FILE: test/broker/15-persist-publish-properties-v5-0.py ================================================ #!/usr/bin/env python3 # Publish a retained messages, check they are restored, with properties attached from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) topic = "test/retainprop" source_id = "persist-retain-properties-v5-0" qos = 0 proto_ver = 5 connect_packet = mosq_test.gen_connect(source_id, proto_ver=proto_ver, clean_session=True) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) base_props = mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 1) base_props += mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "plain/text") base_props += mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "/dev/null") base_props += mqtt5_props.gen_string_prop(mqtt5_props.CORRELATION_DATA, "2357289375902345") base_props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name", "value4") base_props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name", "value3") base_props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name", "value2") base_props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name", "value1") props = base_props + mqtt5_props.gen_uint32_prop(mqtt5_props.MESSAGE_EXPIRY_INTERVAL, 60) publish_packet = mosq_test.gen_publish(topic, qos=qos, payload="retained message 1", retain=True, proto_ver=proto_ver, properties=props) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "test/retainprop", 0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid, qos=0, proto_ver=proto_ver) mid = 2 unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "test/retainprop", proto_ver=proto_ver) unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: # Connect client sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Check no retained messages exist mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Ping will fail if a PUBLISH is received mosq_test.do_ping(sock) # Unsubscribe, so we don't receive the messages mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") # Send some retained messages sock.send(publish_packet) mosq_test.do_ping(sock) sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Subscribe mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Check retained messages exist packet = sock.recv(len(publish_packet)) for i in range(60, 1, -1): props = base_props + mqtt5_props.gen_uint32_prop(mqtt5_props.MESSAGE_EXPIRY_INTERVAL, i) publish_packet = mosq_test.gen_publish(topic, qos=qos, payload="retained message 1", retain=True, proto_ver=proto_ver, properties=props) if packet == publish_packet: rc = 0 break mosq_test.do_ping(sock) (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, base_msgs=1, retain_msgs=1) if rc == 0: rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated (2)") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-retain-clear.py ================================================ #!/usr/bin/env python3 # Publish retained messages, check they are restored, delete one from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) topic1 = "test/retain1" topic2 = "test/retain2" source_id = "persist-retain-delete" qos = 0 payload1 = "retained message 1" payload2 = "retained message 2" proto_ver = 4 connect_packet = mosq_test.gen_connect(source_id, proto_ver=proto_ver, clean_session=True) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish1_packet = mosq_test.gen_publish(topic1, qos=qos, payload=payload1, retain=True, proto_ver=proto_ver) publish2_packet = mosq_test.gen_publish(topic2, qos=qos, payload=payload2, retain=True, proto_ver=proto_ver) publish2_clear_packet = mosq_test.gen_publish(topic2, qos=qos, retain=True, proto_ver=proto_ver) publish2_clear_echo = mosq_test.gen_publish(topic2, qos=qos, retain=False, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 0, proto_ver=4) suback_packet = mosq_test.gen_suback(mid, qos=0, proto_ver=4) mid = 2 unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "#", proto_ver=4) unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=4) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: # Connect client sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Check no retained messages exist mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Ping will fail if a PUBLISH is received mosq_test.do_ping(sock) # Unsubscribe, so we don't receive the messages mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") # Send some retained messages sock.send(publish1_packet) mosq_test.do_ping(sock) sock.send(publish2_packet) mosq_test.do_ping(sock) sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Subscribe mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Check retained messages exist mosq_test.receive_unordered(sock, publish1_packet, publish2_packet, "publish 1a / 2") mosq_test.do_ping(sock) # Clear retained (and wait for the publish to avoid race condition) mosq_test.do_send_receive(sock, publish2_clear_packet, publish2_clear_echo, "clear retain flag") # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Subscribe mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Check retained message exist mosq_test.expect_packet(sock, "publish 1b", publish1_packet) # If the other retained message still exists, this will cause an error mosq_test.do_ping(sock) (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, base_msgs=1, retain_msgs=1) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated (2)") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-retain-v3-1-1.py ================================================ #!/usr/bin/env python3 # Publish a retained messages, check they are restored from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) topic1 = "test/retain1" topic2 = "test/retain2" topic3 = "test/retain3" source_id = "persist-retain-v3-1-1" qos = 0 payload2 = "retained message 2" payload3 = "retained message 3" proto_ver = 4 connect_packet = mosq_test.gen_connect(source_id, proto_ver=proto_ver, clean_session=True) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish1_packet = mosq_test.gen_publish(topic1, qos=qos, payload="retained message 1", retain=True, proto_ver=proto_ver) publish2_packet = mosq_test.gen_publish(topic2, qos=qos, payload=payload2, retain=False, proto_ver=proto_ver) publish3_packet = mosq_test.gen_publish(topic3, qos=qos, payload=payload3, retain=True, proto_ver=proto_ver) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "#", 0, proto_ver=4) suback_packet = mosq_test.gen_suback(mid, qos=0, proto_ver=4) mid = 2 unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "#", proto_ver=4) unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=4) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: # Connect client sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Check no retained messages exist mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Ping will fail if a PUBLISH is received mosq_test.do_ping(sock) # Unsubscribe, so we don't receive the messages mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") # Send some retained messages sock.send(publish1_packet) mosq_test.do_ping(sock) sock.send(publish2_packet) # Not retained mosq_test.do_ping(sock) sock.send(publish3_packet) mosq_test.do_ping(sock) sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Subscribe mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Check retained messages exist mosq_test.receive_unordered(sock, publish1_packet, publish3_packet, "publish 1 / 3") mosq_test.do_ping(sock) (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, base_msgs=2, retain_msgs=2) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated (2)") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-retain-v5-0.py ================================================ #!/usr/bin/env python3 # Publish a retained messages, check they are restored from mosq_test_helper import * persist_help = persist_module() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) topic1 = "test/retain1" topic2 = "test/retain2" topic3 = "test/retain3" source_id = "persist-retain-v5-0" qos = 0 payload2 = "retained message 2" payload3 = "retained message 3" proto_ver = 5 connect_packet = mosq_test.gen_connect(source_id, proto_ver=proto_ver, clean_session=True) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) publish1_packet = mosq_test.gen_publish(topic1, qos=qos, payload="retained message 1", retain=True, proto_ver=proto_ver) publish2_packet = mosq_test.gen_publish(topic2, qos=qos, payload=payload2, retain=False, proto_ver=proto_ver) publish3_packet = mosq_test.gen_publish(topic3, qos=qos, payload=payload3, retain=True, 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, qos=0, proto_ver=proto_ver) mid = 2 unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "#", proto_ver=proto_ver) unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) try: # Connect client sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Check no retained messages exist mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Ping will fail if a PUBLISH is received mosq_test.do_ping(sock) # Unsubscribe, so we don't receive the messages mosq_test.do_send_receive(sock, unsubscribe_packet, unsuback_packet, "unsuback") # Send some retained messages sock.send(publish1_packet) mosq_test.do_ping(sock) sock.send(publish2_packet) # Not retained mosq_test.do_ping(sock) sock.send(publish3_packet) mosq_test.do_ping(sock) sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client sock = mosq_test.do_client_connect(connect_packet, connack_packet, timeout=5, port=port) # Subscribe mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") # Check retained messages exist mosq_test.receive_unordered(sock, publish1_packet, publish3_packet, "publish 1 / 3") mosq_test.do_ping(sock) (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, base_msgs=2, retain_msgs=2) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated (2)") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-subscription-v3-1-1.py ================================================ #!/usr/bin/env python3 # Connect a client, add a subscription, disconnect, restore, reconnect, send a # message with a different client, check it is received. from mosq_test_helper import * persist_help = persist_module() def helper(port, packets): helper_id = "persist-subscription-v3-1-1-helper" connect_packet_helper = mosq_test.gen_connect(helper_id, proto_ver=4, clean_session=True) # Connect helper and publish helper = mosq_test.do_client_connect(connect_packet_helper, packets["connack1"], timeout=5, port=port) helper.send(packets["publish0"]) mosq_test.do_send_receive(helper, packets["publish1"], packets["puback1"], "puback helper") mosq_test.do_send_receive(helper, packets["publish2"], packets["pubrec2"], "pubrec helper") mosq_test.do_send_receive(helper, packets["pubrel2"], packets["pubcomp2"], "pubcomp helper") helper.close() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) client_id = "persist-subscription-v3-1-1" proto_ver = 4 topic0 = "subscription/0" topic1 = "subscription/1" topic2 = "subscription/2" packets = {} packets["connect"] = mosq_test.gen_connect(client_id, proto_ver=proto_ver, clean_session=False) packets["connect_clear"] = mosq_test.gen_connect(client_id, proto_ver=proto_ver, clean_session=True) packets["connack1"] = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) packets["connack2"] = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) mid = 1 packets["subscribe0"] = mosq_test.gen_subscribe(mid, topic0, qos=0, proto_ver=proto_ver) packets["suback0"] = mosq_test.gen_suback(mid=mid, qos=0, proto_ver=proto_ver) packets["subscribe1"] = mosq_test.gen_subscribe(mid, topic1, qos=1, proto_ver=proto_ver) packets["suback1"] = mosq_test.gen_suback(mid=mid, qos=1, proto_ver=proto_ver) packets["subscribe2"] = mosq_test.gen_subscribe(mid, topic2, qos=2, proto_ver=proto_ver) packets["suback2"] = mosq_test.gen_suback(mid=mid, qos=2, proto_ver=proto_ver) packets["unsubscribe2"] = mosq_test.gen_unsubscribe(mid, topic2, proto_ver=proto_ver) packets["unsuback2"] = mosq_test.gen_unsuback(mid=mid, proto_ver=proto_ver) packets["publish0"] = mosq_test.gen_publish(topic=topic0, qos=0, payload="message", proto_ver=proto_ver) mid = 1 packets["publish1"] = mosq_test.gen_publish(topic=topic1, qos=1, payload="message", mid=mid, proto_ver=proto_ver) packets["puback1"] = mosq_test.gen_puback(mid=mid, proto_ver=proto_ver) mid = 2 packets["publish2"] = mosq_test.gen_publish(topic=topic2, qos=2, payload="message", mid=mid, proto_ver=proto_ver) packets["pubrec2"] = mosq_test.gen_pubrec(mid=mid, proto_ver=proto_ver) packets["pubrel2"] = mosq_test.gen_pubrel(mid=mid, proto_ver=proto_ver) packets["pubcomp2"] = mosq_test.gen_pubcomp(mid=mid, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) con = None try: # Connect client sock = mosq_test.do_client_connect(packets["connect"], packets["connack1"], timeout=5, port=port) mosq_test.do_send_receive(sock, packets["subscribe0"], packets["suback0"], "suback 0") mosq_test.do_send_receive(sock, packets["subscribe1"], packets["suback1"], "suback 1") mosq_test.do_send_receive(sock, packets["subscribe2"], packets["suback2"], "suback 2") sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client again, it should have a session sock = mosq_test.do_client_connect(packets["connect"], packets["connack2"], timeout=5, port=port) mosq_test.do_ping(sock) helper(port, packets) # Does the client get the messages mosq_test.expect_packet(sock, "publish 0", packets["publish0"]) mosq_test.do_receive_send(sock, packets["publish1"], packets["puback1"], "publish 1") mosq_test.do_receive_send(sock, packets["publish2"], packets["pubrec2"], "publish 2") mosq_test.do_receive_send(sock, packets["pubrel2"], packets["pubcomp2"], "pubrel 2") # Unsubscribe mosq_test.do_send_receive(sock, packets["unsubscribe2"], packets["unsuback2"], "unsuback 2") sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client again, it should have a session sock = mosq_test.do_client_connect(packets["connect"], packets["connack2"], timeout=5, port=port) mosq_test.do_ping(sock) # Connect helper and publish helper(port, packets) # Does the client get the messages mosq_test.expect_packet(sock, "publish 0", packets["publish0"]) mosq_test.do_receive_send(sock, packets["publish1"], packets["puback1"], "publish 1") mosq_test.do_ping(sock) (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1, subscriptions=2) # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client again, but clear the session sock = mosq_test.do_client_connect(packets["connect_clear"], packets["connack1"], timeout=5, port=port) mosq_test.do_ping(sock) (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated (3)") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/15-persist-subscription-v5-0.py ================================================ #!/usr/bin/env python3 # Connect a client, add a subscription, disconnect, restore, reconnect, send a # message with a different client, check it is received. from mosq_test_helper import * persist_help = persist_module() def helper(port, packets): helper_id = "persist-subscription-v5-0-helper" connect_packet_helper = mosq_test.gen_connect(helper_id, proto_ver=5, clean_session=True) connack_packet_helper = mosq_test.gen_connack(rc=0, proto_ver=5) # Connect helper and publish helper = mosq_test.do_client_connect(connect_packet_helper, connack_packet_helper, timeout=5, port=port, connack_error="helper connack") helper.send(packets["publish0-helper"]) mosq_test.do_send_receive(helper, packets["publish1-helper"], packets["puback1"], "puback helper") mosq_test.do_send_receive(helper, packets["publish2-helper"], packets["pubrec2"], "pubrec helper") mosq_test.do_send_receive(helper, packets["pubrel2"], packets["pubcomp2"], "pubcomp helper") helper.close() port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') persist_help.write_config(conf_file, port) rc = 1 persist_help.init(port) client_id = "persist-subscription-v5-0" proto_ver = 5 topic0 = "subscription/0" topic1 = "subscription/1" topic2 = "subscription/2" packets = {} connect_props = mqtt5_props.gen_uint32_prop(mqtt5_props.SESSION_EXPIRY_INTERVAL, 60) packets["connect"] = mosq_test.gen_connect(client_id, proto_ver=proto_ver, clean_session=False, properties=connect_props) packets["connack1"] = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) packets["connack2"] = mosq_test.gen_connack(rc=0, flags=1, proto_ver=proto_ver) mid = 1 publish_props0 = mqtt5_props.gen_varint_prop(mqtt5_props.SUBSCRIPTION_IDENTIFIER, 100) packets["subscribe0"] = mosq_test.gen_subscribe(mid, topic0, qos=0, proto_ver=proto_ver, properties=publish_props0) packets["suback0"] = mosq_test.gen_suback(mid=mid, qos=0, proto_ver=proto_ver) publish_props1 = mqtt5_props.gen_varint_prop(mqtt5_props.SUBSCRIPTION_IDENTIFIER, 101) packets["subscribe1"] = mosq_test.gen_subscribe(mid, topic1, qos=1, proto_ver=proto_ver, properties=publish_props1) packets["suback1"] = mosq_test.gen_suback(mid=mid, qos=1, proto_ver=proto_ver) publish_props2 = mqtt5_props.gen_varint_prop(mqtt5_props.SUBSCRIPTION_IDENTIFIER, 102) packets["subscribe2"] = mosq_test.gen_subscribe(mid, topic2, qos=2, proto_ver=proto_ver, properties=publish_props2) packets["suback2"] = mosq_test.gen_suback(mid=mid, qos=2, proto_ver=proto_ver) packets["unsubscribe2"] = mosq_test.gen_unsubscribe(mid, topic2, proto_ver=proto_ver) packets["unsuback2"] = mosq_test.gen_unsuback(mid=mid, proto_ver=proto_ver) packets["publish0-helper"] = mosq_test.gen_publish(topic=topic0, qos=0, payload="message", proto_ver=proto_ver) packets["publish0"] = mosq_test.gen_publish(topic=topic0, qos=0, payload="message", proto_ver=proto_ver, properties=publish_props0) mid = 1 packets["publish1-helper"] = mosq_test.gen_publish(topic=topic1, qos=1, payload="message", mid=mid, proto_ver=proto_ver) packets["publish1"] = mosq_test.gen_publish(topic=topic1, qos=1, payload="message", mid=mid, proto_ver=proto_ver, properties=publish_props1) packets["puback1"] = mosq_test.gen_puback(mid=mid, proto_ver=proto_ver) mid = 2 packets["publish2-helper"] = mosq_test.gen_publish(topic=topic2, qos=2, payload="message", mid=mid, proto_ver=proto_ver) packets["publish2"] = mosq_test.gen_publish(topic=topic2, qos=2, payload="message", mid=mid, proto_ver=proto_ver, properties=publish_props2) packets["pubrec2"] = mosq_test.gen_pubrec(mid=mid, proto_ver=proto_ver) packets["pubrel2"] = mosq_test.gen_pubrel(mid=mid, proto_ver=proto_ver) packets["pubcomp2"] = mosq_test.gen_pubcomp(mid=mid, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) con = None try: # Connect client sock = mosq_test.do_client_connect(packets["connect"], packets["connack1"], timeout=5, port=port, connack_error="connack1") mosq_test.do_send_receive(sock, packets["subscribe0"], packets["suback0"], "suback 0") mosq_test.do_send_receive(sock, packets["subscribe1"], packets["suback1"], "suback 1") mosq_test.do_send_receive(sock, packets["subscribe2"], packets["suback2"], "suback 2") sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client again, it should have a session sock = mosq_test.do_client_connect(packets["connect"], packets["connack2"], timeout=5, port=port) mosq_test.do_ping(sock) helper(port, packets) # Does the client get the messages mosq_test.expect_packet(sock, "publish 0", packets["publish0"]) mosq_test.do_receive_send(sock, packets["publish1"], packets["puback1"], "publish 1") mosq_test.do_receive_send(sock, packets["publish2"], packets["pubrec2"], "publish 2") mosq_test.do_receive_send(sock, packets["pubrel2"], packets["pubcomp2"], "pubrel 2") # Unsubscribe mosq_test.do_send_receive(sock, packets["unsubscribe2"], packets["unsuback2"], "unsuback 2") sock.close() # Kill broker (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None # Restart broker broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) # Connect client again, it should have a session sock = mosq_test.do_client_connect(packets["connect"], packets["connack2"], timeout=5, port=port, connack_error="connack2") mosq_test.do_ping(sock) # Connect helper and publish helper(port, packets) # Does the client get the messages mosq_test.expect_packet(sock, "publish 0", packets["publish0"]) mosq_test.do_receive_send(sock, packets["publish1"], packets["puback1"], "publish 1") mosq_test.do_ping(sock) (broker_terminate_rc, stde) = mosq_test.terminate_broker(broker) broker = None persist_help.check_counts(port, clients=1, subscriptions=2) rc = broker_terminate_rc finally: if broker is not None: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated (3)") if rc == 0: rc=1 (_, stde) = broker.communicate() os.remove(conf_file) rc += persist_help.cleanup(port) if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/16-cmd-args.py ================================================ #!/usr/bin/env python3 # Test whether command line args are handled from mosq_test_helper import * port = mosq_test.get_port() do_test_broker_failure("", [], port, cmd_args=["-h"], rc_expected=0, stdout_entry="Usage: mosquitto [-c config_file] [-d] [-h] [-p port] [-v]") do_test_broker_failure("", [], port, cmd_args=["-p", "0"], rc_expected=3, error_log_entry="Error: Invalid port specified (0).") # Port invalid do_test_broker_failure("", [], port, cmd_args=["-p", "65536"], rc_expected=3, error_log_entry="Error: Invalid port specified (65536).") # Port invalid do_test_broker_failure("", [], port, cmd_args=["-p"], rc_expected=3, error_log_entry="Error: -p argument given, but no port specified.") # Missing port do_test_broker_failure("", [], port, cmd_args=["-c"], rc_expected=3, error_log_entry="Error: -c argument given, but no config file specified.") # Missing config do_test_broker_failure("", [], port, cmd_args=["--tls-keylog"], rc_expected=3, error_log_entry="Error: --tls-keylog argument given, but no file specified.") # Missing filename do_test_broker_failure("", [], port, cmd_args=["--unknown"], rc_expected=3, error_log_entry="Error: Unknown option '--unknown'.") # Unknown option exit(0) ================================================ FILE: test/broker/16-config-huge.py ================================================ #!/usr/bin/env python3 # Test many different config options at once, and also reloading. This is # primarily intended as a test of the config code, not the functionality of the # options being set. from mosq_test_helper import * import os import platform import signal def write_acl(filename): with open(filename, 'w') as f: f.write('user new_username\n') f.write('topic readwrite topic/one\n') def write_config(filename, ports, per_listener_settings, plugver, acl_file): with open(filename, 'w') as f: f.write("per_listener_settings %s\n" % (per_listener_settings)) # Global options f.write("allow_duplicate_messages true\n") f.write("autosave_interval 1\n") f.write("autosave_on_changes true\n") f.write("check_retain_source true\n") f.write("enable_control_api true\n") f.write("global_max_clients 10\n") f.write("global_max_connections 10\n") #f.write("include_dir path\n") f.write("global_max_connections 10\n") f.write("log_dest stderr\n") f.write("log_timestamp true\n") f.write("log_timestamp_format %Y-%m-%dT%H:%M:%S\n") f.write("log_type all\n") f.write("max_inflight_bytes 10000\n") f.write("max_inflight_messages 100\n") f.write("max_keepalive 60\n") f.write("max_packet_size 1000\n") f.write("max_queued_bytes 10000\n") f.write("max_queued_messages 100\n") f.write("message_size_limit 1000\n") f.write("memory_limit 100000000\n") f.write("persistence true\n") f.write(f"persistence_file {ports[0]}.db\n") f.write("persistence_location .\n") f.write("persistent_client_expiration 1h\n") f.write(f"pid_file {ports[0]}.pid\n") f.write("queue_qos0_messages true\n") f.write("retain_available true\n") f.write("retry_interval not-used\n") f.write("set_tcp_nodelay true\n") f.write("sys_interval 60\n") f.write("upgrade_outgoing_qos true\n") if os.environ.get('WITH_WEBSOCKETS') != "no": f.write("websockets_log_level 255\n") f.write("websockets_headers_size 4096\n") # Listener and global if not per_listener_settings: f.write("allow_zero_length_clientid false\n") f.write("auto_id_prefix pre\n") f.write(f"acl_file {acl_file}\n") # Bridge options f.write("connection bridge\n") f.write(f"address 127.0.0.1:{ports[2]} 127.0.0.1:{ports[3]}\n") f.write("bridge_alpn alpn\n") f.write("bridge_attempt_unsubscribe false\n") f.write("bridge_bind_address 127.0.0.1\n") f.write(f"bridge_cafile {ssl_dir}/all-ca.crt\n") f.write("bridge_capath asasdf\n") f.write(f"bridge_certfile {ssl_dir}/client.crt\n") f.write(f"bridge_keyfile {ssl_dir}/client.key\n") f.write("bridge_ciphers ECDHE-ECDSA-AES256-GCM-SHA384\n") f.write("bridge_ciphers_tls1.3 TLS_AES_256_GCM_SHA384\n") #f.write("bridge_identity identity\n") f.write("bridge_insecure true\n") f.write("bridge_max_packet_size 10000\n") f.write("bridge_max_topic_alias 1000\n") f.write("bridge_outgoing_retain false\n") f.write("bridge_protocol_version mqttv50\n") #f.write("bridge_psk\n") f.write("bridge_receive_maximum 100\n") #f.write("bridge_reload_type immediate\n") f.write("bridge_reload_type lazy\n") f.write("bridge_require_ocsp false\n") f.write("bridge_session_expiry_interval 63\n") f.write("bridge_tcp_keepalive 100 100 100\n") f.write("bridge_tcp_user_timeout 60\n") f.write("bridge_tls_use_os_certs true\n") f.write("bridge_tls_version tlsv1.2\n") f.write("local_cleansession true\n") f.write("local_clientid blci\n") #f.write("local_username username\n") #f.write("local_password password\n") f.write("connection_messages true\n") f.write("idle_timeout 60\n") f.write("keepalive_interval 40\n") f.write("notification_topic notifications\n") f.write("notifications false\n") f.write("notifications_local_only true\n") f.write("remote_clientid brci\n") f.write("remote_username username\n") f.write("remote_password password\n") f.write("restart_timeout 60\n") f.write("round_robin false\n") f.write("start_type lazy\n") f.write("threshold 100\n") f.write("try_private false\n") f.write("topic bridge both 1\n") # Default listener # Listeners f.write("plugin_load auth c/auth_plugin_v%d.so\n" % (plugver)) f.write("plugin_opt_test true\n") f.write("auth_plugin_deny_special_chars false\n") f.write("listener %d\n" % (ports[0])) f.write("plugin_use auth\n") f.write("listener %d\n" % (ports[1])) f.write("allow_anonymous false\n") #f.write("psk_hint hint\n") f.write("listener %d\n" % (ports[2])) f.write("plugin_use auth\n") f.write("accept_protocol_versions 3,4,5\n") if platform.system() == "Darwin": f.write("bind_interface lo0\n") else: f.write("bind_interface lo\n") f.write(f"cafile {ssl_dir}/all-ca.crt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") #f.write("capath path\n") f.write("ciphers ECDHE-ECDSA-AES256-GCM-SHA384\n") f.write("ciphers_tls1.3 TLS_AES_256_GCM_SHA384\n") f.write("clientid_prefixes client\n") f.write(f"crlfile {ssl_dir}/crl.pem\n") #f.write("dhparamfile file\n") f.write("disable_client_cert_date_checks true\n") f.write("http_dir .\n") f.write("max_connections 10\n") f.write("max_qos 1\n") f.write("mount_point mount/\n") if os.environ.get('WITH_WEBSOCKETS') != "no": f.write("protocol websockets\n") f.write("require_certificate true\n") f.write("socket_domain ipv4\n") f.write("tls_version tlsv1.2\n") f.write("max_topic_alias 15\n") f.write("max_topic_alias_broker 15\n") f.write("use_identity_as_username true\n") f.write("use_subject_as_username true\n") f.write("use_username_as_clientid true\n") if os.environ.get('WITH_WEBSOCKETS') != "no": f.write("websockets_origin localhost\n") if per_listener_settings: f.write("allow_zero_length_clientid false\n") f.write("auto_id_prefix pre\n") f.write(f"acl_file {acl_file}\n") f.write("port %d\n" % (ports[3])) def client_check(username, password, rc, port): connect_packet = mosq_test.gen_connect(client_id="client-id", username=username, password=password) connack_packet = mosq_test.gen_connack(rc=rc) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() def do_test(per_listener_settings): proto_ver = 5 ports = mosq_test.get_port(4) conf_file = os.path.basename(__file__).replace('.py', '.conf') acl_file = os.path.basename(__file__).replace('.py', '.acl') write_acl(acl_file) write_config(conf_file, ports, per_listener_settings, 2, acl_file) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=ports[0]) rc = 1 try: client_check("test-username", "cnwTICONIURW", 0, ports[0]) # Should succeed client_check("test-username", "cnwTICONIURW", 5, ports[1]) # Should fail client_check("bad-actor", "nope", 5, ports[0]) # Should fail client_check("bad-actor", "nope", 5, ports[1]) # Should fail client_check(None, None, 5, ports[0]) # Should fail client_check(None, None, 5, ports[1]) # Should fail broker.send_signal(signal.SIGHUP) client_check("test-username", "cnwTICONIURW", 0, ports[0]) # Should succeed broker.send_signal(signal.SIGHUP) client_check("test-username", "cnwTICONIURW", 0, ports[0]) # Should succeed rc = 0 except Exception as err: print(err) finally: broker.terminate() broker.wait() os.remove(conf_file) os.remove(acl_file) try: os.remove(f"{ports[0]}.db") except FileNotFoundError: pass if broker.returncode == 139: # Crash print("Broker crashed!") rc = 1 if rc: print(f"per_listener_settings:{per_listener_settings}") (_, stde) = broker.communicate() print(stde.decode('utf-8')) exit(rc) do_test("false") do_test("true") ================================================ FILE: test/broker/16-config-includedir.py ================================================ #!/usr/bin/env python3 # Test whether include_dir works properly from mosq_test_helper import * def write_config(filename, port): with open(filename, 'w') as f: f.write(f"include_dir {port}\n") os.mkdir(str(port)) with open(f"{port}/1.conf", 'w') as f: f.write(f"listener {port}\n") with open(f"{port}/2.conf", 'w') as f: f.write(f"allow_anonymous true\n") def do_test(): 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: rc = 1 connect_packet = mosq_test.gen_connect("connect-include-dir") connack_packet = mosq_test.gen_connack(rc=0) sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=port) sock.close() rc = 0 except mosq_test.TestError: pass except Exception as e: print(e) finally: os.remove(conf_file) os.remove(f"{port}/1.conf") os.remove(f"{port}/2.conf") os.rmdir(f"{port}") broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test() exit(0) ================================================ FILE: test/broker/16-config-missing.py ================================================ #!/usr/bin/env python3 # Test whether config parse errors are handled from mosq_test_helper import * port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') do_test_broker_failure(conf_file, [], port, cmd_args=['-c', conf_file], rc_expected=3, error_log_entry=f"Error: Unable to open config file '{conf_file}'.\n") exit(0) ================================================ FILE: test/broker/16-config-parse-errors-tls-psk.py ================================================ #!/usr/bin/env python3 # Test whether config parse errors are handled from mosq_test_helper import * port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') do_test_broker_failure(conf_file, ["bridge_psk string"], port, 3, "Error: The 'bridge_psk' option requires a bridge to be defined first.") do_test_broker_failure(conf_file, ["bridge_identity string"], port, 3, "Error: The 'bridge_identity' option requires a bridge to be defined first.") bridge_config=["connection invalid-psk", "address localhost", "topic dummy-topic"] do_test_broker_failure(conf_file, bridge_config+ ["bridge_psk"], port, 3, "Error: Empty 'bridge_psk' value in configuration.") # Empty bridge_psk in bridge config do_test_broker_failure(conf_file, bridge_config+ ["bridge_identity"], port, 3, "Error: Empty 'bridge_identity' value in configuration.") # Empty bridge_identity in bridge config do_test_broker_failure(conf_file, bridge_config+ ["bridge_psk my_psk"], port, 3, "Error: Invalid bridge configuration: missing bridge_identity.") # Missing bridge_identity in bridge config do_test_broker_failure(conf_file, bridge_config+ ["bridge_identity my_identity"], port, 3, "Error: Invalid bridge configuration: missing bridge_psk.") # Missing bridge_psk in bridge config exit(0) ================================================ FILE: test/broker/16-config-parse-errors-tls.py ================================================ #!/usr/bin/env python3 # Test whether config parse errors are handled from mosq_test_helper import * conf_file = os.path.basename(__file__).replace('.py', '.conf') port = mosq_test.get_port() do_test_broker_failure(conf_file, ["bridge_cafile string"], port, 3) # Missing bridge config do_test_broker_failure(conf_file, ["bridge_alpn string"], port, 3) # Missing bridge config do_test_broker_failure(conf_file, ["bridge_ciphers string"], port, 3) # Missing bridge config do_test_broker_failure(conf_file, ["bridge_ciphers_tls1.3 string"], port, 3) # Missing bridge config do_test_broker_failure(conf_file, ["bridge_capath string"], port, 3) # Missing bridge config do_test_broker_failure(conf_file, ["bridge_certfile string"], port, 3) # Missing bridge config do_test_broker_failure(conf_file, ["bridge_keyfile string"], port, 3) # Missing bridge config do_test_broker_failure(conf_file, ["bridge_tls_version string"], port, 3) # Missing bridge config do_test_broker_failure(conf_file, [f"listener {port}","certfile"], port, 3) # empty certfile do_test_broker_failure(conf_file, [f"listener {port}","keyfile"], port, 3) # empty keyfile do_test_broker_failure(conf_file, [f"listener {port}","certfile ./16-config-parse-errors.py","keyfile ../ssl/server.key"], port, 1, with_test_config=False) # invalid certfile do_test_broker_failure(conf_file, [f"listener {port}","certfile ../ssl/server.crt","keyfile ./16-config-parse-errors.py"], port, 1, with_test_config=False) # invalid keyfile do_test_broker_failure(conf_file, [f"listener {port}","certfile ../ssl/server.crt","keyfile ../ssl/client.key"], port, 1, with_test_config=False) # mismatched certfile / keyfile do_test_broker_failure(conf_file, [f"listener {port}","certfile ../ssl/server.crt","keyfile ../ssl/server.key","tls_version invalid"], port, 1, with_test_config=False) # invalid tls_version do_test_broker_failure(conf_file, [f"listener {port}","certfile ../ssl/server.crt","keyfile ../ssl/server.key","crlfile invalid"], port, 1, with_test_config=False) # missing crl file do_test_broker_failure(conf_file, [f"listener {port}","certfile ../ssl/server.crt","keyfile ../ssl/server.key","ciphers invalid"], port, 1, with_test_config=False) # invalid ciphers do_test_broker_failure(conf_file, [f"listener {port}","certfile ../ssl/server.crt","keyfile ../ssl/server.key","ciphers_tls1.3 invalid"], port, 1, with_test_config=False) # invalid ciphers_tls1.3 exit(0) ================================================ FILE: test/broker/16-config-parse-errors-without-tls.py ================================================ #!/usr/bin/env python3 # Test whether config parse errors are handled from mosq_test_helper import * port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') do_test_broker_failure(conf_file, ["unknown_option unknown"], port, 3, "Error: Unknown configuration variable 'unknown_option'") do_test_broker_failure(conf_file, ["user"], port, 3, "Error: Empty 'user' value in configuration.") # Empty string, no space do_test_broker_failure(conf_file, ["user "], port, 3, "Error: Empty 'user' value in configuration.") # Empty string, single space do_test_broker_failure(conf_file, ["user "], port, 3, "Error: Empty 'user' value in configuration.") # Empty string, double space do_test_broker_failure(conf_file, ["pid_file /tmp/pid","pid_file /tmp/pid"], port, 3, "Error: Duplicate 'pid_file' value in configuration.") # Duplicate string do_test_broker_failure(conf_file, ["memory_limit"], port, 3, "Empty 'memory_limit' value in configuration.") # Empty ssize_t do_test_broker_failure(conf_file, ["accept_protocol_versions 3"], port, 3, "Error: The 'accept_protocol_versions' option requires a listener to be defined first.") # Missing listener do_test_broker_failure(conf_file, [f"listener {port}","accept_protocol_versions"], port, 3, "Error: Empty 'accept_protocol_versions' value in configuration.") # Empty value do_test_broker_failure(conf_file, ["allow_anonymous"], port, 3, "Error: Empty 'allow_anonymous' value in configuration.") # Empty bool do_test_broker_failure(conf_file, ["allow_anonymous falst"], port, 3, "Error: Invalid 'allow_anonymous' value (falst).") # Invalid bool do_test_broker_failure(conf_file, ["autosave_interval"], port, 3, "Error: Empty 'autosave_interval' value in configuration.") # Empty int do_test_broker_failure(conf_file, ["autosave_interval string"], port, 3, "Error: 'autosave_interval' value not a number.") # Invalid int do_test_broker_failure(conf_file, ["listener"], port, 3, "Error: Empty 'listener port' value in configuration.") # Empty listener do_test_broker_failure(conf_file, ["mount_point test/"], port, 3, "Error: The 'mount_point' option requires a listener to be defined first.") # Missing listener config do_test_broker_failure(conf_file, [f"listener {port}","mount_point test/+/"], port, 3, "Error: Invalid 'mount_point' value (test/+/). Does it contain a wildcard character?") # Wildcard in mount point. do_test_broker_failure(conf_file, [f"listener 100000"], port, 3, "Error: Invalid 'port' value (100000).") # Out of range do_test_broker_failure(conf_file, [f"listener 0"], port, 3, "Error: A listener with port 0 must provide a Unix socket path.") # Missing unix socket do_test_broker_failure(conf_file, [f"listener {port}","protocol"], port, 3, "Error: Empty 'protocol' value in configuration.") # Empty proto do_test_broker_failure(conf_file, [f"listener {port}","protocol test"], port, 3, "Error: Invalid 'protocol' value (test).") # Invalid proto do_test_broker_failure(conf_file, [f"listener {port}","accept_protocol_versions"], port, 3, "Error: Empty 'accept_protocol_versions' value in configuration.") do_test_broker_failure(conf_file, ["plugin_opt_inval string"], port, 3, "Error: The 'plugin_opt_inval' option requires plugin/global_plugin/plugin_load to be defined first.") # plugin_opt_ without plugin do_test_broker_failure(conf_file, ["plugin c/auth_plugin.so","plugin_opt_ string"], port, 3, "Error: Invalid 'plugin_opt_' config option.") # Incomplete plugin_opt_ do_test_broker_failure(conf_file, ["plugin c/auth_plugin.so","plugin_opt_test"], port, 3, "Error: Empty 'test' value in configuration.") # Empty plugin_opt_ do_test_broker_failure(conf_file, ["bridge_attempt_unsubscribe true"], port, 3, "Error: The 'bridge_attempt_unsubscribe' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["bridge_bind_address string"], port, 3, "Error: The 'bridge_bind_address' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["bridge_insecure true"], port, 3, "Error: The 'bridge_insecure' option requires a bridge to be defined first.") # Missing bridge config #do_test_broker_failure(conf_file, ["bridge_require_oscp true"], port, 3, "Error: The 'bridge_require_oscp' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["bridge_max_packet_size 1000"], port, 3, "Error: The 'bridge_max_packet_size' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["bridge_max_topic_alias 1000"], port, 3, "Error: The 'bridge_max_topic_alias' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["bridge_outgoing_retain false"], port, 3, "Error: The 'bridge_outgoing_retain' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["bridge_protocol_version string"], port, 3, "Error: The 'bridge_protocol_version' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["bridge_receive_maximum 10"], port, 3, "Error: The 'bridge_receive_maximum' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["bridge_reload_type string"], port, 3, "Error: The 'bridge_reload_type' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["bridge_session_expiry_interval 10000"], port, 3, "Error: The 'bridge_session_expiry_interval' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["bridge_tcp_keepalive 10000"], port, 3, "Error: The 'bridge_tcp_keepalive' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["bridge_tcp_user_timeout 10000"], port, 3, "Error: The 'bridge_tcp_user_timeout' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["connection"], port, 3, "Error: Empty 'connection' value in configuration.") # Missing bridge name do_test_broker_failure(conf_file, ["connection just-name"], port, 3, "Error: Invalid bridge configuration: no remote addresses defined.") # Missing bridge topic and address do_test_broker_failure(conf_file, ["connection no-topic", "address localhost"], port, 3, "Error: Invalid bridge configuration: no topics defined.") # Missing bridge topic do_test_broker_failure(conf_file, ["connection no-address", "topic dummy-topic"], port, 3, "Error: Invalid bridge configuration: no remote addresses defined.") # Missing bridge address do_test_broker_failure(conf_file, ["connection no-address", "topic \"missing quote"], port, 3, "Error: Missing closing quote in topic value (quote).") # Missing topic quote do_test_broker_failure(conf_file, ["local_clientid str"], port, 3, "Error: The 'local_clientid' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["local_password str"], port, 3, "Error: The 'local_password' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["local_username str"], port, 3, "Error: The 'local_username' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["notifications true"], port, 3, "Error: The 'notifications' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["notifications_local_only true"], port, 3, "Error: The 'notifications_local_only' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["notification_topic true"], port, 3, "Error: The 'notification_topic' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["password pw"], port, 3, "Error: The 'password' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["remote_password pw"], port, 3, "Error: The 'remote_password' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["restart_timeout 10"], port, 3, "Error: The 'restart_timeout' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["round_robin true"], port, 3, "Error: The 'round_robin' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["start_type lazy"], port, 3, "Error: The 'start_type' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["threshold 10"], port, 3, "Error: The 'threshold' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["topic topic/10"], port, 3, "Error: The 'topic' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["try_private true"], port, 3, "Error: The 'try_private' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["username un"], port, 3, "Error: The 'username' option requires a bridge to be defined first.") # Missing bridge config do_test_broker_failure(conf_file, ["maximum_qos 3"], port, 3, "Error: 'max_qos' must be between 0 and 2 inclusive.") # Invalid maximum qos do_test_broker_failure(conf_file, ["maximum_qos -1"], port, 3, "Error: 'max_qos' must be between 0 and 2 inclusive.") # Invalid maximum qos do_test_broker_failure(conf_file, ["max_inflight_messages 65536"], port, 3, "Error: 'max_inflight_messages' must be <= 65535.") # Invalid value do_test_broker_failure(conf_file, ["max_packet_size 19"], port, 3, "Error: 'max_packet_size' must be >= 20.") # Invalid value do_test_broker_failure(conf_file, ["message_size_limit 556000000"], port, 3, "Error: Invalid 'message_size_limit' value (556000000).") # Invalid value do_test_broker_failure(conf_file, ["max_keepalive 65536"], port, 3, "Error: Invalid 'max_keepalive' value (65536).") # Invalid value do_test_broker_failure(conf_file, ["max_keepalive -1"], port, 3, "Error: Invalid 'max_keepalive' value (-1).") # Invalid value do_test_broker_failure(conf_file, [f"listener {port}", "max_topic_alias 65536"], port, 3, "Error: Invalid 'max_topic_alias' value in configuration.") # Invalid value do_test_broker_failure(conf_file, [f"listener {port}", "max_topic_alias -1"], port, 3, "Error: Invalid 'max_topic_alias' value in configuration.") # Invalid value do_test_broker_failure(conf_file, [f"listener {port}", "max_topic_alias_broker 65536"], port, 3, "Error: Invalid 'max_topic_alias_broker' value in configuration.") # Invalid value do_test_broker_failure(conf_file, [f"listener {port}", "max_topic_alias_broker -1"], port, 3, "Error: Invalid 'max_topic_alias_broker' value in configuration.") # Invalid value do_test_broker_failure(conf_file, [f"listener {port}", "listener_auto_id_prefix"], port, 3, "Error: Empty 'listener_auto_id_prefix' value in configuration.") # Empty string do_test_broker_failure(conf_file, [f"listener {port}", f"listener_auto_id_prefix {'a'*51}"], port, 3, "Error: 'listener_auto_id_prefix' length must be <= 50.") # Invalid value do_test_broker_failure(conf_file, ["websockets_headers_size 65536"], port, 3, "Error: Packet buffer size must be between 0 and 65535 inclusive.") # Invalid value do_test_broker_failure(conf_file, ["websockets_headers_size -1"], port, 3, "Error: Packet buffer size must be between 0 and 65535 inclusive.") # Invalid value do_test_broker_failure(conf_file, ["memory_limit -1"], port, 3, "Error: Invalid 'memory_limit' value (-1).") # Invalid value do_test_broker_failure(conf_file, ["sys_interval -1"], port, 3, "Error: Invalid 'sys_interval' value (-1).") # Invalid value do_test_broker_failure(conf_file, ["sys_interval 65536"], port, 3, "Error: Invalid 'sys_interval' value (65536).") # Invalid value exit(0) ================================================ FILE: test/broker/17-control-list-listeners.py ================================================ #!/usr/bin/env python3 # Test $CONTROL/broker/v1 listListeners from mosq_test_helper import * import json import shutil def write_config(filename, ports): with open(filename, 'w') as f: f.write("enable_control_api true\n") f.write("allow_anonymous true\n") f.write("listener %d\n" % (ports[0])) f.write("protocol mqtt\n") f.write("listener %d\n" % (ports[1])) f.write("protocol websockets\n") f.write("listener %d\n" % (ports[2])) f.write("protocol mqtt\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") f.write("listener %d\n" % (ports[3])) f.write("protocol websockets\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") f.write("listener 0 17-list-listeners-mqtt.sock\n") f.write("protocol mqtt\n") f.write("listener 0 17-list-listeners-websockets.sock\n") f.write("protocol websockets\n") def command_check(sock, command_payload, expected_response): command_packet = mosq_test.gen_publish(topic="$CONTROL/broker/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) def invalid_command_check(sock, command_payload, cmd_name, error_msg): command_packet = mosq_test.gen_publish(topic="$CONTROL/broker/v1", qos=0, payload=command_payload) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) expected_response = {'responses': [{'command': cmd_name, 'error': error_msg}]} if response != expected_response: print(expected_response) print(response) raise ValueError(response) ports = mosq_test.get_port(4) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, ports) cmd_success = {"commands":[{"command": "listListeners", "correlationData": "m3CtYVnySLCOwnHzITSeowvgla0InV4G"}]} response_success = {'responses': [{'command': 'listListeners', "correlationData": "m3CtYVnySLCOwnHzITSeowvgla0InV4G", 'data':{ 'listeners':[ { 'port': ports[0], 'protocol': 'mqtt', 'tls': False },{ 'port': ports[1], 'protocol': 'mqtt+websockets', 'tls': False },{ 'port': ports[2], 'protocol': 'mqtt', 'tls': True },{ 'port': ports[3], 'protocol': 'mqtt+websockets', 'tls': True },{ 'port': 0, 'protocol': 'mqtt', 'socket-path': '17-list-listeners-mqtt.sock', 'tls': False },{ 'port': 0, 'protocol': 'mqtt+websockets', 'socket-path': '17-list-listeners-websockets.sock', 'tls': False } ]}}]} rc = 1 connect_packet = mosq_test.gen_connect("17-list-listeners") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/broker/#", 0) suback_packet = mosq_test.gen_suback(mid, 0) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=ports[0]) try: sock = mosq_test.do_client_connect(connect_packet, connack_packet, port=ports[0]) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") invalid_command_check(sock, "not valid json", "Unknown command", "Payload not valid JSON") invalid_command_check(sock, "{}", "Unknown command", "Invalid/missing commands") cmd = {"commands":["command"]} invalid_command_check(sock, json.dumps(cmd), "Unknown command", "Command not an object") cmd = {"commands":[{}]} invalid_command_check(sock, json.dumps(cmd), "Unknown command", "Missing command") cmd = {"commands":[{"command": "unknown command"}]} invalid_command_check(sock, json.dumps(cmd), "unknown command", "Unknown command") cmd = {"commands":[{"command": "listListeners", "correlationData": True}]} invalid_command_check(sock, json.dumps(cmd), "listListeners", "Invalid correlationData data type.") command_check(sock, cmd_success, response_success) mosq_test.do_ping(sock) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) for f in ["17-list-listeners-mqtt.sock", "17-list-listeners-websockets.sock"]: try: os.remove(f) except FileNotFoundError: pass broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/17-control-list-plugins.py ================================================ #!/usr/bin/env python3 # Test $CONTROL/broker/v1 listListeners from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("enable_control_api true\n") f.write("allow_anonymous true\n") f.write("listener %d\n" % (port)) f.write("plugin c/auth_plugin_v5_control.so\n") def command_check(sock, command_payload, expected_response): command_packet = mosq_test.gen_publish(topic="$CONTROL/broker/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) def invalid_command_check(sock, command_payload, cmd_name, error_msg): command_packet = mosq_test.gen_publish(topic="$CONTROL/broker/v1", qos=0, payload=command_payload) sock.send(command_packet) response = json.loads(mosq_test.read_publish(sock)) expected_response = {'responses': [{'command': cmd_name, 'error': error_msg}]} 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) cmd_success = {"commands":[{"command": "listPlugins", "correlationData": "m3CtYVnySLCOwnHzITSeowvgla0InV4G"}]} response_success = {'responses': [{'command': 'listPlugins', "correlationData": "m3CtYVnySLCOwnHzITSeowvgla0InV4G", 'data':{ 'plugins':[ { 'name': 'test-plugin', 'control-endpoints': ['$CONTROL/test/v1'] } ]}}]} rc = 1 connect_packet = mosq_test.gen_connect("17-list-listeners") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/broker/#", 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") invalid_command_check(sock, "not valid json", "Unknown command", "Payload not valid JSON") invalid_command_check(sock, "{}", "Unknown command", "Invalid/missing commands") cmd = {"commands":["command"]} invalid_command_check(sock, json.dumps(cmd), "Unknown command", "Command not an object") cmd = {"commands":[{}]} invalid_command_check(sock, json.dumps(cmd), "Unknown command", "Missing command") cmd = {"commands":[{"command": "unknown command"}]} invalid_command_check(sock, json.dumps(cmd), "unknown command", "Unknown command") cmd = {"commands":[{"command": "listListeners", "correlationData": True}]} invalid_command_check(sock, json.dumps(cmd), "listListeners", "Invalid correlationData data type.") command_check(sock, cmd_success, response_success) mosq_test.do_ping(sock) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) for f in ["17-list-listeners-mqtt.sock", "17-list-listeners-websockets.sock"]: try: os.remove(f) except FileNotFoundError: pass broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/17-control-missing-endpoint.py ================================================ #!/usr/bin/env python3 # Test $CONTROL/broker/v1 listListeners from mosq_test_helper import * import json import shutil def write_config(filename, port): with open(filename, 'w') as f: f.write("enable_control_api true\n") f.write("allow_anonymous true\n") f.write(f"listener {port}\n") def command_check(sock, command_payload, expected_response): command_packet = mosq_test.gen_publish(topic="$CONTROL/missing-endpoint/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(1) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) rc = 1 connect_packet = mosq_test.gen_connect("17-missing-endpoint") connack_packet = mosq_test.gen_connack(rc=0) mid = 2 subscribe_packet = mosq_test.gen_subscribe(mid, "$CONTROL/missing-endpoint/#", 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") cmd = {"commands":[{"command": "listListeners", "correlationData": "m3CtYVnySLCOwnHzITSeowvgla0InV4G"}]} response = {"error": "endpoint not available"} command_check(sock, cmd, response) mosq_test.do_ping(sock) rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) ================================================ FILE: test/broker/20-sparkplug-aware.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import uuid namespace = "spBv1.0" client_id = "test-client" username = None password = None 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(f"plugin {mosq_test.get_build_root()}/plugins/sparkplug-aware/mosquitto_sparkplug_aware.so\n") def proc(port, proto_ver): group_id = str(uuid.uuid4()) edge_node_id = str(uuid.uuid4()) device_id = str(uuid.uuid4()) # ====================================================================== # Connect a client to monitor the spBv1.0//NDEATH/# and # $sparkplug/certificates/spBv1.0//# topics # ====================================================================== topic = f"$sparkplug/certificates/{namespace}/{group_id}/#" qos = 1 monitor = mosq_test.sub_helper(port, topic, qos=qos, proto_ver=proto_ver) topic = f"{namespace}/{group_id}/NDEATH/#" qos = 1 subscribe_packet = mosq_test.gen_subscribe(topic=topic, mid=1, qos=qos, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid=1, qos=qos, proto_ver=proto_ver) mosq_test.do_send_receive(monitor, subscribe_packet, suback_packet) # ====================================================================== # Connect a test client that will act as a sparkplug device # ====================================================================== # • [tck-id-message-flow-edge-node-birth-publish-will-message-topic] # The Edge Node’s MQTT Will Message’s topic MUST be of the form # spBv1.0/group_id/NDEATH/edge_node_id where group_id is the Sparkplug # Group ID and the edge_node_id is the Sparkplug Edge Node ID for this # Edge Node NDEATH_topic = f"{namespace}/{group_id}/NDEATH/{edge_node_id}" # • [tck-id-message-flow-edge-node-birth-publish-will-message-payload] # The Edge Node’s MQTT Will Message’s payload MUST be a Sparkplug Google # Protobuf encoded payload. # • [tck-id-message-flow-edge-node-birth-publish-will-message-payload-bdSeq] # The Edge Node’s MQTT Will Message’s payload MUST include a metric with # the name of bdSeq, the datatype of INT64, and the value MUST be # incremented by one from the value in the previous MQTT CONNECT packet # unless the value would be greater than 255. If in the previous NBIRTH a # value of 255 was sent, the next MQTT Connect packet Will Message # payload bdSeq number value MUST have a value of 0. NDEATH_payload = "" # • [tck-id-message-flow-edge-node-birth-publish-will-message-qos] # The Edge Node’s MQTT Will Message’s MQTT QoS MUST be 1. NDEATH_qos = 1 # • [tck-id-message-flow-edge-node-birth-publish-will-message-will-retained] # The Edge Node’s MQTT Will Message’s retained flag MUST be set to false. NDEATH_retain = False # • [tck-id-principles-persistence-clean-session-311] # If the MQTT client is using MQTT v3.1.1, the Edge Node’s MQTT CONNECT # packet MUST set the Clean Session flag to true. # • [tck-id-principles-persistence-clean-session-50] # If the MQTT client is using MQTT v5.0, the Edge Node’s MQTT CONNECT # packet MUST set the Clean Start flag to true and the Session Expiry # Interval to 0. clean_session = True session_expiry_interval = 0 # • [tck-id-message-flow-edge-node-birth-publish-connect] # Any Edge Node in the MQTT infrastructure MUST establish an MQTT Session # prior to publishing NBIRTH and DBIRTH messages. # • [tck-id-message-flow-edge-node-birth-publish-will-message] # When a Sparkplug Edge Node sends its MQTT CONNECT packet, it MUST # include a Will Message. connect_packet = mosq_test.gen_connect(client_id, clean_session=clean_session, username=username, password=password, will_topic=NDEATH_topic, will_qos=NDEATH_qos, will_retain=NDEATH_retain, will_payload=NDEATH_payload, proto_ver=proto_ver, session_expiry=session_expiry_interval) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver) test_client = mosq_test.do_client_connect(connect_packet, connack_packet, port=port, connack_error=f"client connack") # • [tck-id-message-flow-edge-node-ncmd-subscribe] # The MQTT client associated with the Edge Node MUST subscribe to a topic # of the form spBv1.0/group_id/NCMD/edge_node_id where group_id is the # Sparkplug Group ID and the edge_node_id is the Sparkplug Edge Node ID # for this Edge Node. It MUST subscribe on this topic with a QoS of 1. NCMD_topic = f"{namespace}/{group_id}/NCMD/{edge_node_id}" qos = 1 subscribe_packet = mosq_test.gen_subscribe(topic=NCMD_topic, mid=1, qos=qos, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid=1, qos=qos, proto_ver=proto_ver) mosq_test.do_send_receive(test_client, subscribe_packet, suback_packet) # ====================================================================== # Test client publishes its NBIRTH certificate # ====================================================================== # • [tck-id-message-flow-edge-node-birth-publish-nbirth-topic] # The Edge Node’s NBIRTH MQTT topic MUST be of the form # spBv1.0/group_id/NBIRTH/edge_node_id where group_id is the Sparkplug # Group ID and the edge_node_id is the Sparkplug Edge Node ID for this # Edge Node NBIRTH_topic = f"{namespace}/{group_id}/NBIRTH/{edge_node_id}" # • [tck-id-message-flow-edge-node-birth-publish-nbirth-payload] # The Edge Node’s NBIRTH payload MUST be a Sparkplug Google Protobuf # encoded payload. # • [tck-id-message-flow-edge-node-birth-publish-nbirth-payload-bdSeq] # The Edge Node’s NBIRTH payload MUST include a metric with the name of # bdSeq the datatype of INT64 and the value MUST be the same as the # previous MQTT CONNECT packet. # • [tck-id-message-flow-edge-node-birth-publish-nbirth-payload-seq] # The Edge Node’s NBIRTH payload MUST include a seq number that is # between 0 and 255 (inclusive). # ◦ This will become the starting sequence number which all following # messages will include a sequence number that is one more than the # previous up to 255 where it wraps back to zero. # • [tck-id-principles-birth-certificates-order] # Birth Certificates MUST be the first MQTT messages published by any # Edge Node or any Host Application. NBIRTH_payload = "FIXME" # • [tck-id-message-flow-edge-node-birth-publish-nbirth-qos] # The Edge Node’s NBIRTH MQTT QoS MUST be 0. NBIRTH_qos = 0 # • [tck-id-message-flow-edge-node-birth-publish-nbirth-retained] # The Edge Node’s NBIRTH retained flag MUST be set to false. NBIRTH_retain = False publish_packet = mosq_test.gen_publish(topic=NBIRTH_topic, qos=NBIRTH_qos, payload=NBIRTH_payload, retain=NBIRTH_retain, proto_ver=proto_ver) test_client.send(publish_packet) # ********************************************************************** # Monitor client should receive the NBIRTH certificate republished by the # broker # ********************************************************************** NBIRTH_topic_aware = f"$sparkplug/certificates/{namespace}/{group_id}/NBIRTH/{edge_node_id}" publish_packet = mosq_test.gen_publish(NBIRTH_topic_aware, mid=1, qos=0, proto_ver=proto_ver, payload=NBIRTH_payload) mosq_test.expect_packet(monitor, "error1", publish_packet) # ====================================================================== # Test client publishes its DBIRTH certificate # ====================================================================== # • [tck-id-message-flow-device-birth-publish-dbirth-match-edge-node-topic] # The Device’s DBIRTH MQTT topic group_id and edge_node_id MUST match the # group_id and edge_node_id that were sent in the prior NBIRTH message # for the Edge Node this Device is associated with. # • [tck-id-message-flow-device-birth-publish-dbirth-topic] # The Device’s DBIRTH MQTT topic MUST be of the form # spBv1.0/group_id/DBIRTH/edge_node_id/device_id where group_id is the # Sparkplug Group ID the edge_node_id is the Sparkplug Edge Node ID and # the device_id is the Sparkplug Device ID for this Device. DBIRTH_topic = f"{namespace}/{group_id}/DBIRTH/{edge_node_id}/{device_id}" # • [tck-id-message-flow-device-birth-publish-dbirth-payload] # The Device’s DBIRTH payload MUST be a Sparkplug Google Protobuf encoded # payload. # • [tck-id-message-flow-device-birth-publish-dbirth-payload-seq] # The Device’s DBIRTH payload MUST include a seq number that is between 0 # and 255 (inclusive) and be one more than was included in the prior # Sparkplug message sent from the Edge Node associated with this Device. DBIRTH_payload = "FIXME" # • [tck-id-message-flow-device-birth-publish-dbirth-qos] # The Device’s DBIRTH MQTT QoS MUST be 0. DBIRTH_qos = 0 # • [tck-id-message-flow-device-birth-publish-dbirth-retained] # The Device’s DBIRTH retained flag MUST be set to false. DBIRTH_retain = False # • [tck-id-message-flow-device-birth-publish-nbirth-wait] # The NBIRTH message MUST have been sent within the current MQTT session # prior to a DBIRTH being published. publish_packet = mosq_test.gen_publish(topic=DBIRTH_topic, qos=DBIRTH_qos, payload=DBIRTH_payload, retain=DBIRTH_retain, proto_ver=proto_ver) test_client.send(publish_packet) # ********************************************************************** # Monitor client should receive the DBIRTH certificate republished by the # broker # ********************************************************************** DBIRTH_topic_aware = f"$sparkplug/certificates/{namespace}/{group_id}/DBIRTH/{edge_node_id}/{device_id}" publish_packet = mosq_test.gen_publish(DBIRTH_topic_aware, mid=1, qos=0, proto_ver=proto_ver, payload=DBIRTH_payload) mosq_test.expect_packet(monitor, "error0", publish_packet) # ====================================================================== # The test client disconnects "unintentionally" # ====================================================================== # • [tck-id-operational-behavior-edge-node-intentional-disconnect-ndeath] # When an Edge Node disconnects intentionally, it MUST publish an NDEATH # before terminating the connection. # • [tck-id-operational-behavior-edge-node-intentional-disconnect-packet] # Immediately the NDEATH publish, a DISCONNECT packet MAY be sent to the # MQTT Server. test_client.close() # ********************************************************************** # Monitor client should receive the NDEATH certificate # ********************************************************************** publish_packet = mosq_test.gen_publish(NDEATH_topic, mid=1, qos=NDEATH_qos, proto_ver=proto_ver, payload=NDEATH_payload) mosq_test.expect_packet(monitor, "error 2", publish_packet) # ********************************************************************** # Clear the republished certificates ready for the next test # ********************************************************************** publish_packet = mosq_test.gen_publish(NBIRTH_topic_aware, qos=0, proto_ver=proto_ver, payload=None, retain=True) monitor.send(publish_packet) publish_packet = mosq_test.gen_publish(DBIRTH_topic_aware, qos=0, proto_ver=proto_ver, payload=None, retain=True) monitor.send(publish_packet) monitor.close() def do_tests(): rc = 1 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: proc(port, 4) proc(port, 5) rc = 0 except Exception as e: print(e) finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) if __name__ == '__main__': do_tests() ================================================ FILE: test/broker/20-sparkplug-compliance.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import uuid def tck_id_conformance_mqtt_qos0(port, proto_ver): # A Sparkplug conformant MQTT Server MUST support publish and subscribe on # QoS 0 topic = str(uuid.uuid4()) payload = str(uuid.uuid4()) client = mosq_test.sub_helper(port, topic, qos=0, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish(topic, qos=0, payload=payload, retain=False, proto_ver=proto_ver) mosq_test.do_send_receive(client, publish_packet, publish_packet, error_string="tck-id-conformance-mqtt-qos0") client.close() def tck_id_conformance_mqtt_qos1(port, proto_ver): # A Sparkplug conformant MQTT Server MUST support publish and subscribe on # QoS 1 topic = str(uuid.uuid4()) payload = str(uuid.uuid4()) client = mosq_test.sub_helper(port, topic, qos=1, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish(topic, qos=1, mid=1, payload=payload, retain=False, proto_ver=proto_ver) puback_packet = mosq_test.gen_puback(mid=1, proto_ver=proto_ver) client.send(publish_packet) mosq_test.receive_unordered(client, publish_packet, puback_packet, "tck-id-conformance-mqtt-qos1") client.close() def tck_id_conformance_mqtt_will_messages(port, proto_ver): # A Sparkplug conformant MQTT Server MUST support all aspects of Will # Messages including use of the retain flag and QoS 1 pass def tck_id_conformance_mqtt_retained(port, proto_ver): # A Sparkplug conformant MQTT Server MUST support all aspects of the retain # flag topic = str(uuid.uuid4()) payload = str(uuid.uuid4()) client = mosq_test.pub_helper(port, proto_ver=proto_ver) publish_packet = mosq_test.gen_publish(topic, qos=0, payload=payload, retain=True, proto_ver=proto_ver) subscribe_packet = mosq_test.gen_subscribe(mid=1, topic=topic, qos=0, proto_ver=proto_ver) suback_packet = mosq_test.gen_suback(mid=1, qos=0, proto_ver=proto_ver) client.send(publish_packet) client.send(subscribe_packet) mosq_test.receive_unordered(client, publish_packet, suback_packet, "tck-id-conformance-mqtt-retained") client.close() def do_tests(): rc = 1 port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: tck_id_conformance_mqtt_qos0(port, 4) tck_id_conformance_mqtt_qos0(port, 5) tck_id_conformance_mqtt_qos1(port, 4) tck_id_conformance_mqtt_qos1(port, 5) tck_id_conformance_mqtt_will_messages(port, 4) tck_id_conformance_mqtt_will_messages(port, 5) tck_id_conformance_mqtt_retained(port, 4) tck_id_conformance_mqtt_retained(port, 5) rc = 0 except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) if __name__ == '__main__': do_tests() ================================================ FILE: test/broker/21-proxy-bad-version.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import json import shutil import socket def write_config(filename, port, ver): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write(f"enable_proxy_protocol {ver}\n") def do_test(ver, expect_fail_log): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') rc = 1 write_config(conf_file, port, ver) try: broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port, expect_fail=True, expect_fail_log=expect_fail_log) rc = 0 except subprocess.TimeoutExpired: pass os.remove(conf_file) if rc != 0: raise ValueError(rc) do_test(0, "Error: enable_proxy_protocol must be 1 or 2.") do_test(3, "Error: enable_proxy_protocol must be 1 or 2.") ================================================ FILE: test/broker/21-proxy-v1-bad.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 1\n") def do_test(data, expect_log): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) rc = 1 try: sock = do_proxy_v1_connect(port, data) try: d = sock.recv(1) if len(d) == 0: rc = 0 except ConnectionResetError: rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) print(data) exit(1) # Basic do_test(b"PROXY TCP3 192.0.2.5 127.0.0.1 6275 1234\r\n", "Connection rejected, corrupt PROXY header.") # Bad transport do_test(b"PROXY TCP4 192.0.2.5 127.0.0.1 6275 1234 \r\n", "Connection rejected, corrupt PROXY header.") # Too long # TCP4 do_test(b"PROXY TCP4 192.0.2.5 127.0.0.1 6275\r\n", "Connection rejected, corrupt PROXY header.") # Missing dport do_test(b"PROXY TCP4 192.0.2.5 127.0.0.1\r\n", "Connection rejected, corrupt PROXY header.") # Missing sport do_test(b"PROXY TCP4 192.0.2.5\r\n", "Connection rejected, corrupt PROXY header.") # Missing daddr do_test(b"PROXY TCP4 \r\n", "Connection rejected, corrupt PROXY header.") # Missing saddr do_test(b"PROXY TCP4 192.0.2.5 127.0.0.1 6275 0\r\n", "Connection rejected, corrupt PROXY header.") # dport == 0 do_test(b"PROXY TCP4 192.0.2.5 127.0.0.1 6275 65536\r\n", "Connection rejected, corrupt PROXY header.") # dport == 65536 do_test(b"PROXY TCP4 192.0.2.5 127.0.0.1 0 1234\r\n", "Connection rejected, corrupt PROXY header.") # sport == 0 do_test(b"PROXY TCP4 192.0.2.5 127.0.0.1 65536 1234\r\n", "Connection rejected, corrupt PROXY header.") # sport == 65536 do_test(b"PROXY TCP4 192.0.2.5 127.0.0.256 6275 1234\r\n", "Connection rejected, corrupt PROXY header.") # daddr invalid do_test(b"PROXY TCP4 192.0.2.256 127.0.0.1 6275 1234\r\n", "Connection rejected, corrupt PROXY header.") # saddr invalid # TCP6 do_test(b"PROXY TCP6 192.0.2.5 127.0.0.1 6275\r\n", "Connection rejected, corrupt PROXY header.") # Missing dport do_test(b"PROXY TCP6 192.0.2.5 127.0.0.1\r\n", "Connection rejected, corrupt PROXY header.") # Missing sport do_test(b"PROXY TCP6 192.0.2.5\r\n", "Connection rejected, corrupt PROXY header.") # Missing daddr do_test(b"PROXY TCP6 \r\n", "Connection rejected, corrupt PROXY header.") # Missing saddr do_test(b"PROXY TCP6 192.0.2.5 127.0.0.1 6275 0\r\n", "Connection rejected, corrupt PROXY header.") # dport == 0 do_test(b"PROXY TCP6 192.0.2.5 127.0.0.1 6275 65536\r\n", "Connection rejected, corrupt PROXY header.") # dport == 65536 do_test(b"PROXY TCP6 192.0.2.5 127.0.0.1 0 1234\r\n", "Connection rejected, corrupt PROXY header.") # sport == 0 do_test(b"PROXY TCP6 192.0.2.5 127.0.0.1 65536 1234\r\n", "Connection rejected, corrupt PROXY header.") # sport == 65536 do_test(b"PROXY TCP6 192.0.2.5 127.0.0.256 6275 1234\r\n", "Connection rejected, corrupt PROXY header.") # daddr invalid do_test(b"PROXY TCP6 192.0.2.256 127.0.0.1 6275 1234\r\n", "Connection rejected, corrupt PROXY header.") # saddr invalid ================================================ FILE: test/broker/21-proxy-v1-success.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 1\n") def do_test(data, expect_log): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) rc = 1 try: sock = do_proxy_v1_connect(port, data) mosq_test.do_send_receive(sock, connect_packet, connack_packet, "connack") mosq_test.do_ping(sock) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) exit(1) do_test(b"PROXY TCP4 192.0.2.5 127.0.0.1 6275 1234\r\n", "New client connected from 192.0.2.5:6275") do_test(b"PROXY TCP6 2001:db8:506:708:900::1 ::1 6275 1234\r\n", "New client connected from 2001:db8:506:708:900::1:6275 as proxy-test (p5, c0, k42)") do_test(b"PROXY UNKNOWN \r\n", "New client connected from 127.0.0.1:") ================================================ FILE: test/broker/21-proxy-v2-bad-config.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port, extra_options): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") f.write(extra_options) def do_test(extra_options, expect_fail_log): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') rc = 1 write_config(conf_file, port, extra_options) try: broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port, expect_fail=True, expect_fail_log=expect_fail_log) rc = 0 except subprocess.TimeoutExpired: pass os.remove(conf_file) if rc != 0: raise ValueError(rc) do_test("use_subject_as_username true\n", "Error: use_subject_as_username cannot be used with `enable_proxy_protocol 2`.") do_test(f"certfile {ssl_dir}/server.crt\nkeyfile {ssl_dir}/server.key\n", "Error: certfile and keyfile cannot be used with `enable_proxy_protocol 2`.") ================================================ FILE: test/broker/21-proxy-v2-bad-header.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) def do_test(headers): 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) rc = len(headers) try: for header in headers: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5) sock.connect(("localhost", port)) sock.send(header) try: data = sock.recv(10) if len(data) == 0: rc -= 1 except ConnectionResetError: rc -= 1 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0: print(stde.decode('utf-8')) rc = 1 raise ValueError(rc) magic = b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a" proxy_headers = [] # Bad magic proxy_headers.append(b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0b" + b"\x21\x01\x00\x0c" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00" + b"\x00\x00") # Bad version proxy_headers.append(magic + b"\x31\x01\x00\x0c" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00" + b"\x00\x00") # Bad command proxy_headers.append(magic + b"\x23\x01\x00\x0c" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00" + b"\x00\x00") # Bad family (proxy command with unspecified family) proxy_headers.append(magic + b"\x21\x00\x00\x0c" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00" + b"\x00\x00") # Short length IPv4 proxy_headers.append(magic + b"\x21\x11\x00\x0b" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00" + b"\x00\x00") # IPv4 with header zero length proxy_headers.append(magic + b"\x21\x11\x00\x00" + b"\xc0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00") # Short length IPv6 proxy_headers.append(magic + b"\x21\x21\x00\x0b" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00" + b"\x00\x00") # IPv6 with header zero length proxy_headers.append(magic + b"\x21\x21\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00" + b"\x00\x00") # Unix sock with header zero length proxy_headers.append(magic + b"\x21\x31\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00" + b"\x00\x00") # Short SSL TLV proxy_headers.append(magic + b"\x21\x11\x00\x10" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00" + b"\x00\x00" + b"\x20" + b"\x00\x01" + b"\x21\x00") # Too long SSL TLV for overall length proxy_headers.append(magic + b"\x21\x11\x00\x10" + b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" \ + b"\x20" \ + b"\x00\x19" \ + b"\x05" \ + b"\x00\x00\x00\x00" \ + b"\x21" \ + b"\x00\x07" \ + b"\x54\x4C\x53\x76\x31\x2E\x33" \ + b"\x23" \ + b"\x00\x08" \ + b"\x70\x71\x72\x73\x74\x75\x76") # Too long SSL sub TLV for overall length proxy_headers.append(magic + b"\x21\x11\x00\x28" + b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" \ + b"\x20" \ + b"\x00\x19" \ + b"\x05" \ + b"\x00\x00\x00\x00" \ + b"\x21" \ + b"\x00\x07" \ + b"\x54\x4C\x53\x76\x31\x2E\x33" \ + b"\x23" \ + b"\x00\x0A" \ + b"\x70\x71\x72\x73\x74\x75\x76") do_test(proxy_headers) ================================================ FILE: test/broker/21-proxy-v2-ipv4.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) rc = 1 expect_log = "New client connected from 192.0.2.5:6275" try: data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, PROXY_FAM_IPV4 | PROXY_PROTO_TCP, data) mosq_test.do_send_receive(sock, connect_packet, connack_packet, "connack") mosq_test.do_ping(sock) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) rc = 1 exit(rc) ================================================ FILE: test/broker/21-proxy-v2-ipv6.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) rc = 1 expected_log = "New client connected from 2001:db8:506:708:900::1:6275 as proxy-test (p5, c0, k42)" try: data = b"\x20\x01\x0d\xb8\x05\x06\x07\x08\x09\x00\x00\x00\x00\x00\x00\x01" \ + b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" \ + b"\x18\x83" + b"\x00\x00" sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, PROXY_FAM_IPV6 | PROXY_PROTO_TCP, data) mosq_test.do_send_receive(sock, connect_packet, connack_packet, "connack") mosq_test.do_ping(sock) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expected_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) rc = 1 exit(rc) ================================================ FILE: test/broker/21-proxy-v2-local.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") def do_test(header): 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) rc = 1 try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5) sock.connect(("localhost", port)) sock.send(header) try: data = sock.recv(10) if len(data) == 0: rc = 0 except ConnectionResetError: rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0: print(stde.decode('utf-8')) rc = 1 raise ValueError(rc) proxy_header = b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a" + b"\x20\x00\x00\x00" do_test(proxy_header) ================================================ FILE: test/broker/21-proxy-v2-long-tlv.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") def do_test(fam): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) rc = 1 expect_log = "Bad socket read/write on client : Invalid input" try: data = b"a"*501 sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, fam | PROXY_PROTO_TCP, data) try: data = sock.recv(10) if len(data) == 0: rc = 0 except ConnectionResetError: rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) rc = 1 do_test(PROXY_FAM_IPV4) do_test(PROXY_FAM_IPV6) do_test(PROXY_FAM_UNIX) ================================================ FILE: test/broker/21-proxy-v2-lost-connection.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) def do_test(header): 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) rc = 1 try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5) sock.connect(("localhost", port)) sock.send(header) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0: print(stde.decode('utf-8')) rc = 1 raise ValueError(rc) # This test essentially should never fail, but it covers a code path that is # not covered by the other tests and should be used with valgrind/sanitisers # Not enough data, IPv4 proxy_header = b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a" + b"\x21\x11\x00\x0f" + b"\x00\x00\x00\x00" + b"\x00\x00\x00\x00" + b"\x00\x00" + b"\x00\x00" do_test(proxy_header) ================================================ FILE: test/broker/21-proxy-v2-ssl-cipher.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") def do_test(data): expect_log = "Connection from 192.0.2.5:6275 negotiated TLSv1.3 cipher pqrstuv" 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) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5, username="none", password="pw") connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) rc = 1 try: sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, PROXY_FAM_IPV4 | PROXY_PROTO_TCP, data) mosq_test.do_send_receive(sock, connect_packet, connack_packet, "connack") mosq_test.do_ping(sock) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) rc = 1 raise ValueError(rc) data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" \ + b"\x20" \ + b"\x00\x19" \ + b"\x05" \ + b"\x00\x00\x00\x00" \ + b"\x21" \ + b"\x00\x07" \ + b"\x54\x4C\x53\x76\x31\x2E\x33" \ + b"\x23" \ + b"\x00\x07" \ + b"\x70\x71\x72\x73\x74\x75\x76" do_test(data) ================================================ FILE: test/broker/21-proxy-v2-ssl-common-name-failure.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") f.write("require_certificate true\n") f.write("use_identity_as_username true\n") def do_test(data, expect_log): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=134, proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) rc = 1 try: sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, PROXY_FAM_IPV4 | PROXY_PROTO_TCP, data) sock.send(connect_packet) try: mosq_test.expect_packet(sock, "connack", connack_packet) data = sock.recv(10) if len(data) == 0: rc = 0 except (BrokenPipeError, ConnectionResetError): rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) print(expect_log) rc = 1 raise ValueError(rc) # No SSL at all data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" expect_log = "rejected, client did not provide a certificate." do_test(data, expect_log) # SSL but no certificate at all - this should fail # IP, IP, port, port, SSL-tlv, length, client, verify, SSL-version sub-tlv, length, value data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" \ + b"\x20" \ + b"\x00\x0F" \ + b"\x01" \ + b"\x00\x00\x00\x01" \ + b"\x21" \ + b"\x00\x07" \ + b"\x54\x4C\x53\x76\x31\x2E\x33" expect_log = "rejected, client did not provide a certificate." do_test(data, expect_log) # SSL, verify 0 but no certificate presented this session # IP, IP, port, port, SSL-tlv, length, client, verify, SSL-version sub-tlv, length, value data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" \ + b"\x20" \ + b"\x00\x0F" \ + b"\x01" \ + b"\x00\x00\x00\x00" \ + b"\x21" \ + b"\x00\x07" \ + b"\x54\x4C\x53\x76\x31\x2E\x33" expect_log = "rejected, client did not provide a certificate." do_test(data, expect_log) data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" \ + b"\x20" \ + b"\x00\x0F" \ + b"\x05" \ + b"\x00\x00\x00\x00" \ + b"\x21" \ + b"\x00\x07" \ + b"\x54\x4C\x53\x76\x31\x2E\x33" expect_log = "Client proxy-test [192.0.2.5:6275] disconnected: not authorised." do_test(data, expect_log) ================================================ FILE: test/broker/21-proxy-v2-ssl-common-name-success.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") f.write("require_certificate true\n") f.write("use_identity_as_username true\n") def do_test(data): expect_log = "New client connected from 192.0.2.5:6275 as proxy-test (p5, c0, k42, u'ppppppp')." 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) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5, username="none", password="pw") connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) rc = 1 try: sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, PROXY_FAM_IPV4 | PROXY_PROTO_TCP, data) mosq_test.do_send_receive(sock, connect_packet, connack_packet, "connack") mosq_test.do_ping(sock) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) rc = 1 raise ValueError(rc) data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" \ + b"\x20" \ + b"\x00\x19" \ + b"\x05" \ + b"\x00\x00\x00\x00" \ + b"\x21" \ + b"\x00\x07" \ + b"\x54\x4C\x53\x76\x31\x2E\x33" \ + b"\x22" \ + b"\x00\x07" \ + b"\x70\x70\x70\x70\x70\x70\x70" do_test(data) ================================================ FILE: test/broker/21-proxy-v2-ssl-require-cert-failure.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") f.write("require_certificate true\n") def do_test(data): 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) rc = 1 expect_log = "Connection from 192.0.2.5:6275 rejected, client did not provide a certificate." try: sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, PROXY_FAM_IPV4 | PROXY_PROTO_TCP, data) try: data = sock.recv(10) if len(data) == 0: rc = 0 except ConnectionResetError: rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) rc = 1 raise ValueError(rc) # No SSL at all data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" do_test(data) # SSL but no certificate at all - this should fail # IP, IP, port, port, SSL-tlv, length, client, verify, SSL-version sub-tlv, length, value data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" \ + b"\x20" \ + b"\x00\x0F" \ + b"\x01" \ + b"\x00\x00\x00\x01" \ + b"\x21" \ + b"\x00\x07" \ + b"\x54\x4C\x53\x76\x31\x2E\x33" do_test(data) # SSL, verify 0 but no certificate presented this session # IP, IP, port, port, SSL-tlv, length, client, verify, SSL-version sub-tlv, length, value data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" \ + b"\x20" \ + b"\x00\x0F" \ + b"\x01" \ + b"\x00\x00\x00\x00" \ + b"\x21" \ + b"\x00\x07" \ + b"\x54\x4C\x53\x76\x31\x2E\x33" do_test(data) ================================================ FILE: test/broker/21-proxy-v2-ssl-require-cert-success.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") f.write("require_certificate true\n") def do_test(data): 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) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) rc = 1 expect_log = "New client connected from 192.0.2.5:6275 as proxy-test (p5, c0, k42)." try: sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, PROXY_FAM_IPV4 | PROXY_PROTO_TCP, data) mosq_test.do_send_receive(sock, connect_packet, connack_packet, "connack") mosq_test.do_ping(sock) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) rc = 1 raise ValueError(rc) data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" \ + b"\x02" \ + b"\x00\x05" \ + b"\x70\x71\x72\x73\x74" \ + b"\x20" \ + b"\x00\x0F" \ + b"\x05" \ + b"\x00\x00\x00\x00" \ + b"\x21" \ + b"\x00\x07" \ + b"\x54\x4C\x53\x76\x31\x2E\x33" do_test(data) ================================================ FILE: test/broker/21-proxy-v2-ssl-require-tls-failure.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") f.write("proxy_protocol_v2_require_tls true\n") def do_test(data): 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) rc = 1 expect_log = "Connection from 192.0.2.5:6275 rejected, client did not connect using TLS." try: sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, PROXY_FAM_IPV4 | PROXY_PROTO_TCP, data) try: data = sock.recv(10) if len(data) == 0: rc = 0 except ConnectionResetError: rc = 0 sock.close() except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) rc = 1 raise ValueError(rc) # No SSL at all data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" do_test(data) ================================================ FILE: test/broker/21-proxy-v2-ssl-require-tls-success.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") f.write("proxy_protocol_v2_require_tls true\n") def do_test(data): 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) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) rc = 1 expect_log = "New client connected from 192.0.2.5:6275 as proxy-test (p5, c0, k42)." try: sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, PROXY_FAM_IPV4 | PROXY_PROTO_TCP, data) mosq_test.do_send_receive(sock, connect_packet, connack_packet, "connack") mosq_test.do_ping(sock) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) rc = 1 raise ValueError(rc) data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" \ + b"\x02" \ + b"\x00\x05" \ + b"\x70\x71\x72\x73\x74" \ + b"\x20" \ + b"\x00\x0F" \ + b"\x05" \ + b"\x00\x00\x00\x00" \ + b"\x21" \ + b"\x00\x07" \ + b"\x54\x4C\x53\x76\x31\x2E\x33" do_test(data) ================================================ FILE: test/broker/21-proxy-v2-unix.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) rc = 1 expected_log = "New client connected from /path:0 as proxy-test (p5, c0, k42)." try: data = b"/path" sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, PROXY_FAM_UNIX | PROXY_PROTO_TCP, data) mosq_test.do_send_receive(sock, connect_packet, connack_packet, "connack") mosq_test.do_ping(sock) sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expected_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) rc = 1 exit(rc) ================================================ FILE: test/broker/21-proxy-v2-websockets.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * from proxy_helper import * import json import shutil import socket def write_config(filename, port): with open(filename, 'w') as f: f.write("log_type all\n") f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write("enable_proxy_protocol 2\n") f.write("protocol websockets\n") port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, port) connect_packet = mosq_test.gen_connect("proxy-test", keepalive=42, clean_session=False, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=port) rc = 1 expect_log = "New client connected from 192.0.2.5:6275" try: data = b"\xC0\x00\x02\x05" + b"\x00\x00\x00\x00" + b"\x18\x83" + b"\x00\x00" sock = do_proxy_v2_connect(port, PROXY_VER, PROXY_CMD_PROXY, PROXY_FAM_IPV4 | PROXY_PROTO_TCP, data) websocket_req_good = b"GET /mqtt HTTP/1.1\r\n" \ + b"Host: localhost\r\n" \ + b"Upgrade: websocket\r\n" \ + b"Connection: Upgrade\r\n" \ + B"Sec-WebSocket-Key: 1JaITHdgDZVd/4OE2AzTTA==\r\n" \ + b"Sec-WebSocket-Protocol: mqtt\r\n" \ + b"Sec-WebSocket-Version: 13\r\n" \ + b"Origin: example.org\r\n" \ + b"\r\n" websocket_resp_good = b"HTTP/1.1 101 Switching Protocols\r\n" \ + b"Upgrade: WebSocket\r\n" \ + b"Connection: Upgrade\r\n" \ + b"Sec-WebSocket-Accept: Ako91O0lxiq8gN0+b9YCijMx8lk=\r\n" \ + b"Sec-WebSocket-Protocol: mqtt\r\n" \ + b"\r\n" connect_frame = bytearray() length = len(connect_packet) mask_key = bytearray(os.urandom(4)) connect_frame.append(0x82) # FIN + opcode connect_frame.append(0x80 | length) connect_frame.extend(mask_key) for i in range(len(connect_packet)): connect_frame.append(connect_packet[i] ^ mask_key[i % 4]) connack_frame = bytearray() length = len(connack_packet) connack_frame.append(0x82) # FIN + opcode connack_frame.append(length) for i in range(len(connack_packet)): connack_frame.append(connack_packet[i]) connack_frame = bytes(connack_frame) mosq_test.do_send_receive(sock, websocket_req_good, websocket_resp_good, "websocket handshake") mosq_test.do_send_receive(sock, connect_frame, connack_frame, "connack") sock.close() rc = 0 except mosq_test.TestError: pass finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0 or expect_log not in stde.decode('utf-8'): print(stde.decode('utf-8')) rc = 1 exit(rc) ================================================ FILE: test/broker/22-http-api-acl.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import http.client import json import re def write_config(filename, mqtt_port, http_port): with open(filename, 'w') as f: f.write(f"allow_anonymous true\n") f.write(f"listener {mqtt_port}\n") f.write(f"listener {http_port}\n") f.write("protocol http_api\n") f.write(f"plugin {mosq_test.get_build_root()}/plugins/acl-file/mosquitto_acl_file.so\n") f.write(f"plugin_opt_acl_file {http_port}.acl\n") mqtt_port, http_port = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, mqtt_port, http_port) with open(f"{http_port}.acl", "wt") as f: f.write("topic read /api/v1/version") broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=mqtt_port) rc = 1 try: http_conn = http.client.HTTPConnection(f"localhost:{http_port}") # systree API http_conn.request("GET", "/api/v1/systree") response = http_conn.getresponse() if response.status != 401: raise ValueError(f"/api/v1/systree {response.status}") payload = response.read().decode('utf-8') if payload != "Not authorised\n": raise ValueError(f"Error: {payload}") # Version API http_conn.request("GET", "/api/v1/version") response = http_conn.getresponse() if response.status != 200: raise ValueError(f"Error: /api/v1/version {response.status}") payload = response.read().decode('utf-8') if not re.match(r'^\d+\.\d+\.\d+.*$', payload): raise ValueError(f"Error: /api/v1/version\n{payload}") rc = 0 except mosq_test.TestError: pass except Exception as e: print(e) finally: os.remove(conf_file) os.remove(f"{http_port}.acl") broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0: print(stde.decode('utf-8')) rc = 1 exit(rc) ================================================ FILE: test/broker/22-http-api-api.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import http.client import json import re def write_config(filename, mqtt_port, ws_port, http_port): with open(filename, 'w') as f: f.write(f"allow_anonymous true\n") f.write(f"listener {mqtt_port}\n") f.write(f"listener 0 {mqtt_port}.sock\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") f.write(f"listener {ws_port}\n") f.write("protocol websockets\n") f.write(f"listener {http_port}\n") f.write("protocol http_api\n") mqtt_port, ws_port, http_port = mosq_test.get_port(3) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, mqtt_port, ws_port, http_port) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=mqtt_port) rc = 1 try: http_conn = http.client.HTTPConnection(f"localhost:{http_port}") # Bad request type http_conn.request("POST", "/api/badrequest") response = http_conn.getresponse() if response.status != 405: raise ValueError(f"/api/badrequest {response.status}") # Missing API http_conn.request("GET", "/api/missing") response = http_conn.getresponse() if response.status != 404: raise ValueError(f"/api/missing {response.status}") # Listeners API http_conn.request("GET", "/api/v1/listeners") response = http_conn.getresponse() if response.status != 200: raise ValueError(f"/api/v1/listeners {response.status}") payload = json.loads(response.read().decode('utf-8')) expected_payload = { "listeners": [{ "port": mqtt_port, "protocol": "mqtt", "tls": False, "mtls": False, "allow_anonymous": True }, { "path": f"{mqtt_port}.sock", "protocol": "mqtt", "tls": True, "mtls": False, "allow_anonymous": True }, { "port": ws_port, "protocol": "websockets", "tls": False, "mtls": False, "allow_anonymous": True }, { "port": http_port, "protocol": "httpapi", "tls": False, "mtls": False, "allow_anonymous": True }] } if payload != expected_payload: raise ValueError(f"/api/v1/listeners payload\n{payload}\n{expected_payload}") # systree API http_conn.request("GET", "/api/v1/systree") response = http_conn.getresponse() if response.status != 200: raise ValueError(f"/api/v1/systree {response.status}") payload = json.loads(response.read().decode('utf-8')) for topic in [ '$SYS/broker/clients/connected', '$SYS/broker/clients/disconnected', '$SYS/broker/clients/maximum', '$SYS/broker/connections/socket/count', '$SYS/broker/heap/current', '$SYS/broker/heap/maximum', '$SYS/broker/messages/stored', '$SYS/broker/retained messages/count', '$SYS/broker/store/messages/bytes', '$SYS/broker/uptime']: # Protect against values being slightly different by # setting to a known value # This read will fail if the key doesn't already exist if payload[topic] >= 0: payload[topic] = -1 expected_payload = { '$SYS/broker/clients/total': 0, '$SYS/broker/clients/maximum': -1, '$SYS/broker/clients/disconnected': -1, '$SYS/broker/clients/connected': -1, '$SYS/broker/clients/expired': 0, '$SYS/broker/messages/stored': -1, '$SYS/broker/store/messages/bytes': -1, '$SYS/broker/subscriptions/count': 0, '$SYS/broker/shared_subscriptions/count': 0, '$SYS/broker/retained messages/count': -1, '$SYS/broker/heap/current': -1, '$SYS/broker/heap/maximum': -1, '$SYS/broker/messages/received': 0, '$SYS/broker/messages/sent': 0, '$SYS/broker/bytes/received': 0, '$SYS/broker/bytes/sent': 0, '$SYS/broker/publish/bytes/received': 0, '$SYS/broker/publish/bytes/sent': 0, '$SYS/broker/packet/out/count': 0, '$SYS/broker/packet/out/bytes': 0, '$SYS/broker/connections/socket/count': -1, '$SYS/broker/publish/messages/dropped': 0, '$SYS/broker/publish/messages/received': 0, '$SYS/broker/publish/messages/sent': 0, '$SYS/broker/uptime': -1 } if payload != expected_payload: raise ValueError(f"/api/v1/systree payload\n{payload}\n{expected_payload}") # Version API http_conn.request("GET", "/api/v1/version") response = http_conn.getresponse() if response.status != 200: raise ValueError(f"Error: /api/v1/version {response.status}") payload = response.read().decode('utf-8') if not re.match(r'^\d+\.\d+\.\d+.*$', payload): raise ValueError(f"Error: /api/v1/version\n{payload}") rc = 0 except mosq_test.TestError: pass except Exception as e: print(e) finally: os.remove(conf_file) os.remove(f"{mqtt_port}.sock") broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0: print(stde.decode('utf-8')) rc = 1 exit(rc) ================================================ FILE: test/broker/22-http-api-auth.pwfile ================================================ user:$6$Ut1cUS9PG8+gC3vn$tOjCfSJJDe1Alu9HktxxyyzwN4+6mAMSWGRAF9gmMN8pzcGTPVEYYMAZpCEp96Oz2ZRRz5YKM6lPMf1tUbb6zA== ================================================ FILE: test/broker/22-http-api-auth.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import base64 import http.client import json import re def write_config(filename, mqtt_port, http_port): with open(filename, 'w') as f: f.write(f"listener {mqtt_port}\n") f.write(f"listener {http_port}\n") f.write("protocol http_api\n") f.write(f"plugin {mosq_test.get_build_root()}/plugins/password-file/mosquitto_password_file.so\n") f.write("plugin_opt_password_file %s/%s\n" % (Path(__file__).resolve().parent, filename.replace('.conf', '.pwfile'))) mqtt_port, http_port = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, mqtt_port, http_port) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=mqtt_port) rc = 1 try: http_conn = http.client.HTTPConnection(f"localhost:{http_port}") # No auth http_conn.request("GET", "/api/v1/version") response = http_conn.getresponse() if response.status != 401: raise ValueError(f"Error: /api/v1/version {response.status}") payload = response.read().decode('utf-8') if payload != "Not authorised\n": raise ValueError(f"Error: {payload}") # Bad auth credentials = "user:invalid" encoded_credentials = base64.b64encode(credentials.encode()).decode() headers = { "Authorization": f"Basic {encoded_credentials}" } http_conn.request("GET", "/api/v1/version", headers=headers) response = http_conn.getresponse() if response.status != 401: raise ValueError(f"Error: /api/v1/version {response.status}") payload = response.read().decode('utf-8') if payload != "Not authorised\n": raise ValueError(f"Error: {payload}") # Good auth credentials = "user:password" encoded_credentials = base64.b64encode(credentials.encode()).decode() headers = { "Authorization": f"Basic {encoded_credentials}" } http_conn.request("GET", "/api/v1/version", headers=headers) response = http_conn.getresponse() if response.status != 200: raise ValueError(f"Error: /api/v1/version {response.status}") rc = 0 except mosq_test.TestError: pass except Exception as e: print(e) finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0: print(stde.decode('utf-8')) rc = 1 exit(rc) ================================================ FILE: test/broker/22-http-api-file.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import http.client import json def write_config(filename, mqtt_port, http_port): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write(f"listener {mqtt_port}\n") f.write(f"listener {http_port} 127.0.0.1\n") f.write("protocol http_api\n") f.write(f"http_dir ./\n") def write_index(): with open("index.html", 'w') as f: f.write("") mqtt_port, http_port = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, mqtt_port, http_port) write_index() broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=mqtt_port) rc = 1 try: http_conn = http.client.HTTPConnection(f"localhost:{http_port}") # Bad request http_conn.request("POST", "/post") response = http_conn.getresponse() if response.status != 405: raise ValueError(f"Error: /post {response.status}") # Bad request http_conn.request("PUT", "/put") response = http_conn.getresponse() if response.status != 405: raise ValueError(f"Error: /put {response.status}") # Missing file http_conn.request("GET", "/missing") response = http_conn.getresponse() if response.status != 404: raise ValueError(f"Error: /api/missing {response.status}") # File not in dir http_conn.request("GET", "../../../../../../../../etc/passwd") response = http_conn.getresponse() if response.status != 404: raise ValueError(f"Error: ../../../../../../../../etc/passwd {response.status}") # Present file http_conn.request("GET", "/index.html") response = http_conn.getresponse() if response.status != 200: raise ValueError(f"Error: /index.html {response.status}") # Root http_conn.request("GET", "/") response = http_conn.getresponse() if response.status != 200: raise ValueError(f"Error: / {response.status}") payload = response.read().decode('utf-8') if payload != "": raise ValueError(f"Error: / {payload}") rc = 0 except mosq_test.TestError: pass except Exception as e: print(e) finally: os.remove(conf_file) os.remove("index.html") broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0: print(stde.decode('utf-8')) rc = 1 exit(rc) ================================================ FILE: test/broker/22-http-api-tls.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import http.client import json import ssl def write_config(filename, mqtt_port, http_port): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write(f"listener {mqtt_port}\n") f.write(f"listener 0 {mqtt_port}.sock\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") f.write(f"listener {http_port}\n") f.write("protocol http_api\n") f.write(f"certfile {ssl_dir}/server.crt\n") f.write(f"keyfile {ssl_dir}/server.key\n") mqtt_port, http_port = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config(conf_file, mqtt_port, http_port) broker = mosq_test.start_broker(filename=os.path.basename(__file__), use_conf=True, port=mqtt_port) rc = 1 try: context = ssl.create_default_context() context.minimum_version = ssl.TLSVersion.TLSv1_2 context.load_verify_locations(cafile=f"{ssl_dir}/all-ca.crt") http_conn = http.client.HTTPSConnection(f"localhost:{http_port}", context=context) # Bad request type http_conn.request("POST", "/api/badrequest") response = http_conn.getresponse() if response.status != 405: raise ValueError(f"Error: /api/badrequest {response.status}") # Missing API http_conn.request("GET", "/api/missing") response = http_conn.getresponse() if response.status != 404: raise ValueError(f"Error: /api/missing {response.status}") # Listeners API http_conn.request("GET", "/api/v1/listeners") response = http_conn.getresponse() if response.status != 200: raise ValueError(f"Error: /api/v1/listeners {response.status}") payload = json.loads(response.read().decode('utf-8')) expected_payload = { "listeners": [{ "port": mqtt_port, "protocol": "mqtt", "tls": False, "mtls": False, "allow_anonymous": True }, { "path": f"{mqtt_port}.sock", "protocol": "mqtt", "tls": True, "mtls": False, "allow_anonymous": True }, { "port": http_port, "protocol": "httpapi", "tls": True, "mtls": False, "allow_anonymous": True }] } if payload != expected_payload: raise ValueError(f"Error: /api/v1/listeners payload {payload}") # systree API http_conn.request("GET", "/api/v1/systree") response = http_conn.getresponse() if response.status != 200: raise ValueError(f"Error: /api/v1/systree {response.status}") payload = json.loads(response.read().decode('utf-8')) for topic in [ '$SYS/broker/clients/maximum', '$SYS/broker/connections/socket/count', '$SYS/broker/heap/current', '$SYS/broker/heap/maximum', '$SYS/broker/messages/received', '$SYS/broker/bytes/received', '$SYS/broker/messages/stored', '$SYS/broker/retained messages/count', '$SYS/broker/store/messages/bytes', '$SYS/broker/uptime']: # Protect against values being slightly different by # setting to a known value # This read will fail if the key doesn't already exist if payload[topic] >= 0: payload[topic] = -1 expected_payload = { '$SYS/broker/clients/total': 0, '$SYS/broker/clients/maximum': -1, '$SYS/broker/clients/disconnected': 0, '$SYS/broker/clients/connected': 0, '$SYS/broker/clients/expired': 0, '$SYS/broker/messages/stored': -1, '$SYS/broker/store/messages/bytes': -1, '$SYS/broker/subscriptions/count': 0, '$SYS/broker/shared_subscriptions/count': 0, '$SYS/broker/retained messages/count': -1, '$SYS/broker/heap/current': -1, '$SYS/broker/heap/maximum': -1, '$SYS/broker/messages/received': -1, '$SYS/broker/messages/sent': 0, '$SYS/broker/bytes/received': -1, '$SYS/broker/bytes/sent': 0, '$SYS/broker/publish/bytes/received': 0, '$SYS/broker/publish/bytes/sent': 0, '$SYS/broker/packet/out/count': 0, '$SYS/broker/packet/out/bytes': 0, '$SYS/broker/connections/socket/count': -1, '$SYS/broker/publish/messages/dropped': 0, '$SYS/broker/publish/messages/received': 0, '$SYS/broker/publish/messages/sent': 0, '$SYS/broker/uptime': -1 } if payload != expected_payload: raise ValueError(f"Error: /api/v1/systree payload\n{payload}\n{expected_payload}") rc = 0 except mosq_test.TestError: pass except Exception as e: print(e) finally: os.remove(conf_file) try: os.remove(f"{mqtt_port}.sock") except FileNotFoundError: pass broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc != 0: print(stde.decode('utf-8')) rc = 1 exit(rc) ================================================ FILE: test/broker/23-security-acl-file-reload.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import signal def write_config_default(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write(f"acl_file {port}.acl\n") f.write("allow_anonymous true\n") def write_config_plugin(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write(f"plugin {mosq_test.get_build_root()}/plugins/acl-file/mosquitto_acl_file.so\n") f.write(f"plugin_opt_acl_file {port}.acl\n") f.write("allow_anonymous true\n") def do_test(write_config_func): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config_func(conf_file, port) rc = 1 connect_packet = mosq_test.gen_connect("acl-change-test") connack_packet = mosq_test.gen_connack(rc=0) with open(f"{port}.acl", "wt") as f: f.write("topic readwrite a/#") 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() with open(f"{port}.acl", "wt") as f: f.write("topic readwrite a#") broker.send_signal(signal.SIGHUP) # Broker should terminate if mosq_test.wait_for_subprocess(broker) == 0 and broker.returncode == 3: rc = 0 except mosq_test.TestError: pass except Exception as err: print(err) finally: os.remove(conf_file) os.remove(f"{port}.acl") broker.terminate() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(write_config_default) do_test(write_config_plugin) ================================================ FILE: test/broker/23-security-password-file-reload.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import signal def write_config_default(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write(f"password_file {port}.password\n") f.write("allow_anonymous true\n") def write_config_plugin(filename, port): with open(filename, 'w') as f: f.write("listener %d\n" % (port)) f.write(f"plugin {mosq_test.get_build_root()}/plugins/password-file/mosquitto_password_file.so\n") f.write(f"plugin_opt_password_file {port}.password\n") f.write("allow_anonymous true\n") def do_test(write_config_func): port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') write_config_func(conf_file, port) rc = 1 connect_packet = mosq_test.gen_connect("password-change-test") connack_packet = mosq_test.gen_connack(rc=0) with open(f"{port}.password", "wt") as f: f.write("test:$7$1000$97ozvObcN5zP4MGzYUw4uRp8+mPQbThrHOX69vdHHNVwV4iZf2K2X23FS7weilZMKeV+9oLHdilybmpXcFApYg==$WlM0jUhsiQNQJe4IDt5K1rmtAdaenWGdntswJmDkp74W9pdrt/+RdIK3YaJ09o3pD1xbtokXq933bQh+CrjA4Q==\n") 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() with open(f"{port}.password", "wt") as f: f.write("test:bad\n") broker.send_signal(signal.SIGHUP) # Broker should terminate if mosq_test.wait_for_subprocess(broker) == 0 and broker.returncode == 3: rc = 0 except mosq_test.TestError: pass except Exception as err: print(err) finally: os.remove(conf_file) os.remove(f"{port}.password") broker.terminate() (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test(write_config_default) do_test(write_config_plugin) ================================================ FILE: test/broker/CMakeLists.txt ================================================ add_subdirectory(c) file(GLOB PY_TEST_FILES [0-9][0-9]-*.py) file(GLOB PY_PERSIST_TEST_FILES 15-*.py) file(GLOB PY_HTTP_API_TEST_FILES 22-*.py) list(APPEND PY_TEST_FILES "${CMAKE_CURRENT_SOURCE_DIR}/msg_sequence_test.py") set(PERSIST_LIST persist_sqlite ) set(EXCLUDE_LIST 01-connect-uname-password-success-no-tls 03-publish-qos1-queued-bytes 03-publish-qos2-max-inflight-exceeded 09-extended-auth-single2 # Not a test 06-bridge-clean-session-core 08-ssl-bridge-helper ) if(NOT MICROHTTPD_LIBRARY) foreach(PY_HTTP_API_TEST_FILE ${PY_HTTP_API_TEST_FILES}) get_filename_component(PY_HTTP_API_TEST_NAME ${PY_HTTP_API_TEST_FILE} NAME_WE) list(APPEND EXCLUDE_LIST ${PY_HTTP_API_TEST_NAME}) endforeach() endif() foreach(PY_PERSIST_TEST_FILE ${PY_PERSIST_TEST_FILES}) get_filename_component(PY_PERSIST_TEST_NAME ${PY_PERSIST_TEST_FILE} NAME_WE) list(APPEND EXCLUDE_LIST ${PY_PERSIST_TEST_NAME}) endforeach() foreach(PY_TEST_FILE ${PY_TEST_FILES}) get_filename_component(PY_TEST_NAME ${PY_TEST_FILE} NAME_WE) if(${PY_TEST_NAME} IN_LIST EXCLUDE_LIST OR ${PY_TEST_NAME} IN_LIST SQLITE_LIST) continue() endif() add_test(NAME broker-${PY_TEST_NAME} COMMAND ${PY_TEST_FILE} ) set_tests_properties(broker-${PY_TEST_NAME} PROPERTIES ENVIRONMENT "BUILD_ROOT=${CMAKE_BINARY_DIR}" ) endforeach() foreach(PERSIST_TYPE ${PERSIST_LIST}) foreach(PY_TEST_FILE ${PY_PERSIST_TEST_FILES}) get_filename_component(PY_TEST_NAME ${PY_TEST_FILE} NAME_WE) add_test(NAME broker-${PY_TEST_NAME}-${PERSIST_TYPE} COMMAND ${PY_TEST_FILE} ${PERSIST_TYPE} ) set_tests_properties(broker-${PY_TEST_NAME}-${PERSIST_TYPE} PROPERTIES ENVIRONMENT "BUILD_ROOT=${CMAKE_BINARY_DIR}" ) endforeach() endforeach() ================================================ FILE: test/broker/Makefile ================================================ R=../.. include ${R}/config.mk .PHONY: all check clean test ptest seqtest .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 msg_sequence_test 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 20 21 22 23 msg_sequence_test: ./msg_sequence_test.py 01 : ./01-bad-initial-packets.py ./01-connect-575314.py ./01-connect-accept-protocol.py ./01-connect-allow-anonymous.py ./01-connect-auto-id.py ./01-connect-disconnect-v5.py ./01-connect-global-max-clients.py ./01-connect-global-max-connections.py ./01-connect-listener-allow-anonymous.py ./01-connect-max-connections.py ./01-connect-max-keepalive.py ./01-connect-take-over.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-unix-socket.py ./01-connect-windows-line-endings.py ./01-connect-zero-length-id.py ./01-plugin-connect-uname-password-denied.py 02 : ./02-shared-nolocal.py ./02-shared-qos0-v5.py ./02-subhier-crash.py ./02-subpub-b2c-topic-alias.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-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-max-inflight-bytes.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-subpub-recover-subscriptions.py ./02-subscribe-dollar-v5.py ./02-subscribe-invalid-utf8.py ./02-subscribe-long-topic.py ./02-subscribe-persistence-flipflop.py 03 : #./03-publish-qos1-queued-bytes.py ./03-pattern-matching.py ./03-publish-bad-flags.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-dup.py #./03-publish-qos2-max-inflight-exceeded.py ./03-publish-qos2-max-inflight.py ./03-publish-qos2-reuse-mid.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-clear-multiple.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 ./05-session-expiry-kick.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-csF-lcsF.py ./06-bridge-clean-session-csF-lcsN.py ./06-bridge-clean-session-csF-lcsT.py ./06-bridge-clean-session-csT-lcsF.py ./06-bridge-clean-session-csT-lcsN.py ./06-bridge-clean-session-csT-lcsT.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 ./06-bridge-remote-shutdown.py ./06-bridge-config-reload.py ./06-bridge-remap-receive-wildcard.py 07 : ./07-will-control.py ./07-will-delay-invalid-573191.py ./07-will-delay-reconnect.py ./07-will-delay-recover.py ./07-will-delay-session-expiry-0.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-per-listener.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-allowed.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-dhparam.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-reauth.py ./09-extended-auth-single.py ./09-plugin-acl-access-variants.py ./09-plugin-acl-change.py ./09-plugin-auth-acl-pub.py ./09-plugin-auth-acl-pub-prop.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-auth-v3-unpwd-fail.py ./09-plugin-auth-v3-unpwd-success.py ./09-plugin-auth-v4-unpwd-fail.py ./09-plugin-auth-v4-unpwd-success.py ./09-plugin-auth-v5-unpwd-fail.py ./09-plugin-auth-v5-unpwd-success.py ./09-plugin-bad.py ./09-plugin-change-id.py ./09-plugin-delayed-auth.py ./09-plugin-evt-client-offline.py ./09-plugin-evt-message-in.py ./09-plugin-evt-message-out.py ./09-plugin-evt-psk-key.py ./09-plugin-evt-reload.py ./09-plugin-evt-subscribe.py ./09-plugin-evt-tick.py ./09-plugin-evt-unsubscribe.py ./09-plugin-load-acl.py ./09-plugin-load-basic-auth.py ./09-plugin-load-extended-auth.py ./09-plugin-publish.py ./09-plugin-unsupported.py ./09-pwfile-parse-invalid.py 10 : ./10-listener-mount-point.py 11 : ./11-message-expiry.py ./11-persistence-autosave-changes.py ./11-persistent-subscription-no-local.py ./11-persistent-subscription.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-publish-qos1.py ./12-prop-maximum-packet-size-publish-qos2.py ./12-prop-response-topic-correlation-data.py ./12-prop-response-topic.py ./12-prop-server-keepalive.py ./12-prop-subpub-content-type.py ./12-prop-subpub-payload-format.py 13 : ifneq ($(WITH_WEBSOCKETS),no) ./13-websocket-bad-origin.py endif 14 : ifeq ($(WITH_TLS),yes) ./14-dynsec-acl.py ./14-dynsec-allow-wildcard.py ./14-dynsec-anon-group.py ./14-dynsec-auth.py ./14-dynsec-client-invalid.py ./14-dynsec-client.py ./14-dynsec-config-init-env.py ./14-dynsec-config-init-file.py ./14-dynsec-config-init-random.py ./14-dynsec-default-access.py ./14-dynsec-disable-client.py ./14-dynsec-group-invalid.py ./14-dynsec-group.py ./14-dynsec-modify-client.py ./14-dynsec-modify-group.py ./14-dynsec-modify-role.py ./14-dynsec-plugin-invalid.py ./14-dynsec-role-invalid.py ./14-dynsec-role.py endif PERSIST_TESTS = \ ./15-persist-bridge-queue.py \ ./15-persist-client-drop-expired-messages.py \ ./15-persist-client-expired-session.py \ ./15-persist-client-msg-in-v3-1-1.py \ ./15-persist-client-msg-in-v5-0.py \ ./15-persist-client-msg-modify-acl.py \ ./15-persist-client-msg-out-clear-v3-1-1.py \ ./15-persist-client-msg-out-dup-v3-1-1.py \ ./15-persist-client-msg-out-queue-v3-1-1.py \ ./15-persist-client-msg-out-v3-1-1-db.py \ ./15-persist-client-msg-out-v3-1-1.py \ ./15-persist-client-msg-out-v5-0.py \ ./15-persist-client-v3-1-1.py \ ./15-persist-client-v5-0.py \ ./15-persist-client-will.py \ ./15-persist-publish-properties-v5-0.py \ ./15-persist-retain-clear.py \ ./15-persist-retain-v3-1-1.py \ ./15-persist-retain-v5-0.py \ ./15-persist-subscription-v3-1-1.py \ ./15-persist-subscription-v5-0.py PERSIST_PLUGINS = ifeq ($(WITH_SQLITE),yes) PERSIST_PLUGINS+=persist_sqlite endif 15 : $(PERSISTENCE_TESTS) set -e; for p in $(PERSIST_PLUGINS); do for t in $(PERSIST_TESTS); do echo $$t $$p; $$t $$p; done; done ifeq ($(WITH_SQLITE),yes) ./15-persist-migrate-db.py persist_sqlite endif 16 : ./16-cmd-args.py ./16-config-huge.py ./16-config-includedir.py ./16-config-missing.py ./16-config-parse-errors-without-tls.py ifeq ($(WITH_TLS),yes) ./16-config-parse-errors-tls.py ifeq ($(WITH_TLS_PSK),yes) ./16-config-parse-errors-tls-psk.py endif endif 17 : ifneq ($(WITH_WEBSOCKETS),no) ./17-control-list-listeners.py endif ./17-control-list-plugins.py ./17-control-missing-endpoint.py 20 : ./20-sparkplug-compliance.py ./20-sparkplug-aware.py 21: ./21-proxy-bad-version.py ./21-proxy-v1-bad.py ./21-proxy-v1-success.py ./21-proxy-v2-bad-config.py ./21-proxy-v2-bad-header.py ./21-proxy-v2-local.py ./21-proxy-v2-ipv4.py ./21-proxy-v2-ipv6.py ./21-proxy-v2-unix.py ifneq ($(WITH_WEBSOCKETS),no) ./21-proxy-v2-websockets.py endif ./21-proxy-v2-long-tlv.py ./21-proxy-v2-lost-connection.py ./21-proxy-v2-ssl-require-cert-failure.py ./21-proxy-v2-ssl-require-cert-success.py ./21-proxy-v2-ssl-common-name-failure.py ./21-proxy-v2-ssl-common-name-success.py ./21-proxy-v2-ssl-cipher.py ./21-proxy-v2-ssl-require-tls-failure.py ./21-proxy-v2-ssl-require-tls-success.py 22: ifeq ($(WITH_HTTP_API),yes) ./22-http-api-acl.py ./22-http-api-api.py ./22-http-api-auth.py ./22-http-api-file.py ./22-http-api-tls.py endif 23: ./23-security-acl-file-reload.py ================================================ FILE: test/broker/c/08-tls-psk-bridge.c ================================================ #include #include #include #include #include #include static int run = -1; static int sent_mid; static void on_log(struct mosquitto *mosq, void *obj, int level, const char *str) { (void)mosq; (void)obj; (void)level; printf("%s\n", str); } static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_publish(mosq, &sent_mid, "psk/test", strlen("message"), "message", 1, false); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; if(mid == sent_mid){ mosquitto_disconnect(mosq); run = 0; }else{ exit(1); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/broker/c/08-tls-psk-pub.c ================================================ #include #include #include #include #include #include #ifndef WIN32 # include #endif static int run = -1; static int sent_mid; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_publish(mosq, &sent_mid, "psk/test", strlen("message"), "message", 0, false); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; if(mid == sent_mid){ mosquitto_disconnect(mosq); }else{ exit(1); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); #ifndef WIN32 signal(SIGPIPE, SIG_IGN); #endif mosquitto_lib_init(); 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; } ================================================ FILE: test/broker/c/CMakeLists.txt ================================================ set(PLUGINS auth_plugin_acl auth_plugin_acl_change auth_plugin_acl_sub_denied auth_plugin_context_params auth_plugin_delayed auth_plugin_extended_multiple auth_plugin_extended_reauth auth_plugin_extended_single auth_plugin_extended_single2 auth_plugin_id_change auth_plugin_msg_params auth_plugin_publish auth_plugin_pwd auth_plugin_v2 auth_plugin_v3 auth_plugin_v4 auth_plugin_v5 auth_plugin_v5_control bad_v1 bad_v2_1 bad_v2_2 bad_v2_3 bad_v2_4 bad_v2_5 bad_v2_6 bad_v2_7 bad_v3_1 bad_v3_2 bad_v3_3 bad_v3_4 bad_v3_5 bad_v3_6 bad_v3_7 bad_v4_1 bad_v4_2 bad_v4_3 bad_v4_4 bad_v5_1 bad_v6 bad_vnone_1 kick_last_client plugin_control plugin_evt_client_offline plugin_evt_message_in plugin_evt_message_out plugin_evt_persist_client_update plugin_evt_psk_key plugin_evt_reload plugin_evt_subscribe plugin_evt_tick plugin_evt_unsubscribe plugin_load_acl plugin_load_extended_auth ) foreach(PLUGIN ${PLUGINS}) add_library(${PLUGIN} MODULE ${PLUGIN}.c ) set_property(TARGET ${PLUGIN} PROPERTY PREFIX "" ) target_link_libraries(${PLUGIN} PRIVATE mosquitto) endforeach() set(BINARIES 08-tls-psk-pub 08-tls-psk-bridge ) foreach(BINARY ${BINARIES}) add_executable(${BINARY} ${BINARY}.c ) set_property(TARGET ${BINARY} PROPERTY SUFFIX .test ) target_link_libraries(${BINARY} PRIVATE common-options libmosquitto) endforeach() ================================================ FILE: test/broker/c/Makefile ================================================ R=../../.. include ${R}/config.mk .PHONY: all test clean reallyclean LOCAL_CPPFLAGS+=-I${R}/include LOCAL_CFLAGS+=-Wall -Werror LOCAL_LDFLAGS+=-fPIC -shared PLUGIN_SRC = \ auth_plugin_acl.c \ auth_plugin_acl_change.c \ auth_plugin_acl_sub_denied.c \ auth_plugin_context_params.c \ auth_plugin_delayed.c \ auth_plugin_extended_multiple.c \ auth_plugin_extended_reauth.c \ auth_plugin_extended_single.c \ auth_plugin_extended_single2.c \ auth_plugin_id_change.c \ auth_plugin_msg_params.c \ auth_plugin_publish.c \ auth_plugin_pwd.c \ auth_plugin_v2.c \ auth_plugin_v3.c \ auth_plugin_v4.c \ auth_plugin_v5.c \ auth_plugin_v5_control.c \ bad_vnone_1.c \ bad_v1.c \ bad_v2_1.c \ bad_v2_2.c \ bad_v2_3.c \ bad_v2_4.c \ bad_v2_5.c \ bad_v2_6.c \ bad_v2_7.c \ bad_v3_1.c \ bad_v3_2.c \ bad_v3_3.c \ bad_v3_4.c \ bad_v3_5.c \ bad_v3_6.c \ bad_v3_7.c \ bad_v4_1.c \ bad_v4_2.c \ bad_v4_3.c \ bad_v4_4.c \ bad_v5_1.c \ bad_v6.c \ kick_last_client.c \ plugin_control.c \ plugin_evt_client_offline.c \ plugin_evt_message_in.c \ plugin_evt_message_out.c \ plugin_evt_psk_key.c \ plugin_evt_reload.c \ plugin_evt_subscribe.c \ plugin_evt_tick.c \ plugin_evt_unsubscribe.c \ plugin_evt_persist_client_update.c \ plugin_load_acl.c \ plugin_load_extended_auth.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) $(LOCAL_CPPFLAGS) ${LOCAL_CFLAGS} ${LOCAL_LDFLAGS} $< -o $@ ${TESTS} : %.test: %.c $(CC) $(LOCAL_CPPFLAGS) ${LOCAL_CFLAGS} $< -o $@ ${LIBMOSQ} reallyclean : clean -rm -f *.orig clean : rm -f *.so *.test ================================================ FILE: test/broker/c/auth_plugin_acl.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)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); (void)user_data; 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) { (void)user_data; (void)client; (void)username; (void)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) { (void)user_data; (void)client; (void)hint; (void)identity; (void)key; (void)max_key_len; return MOSQ_ERR_AUTH; } ================================================ FILE: test/broker/c/auth_plugin_acl_change.c ================================================ #include #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; static int login_count = 0; MOSQUITTO_PLUGIN_DECLARE_VERSION(5); int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)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; (void)user_data; if(event != MOSQ_EVT_ACL_CHECK){ abort(); } if(login_count == 2 && ed->access == MOSQ_ACL_WRITE){ return MOSQ_ERR_ACL_DENIED; }else{ return MOSQ_ERR_SUCCESS; } } int mosquitto_auth_unpwd_check_v5(int event, void *event_data, void *user_data) { (void)user_data; (void)event_data; if(event != MOSQ_EVT_BASIC_AUTH){ abort(); } login_count++; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/auth_plugin_acl_sub_denied.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { (void)user_data; (void)client; (void)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) { (void)user_data; (void)client; (void)username; (void)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) { (void)user_data; (void)client; (void)hint; (void)identity; (void)key; (void)max_key_len; return MOSQ_ERR_AUTH; } ================================================ FILE: test/broker/c/auth_plugin_context_params.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { (void)user_data; (void)access; (void)client; (void)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; (void)user_data; (void)username; (void)password; 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 clientid 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) { (void)user_data; (void)client; (void)hint; (void)identity; (void)key; (void)max_key_len; return MOSQ_ERR_AUTH; } ================================================ FILE: test/broker/c/auth_plugin_delayed.c ================================================ #include #include #include #include #include #include static int tick_callback(int event, void *event_data, void *user_data); static int unpwd_check_callback(int event, void *event_data, void *user_data); static mosquitto_plugin_id_t *plg_id; static char *username = NULL; static char *password = NULL; static char *clientid = NULL; static int auth_delay = -1; MOSQUITTO_PLUGIN_DECLARE_VERSION(5); int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_TICK, tick_callback, NULL, NULL); mosquitto_callback_register(plg_id, MOSQ_EVT_BASIC_AUTH, unpwd_check_callback, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; free(username); free(password); free(clientid); mosquitto_callback_unregister(plg_id, MOSQ_EVT_BASIC_AUTH, unpwd_check_callback, NULL); mosquitto_callback_unregister(plg_id, MOSQ_EVT_TICK, tick_callback, NULL); return MOSQ_ERR_SUCCESS; } static int tick_callback(int event, void *event_data, void *user_data) { struct mosquitto_evt_tick *ed = event_data; (void)user_data; if(event != MOSQ_EVT_TICK){ abort(); } if(auth_delay == 0){ if(clientid && username && password && !strcmp(username, "delayed-username") && !strcmp(password, "good")){ mosquitto_complete_basic_auth(clientid, MOSQ_ERR_SUCCESS); }else{ mosquitto_complete_basic_auth(clientid, MOSQ_ERR_AUTH); } free(username); free(password); free(clientid); username = NULL; password = NULL; clientid = NULL; }else if(auth_delay > 0){ auth_delay--; } /* fast turn around for quick testing */ ed->next_ms = 10; return MOSQ_ERR_SUCCESS; } static int unpwd_check_callback(int event, void *event_data, void *user_data) { struct mosquitto_evt_basic_auth *ed = event_data; (void)event; (void)user_data; free(username); free(password); free(clientid); if(ed->username){ username = strdup(ed->username); } if(ed->password){ password = strdup(ed->password); } clientid = strdup(mosquitto_client_id(ed->client)); /* Delay for arbitrary 10 ticks */ auth_delay = 10; return MOSQ_ERR_AUTH_DELAYED; } ================================================ FILE: test/broker/c/auth_plugin_extended_multiple.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { (void)user_data; (void)access; (void)client; (void)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; (void)user_data; (void)client; (void)reauth; 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; } ================================================ FILE: test/broker/c/auth_plugin_extended_reauth.c ================================================ #include #include #include #include #include #include #define UNUSED(A) (void)(A) static int auth_count = 0; 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) { UNUSED(user_data); UNUSED(auth_opts); UNUSED(auth_opt_count); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { UNUSED(user_data); UNUSED(auth_opts); UNUSED(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) { UNUSED(user_data); UNUSED(auth_opts); UNUSED(auth_opt_count); UNUSED(reload); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { UNUSED(user_data); UNUSED(auth_opts); UNUSED(auth_opt_count); UNUSED(reload); return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { UNUSED(user_data); UNUSED(access); UNUSED(client); UNUSED(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) { UNUSED(user_data); UNUSED(client); UNUSED(method); UNUSED(reauth); UNUSED(data); UNUSED(data_len); UNUSED(data_out); UNUSED(data_out_len); if(auth_count == 0){ auth_count++; return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } int mosquitto_auth_continue(void *user_data, struct mosquitto *client, const char *method, const void *data, uint16_t data_len, void **data_out, uint16_t *data_out_len) { UNUSED(user_data); UNUSED(client); UNUSED(method); UNUSED(data); UNUSED(data_len); UNUSED(data_out); UNUSED(data_out_len); return MOSQ_ERR_AUTH; } ================================================ FILE: test/broker/c/auth_plugin_extended_single.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { (void)user_data; (void)access; (void)client; (void)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; (void)user_data; (void)reauth; 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 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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { (void)user_data; (void)access; (void)client; (void)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; (void)user_data; (void)reauth; 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 #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; MOSQUITTO_PLUGIN_DECLARE_VERSION(5); int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)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; int rc; (void)user_data; if(event != MOSQ_EVT_ACL_CHECK){ abort(); } if(!strcmp(mosquitto_client_id(ed->client), "allowed")){ /* Attempt to change to a different existing ID after we have * authenticated - should fail */ rc = mosquitto_set_clientid(ed->client, "already-exists"); if(rc != MOSQ_ERR_ALREADY_EXISTS){ exit(1); } } if(!strcmp(mosquitto_client_id(ed->client), "allowed")){ return MOSQ_ERR_SUCCESS; }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; const char *clientid; int rc; (void)user_data; clientid = mosquitto_client_id(ed->client); if(event != MOSQ_EVT_BASIC_AUTH){ abort(); } if(!strcmp(clientid, "id-change-test")){ rc = mosquitto_set_clientid(ed->client, "allowed"); if(strcmp(mosquitto_client_id(ed->client), "allowed")){ rc = MOSQ_ERR_INVAL; } if(rc != MOSQ_ERR_SUCCESS){ exit(1); } } return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/auth_plugin_msg_params.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { (void)user_data; (void)client; 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) { (void)user_data; (void)client; (void)username; (void)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) { (void)user_data; (void)client; (void)hint; (void)identity; (void)key; (void)max_key_len; return MOSQ_ERR_AUTH; } ================================================ FILE: test/broker/c/auth_plugin_publish.c ================================================ #include #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)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; (void)user_data; (void)client; (void)msg; 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{ if(mosquitto_property_add_byte(&props, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1)){ abort(); } mosquitto_broker_publish_copy("test-client", "topic/0", strlen("test-message-0"), "test-message-0", 0, true, props); props = NULL; if(mosquitto_property_add_byte(&props, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1)){ abort(); } mosquitto_broker_publish_copy("test-client", "topic/1", strlen("test-message-1"), "test-message-1", 1, true, props); props = NULL; if(mosquitto_property_add_byte(&props, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1)){ abort(); } 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) { (void)user_data; (void)client; (void)username; (void)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) { (void)user_data; (void)client; (void)hint; (void)identity; (void)key; (void)max_key_len; return MOSQ_ERR_AUTH; } ================================================ FILE: test/broker/c/auth_plugin_pwd.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, int access, struct mosquitto *client, const struct mosquitto_acl_msg *msg) { (void)user_data; (void)access; (void)client; (void)msg; return MOSQ_ERR_PLUGIN_DEFER; } int mosquitto_auth_unpwd_check(void *user_data, struct mosquitto *client, const char *username, const char *password) { (void)user_data; (void)client; 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) { (void)user_data; (void)client; (void)hint; (void)identity; (void)key; (void)max_key_len; return MOSQ_ERR_AUTH; } ================================================ FILE: test/broker/c/auth_plugin_v2.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, const char *clientid, const char *username, const char *topic, int access) { (void)user_data; (void)clientid; (void)topic; if(access != MOSQ_ACL_READ && access != MOSQ_ACL_WRITE){ return MOSQ_ERR_ACL_DENIED; }else if(username && !strcmp(username, "readonly") && access == MOSQ_ACL_READ){ return MOSQ_ERR_SUCCESS; }else if(username && !strcmp(username, "readwrite")){ if((!strcmp(topic, "readonly") && access == MOSQ_ACL_READ) || !strcmp(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, const char *username, const char *password) { (void)user_data; if(username && !strcmp(username, "test-username") && password && !strcmp(password, "cnwTICONIURW")){ return MOSQ_ERR_SUCCESS; }else if(username && (!strcmp(username, "readonly") || !strcmp(username, "readwrite"))){ return MOSQ_ERR_SUCCESS; }else if(username && !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) { (void)user_data; (void)hint; (void)identity; (void)key; (void)max_key_len; return MOSQ_ERR_AUTH; } ================================================ FILE: test/broker/c/auth_plugin_v3.c ================================================ #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 3; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)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); (void)user_data; 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) { (void)user_data; (void)client; if(username && !strcmp(username, "test-username") && password && !strcmp(password, "cnwTICONIURW")){ return MOSQ_ERR_SUCCESS; }else if(username && (!strcmp(username, "readonly") || !strcmp(username, "readwrite"))){ return MOSQ_ERR_SUCCESS; }else if(username && !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) { (void)user_data; (void)client; (void)hint; (void)identity; (void)key; (void)max_key_len; return MOSQ_ERR_AUTH; } ================================================ FILE: test/broker/c/auth_plugin_v4.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)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); (void)user_data; 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) { (void)user_data; (void)client; if(username && !strcmp(username, "test-username") && password && !strcmp(password, "cnwTICONIURW")){ return MOSQ_ERR_SUCCESS; }else if(username && (!strcmp(username, "readonly") || !strcmp(username, "readwrite"))){ return MOSQ_ERR_SUCCESS; }else if(username && !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) { (void)user_data; (void)client; (void)hint; (void)identity; (void)key; (void)max_key_len; return MOSQ_ERR_AUTH; } ================================================ FILE: test/broker/c/auth_plugin_v5.c ================================================ #include #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; MOSQUITTO_PLUGIN_DECLARE_VERSION(5); int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)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); char *prop_name = NULL, *prop_value = NULL; (void)user_data; if(event != MOSQ_EVT_ACL_CHECK){ abort(); } 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 if(mosquitto_property_read_string_pair(ed->properties, MQTT_PROP_USER_PROPERTY, &prop_name, &prop_value, false) && !strcmp(prop_name, "custom-name") && !strcmp(prop_value, "custom-value")){ mosquitto_FREE(prop_name); mosquitto_FREE(prop_value); return MOSQ_ERR_SUCCESS; }else{ mosquitto_FREE(prop_name); mosquitto_FREE(prop_value); 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; const char binary_pw[8] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; (void)user_data; if(event != MOSQ_EVT_BASIC_AUTH){ abort(); } if(ed->username && !strcmp(ed->username, "test-username") && ed->password && !strcmp(ed->password, "cnwTICONIURW") && strlen("cnwTICONIURW") == ed->password_len ){ return MOSQ_ERR_SUCCESS; }else if(ed->username && !strcmp(ed->username, "binary-password") && ed->password && ed->password_len == sizeof(binary_pw) && !memcmp(ed->password, binary_pw, ed->password_len) ){ return MOSQ_ERR_SUCCESS; }else if(ed->username && (!strcmp(ed->username, "readonly") || !strcmp(ed->username, "readwrite"))){ return MOSQ_ERR_SUCCESS; }else if(ed->username && !strcmp(ed->username, "test-username@v2")){ return MOSQ_ERR_PLUGIN_DEFER; }else{ return MOSQ_ERR_AUTH; } } ================================================ FILE: test/broker/c/auth_plugin_v5_control.c ================================================ #include #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; MOSQUITTO_PLUGIN_DECLARE_VERSION(5); int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; plg_id = identifier; mosquitto_plugin_set_info(identifier, "test-plugin", NULL); 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); mosquitto_callback_register(plg_id, MOSQ_EVT_CONTROL, mosquitto_auth_unpwd_check_v5, "$CONTROL/test/v1", NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)event; (void)event_data; (void)user_data; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_unpwd_check_v5(int event, void *event_data, void *user_data) { (void)event; (void)event_data; (void)user_data; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v1.c ================================================ #include #include #include #include #include #include MOSQUITTO_PLUGIN_DECLARE_VERSION(1); ================================================ FILE: test/broker/c/bad_v2_1.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, const char *clientid, const char *username, const char *topic, int access) { (void)user_data; (void)clientid; (void)topic; if(access != MOSQ_ACL_READ && access != MOSQ_ACL_WRITE){ return MOSQ_ERR_ACL_DENIED; }else if(username && !strcmp(username, "readonly") && access == MOSQ_ACL_READ){ return MOSQ_ERR_SUCCESS; }else if(username && !strcmp(username, "readwrite")){ if((!strcmp(topic, "readonly") && access == MOSQ_ACL_READ) || !strcmp(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, const char *username, const char *password) { (void)user_data; 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_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } ================================================ FILE: test/broker/c/bad_v2_2.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_acl_check(void *user_data, const char *clientid, const char *username, const char *topic, int access) { (void)user_data; (void)clientid; (void)topic; if(access != MOSQ_ACL_READ && access != MOSQ_ACL_WRITE){ return MOSQ_ERR_ACL_DENIED; }else if(username && !strcmp(username, "readonly") && access == MOSQ_ACL_READ){ return MOSQ_ERR_SUCCESS; }else if(username && !strcmp(username, "readwrite")){ if((!strcmp(topic, "readonly") && access == MOSQ_ACL_READ) || !strcmp(topic, "writeable")){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } }else{ return MOSQ_ERR_ACL_DENIED; } } ================================================ FILE: test/broker/c/bad_v2_3.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v2_4.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v2_5.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v2_6.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v2_7.c ================================================ #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; } ================================================ FILE: test/broker/c/bad_v3_1.c ================================================ #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 3; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)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); (void)user_data; 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) { (void)user_data; (void)client; 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; } } ================================================ FILE: test/broker/c/bad_v3_2.c ================================================ #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 3; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)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); (void)user_data; 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; } } ================================================ FILE: test/broker/c/bad_v3_3.c ================================================ #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 3; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_security_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count, bool reload) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v3_4.c ================================================ #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 3; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v3_5.c ================================================ #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 3; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v3_6.c ================================================ #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 3; } int mosquitto_auth_plugin_init(void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v3_7.c ================================================ #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 3; } ================================================ FILE: test/broker/c/bad_v4_1.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; (void)reload; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v4_2.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } int mosquitto_auth_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v4_3.c ================================================ #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) { (void)user_data; (void)auth_opts; (void)auth_opt_count; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/bad_v4_4.c ================================================ #include #include #include #include #include int mosquitto_auth_plugin_version(void) { return 4; } ================================================ FILE: test/broker/c/bad_v5_1.c ================================================ #include #include #include #include #include #include MOSQUITTO_PLUGIN_DECLARE_VERSION(5); ================================================ FILE: test/broker/c/bad_v6.c ================================================ #include #include #include #include #include #include MOSQUITTO_PLUGIN_DECLARE_VERSION(6); ================================================ FILE: test/broker/c/bad_vnone_1.c ================================================ int dummy(void) { return 4; } ================================================ FILE: test/broker/c/kick_last_client.c ================================================ #include #include #include #include #include #include #define UNUSED(A) (void)(A) static int handle_tick(int event, void *event_data, void *user_data); static int handle_connect(int event, void *event_data, void *user_data); static int handle_disconnect(int event, void *event_data, void *user_data); static mosquitto_plugin_id_t *plg_id; static char *last_clientid = NULL; static int can_kick = 0; int mosquitto_plugin_version(int supported_version_count, const int *supported_versions) { UNUSED(supported_version_count); UNUSED(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) { UNUSED(user_data); UNUSED(auth_opts); UNUSED(auth_opt_count); plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_BASIC_AUTH, handle_connect, NULL, NULL); mosquitto_callback_register(plg_id, MOSQ_EVT_DISCONNECT, handle_disconnect, NULL, NULL); mosquitto_callback_register(plg_id, MOSQ_EVT_CLIENT_OFFLINE, handle_disconnect, NULL, NULL); mosquitto_callback_register(plg_id, MOSQ_EVT_TICK, handle_tick, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { UNUSED(user_data); UNUSED(auth_opts); UNUSED(auth_opt_count); mosquitto_callback_unregister(plg_id, MOSQ_EVT_CONNECT, handle_connect, NULL); mosquitto_callback_unregister(plg_id, MOSQ_EVT_DISCONNECT, handle_disconnect, NULL); mosquitto_callback_unregister(plg_id, MOSQ_EVT_CLIENT_OFFLINE, handle_disconnect, NULL); mosquitto_callback_unregister(plg_id, MOSQ_EVT_TICK, handle_tick, NULL); mosquitto_FREE(last_clientid); return MOSQ_ERR_SUCCESS; } int handle_tick(int event, void *event_data, void *user_data) { UNUSED(event); UNUSED(event_data); UNUSED(user_data); mosquitto_log_printf(MOSQ_LOG_INFO, "plugin tick %p %d", last_clientid, can_kick); if(last_clientid && can_kick){ if(can_kick == 1){ mosquitto_log_printf(MOSQ_LOG_INFO, "plugin kick %s", last_clientid); mosquitto_kick_client_by_clientid(last_clientid, false); mosquitto_FREE(last_clientid); can_kick--; }else{ can_kick--; } } return MOSQ_ERR_SUCCESS; } int handle_connect(int event, void *event_data, void *user_data) { struct mosquitto_evt_basic_auth *ed = event_data; UNUSED(event); UNUSED(user_data); const char *id = mosquitto_client_id(ed->client); mosquitto_log_printf(MOSQ_LOG_INFO, "plugin connect %s", id); mosquitto_FREE(last_clientid); last_clientid = mosquitto_strdup(id); return MOSQ_ERR_SUCCESS; } int handle_disconnect(int event, void *event_data, void *user_data) { UNUSED(event); UNUSED(event_data); UNUSED(user_data); mosquitto_log_printf(MOSQ_LOG_INFO, "plugin disconnect %d", event); can_kick = 5; return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/mosquitto_plugin_v2.h ================================================ /* 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_V2_H #define MOSQUITTO_PLUGIN_V2_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 ================================================ FILE: test/broker/c/plugin_control.c ================================================ #include #include #include #include #include #include #include static mosquitto_plugin_id_t *plg_id = NULL; MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static int control_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_control *ed = event_data; (void)userdata; if(event != MOSQ_EVT_CONTROL){ abort(); } mosquitto_broker_publish_copy(NULL, ed->topic, (int)ed->payloadlen, ed->payload, 0, 0, NULL); return 0; } 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]; (void)user_data; (void)auth_opts; (void)auth_opt_count; 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]; (void)user_data; (void)auth_opts; (void)auth_opt_count; 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; } ================================================ FILE: test/broker/c/plugin_evt_client_offline.c ================================================ #include #include #include #include #include #include MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *plg_id; int callback_client_offline(int event, void *event_data, void *user_data) { struct mosquitto_evt_client_offline *ed = event_data; const char *clientid; (void)user_data; if(event != MOSQ_EVT_CLIENT_OFFLINE){ abort(); } clientid = mosquitto_client_id(ed->client); mosquitto_broker_publish_copy(NULL, "evt/client/offline", (int)strlen(clientid), clientid, 0, false, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_CLIENT_OFFLINE, callback_client_offline, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; mosquitto_callback_unregister(plg_id, MOSQ_EVT_CLIENT_OFFLINE, callback_client_offline, NULL); return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/plugin_evt_message_in.c ================================================ #include #include #include #include #include #include MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *plg_id; int callback_message_in(int event, void *event_data, void *user_data) { struct mosquitto_evt_message *ed = event_data; (void)user_data; if(event != MOSQ_EVT_MESSAGE_IN){ abort(); } ed->topic = mosquitto_strdup("fixed-topic"); ed->payload = mosquitto_strdup("new-message"); ed->payloadlen = (uint32_t)strlen(ed->payload); ed->properties = NULL; if(mosquitto_property_add_string_pair(&ed->properties, MQTT_PROP_USER_PROPERTY, "key", "value")){ abort(); } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; mosquitto_callback_unregister(plg_id, MOSQ_EVT_MESSAGE_IN, callback_message_in, NULL); return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/plugin_evt_message_out.c ================================================ #include #include #include #include #include #include MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *plg_id; int callback_message_out(int event, void *event_data, void *user_data) { struct mosquitto_evt_message *ed = event_data; (void)user_data; if(event != MOSQ_EVT_MESSAGE_OUT){ abort(); } if(!strcmp(ed->topic, "deny")){ return MOSQ_ERR_ACL_DENIED; } ed->topic = mosquitto_strdup("new-topic"); ed->payload = mosquitto_strdup("new-message"); ed->payloadlen = (uint32_t)strlen(ed->payload); ed->properties = NULL; if(mosquitto_property_add_string_pair(&ed->properties, MQTT_PROP_USER_PROPERTY, "key", "value")){ abort(); } return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_MESSAGE_OUT, callback_message_out, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; mosquitto_callback_unregister(plg_id, MOSQ_EVT_MESSAGE_OUT, callback_message_out, NULL); return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/plugin_evt_persist_client_update.c ================================================ #include #include #include #include #include #include MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *plg_id; int callback_persist_client_update(int event, void *event_data, void *user_data) { struct mosquitto_evt_persist_client *ed = event_data; const char *clientid; (void)user_data; if(event != MOSQ_EVT_PERSIST_CLIENT_UPDATE){ abort(); } clientid = ed->data.clientid; mosquitto_broker_publish_copy(NULL, "evt/persist/client/update", (int)strlen(clientid), clientid, 0, false, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_PERSIST_CLIENT_UPDATE, callback_persist_client_update, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; mosquitto_callback_unregister(plg_id, MOSQ_EVT_PERSIST_CLIENT_UPDATE, callback_persist_client_update, NULL); return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/plugin_evt_psk_key.c ================================================ #include #include #include #include #include #include #include #define UNUSED(A) (void)(A) static mosquitto_plugin_id_t *plg_id = NULL; MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static int psk_callback(int event, void *event_data, void *userdata) { struct mosquitto_evt_psk_key *ed = event_data; UNUSED(event); UNUSED(userdata); if(!strcmp(ed->hint, "myhint") && !strcmp(ed->identity, "subidentity")){ snprintf(ed->key, (size_t)ed->max_key_len, "159445"); }else if(!strcmp(ed->hint, "myhint") && !strcmp(ed->identity, "pubidentity")){ snprintf(ed->key, (size_t)ed->max_key_len, "297A49"); }else{ return MOSQ_ERR_INVAL; } return 0; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { UNUSED(user_data); UNUSED(auth_opts); UNUSED(auth_opt_count); plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_PSK_KEY, psk_callback, NULL, NULL); return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/plugin_evt_reload.c ================================================ #include #include #include #include #include #include #define UNUSED(A) (void)(A) static int handle_reload(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) { UNUSED(supported_version_count); UNUSED(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) { UNUSED(user_data); UNUSED(auth_opts); UNUSED(auth_opt_count); plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_RELOAD, handle_reload, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { UNUSED(user_data); UNUSED(auth_opts); UNUSED(auth_opt_count); mosquitto_callback_unregister(plg_id, MOSQ_EVT_RELOAD, handle_reload, NULL); return MOSQ_ERR_SUCCESS; } int handle_reload(int event, void *event_data, void *user_data) { UNUSED(event); UNUSED(event_data); UNUSED(user_data); mosquitto_broker_publish_copy("plugin-reload-test", "topic/reload", strlen("test-message"), "test-message", 0, false, NULL); printf("reload\n"); return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/plugin_evt_subscribe.c ================================================ #include #include #include #include #include #include MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *plg_id; int callback_subscribe(int event, void *event_data, void *user_data) { struct mosquitto_evt_subscribe *ed = event_data; (void)user_data; if(event != MOSQ_EVT_SUBSCRIBE){ abort(); } ed->data.topic_filter = mosquitto_strdup("new-topic"); MQTT_SUB_OPT_SET_QOS(ed->data.options, 0); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_SUBSCRIBE, callback_subscribe, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; mosquitto_callback_unregister(plg_id, MOSQ_EVT_SUBSCRIBE, callback_subscribe, NULL); return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/plugin_evt_tick.c ================================================ #include #include #include #include #include #include #define UNUSED(A) (void)(A) static int handle_tick(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) { UNUSED(supported_version_count); UNUSED(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) { UNUSED(user_data); UNUSED(auth_opts); UNUSED(auth_opt_count); plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_TICK, handle_tick, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { UNUSED(user_data); UNUSED(auth_opts); UNUSED(auth_opt_count); mosquitto_callback_unregister(plg_id, MOSQ_EVT_TICK, handle_tick, NULL); return MOSQ_ERR_SUCCESS; } int handle_tick(int event, void *event_data, void *user_data) { UNUSED(event); UNUSED(event_data); UNUSED(user_data); mosquitto_broker_publish_copy("plugin-tick-test", "topic/tick", strlen("test-message"), "test-message", 0, false, NULL); return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/plugin_evt_unsubscribe.c ================================================ #include #include #include #include #include #include MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static mosquitto_plugin_id_t *plg_id; int callback_unsubscribe(int event, void *event_data, void *user_data) { struct mosquitto_evt_unsubscribe *ed = event_data; (void)user_data; if(event != MOSQ_EVT_UNSUBSCRIBE){ abort(); } ed->data.topic_filter = mosquitto_strdup("missing-topic"); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; plg_id = identifier; mosquitto_callback_register(plg_id, MOSQ_EVT_UNSUBSCRIBE, callback_unsubscribe, NULL, NULL); return MOSQ_ERR_SUCCESS; } int mosquitto_plugin_cleanup(void *user_data, struct mosquitto_opt *opts, int opt_count) { (void)user_data; (void)opts; (void)opt_count; mosquitto_callback_unregister(plg_id, MOSQ_EVT_UNSUBSCRIBE, callback_unsubscribe, NULL); return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/c/plugin_load_acl.c ================================================ #include #include #include #include #include #include int mosquitto_auth_acl_check_v5(int event, void *event_data, void *user_data); MOSQUITTO_PLUGIN_DECLARE_VERSION(5); int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; mosquitto_callback_register(identifier, MOSQ_EVT_ACL_CHECK, mosquitto_auth_acl_check_v5, NULL, 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; (void)user_data; if(event != MOSQ_EVT_ACL_CHECK){ abort(); } if(!strcmp(ed->topic, "allowed-topic")){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_ACL_DENIED; } } ================================================ FILE: test/broker/c/plugin_load_extended_auth.c ================================================ #include #include #include #include #include #include MOSQUITTO_PLUGIN_DECLARE_VERSION(5); static int on_ext_auth_start(int event, void *event_data, void *user_data) { struct mosquitto_evt_extended_auth *ed = event_data; (void)user_data; if(event != MOSQ_EVT_EXT_AUTH_START){ abort(); } if(!strcmp((char *)ed->data_in, "allowed-start")){ ed->data_out = mosquitto_strdup("start-ok"); ed->data_out_len = (uint16_t)strlen(ed->data_out); return MOSQ_ERR_AUTH_CONTINUE; }else{ return MOSQ_ERR_AUTH; } } static int on_ext_auth_continue(int event, void *event_data, void *user_data) { struct mosquitto_evt_extended_auth *ed = event_data; (void)user_data; if(event != MOSQ_EVT_EXT_AUTH_CONTINUE){ abort(); } if(!strcmp((char *)ed->data_in, "allowed-continue")){ return MOSQ_ERR_SUCCESS; }else{ return MOSQ_ERR_AUTH; } } int mosquitto_plugin_init(mosquitto_plugin_id_t *identifier, void **user_data, struct mosquitto_opt *auth_opts, int auth_opt_count) { (void)user_data; (void)auth_opts; (void)auth_opt_count; mosquitto_callback_register(identifier, MOSQ_EVT_EXT_AUTH_START, on_ext_auth_start, NULL, NULL); mosquitto_callback_register(identifier, MOSQ_EVT_EXT_AUTH_CONTINUE, on_ext_auth_continue, NULL, NULL); return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/broker/data/AUTH.json ================================================ [ { "comment": "AUTH TESTS ARE INCOMPLETE", "group": "v3.1.1 AUTH", "ver":4, "tests": [ { "name": "F0 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"F0 r0"}]}, { "name": "F0 long", "msgs": [{"type":"send", "payload":"F0 r1 00"}]}, { "name": "F1", "msgs": [{"type":"send", "payload":"F1 r0"}]}, { "name": "F2", "msgs": [{"type":"send", "payload":"F2 r0"}]}, { "name": "F4", "msgs": [{"type":"send", "payload":"F4 r0"}]}, { "name": "F8", "msgs": [{"type":"send", "payload":"F8 r0"}]}, { "name": "F0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"F0 r268435456"}]} ] }, { "group": "v5.0 AUTH", "ver":5, "tests": [ { "name": "F0 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"F0 00"}]}, { "name": "F0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"F0 r268435456"}]}, { "name": "F0 long", "msgs": [ {"type":"send", "payload":"F0 r1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "F1", "msgs": [ {"type":"send", "payload":"F1 r0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "F2", "msgs": [ {"type":"send", "payload":"F2 r0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "F4", "msgs": [ {"type":"send", "payload":"F4 r0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "F8", "msgs": [ {"type":"send", "payload":"F8 r0"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] } ] ================================================ FILE: test/broker/data/CONNACK.json ================================================ [ { "group": "v3.1.1 CONNACK", "ver":4, "tests": [ { "name": "20 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"20 r2 00 00"}]}, { "name": "20 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"20 r268435456"}]}, { "name": "20 long", "msgs": [{"type":"send", "payload":"20 r3 00 00 00"}]}, { "name": "20 short 1", "msgs": [{"type":"send", "payload":"20 r1 00"}]}, { "name": "20 short 0", "msgs": [{"type":"send", "payload":"20 r0"}]}, { "name": "20", "msgs": [{"type":"send", "payload":"20 r2 00 00"}]}, { "name": "21", "msgs": [{"type":"send", "payload":"21 r2 00 00"}]}, { "name": "22", "msgs": [{"type":"send", "payload":"22 r2 00 00"}]}, { "name": "24", "msgs": [{"type":"send", "payload":"24 r2 00 00"}]}, { "name": "28", "msgs": [{"type":"send", "payload":"28 r2 00 00"}]}, { "name": "issue 2163 v3", "ver":3, "msgs": [{"type":"send", "payload":"29 r2 00 01"}]}, { "name": "issue 2163 v4", "msgs": [{"type":"send", "payload":"29 r2 00 01"}]}, { "name": "20 CAF=0x01", "msgs": [{"type":"send", "payload":"20 r2 01 00"}]}, { "name": "20 CAF=0x02", "msgs": [{"type":"send", "payload":"20 r2 02 00"}]}, { "name": "20 CAF=0x04", "msgs": [{"type":"send", "payload":"20 r2 04 00"}]}, { "name": "20 CAF=0x08", "msgs": [{"type":"send", "payload":"20 r2 08 00"}]}, { "name": "20 CAF=0x10", "msgs": [{"type":"send", "payload":"20 r2 10 00"}]}, { "name": "20 CAF=0x20", "msgs": [{"type":"send", "payload":"20 r2 20 00"}]}, { "name": "20 CAF=0x40", "msgs": [{"type":"send", "payload":"20 r2 40 00"}]}, { "name": "20 CAF=0x80", "msgs": [{"type":"send", "payload":"20 r2 80 00"}]} ] }, { "group": "v5.0 CONNACK", "comment": "CMD RL FLAG RC PROPLEN PROPS", "ver":5, "tests": [ { "name": "20 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"20 r3 00 00 00"}]}, { "name": "20 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"20 r268435456"}]}, { "name": "20 with properties", "msgs": [ {"type":"send", "payload":"20 r6 00 00 03 21 000A"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 long", "msgs": [ {"type":"send", "payload":"20 r4 00 00 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 short 2", "msgs": [ {"type":"send", "payload":"20 r2 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 short 1", "msgs": [ {"type":"send", "payload":"20 r1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 short 0", "msgs": [ {"type":"send", "payload":"20 r0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20", "msgs": [ {"type":"send", "payload":"20 r3 00 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "21", "msgs": [ {"type":"send", "payload":"21 r3 00 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "22", "msgs": [ {"type":"send", "payload":"22 r3 00 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "24", "msgs": [ {"type":"send", "payload":"24 r3 00 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "28", "msgs": [ {"type":"send", "payload":"28 r3 00 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "issue 2163 v5", "msgs": [ {"type":"send", "payload":"29 r2 00 01"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 CAF=0x01", "msgs": [ {"type":"send", "payload":"20 r3 01 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 CAF=0x02", "msgs": [ {"type":"send", "payload":"20 r3 02 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 CAF=0x04", "msgs": [ {"type":"send", "payload":"20 r3 04 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 CAF=0x08", "msgs": [ {"type":"send", "payload":"20 r3 08 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 CAF=0x10", "msgs": [ {"type":"send", "payload":"20 r3 10 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 CAF=0x20", "msgs": [ {"type":"send", "payload":"20 r3 20 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 CAF=0x40", "msgs": [ {"type":"send", "payload":"20 r3 40 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 CAF=0x80", "msgs": [ {"type":"send", "payload":"20 r3 80 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x01 (invalid)", "msgs": [ {"type":"send", "payload":"20 r3 00 01 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x80 (unspecified error)", "msgs": [ {"type":"send", "payload":"20 r3 00 80 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x81 (malformed packet)", "msgs": [ {"type":"send", "payload":"20 r3 00 81 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x82 (protocol error)", "msgs": [ {"type":"send", "payload":"20 r3 00 82 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x83 (implementation specific error)", "msgs": [ {"type":"send", "payload":"20 r3 00 83 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x84 (unsupported protocol version)", "msgs": [ {"type":"send", "payload":"20 r3 00 84 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x85 (client identifier not valid)", "msgs": [ {"type":"send", "payload":"20 r3 00 85 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x86 (bad user name or password)", "msgs": [ {"type":"send", "payload":"20 r3 00 86 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x87 (not authorised)", "msgs": [ {"type":"send", "payload":"20 r3 00 87 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x88 (server unavailable)", "msgs": [ {"type":"send", "payload":"20 r3 00 88 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x89 (server busy)", "msgs": [ {"type":"send", "payload":"20 r3 00 89 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x8A (banned)", "msgs": [ {"type":"send", "payload":"20 r3 00 8A 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x8C (bad authentication method)", "msgs": [ {"type":"send", "payload":"20 r3 00 8C 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x90 (topic name invalid)", "msgs": [ {"type":"send", "payload":"20 r3 00 90 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x95 (packet too large)", "msgs": [ {"type":"send", "payload":"20 r3 00 95 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x97 (quota exceeded)", "msgs": [ {"type":"send", "payload":"20 r3 00 97 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x99 (payload format invalid)", "msgs": [ {"type":"send", "payload":"20 r3 00 99 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x9A (retain not supported)", "msgs": [ {"type":"send", "payload":"20 r3 00 9A 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x9B (qos not supported)", "msgs": [ {"type":"send", "payload":"20 r3 00 9B 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x9C (use another server)", "msgs": [ {"type":"send", "payload":"20 r3 00 9C 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x9D (server moved)", "msgs": [ {"type":"send", "payload":"20 r3 00 9D 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0x9F (connection rate exceeded)", "msgs": [ {"type":"send", "payload":"20 r3 00 9F 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 RC=0xFF (invalid)", "msgs": [ {"type":"send", "payload":"20 r3 00 FF 00"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] }, { "group": "v5.0 CONNACK ALLOWED PROPERTIES", "comment": "CMD RL FLAG RC PROPLEN PROPS", "ver":5, "tests": [ { "name": "20 with session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"20 r8 00 00 v5 11 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with session-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 11"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"20 r6 00 00 v3 21 0101"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with receive-maximum (two byte integer) 0 value", "msgs": [ {"type":"send", "payload":"20 r6 00 00 v3 21 H0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 21"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 24 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with maximum-qos (byte) 2 value", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 24 i2"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 24"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with retain-available (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 25 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 25"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"20 r8 00 00 v5 27 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"20 r8 00 00 v5 27 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with maximum-packet-size (four byte integer) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 27"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 12 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with assigned-client-identifier (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 12"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with assigned-client-identifier (UTF-8 string) empty", "msgs": [ {"type":"send", "payload":"20 r6 00 00 v3 12 0000"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"20 r6 00 00 v3 220101"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 22"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with reason-string property", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 1F s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with reason-string property missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 1F"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with reason-string property empty", "msgs": [ {"type":"send", "payload":"20 r6 00 00 v3 1F s0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 28 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 28"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 29 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 29"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"20 r6 00 00 v3 13 0101"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with server-keep-alive (two byte integer) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 13"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 2A i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 2A"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 1A s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with response-information (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 1A"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 1C s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with server-reference (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 1C"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 15 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 15"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 16 H1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with authentication-data (binary data) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 16"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with user-property", "msgs": [ {"type":"send", "payload":"20 r10 00 00 v7 26 s1 'p' s1 'q'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with user-property missing value", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 26 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with user-property missing key,value", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 26"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] }, { "group": "v5.0 CONNACK DISALLOWED PROPERTIES", "comment": "CMD RL FLAG RC PROPLEN PROPS", "ver":5, "tests": [ { "name": "20 with payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 01 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 17 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 01"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 17"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with message-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"20 r8 00 00 v5 02 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"20 r8 00 00 v5 18 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with message-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 02"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with will-delay-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 18"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 03 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 08 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with content-type (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 03"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with response-topic (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 08"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 09 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with correlation-data (binary data) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 09"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with subscription-identifier (variable byte integer)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 0B v1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 0B"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"20 r6 00 00 v3 23 0101"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with topic-alias (two byte integer) missing", "msgs": [ {"type":"send", "payload":"20 r4 00 00 v1 23"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 00 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 04 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 05 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 06 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 07 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 0A i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 0C i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 0D i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 0E i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 0F i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 10 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 14 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 1B i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 1D i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 1E i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 20 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"20 r5 00 00 v2 7F i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"20 r6 00 00 v3 8000 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"20 r6 00 00 v3 8001 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"20 r6 00 00 v3 FF7F i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 808001 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"20 r7 00 00 v4 FFFF7F i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"20 r8 00 00 v5 80808001 i1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "20 with unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"20 r8 00 00 v5 FFFFFF7F i1"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] } ] ================================================ FILE: test/broker/data/CONNECT.json ================================================ [ { "comment": "CONNECT TESTS ARE INCOMPLETE", "group": "v3.1 CONNECT", "ver":3, "connect":false, "tests": [ { "name": "10 ok ", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r15 s6 'MQIsdp' 03 01 k10 s1 'p'", "comment":"minimal valid CONNECT"}, {"type":"recv", "payload":"20 r2 00 00", "comment": "CONNACK"} ]}, { "name": "14 ok ", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"14 r15 s6 'MQIsdp' 03 01 k10 s1 'p'", "comment":"CONNECT with QoS=1"}, {"type":"recv", "payload":"20 r2 00 00", "comment": "CONNACK"} ]}, { "name": "10 proto ver 2", "msgs":[ {"type":"send", "payload":"10 r15 s6 'MQIsdp' 02 00 k10 s1 'p'", "comment":"CONNECT"}, {"type":"recv", "payload":"20 r3 00 84 00", "comment": "CONNACK identifier rejected"} ]}, { "name": "10 proto ver 6", "msgs":[ {"type":"send", "payload":"10 r15 s6 'MQIsdp' 06 00 k10 s1 'p'", "comment":"CONNECT"}, {"type":"recv", "payload":"20 r3 00 84 00", "comment": "CONNACK identifier rejected"} ]}, { "name": "10 empty client ID", "msgs":[ {"type":"send", "payload":"10 r14 s6 'MQIsdp' 03 02 k10 0000", "comment":"CONNECT clean session true, no client id"}, {"type":"recv", "payload":"20 r2 00 02", "comment": "CONNACK"} ]}, { "name": "10 ok", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r15 s6 'MQIsdp' 03 02 k10 s1 'p'", "comment":"CONNECT clean session true, no client id"}, {"type":"recv", "payload":"20 r2 00 00", "comment": "CONNACK"} ]}, { "name": "10 remaining length 5 bytes", "msgs":[ {"type":"send", "payload":"10 r268435456 s6 'MQIsdp' 03 02 k10 s1 'p'", "comment":"minimal valid CONNECT"} ]} ] }, { "group": "v3.1.1 CONNECT", "ver":4, "connect":false, "tests": [ { "name": "10 ok ", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r13 s4 'MQTT' 04 02 k10 s1 'p'", "comment":"minimal valid CONNECT"}, {"type":"recv", "payload":"20 r2 00 00", "comment": "CONNACK"} ]}, { "name": "10 [MQTT-3.1.0-2]", "msgs":[ {"type":"send", "payload":"10 r13 s4 'MQTT' 04 02 k10 s1 'p'", "comment":"minimal valid CONNECT"}, {"type":"recv", "payload":"20 r2 00 00", "comment": "CONNACK"}, {"type":"send", "payload":"10 r13 s4 'MQTT' 04 02 k10 s1 'p'", "comment":"minimal valid CONNECT"} ]}, { "name": "10 missing client ID", "connect":false, "msgs":[{"type":"send", "payload":"10 r10 s4 'MQTT' 04 02 k10"}]}, { "name": "10 empty client ID", "connect":false, "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r12 s4 'MQTT' 04 02 k10 0000", "comment":"CONNECT clean session true, no client id"}, {"type":"recv", "payload":"20 r2 00 00", "comment": "CONNACK"} ]}, { "name": "10 empty client ID clean false [MQTT-3.1.3-7]", "expect_disconnect":true, "msgs":[ {"type":"send", "payload":"10 r12 s4 'MQTT' 04 00 k10 0000", "comment":"CONNECT clean session false, no client id"}, {"type":"recv", "payload":"20 r2 00 02", "comment": "CONNACK"} ]}, { "name": "10 proto ver 2 [MQTT-3.1.2-2]", "msgs":[ {"type":"send", "payload":"10 r13 s4 'MQTT' 02 00 k10 s1 'p'", "comment":"CONNECT"}, {"type":"recv", "payload":"20 r3 00 84 00", "comment": "v3.1.1 CONNACK identifier rejected"} ]}, { "name": "10 proto ver 6 [MQTT-3.1.2-2]", "msgs":[ {"type":"send", "payload":"10 r13 s4 'MQTT' 06 00 k10 s1 'p'", "comment":"CONNECT"}, {"type":"recv", "payload":"20 r3 00 84 00", "comment": "v3.1.1 CONNACK identifier rejected"} ]}, { "name": "10 remaining length 5 bytes", "msgs":[ {"type":"send", "payload":"10 r268435456 s4 'MQTT' 05 02 k10 s1 'p'", "comment":"CONNECT"} ]}, { "name": "11", "msgs":[{"type":"send", "payload":"11 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "12", "msgs":[{"type":"send", "payload":"12 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "14", "msgs":[{"type":"send", "payload":"14 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "18", "msgs":[{"type":"send", "payload":"18 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "10 short proto", "msgs":[{"type":"send", "payload":"10 r12 s3 'MQT' 04 02 k10 s1 'p'"}]}, { "name": "10 zero proto", "msgs":[{"type":"send", "payload":"10 r9 s0 04 02 k10 s1 'p'"}]}, { "name": "10 long proto", "msgs":[{"type":"send", "payload":"10 r14 s5 'MQTTT' 04 02 k10 s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-1]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTU' 04 02 k10 s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-3] ", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 01 k10 s1 'p'"}]}, { "name": "10 Will flag 0 Will QoS 1 [MQTT-3.1.2-11]", "msgs":[ {"type":"send", "payload":"10 r13 s4 'MQTT' 04 0A k10 s1 'p'"} ]}, { "name": "10 Will flag 0 Will retain 1 [MQTT-3.1.2-11]", "msgs":[ {"type":"send", "payload":"10 r13 s4 'MQTT' 04 12 k10 s1 'p'"} ]}, { "name": "10 Will flag 1 no Will topic no Will message [MQTT-3.1.2-9]", "msgs":[ {"type":"send", "payload":"10 r13 s4 'MQTT' 04 06 k10 s1 'p'"} ]}, { "name": "10 Will flag 1 no Will topic [MQTT-3.1.2-9]", "msgs":[ {"type":"send", "payload":"10 r16 s4 'MQTT' 04 06 k10 s1 'p' s1 'p'"} ]}, { "name": "10 Will flag 1 ok", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 04 06 k10 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r2 00 00", "comment": "CONNACK"} ]}, { "name": "10 Will flag 1 Will Qos 3 [MQTT-3.1.2-14]", "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 04 1E k10 s1 'p' s1 'p' s1 'p'"} ]}, { "name": "10 Will topic with 0x0000", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F700000 s1 'p'"}]}, { "name": "10 Will topic with U+D800", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746FEDA080 s1 'p'"}]}, { "name": "10 Will topic with U+0001", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F700170 s1 'p'"}]}, { "name": "10 Will topic with U+001F", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F701F70 s1 'p'"}]}, { "name": "10 Will topic with U+007F", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F707F70 s1 'p'"}]}, { "name": "10 Will topic with U+009F", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746FC29F70 s1 'p'"}]}, { "name": "10 Will topic with U+FFFF", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746FEDBFBF s1 'p'"}]}, { "name": "10 Client ID with 0x0000", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F700000"}]}, { "name": "10 Client ID with U+D800", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746FEDA080"}]}, { "name": "10 Client ID with U+0001", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F700170"}]}, { "name": "10 Client ID with U+001F", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F701F70"}]}, { "name": "10 Client ID with U+007F", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F707F70"}]}, { "name": "10 Client ID with U+009F", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746FC29F70"}]}, { "name": "10 Client ID with U+FFFF", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746FEDBFBF"}]}, { "name": "10 [MQTT-3.1.2-18]", "msgs":[{"type":"send", "payload":"10 r16 s4 'MQTT' 04 02 k10 s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-19]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 82 k10 s1 'p'"}]}, { "name": "10 Username with 0x0000", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F700000"}]}, { "name": "10 Username with 0xD800", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746FEDA080"}]}, { "name": "10 Username with 0x0001", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F700170"}]}, { "name": "10 Username with 0x001F", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F701F70"}]}, { "name": "10 Username with 0x007F", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F707F70"}]}, { "name": "10 Username with 0x009F", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746FC29F70"}]}, { "name": "10 Username with 0xFFFF", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746FEDBFBF"}]}, { "name": "10 Username zero length ok", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 04 82 k10 s1 'p' s0"}, {"type":"recv", "payload":"20 r2 00 00", "comment": "CONNACK"} ]}, { "name": "10 Username flag 1 Password flag 1 ok", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 04 C2 k10 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r2 00 00", "comment": "CONNACK"} ]}, { "name": "10 [MQTT-3.1.2-20]", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 04 82 k10 s1 'p' s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-21]", "msgs":[{"type":"send", "payload":"10 r16 s4 'MQTT' 04 C2 k10 s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-22]", "msgs":[{"type":"send", "payload":"10 r16 s4 'MQTT' 04 42 k10 s1 'p' s1 'p'"}]}, { "name": "10 Password with 0x0000", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r23 00 04 'MQTT' 04 C2 k10 s1 'p' s1 'p' s5 746F700000"}, {"type":"recv", "payload":"20 r2 00 00", "comment": "CONNACK"} ]}, { "name": "duplicate CONNECT", "connect":true, "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 02 k10 s1 'p'", "comment":"minimal valid duplicate CONNECT"}]}, { "name": "NanoMQ CWE-119", "msgs":[{"type":"send", "payload":"10 r7 s4 'MQTT' 04 C2 k60 s11 'test-python' s5 'admin' s8 'password'"}]} ] }, { "group": "v5.0 CONNECT", "ver":5, "connect":false, "tests": [ { "name": "10 ok ", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r14 s4 'MQTT' 05 02 k10 v0 s1 'p'", "comment":"minimal valid CONNECT"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "10 remaining length 5 bytes", "msgs":[ {"type":"send", "payload":"10 r268435456 s4 'MQTT' 05 02 k10 s1 'p'", "comment":"CONNECT"} ]}, { "name": "10 Username flag 1 ok", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 82 k10 v0 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "10 Client ID with 0x0000", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 v0 s5 746F700000"}, {"type":"recv", "payload":"20 r3 00 85 00"} ]}, { "name": "10 Client ID with U+D800", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 v0 s5 746FEDA080"}, {"type":"recv", "payload":"20 r3 00 85 00"} ]}, { "name": "10 Client ID with U+0001", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 v0 s5 746F700170"}, {"type":"recv", "payload":"20 r3 00 85 00"} ]}, { "name": "10 Client ID with U+001F", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 v0 s5 746F701F70"}, {"type":"recv", "payload":"20 r3 00 85 00"} ]}, { "name": "10 Client ID with U+007F", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 v0 s5 746F707F70"}, {"type":"recv", "payload":"20 r3 00 85 00"} ]}, { "name": "10 Client ID with U+009F", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 v0 s5 746FC29F70"}, {"type":"recv", "payload":"20 r3 00 85 00"} ]}, { "name": "10 Client ID with U+FFFF", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 v0 s5 746FEDBFBF"}, {"type":"recv", "payload":"20 r3 00 85 00"} ]}, { "name": "10 [MQTT-3.1.2-16]", "msgs":[ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 v0 s1 'q' s1 'q'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "10 [MQTT-3.1.2-17]", "msgs":[ {"type":"send", "payload":"10 r14 s4 'MQTT' 05 82 k10 v0 s1 'p'"} ]}, { "name": "10 Username with 0x0000", "msgs":[ {"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 v0 s1 'p' s5 746F700000"} ]}, { "name": "10 Username with 0xD800", "msgs":[ {"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 v0 s1 'p' s5 746FEDA080"} ]}, { "name": "10 Username with 0x0001", "msgs":[ {"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 v0 s1 'p' s5 746F700170"} ]}, { "name": "10 Username with 0x001F", "msgs":[ {"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 v0 s1 'p' s5 746F701F70"} ]}, { "name": "10 Username with 0x007F", "msgs":[ {"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 v0 s1 'p' s5 746F707F70"} ]}, { "name": "10 Username with 0x009F", "msgs":[ {"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 v0 s1 'p' s5 746FC29F70"} ]}, { "name": "10 Username with 0xFFFF", "msgs":[ {"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 v0 s1 'p' s5 746FEDBFBF"} ]}, { "name": "10 [MQTT-3.1.2-18]", "msgs":[ {"type":"send", "payload":"10 r20 s4 'MQTT' 05 82 k10 v0 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "10 [MQTT-3.1.2-19]", "msgs":[ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 C2 k10 v0 s1 'p' s1 'p'"} ]}, { "name": "10 Will flag 1 ok", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r21 s4 'MQTT' 05 06 k10 v0 s1 'p' 00 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "tiny max packet", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 27 L2 s1 'p'"}]} ] }, { "group": "v5.0 CONNECT EXTENDED AUTH", "ver":5, "connect":false, "tests": [ { "name": "unsupported authentication method", "msgs":[ {"type":"send", "payload":"10 r35 s4 'MQTT' 05 02 k10 15 15000B756E737570706F7274656416000474657374 s1 'p'", "comment":"auth-method:unsupported, auth-data:test"}, {"type":"recv", "payload":"20 r3 00 8C 00", "comment": "CONNACK Bad authentication method"} ]} ] }, { "group": "v5.0 CONNECT ALLOWED PROPERTIES", "ver":5, "connect":false, "tests": [ { "name": "session-expiry-interval (four byte integer)", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 11 L1 s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "2*session-expiry-interval (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 02 k10 0A 11 L1 11 L1 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "session-expiry-interval (four byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 11 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "receive-maximum (two byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 21 0101 s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "receive-maximum (two byte integer) 0 value", "msgs": [ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 21 0000 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 21 0101 21 0101 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 21 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "maximum-packet-size (four byte integer)", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 27 10000001 s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "2*maximum-packet-size (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 02 k10 0A 27 10000001 27 10000001 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "maximum-packet-size (four byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 27 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "maximum-packet-size (four byte integer) 0 value", "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 27 L0 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "maximum-packet-size (four byte integer) FFFFFFFF value", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 27 FFFFFFFF s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "topic-alias-maximum (two byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 22 0101 s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "topic-alias-maximum (two byte integer) 0 value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 22 0000 s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "2*topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 22 0101 22 0101 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 22 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "request-response-information (byte)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 19 01 s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "2*request-response-information (byte)", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 19 01 19 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "request-response-information (byte) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 19 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "request-response-information (byte) 2 value", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 19 02 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "request-problem-information (byte)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 17 01 s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "2*request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 17 01 17 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 17 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "request-problem-information (byte) 2 value", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 17 02 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"10 r21 s4 'MQTT' 05 02 k10 07 26 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "2*user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"10 r28 s4 'MQTT' 05 02 k10 0E 26 s1 'p' s1 'p' 26 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "user-property missing value", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 26 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "user-property missing key,value", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 26 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "user-property empty key", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 26 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "user-property empty value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 26 s1 'p' 0000 s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "user-property empty key,value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 26 0000 0000 s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 15 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 02 k10 08 15 s1 'p' 15 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "authentication-data (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 15 s1 'p' 16 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "authentication-data (UTF-8 string) no authentication-method", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 16 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*authentication-data (UTF-8 string)", "msgs": [ {"type":"send", "payload":"10 r26 s4 'MQTT' 05 02 k10 0C 15 s1 'p' 16 s1 'p' 16 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]} ] }, { "group": "v5.0 CONNECT DISALLOWED PROPERTIES", "ver":5, "connect":false, "tests": [ { "name": "payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 01 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 24 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 24 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "retain-available (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 25 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 25 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 28 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 28 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 29 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 29 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 2A 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 2A 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 00 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 04 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 05 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 06 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 07 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0A 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0C 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0D 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0E 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0F 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 10 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 14 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 1B 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 1D 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 1E 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 20 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 7F 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 8000 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 8001 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 FF7F 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 808001 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 FFFF7F 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 80808001 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 FFFFFF7F 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "unknown-property 0x8080808001 (byte)", "msgs": [ {"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 8080808001 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "message-expiry-interval (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 02 10000001 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*message-expiry-interval (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 02 k10 0A 02 10000001 02 10000001 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "message-expiry-interval (four byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 02 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "message-expiry-interval (four byte integer) 0 value", "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 02 L0 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "message-expiry-interval (four byte integer) FFFFFFFF value", "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 02 FFFFFFFF s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "will-delay-interval (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 18 10000001 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*will-delay-interval (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 02 k10 0A 18 10000001 18 10000001 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "will-delay-interval (four byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 18 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "will-delay-interval (four byte integer) 0 value", "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 18 L0 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "will-delay-interval (four byte integer) FFFFFFFF value", "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 18 FFFFFFFF s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "server-keep-alive (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 13 0001 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*server-keep-alive (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 13 0001 13 0001 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "server-keep-alive (two byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 13 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "topic-alias (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 23 0001 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*topic-alias (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 23 0001 23 0001 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "topic-alias (two byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 23 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "content-type (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 03 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "content-type (UTF-8 string) missing", "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 03 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "content-type (UTF-8 string) empty", "msgs":[ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 03 0000 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "response-topic (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 08 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "response-topic (UTF-8 string) missing", "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 08 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "response-topic (UTF-8 string) empty", "msgs":[ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 08 0000 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "assigned-client-identifier (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 12 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "assigned-client-identifier (UTF-8 string) missing", "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 12 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "assigned-client-identifier (UTF-8 string) empty", "msgs":[ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 12 0000 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "response-information (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 1A s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "response-information (UTF-8 string) missing", "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 1A s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "response-information (UTF-8 string) empty", "msgs":[ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 1A 0000 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "correlation-data (binary)", "msgs":[ {"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 09 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "correlation-data (binary) missing", "msgs":[ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 09 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "correlation-data (binary) empty", "msgs":[ {"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 09 0000 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, {"name": "subscription-identifier (variable byte integer)", "msgs": [ {"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0B 01 s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, {"name": "subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 0B s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]} ] }, { "group": "v5.0 WILL ALLOWED PROPERTIES", "ver":5, "connect":false, "tests": [ { "name": "payload-format-indicator (byte)", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 v0 s1 'p' 02 01 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "payload-format-indicator (byte) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*payload-format-indicator (byte)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 01 01 01 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "message-expiry-interval (four byte integer)", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r26 s4 'MQTT' 05 06 k10 v0 s1 'p' 05 02 L1 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "2*message-expiry-interval (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r31 s4 'MQTT' 05 06 k10 v0 s1 'p' 0A 02 L1 02 L1 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "message-expiry-interval (four byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 02 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "will-delay-interval (four byte integer)", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r26 s4 'MQTT' 05 06 k10 v0 s1 'p' 05 18 L1 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "will-delay-interval (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r31 s4 'MQTT' 05 06 k10 v0 s1 'p' 0A 18 L1 18 L1 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "will-delay-interval (four byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 18 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "content-type (UTF-8 string)", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 03 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "2*content-type (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 v0 s1 'p' 08 03 s1 'p' 03 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "content-type (UTF-8 string) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 03 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "content-type (UTF-8 string) empty", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 03 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "response-topic (UTF-8 string)", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 08 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "2*response-topic (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 v0 s1 'p' 08 08 s1 'p' 08 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "response-topic (UTF-8 string) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 08 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "response-topic (UTF-8 string) empty", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 08 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00", "comment": "CONNACK"} ]}, { "name": "correlation-data (binary)", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 09 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "2*correlation-data (binary)", "msgs":[ {"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 v0 s1 'p' 08 09 s1 'p' 09 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "correlation-data (binary) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 09 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "correlation-data (binary) empty", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 09 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "user-property", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r28 s4 'MQTT' 05 06 k10 v0 s1 'p' 07 26 s1 'p' s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "2*user-property", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r35 s4 'MQTT' 05 06 k10 v0 s1 'p' 0E 26 s1 'p' s1 'p' 26 s1 'p' s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "user-property missing value", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 26 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "user-property missing key,value", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 26 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "user-property empty key", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 v0 s1 'p' 06 26 0000 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "user-property empty value", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 v0 s1 'p' 06 26 s1 'p' 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]}, { "name": "user-property empty key,value", "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r26 s4 'MQTT' 05 06 k10 v0 s1 'p' 05 26 0000 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"} ]} ] }, { "group": "v5.0 WILL DISALLOWED PROPERTIES", "ver":5, "connect":false, "tests": [ { "name": "request-problem-information (byte)", "msgs":[ {"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 v0 s1 'p' 02 17 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "request-problem-information (byte) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 17 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*request-problem-information (byte)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 17 01 17 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "request-response-information (byte)", "msgs":[ {"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 v0 s1 'p' 02 19 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "request-response-information (byte) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 19 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*request-response-information (byte)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 19 01 19 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "maximum-qos (byte)", "msgs":[ {"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 v0 s1 'p' 02 24 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "maximum-qos (byte) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 24 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*maximum-qos (byte)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 24 01 24 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "retain-available (byte)", "msgs":[ {"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 v0 s1 'p' 02 25 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "retain-available (byte) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 25 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*retain-available (byte)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 25 01 25 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "wildcard-subscription-available (byte)", "msgs":[ {"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 v0 s1 'p' 02 28 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "wildcard-subscription-available (byte) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 28 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*wildcard-subscription-available (byte)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 28 01 28 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "subscription-identifier-available (byte)", "msgs":[ {"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 v0 s1 'p' 02 29 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "subscription-identifier-available (byte) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 29 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*subscription-identifier-available (byte)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 29 01 29 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "shared-subscription-available (byte)", "msgs":[ {"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 v0 s1 'p' 02 2A 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "shared-subscription-available (byte) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 2A s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*shared-subscription-available (byte)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 2A 01 2A 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "server-keep-alive (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 13 0001 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "server-keep-alive (two byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 13 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*server-keep-alive (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 v0 s1 'p' 06 13 0001 13 0001 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "receive-maximum (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 21 0001 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "receive-maximum (two byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 21 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*receive-maximum (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 v0 s1 'p' 06 21 0001 21 0001 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "topic-alias-maximum (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 22 0001 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "topic-alias-maximum (two byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 22 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*topic-alias-maximum (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 v0 s1 'p' 06 22 0001 22 0001 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "topic-alias (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 23 0001 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "topic-alias (two byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 23 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*topic-alias (two byte integer)", "msgs":[ {"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 v0 s1 'p' 06 23 0001 23 0001 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "session-expiry-interval (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r26 s4 'MQTT' 05 06 k10 v0 s1 'p' 05 11 L1 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "session-expiry-interval (four byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 11 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*session-expiry-interval (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r31 s4 'MQTT' 05 06 k10 v0 s1 'p' 0A 11 L1 11 L1 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "maximum-packet-size (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r26 s4 'MQTT' 05 06 k10 v0 s1 'p' 05 27 L1 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "maximum-packet-size (four byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 27 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "2*maximum-packet-size (four byte integer)", "msgs":[ {"type":"send", "payload":"10 r31 s4 'MQTT' 05 06 k10 v0 s1 'p' 0A 27 L1 27 L1 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "assigned-client-identifier (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 12 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*assigned-client-identifier (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 v0 s1 'p' 08 12 s1 'p' 12 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "assigned-client-identifier (UTF-8 string) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 12 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "assigned-client-identifier (UTF-8 string) empty", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 12 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "authentication-method (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 15 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*authentication-method (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 v0 s1 'p' 08 15 s1 'p' 15 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "authentication-method (UTF-8 string) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 15 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "authentication-method (UTF-8 string) empty", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 15 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "response-information (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 1A s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*response-information (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 v0 s1 'p' 08 1A s1 'p' 1A s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "response-information (UTF-8 string) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 1A s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "response-information (UTF-8 string) empty", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 1A 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "server-reference (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 1C s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*server-reference (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 v0 s1 'p' 08 1C s1 'p' 1C s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "server-reference (UTF-8 string) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 1C s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "server-reference (UTF-8 string) empty", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 1C 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "reason-string (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 1F s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*reason-string (UTF-8 string)", "msgs":[ {"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 v0 s1 'p' 08 1F s1 'p' 1F s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "reason-string (UTF-8 string) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 1F s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "reason-string (UTF-8 string) empty", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 1F 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "authentication-data (binary)", "msgs":[ {"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 v0 s1 'p' 04 16 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "2*authentication-data (binary)", "msgs":[ {"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 v0 s1 'p' 08 16 s1 'p' 16 s1 'p' s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "authentication-data (binary) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 16 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]}, { "name": "authentication-data (binary) empty", "msgs":[ {"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 v0 s1 'p' 03 16 0000 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "subscription-identifier (variable byte integer)", "msgs":[ {"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 v0 s1 'p' 02 0B 01 s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 82 00"} ]}, { "name": "subscription-identifier (variable byte integer) missing", "msgs":[ {"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 v0 s1 'p' 01 0B s1 'p' s1 'p'"}, {"type":"recv", "payload":"20 r3 00 81 00"} ]} ] } ] ================================================ FILE: test/broker/data/DISCONNECT.json ================================================ [ { "group": "v3.1.1 DISCONNECT", "ver":4, "tests": [ { "name": "E0 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"E0 r0"}]}, { "name": "E0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"E0 r268435456"}]}, { "name": "E0 long", "msgs": [{"type":"send", "payload":"E0 r1 00"}]}, { "name": "E0 valid", "msgs": [{"type":"send", "payload":"E0 r0"}]}, { "name": "E1 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E1 r0"}]}, { "name": "E2 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E2 r0"}]}, { "name": "E4 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E4 r0"}]}, { "name": "E8 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E8 r0"}]} ] }, { "group": "v5.0 DISCONNECT", "ver":5, "tests": [ { "name": "E0 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"E0 r0"}]}, { "name": "E0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"E0 r268435456"}]}, { "name": "E0 long", "msgs": [{"type":"send", "payload":"E0 r1 00"}]}, { "name": "E0 valid", "msgs": [{"type":"send", "payload":"E0 r0"}]}, { "name": "E1 [MQTT-3.14.1-1]", "msgs": [ {"type":"send", "payload":"E1 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E2 [MQTT-3.14.1-1]", "msgs": [ {"type":"send", "payload":"E2 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E4 [MQTT-3.14.1-1]", "msgs": [ {"type":"send", "payload":"E4 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E8 [MQTT-3.14.1-1]", "msgs": [ {"type":"send", "payload":"E8 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 RC=0x00 (normal disconnection)", "msgs": [{"type":"send", "payload":"E0 r1 00"}]}, { "name": "E0 RC=0x01 (qos 1 - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 01"}]}, { "name": "E0 RC=0x04 (disconnect with will)", "msgs": [{"type":"send", "payload":"E0 r1 04"}]}, { "name": "E0 RC=0x05 (invalid)", "msgs": [{"type":"send", "payload":"E0 r1 05"}]}, { "name": "E0 RC=0x80 (unspecified error)", "msgs": [{"type":"send", "payload":"E0 r1 80"}]}, { "name": "E0 RC=0x81 (malformed packet)", "msgs": [{"type":"send", "payload":"E0 r1 81"}]}, { "name": "E0 RC=0x82 (protocol error)", "msgs": [{"type":"send", "payload":"E0 r1 82"}]}, { "name": "E0 RC=0x83 (implementation specific error)", "msgs": [{"type":"send", "payload":"E0 r1 83"}]}, { "name": "E0 RC=0x87 (not authorised - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 87"}]}, { "name": "E0 RC=0x89 (server busy - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 89"}]}, { "name": "E0 RC=0x8B (server shutting down - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 8B"}]}, { "name": "E0 RC=0x8D (keep alive timeout - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 8D"}]}, { "name": "E0 RC=0x8E (session taken over - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 8E"}]}, { "name": "E0 RC=0x8F (topic filter invalid - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 8F"}]}, { "name": "E0 RC=0x90 (topic name invalid)", "msgs": [{"type":"send", "payload":"E0 r1 90"}]}, { "name": "E0 RC=0x93 (receive maximum exceeded)", "msgs": [{"type":"send", "payload":"E0 r1 93"}]}, { "name": "E0 RC=0x94 (topic alias invalid)", "msgs": [{"type":"send", "payload":"E0 r1 94"}]}, { "name": "E0 RC=0x95 (packet too large)", "msgs": [{"type":"send", "payload":"E0 r1 95"}]}, { "name": "E0 RC=0x96 (message rate too high)", "msgs": [{"type":"send", "payload":"E0 r1 96"}]}, { "name": "E0 RC=0x97 (quota exceeded)", "msgs": [{"type":"send", "payload":"E0 r1 97"}]}, { "name": "E0 RC=0x98 (administrative action)", "msgs": [{"type":"send", "payload":"E0 r1 98"}]}, { "name": "E0 RC=0x99 (payload format invalid)", "msgs": [{"type":"send", "payload":"E0 r1 99"}]}, { "name": "E0 RC=0x9A (retain not supported - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9A"}]}, { "name": "E0 RC=0x9B (qos not supported - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9B"}]}, { "name": "E0 RC=0x9C (use another server - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9C"}]}, { "name": "E0 RC=0x9D (server moved - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9D"}]}, { "name": "E0 RC=0x9E (shared subs not supported - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9E"}]}, { "name": "E0 RC=0x9F (connection rate exceeded - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9F"}]}, { "name": "E0 RC=0xA0 (maximum connect time - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 A0"}]}, { "name": "E0 RC=0xA1 (subscription ids not supported - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 A1"}]}, { "name": "E0 RC=0xA2 (wildcard subs not supported - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 A2"}]}, { "name": "E0 RC=0x82 PL=0", "msgs": [{"type":"send", "payload":"E0 r2 82 00"}]}, { "name": "E0 RC=0x00 PL=1 P=0", "msgs": [ {"type":"send", "payload":"E0 r3 0001 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 RC=0x00 PL=1 P=0x11", "msgs": [ {"type":"send", "payload":"E0 r3 0001 11"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 RC=0x00 PL=2 P=0x11", "msgs": [ {"type":"send", "payload":"E0 r4 0002 1100"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 RC=0x00 PL=3 P=0x11", "msgs": [ {"type":"send", "payload":"E0 r5 0003 110000"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 RC=0x00 PL=4 P=0x11", "msgs": [ {"type":"send", "payload":"E0 r6 0004 11000000"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 RC=0x00 PL=5 P=0x11", "msgs": [ {"type":"send", "payload":"E0 r7 0005 1100000000"} ]}, { "name": "E0 non-zero session expiry", "connect":false, "msgs": [ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 11 L0 s1 'p'", "comment":"CONNECT with session expiry=0"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"}, {"type":"send", "payload":"E0 r7 00 05 11 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] }, { "group": "v5.0 DISCONNECT ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "E0 with reason-string property", "msgs": [{"type":"send", "payload":"E0 r6 00 04 1F s1 'p'"}]}, { "name": "E0 with 2*reason-string property (invalid)", "msgs": [ {"type":"send", "payload":"E0 r10 00 08 1F s1 'p' 1F s1 'q'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with reason-string property missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 1F"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with reason-string property empty", "msgs": [ {"type":"send", "payload":"E0 r5 00 03 1F 0000"} ]}, { "name": "E0 with user-property", "msgs": [{"type":"send", "payload":"E0 r9 00 07 26 s1 'p' s1 'q'"}]}, { "name": "E0 with user-property missing value", "msgs": [ {"type":"send", "payload":"E0 r6 00 04 26 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with user-property missing key,value", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 26"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with user-property empty key", "msgs": [ {"type":"send", "payload":"E0 r8 00 06 26 0000 s1 'p'"} ]}, { "name": "E0 with user-property empty key,value", "msgs": [ {"type":"send", "payload":"E0 r8 00 06 26 s1 'p' 0000"} ]}, { "name": "E0 with user-property empty key,value", "msgs": [ {"type":"send", "payload":"E0 r7 00 05 26 0000 0000"} ]}, { "name": "E0 with session-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"E0 r7 00 05 1100000000"}]}, { "name": "E0 with 2*session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"E0 r12 00 0A 1100000000 1100000000"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with session-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 11"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with server-reference (UTF-8 string)", "msgs": [{"type":"send", "payload":"E0 r6 00 04 1C s1 'p'"}]}, { "name": "E0 with 2*server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"E0 r10 00 08 1C s1 'p' 1C s1 'q'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with server-reference (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 1C"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with server-reference (UTF-8 string) empty", "msgs": [ {"type":"send", "payload":"E0 r5 00 03 1C 0000"} ]} ] }, { "group": "v5.0 DISCONNECT DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "E0 with payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0100"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 1700"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 2400"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with retain-available (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 2500"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 2800"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 2900"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 2A00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 17"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 24"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 25"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 28"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 29"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 2A"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with message-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"E0 r7 00 05 0200000001"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"E0 r7 00 05 1800000001"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"E0 r7 00 05 2700000001"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with message-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 02"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with will-delay-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 18"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with maximum-packet-size (four byte integer) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 27"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"E0 r6 00 04 03 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"E0 r6 00 04 08 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"E0 r6 00 04 12 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"E0 r6 00 04 15 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"E0 r6 00 04 1A s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with content-type (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 03"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with response-topic (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 08"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with assigned-client-identifier (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 12"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 15"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with response-information (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 1A"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"E0 r6 00 04 09 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"E0 r6 00 04 16 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with correlation-data (binary data) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 0109"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with authentication-data (binary data) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 0116"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with subscription-identifier (variable byte integer)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0B01"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 0B"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"E0 r5 00 03 130101"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"E0 r5 00 03 210101"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"E0 r5 00 03 220101"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"E0 r5 00 03 230101"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "E0 with server-keep-alive (two byte integer) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 13"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 21"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 22"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with topic-alias (two byte integer) missing", "msgs": [ {"type":"send", "payload":"E0 r3 00 01 23"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0001"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0401"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0501"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0601"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0701"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0A01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0C01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0D01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0E01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 0F01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 1001"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 1401"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 1B01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 1D01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 1E01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 2001"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"E0 r4 00 02 7F01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"E0 r5 00 03 800001"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"E0 r5 00 03 800101"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"E0 r5 00 03 FF7F01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"E0 r6 00 04 80800101"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"E0 r6 00 04 FFFF7F01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"E0 r7 00 05 8080800101"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "E0 with unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"E0 r7 00 05 FFFFFF7F01"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] } ] ================================================ FILE: test/broker/data/FLOW.json ================================================ [ { "comment": "FLOW TESTS ARE INCOMPLETE", "group": "v3.1.1 FLOW", "ver":4, "tests": [ { "name": "QoS 0 self receive ok", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 01", "comment":"SUBSCRIBE, 'p' qos1"}, {"type":"recv", "payload":"90 r3 m1234 01", "comment":"SUBACK"}, {"type":"send", "payload":"30 r10 s1 'p' 'message'", "comment":"PUBLISH send"}, {"type":"recv", "payload":"30 r10 s1 'p' 'message'", "comment":"PUBLISH receive"} ]}, { "name": "QoS 1 receive ok", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 01", "comment":"SUBSCRIBE, 'p' qos1"}, {"type":"recv", "payload":"90 r3 m1234 01", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":1, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"32 r12 s1 'p' m1 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"40 r2 m1", "comment":"PUBACK"} ]}, { "name": "QoS 1 PUBLISH-PUBREC", "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 01", "comment":"SUBSCRIBE, 'p' qos1"}, {"type":"recv", "payload":"90 r3 m1234 01", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":1, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"32 r12 s1 'p' m1 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"50 r2 m1", "comment":"PUBREC"} ]}, { "name": "QoS 1 PUBLISH-PUBCOMP", "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 01", "comment":"SUBSCRIBE, 'p' qos1"}, {"type":"recv", "payload":"90 r3 m1234 01", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":1, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"32 r12 s1 'p' m1 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"70 r2 m1", "comment":"PUBCOMP"} ]}, { "name": "QoS 2 receive ok", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 02", "comment":"SUBSCRIBE, 'p' qos2"}, {"type":"recv", "payload":"90 r3 m1234 02", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":2, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"34 r12 s1 'p' m1 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"50 r2 m1", "comment":"PUBREC"}, {"type":"recv", "payload":"62 r2 m1", "comment":"PUBREL"}, {"type":"send", "payload":"70 r2 m1", "comment":"PUBCOMP"} ]}, { "name": "QoS 2 PUBLISH-PUBACK", "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 02", "comment":"SUBSCRIBE, 'p' qos2"}, {"type":"recv", "payload":"90 r3 m1234 02", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":2, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"34 r12 s1 'p' m1 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"40 r2 m1", "comment": "PUBACK (should be PUBREC)"} ]}, { "name": "QoS 2 PUBLISH-PUBCOMP", "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 02", "comment":"SUBSCRIBE, 'p' qos2"}, {"type":"recv", "payload":"90 r3 m1234 02", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":2, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"34 r12 s1 'p' m1 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"70 r2 m1", "comment": "PUBCOMP (should be PUBREC)"} ]}, { "name": "QoS 2 PUBLISH-PUBREC-PUBREL-PUBACK", "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 02", "comment":"SUBSCRIBE, 'p' qos2"}, {"type":"recv", "payload":"90 r3 m1234 02", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":2, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"34 r12 s1 'p' m1 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"50 r2 m1", "comment": "PUBREC)"}, {"type":"recv", "payload":"62 r2 m1", "comment": "PUBREL)"}, {"type":"send", "payload":"40 r2 m1", "comment": "PUBACK (should be PUBCOMP))"} ]}, { "name": "QoS 2 PUBLISH-PUBREC-PUBREL-PUBREC", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 02", "comment":"SUBSCRIBE, 'p' qos2"}, {"type":"recv", "payload":"90 r3 m1234 02", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":2, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"34 r12 s1 'p' m1 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"50 r2 m1", "comment": "PUBREC)"}, {"type":"recv", "payload":"62 r2 m1", "comment": "PUBREL)"}, {"type":"send", "payload":"50 r2 m1", "comment": "PUBREC (should be PUBCOMP))"}, {"type":"recv", "payload":"62 r2 m1", "comment": "PUBREL)"} ]} ] }, { "group": "v5.0 FLOW", "ver":5, "tests": [ { "name": "QoS 0 self receive ok", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 00 s1 'p' 01", "comment":"SUBSCRIBE, 'p' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"send", "payload":"30 r11 s1 'p' 00 'message'", "comment":"PUBLISH send"}, {"type":"recv", "payload":"30 r11 s1 'p' 00 'message'", "comment":"PUBLISH receive"} ]}, { "name": "QoS 1 receive ok", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 00 s1 'p' 01", "comment":"SUBSCRIBE, 'p' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":1, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"32 r13 s1 'p' m1 00 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"40 r2 m1", "comment":"PUBACK"} ]}, { "name": "QoS 1 PUBLISH-PUBREC", "msgs": [ {"type":"send", "payload":"82 r7 m1234 00 s1 'p' 01", "comment":"SUBSCRIBE, 'p' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":1, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"32 r13 s1 'p' m1 00 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"50 r2 m1", "comment":"PUBREC"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "QoS 1 PUBLISH-PUBCOMP", "msgs": [ {"type":"send", "payload":"82 r7 m1234 00 s1 'p' 01", "comment":"SUBSCRIBE, 'p' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":1, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"32 r13 s1 'p' m1 00 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"70 r2 m1", "comment":"PUBCOMP"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "QoS 2 receive ok", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 00 s1 'p' 02", "comment":"SUBSCRIBE, 'p' qos2"}, {"type":"recv", "payload":"90 r4 m1234 00 02", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":2, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"34 r13 s1 'p' m1 00 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"50 r2 m1", "comment":"PUBREC"}, {"type":"recv", "payload":"62 r2 m1", "comment":"PUBREL"}, {"type":"send", "payload":"70 r2 m1", "comment":"PUBCOMP"} ]}, { "name": "QoS 2 PUBLISH-PUBACK", "msgs": [ {"type":"send", "payload":"82 r7 m1234 00 s1 'p' 02", "comment":"SUBSCRIBE, 'p' qos2"}, {"type":"recv", "payload":"90 r4 m1234 00 02", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":2, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"34 r13 s1 'p' m1 00 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"40 r2 m1", "comment": "PUBACK (should be PUBREC)"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "QoS 2 PUBLISH-PUBCOMP", "msgs": [ {"type":"send", "payload":"82 r7 m1234 00 s1 'p' 02", "comment":"SUBSCRIBE, 'p' qos2"}, {"type":"recv", "payload":"90 r4 m1234 00 02", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":2, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"34 r13 s1 'p' m1 00 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"70 r2 m1", "comment": "PUBCOMP (should be PUBREC)"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "QoS 2 PUBLISH-PUBREC-PUBREL-PUBACK", "msgs": [ {"type":"send", "payload":"82 r7 m1234 00 s1 'p' 02", "comment":"SUBSCRIBE, 'p' qos2"}, {"type":"recv", "payload":"90 r4 m1234 00 02", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":2, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"34 r13 s1 'p' m1 00 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"50 r2 m1", "comment": "PUBREC)"}, {"type":"recv", "payload":"62 r2 m1", "comment": "PUBREL)"}, {"type":"send", "payload":"40 r2 m1", "comment": "PUBACK (should be PUBCOMP))"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "QoS 2 PUBLISH-PUBREC-PUBREL-PUBREC", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 00 s1 'p' 02", "comment":"SUBSCRIBE, 'p' qos2"}, {"type":"recv", "payload":"90 r4 m1234 00 02", "comment":"SUBACK"}, {"type":"publish", "topic":"p", "qos":2, "payload":"message", "comment":"helper"}, {"type":"recv", "payload":"34 r13 s1 'p' m1 00 'message'", "comment":"PUBLISH receive"}, {"type":"send", "payload":"50 r2 m1", "comment": "PUBREC)"}, {"type":"recv", "payload":"62 r2 m1", "comment": "PUBREL)"}, {"type":"send", "payload":"50 r2 m1", "comment": "PUBREC (should be PUBCOMP))"}, {"type":"recv", "payload":"62 r2 m1", "comment": "PUBREL)"} ]} ] }, { "group": "v5.0 FLOW WITH PROPERTIES", "ver":5, "tests": [ { "name": "payload-format-indicator=1 (byte)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r11 m1234 00 s5 'topic' 01", "comment":"SUBSCRIBE, 'topic' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"send", "payload":"30 r17 s5 'topic' 02 0101 'payload'", "comment": "PUBLISH send"}, {"type":"recv", "payload":"30 r17 s5 'topic' 02 0101 'payload'", "comment": "PUBLISH recv"} ]}, { "name": "message-expiry-interval=1 (four byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r11 m1234 00 s5 'topic' 01", "comment":"SUBSCRIBE, 'topic' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"send", "payload":"30 r20 s5 'topic' 05 02 L1 'payload'"}, {"type":"recv", "payload":"30 r20 s5 'topic' 05 02 L1 'payload'"} ]}, { "name": "topic-alias", "expect_disconnect":false, "comment":"broker doesn't initiate topic alias", "msgs": [ {"type":"send", "payload":"82 r11 m1234 00 s5 'topic' 01", "comment":"SUBSCRIBE, 'topic' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"send", "payload":"30 r18 s5 'topic' 03 23 s1 'payload'", "comment":"PUBLISH with topic alias 1"}, {"type":"recv", "payload":"30 r15 s5 'topic' 00 'payload'", "comment":"PUBLISH receive 1"}, {"type":"send", "payload":"30 r13 s0 03 23 s1 'payload'", "comment":"PUBLISH with topic alias 1, no topic"}, {"type":"recv", "payload":"30 r15 s5 'topic' 00 'payload'", "comment":"PUBLISH receive 2"} ]}, { "name": "response-topic", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r11 m1234 00 s5 'topic' 01", "comment":"SUBSCRIBE, 'topic' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"send", "payload":"30 r19 s5 'topic' 04 08 s1 'p' 'payload'"}, {"type":"recv", "payload":"30 r19 s5 'topic' 04 08 s1 'p' 'payload'"} ]}, { "name": "correlation-data", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r11 m1234 00 s5 'topic' 01", "comment":"SUBSCRIBE, 'topic' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"send", "payload":"30 r19 s5 'topic' 04 09 s1 'p' 'payload'"}, {"type":"recv", "payload":"30 r19 s5 'topic' 04 09 s1 'p' 'payload'"} ]}, { "name": "user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r11 m1234 00 s5 'topic' 01", "comment":"SUBSCRIBE, 'topic' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"send", "payload":"30 r22 s5 'topic' 07 26 s1 'p' s1 'q' 'payload'"}, {"type":"recv", "payload":"30 r22 s5 'topic' 07 26 s1 'p' s1 'q' 'payload'"} ]}, { "name": "subscription-identifier", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r13 m1234 02 0B01 s5 'topic' 01", "comment":"SUBSCRIBE, 'topic' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"send", "payload":"30 r15 s5 'topic' 00 'payload'"}, {"type":"recv", "payload":"30 r17 s5 'topic' 02 0B01 'payload'"} ]}, { "name": "content-type", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r11 m1234 00 s5 'topic' 01", "comment":"SUBSCRIBE, 'topic' qos1"}, {"type":"recv", "payload":"90 r4 m1234 00 01", "comment":"SUBACK"}, {"type":"send", "payload":"30 r19 s5 'topic' 04 03 s1 'p' 'payload'"}, {"type":"recv", "payload":"30 r19 s5 'topic' 04 03 s1 'p' 'payload'"} ]} ] } ] ================================================ FILE: test/broker/data/FORBIDDEN.json ================================================ [ { "group": "v3.1.1 FORBIDDEN", "ver":4, "tests": [ { "name": "00 first packet", "connect": false, "msgs": [{"type":"send", "payload":"00 r0"}]}, { "name": "00 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"00 r268435456"}]}, { "name": "01 first packet", "connect": false, "msgs": [{"type":"send", "payload":"01 r0"}]}, { "name": "02 first packet", "connect": false, "msgs": [{"type":"send", "payload":"02 r0"}]}, { "name": "04 first packet", "connect": false, "msgs": [{"type":"send", "payload":"04 r0"}]}, { "name": "08 first packet", "connect": false, "msgs": [{"type":"send", "payload":"08 r0"}]}, { "name": "00 long", "msgs": [{"type":"send", "payload":"00 r1 00"}]}, { "name": "00", "msgs": [{"type":"send", "payload":"00 r0"}]}, { "name": "01", "msgs": [{"type":"send", "payload":"01 r0"}]}, { "name": "02", "msgs": [{"type":"send", "payload":"02 r0"}]}, { "name": "04", "msgs": [{"type":"send", "payload":"04 r0"}]}, { "name": "08", "msgs": [{"type":"send", "payload":"08 r0"}]} ] }, { "group": "v5.0 FORBIDDEN", "ver":5, "tests": [ { "name": "00 first packet", "connect": false, "msgs": [{"type":"send", "payload":"00 r0"}]}, { "name": "00 remaining length 5 bytes", "msgs":[ {"type":"send", "payload":"00 r268435456"}, {"type":"recv", "payload":"E0 r1 82", "comment":"DISCONNECT protocol error"} ]}, { "name": "01 first packet", "connect": false, "msgs": [{"type":"send", "payload":"01 r0"}]}, { "name": "02 first packet", "connect": false, "msgs": [{"type":"send", "payload":"02 r0"}]}, { "name": "04 first packet", "connect": false, "msgs": [{"type":"send", "payload":"04 r0"}]}, { "name": "08 first packet", "connect": false, "msgs": [{"type":"send", "payload":"08 r0"}]}, { "name": "00 long", "msgs": [ {"type":"send", "payload":"00 r1 00"}, {"type":"recv", "payload":"E0 r1 82", "comment":"DISCONNECT protocol error"} ]}, { "name": "00", "msgs": [ {"type":"send", "payload":"00 r0"}, {"type":"recv", "payload":"E0 r1 82", "comment":"DISCONNECT protocol error"} ]}, { "name": "01", "msgs": [ {"type":"send", "payload":"01 r0"}, {"type":"recv", "payload":"E0 r1 82", "comment":"DISCONNECT protocol error"} ]}, { "name": "02", "msgs": [ {"type":"send", "payload":"02 r0"}, {"type":"recv", "payload":"E0 r1 82", "comment":"DISCONNECT protocol error"} ]}, { "name": "04", "msgs": [ {"type":"send", "payload":"04 r0"}, {"type":"recv", "payload":"E0 r1 82", "comment":"DISCONNECT protocol error"} ]}, { "name": "08", "msgs": [ {"type":"send", "payload":"08 r0"}, {"type":"recv", "payload":"E0 r1 82", "comment":"DISCONNECT protocol error"} ]}, { "name": "0A with illegal length C0", "ver":5, "expect_disconnect":true, "msgs": [ {"type":"send", "payload":"0A C0"}, {"type":"recv", "payload":"E0 r1 82", "comment":"DISCONNECT protocol error"} ]} ] } ] ================================================ FILE: test/broker/data/PINGREQ.json ================================================ [ { "group": "v3.1.1 PINGREQ", "ver":4, "tests": [ { "name": "C0 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"C0 r0"}]}, { "name": "C0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"C0 r268435456"}]}, { "name": "C0 long", "msgs": [{"type":"send", "payload":"C00100"}]}, { "name": "C0 valid", "expect_disconnect": false, "msgs": [{"type":"send", "payload":"C0 r0"}, {"type":"recv", "payload":"D0 00"}]}, { "name": "C1", "msgs": [{"type":"send", "payload":"C1 r0"}]}, { "name": "C2", "msgs": [{"type":"send", "payload":"C2 r0"}]}, { "name": "C4", "msgs": [{"type":"send", "payload":"C4 r0"}]}, { "name": "C8", "msgs": [{"type":"send", "payload":"C8 r0"}]} ] }, { "group": "v5.0 PINGREQ", "ver":5, "tests": [ { "name": "C0 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"C0 r0"}]}, { "name": "C0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"C0 r268435456"}]}, { "name": "C0 long", "msgs": [{"type":"send", "payload":"C0 r1 00"}]}, { "name": "C0 valid", "expect_disconnect": false, "msgs": [{"type":"send", "payload":"C0 r0"}, {"type":"recv", "payload":"D0 00"}]}, { "name": "C1", "msgs": [ {"type":"send", "payload":"C1 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "C2", "msgs": [ {"type":"send", "payload":"C2 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "C4", "msgs": [ {"type":"send", "payload":"C4 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "C8", "msgs": [ {"type":"send", "payload":"C8 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] } ] ================================================ FILE: test/broker/data/PINGRESP.json ================================================ [ { "group": "v3.1.1 PINGRESP", "ver":4, "tests": [ { "name": "D0 [MQTT-3.1.0-1]", "connect": false, "msgs": [{"type":"send", "payload":"D0 r0"}]}, { "name": "D0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"D0 r268435456"}]}, { "name": "D0 long", "msgs": [{"type":"send", "payload":"D0 r1 00"}]}, { "name": "D0", "msgs": [{"type":"send", "payload":"D0 r0"}]}, { "name": "D1", "msgs": [{"type":"send", "payload":"D1 r0"}]}, { "name": "D2", "msgs": [{"type":"send", "payload":"D2 r0"}]}, { "name": "D4", "msgs": [{"type":"send", "payload":"D4 r0"}]}, { "name": "D8", "msgs": [{"type":"send", "payload":"D8 r0"}]} ] }, { "group": "v5.0 PINGRESP", "ver":5, "tests": [ { "name": "D0 [MQTT-3.1.0-1]", "connect": false, "msgs": [{"type":"send", "payload":"D0 r0"}]}, { "name": "D0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"D0 r268435456"}]}, { "name": "D0 long", "msgs": [{"type":"send", "payload":"D0 r1 00"}]}, { "name": "D0", "msgs": [ {"type":"send", "payload":"D0 r0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "D1", "msgs": [ {"type":"send", "payload":"D1 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "D2", "msgs": [ {"type":"send", "payload":"D2 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "D4", "msgs": [ {"type":"send", "payload":"D4 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "D8", "msgs": [ {"type":"send", "payload":"D8 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] } ] ================================================ FILE: test/broker/data/PUBACK.json ================================================ [ { "group": "v3.1.1 PUBACK", "ver":4, "tests": [ { "name": "40 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"40 r2 m1"}]}, { "name": "40 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"40 r268435456"}]}, { "name": "40 unsolicited long", "msgs": [{"type":"send", "payload":"40 r3 m1 00"}]}, { "name": "40 unsolicited mid 0", "msgs": [{"type":"send", "payload":"40 r2 m0"}]}, { "name": "40 unsolicited short 0", "msgs": [{"type":"send", "payload":"40 r0"}]}, { "name": "40 unsolicited short 1", "msgs": [{"type":"send", "payload":"40 r1 01"}]}, { "name": "40 unsolicited", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r2 m1"}]}, { "name": "41 unsolicited", "msgs": [{"type":"send", "payload":"41 r2 m1"}]}, { "name": "42 unsolicited", "msgs": [{"type":"send", "payload":"42 r2 m1"}]}, { "name": "44 unsolicited", "msgs": [{"type":"send", "payload":"44 r2 m1"}]}, { "name": "48 unsolicited", "msgs": [{"type":"send", "payload":"48 r2 m1"}]} ] }, { "group": "v5.0 PUBACK", "ver":5, "tests": [ { "name": "40 [MQTT-3.1.0-1] (no reason code)", "connect":false, "msgs": [{"type":"send", "payload":"40 r2 m1"}]}, { "name": "40 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"40 r268435456"}]}, { "name": "40 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"40 r3 m1 00"}]}, { "name": "40 unsolicited long", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 00 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 unsolicited mid 0", "msgs": [ {"type":"send", "payload":"40 r3 m0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 unsolicited short 0", "msgs": [ {"type":"send", "payload":"40 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 unsolicited short 1", "msgs": [ {"type":"send", "payload":"40 r1 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 unsolicited len=2", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r2 m1"}]}, { "name": "40 unsolicited len=3", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r3 m1 00"}]}, { "name": "40 unsolicited len=3 fail", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r3 m1 80"}]}, { "name": "40 unsolicited len=4 ok", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r4 m1 00 00"}]}, { "name": "40 unsolicited len=4 rc=fail", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r4 m1 80 00"}]}, { "name": "40 unsolicited len=4 rc=unknown", "msgs": [ {"type":"send", "payload":"40 r4 m1 FF 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 unsolicited len=4 short", "msgs": [ {"type":"send", "payload":"40 r4 m1 00 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "41 unsolicited", "msgs": [ {"type":"send", "payload":"41 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "42 unsolicited", "msgs": [ {"type":"send", "payload":"42 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "44 unsolicited", "msgs": [ {"type":"send", "payload":"44 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "48 unsolicited", "msgs": [ {"type":"send", "payload":"48 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] }, { "group": "v5.0 PUBACK ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "40 with reason-string property", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r8 m1 00 v4 1F s1 'p'"}]}, { "name": "40 with 2*reason-string property", "msgs": [ {"type":"send", "payload":"40 r12 m1 00 v8 1F s1 'p' 1F s1 'q'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with reason-string property missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 m1 1F"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with reason-string property incomplete string", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 1F 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with reason-string property empty string", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 1F s0"} ]}, { "name": "40 with user-property", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r11 m1 00 v7 26 s1 'p' s1 'q'"}]}, { "name": "40 with 2*user-property", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r18 m1 00 v14 26 s1 'p' s1 'q' 26 s1 'p' s1 'q'"}]}, { "name": "40 with user-property missing value", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 26 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with user-property missing key,value", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 26"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with user-property empty key", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"40 r10 m1 00 v6 26 s0 s1 'p'"} ]}, { "name": "40 with user-property empty value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"40 r10 m1 00 v6 26 s1 'p' s0"} ]}, { "name": "40 with user-property empty key,value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 26 s0 s0"} ]} ] }, { "group": "v5.0 PUBACK DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "40 with payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 01 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 17 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 24 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with retain-available (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 25 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 28 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 29 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 2A i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 17"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 24"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 25"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 28"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 29"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 2A"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with message-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 02 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 11 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 18 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 27 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with message-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 02"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with session-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 11"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with will-delay-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 18"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with maximum-packet-size (four byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 27"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 03 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 08 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 12 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 15 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 1A s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 1C s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with content-type (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 03"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with response-topic (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 08"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with assigned-client-identifier (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 12"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 15"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with response-information (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 1A"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with server-reference (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 1C"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 09 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 16 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with correlation-data (binary data) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 09"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with authentication-data (binary data) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 16"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with subscription-identifier (variable byte integer)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0B v1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 0B"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 13 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 21 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 22 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 23 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "40 with server-keep-alive (two byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 13"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 21"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 22"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with topic-alias (two byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 23"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 00 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 04 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 05 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 06 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 07 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0A i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0C i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0D i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0E i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 10 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 14 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 1B i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 1D i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 1E i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 20 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 8000 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 8001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 FF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 808001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 FFFF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 80808001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "40 with unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 FFFFFF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] } ] ================================================ FILE: test/broker/data/PUBCOMP.json ================================================ [ { "group": "v3.1.1 PUBCOMP", "ver":4, "tests": [ { "name": "70 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"70 r2 m1"}]}, { "name": "70 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"70 r268435456"}]}, { "name": "70 unsolicited long", "msgs": [{"type":"send", "payload":"70 r3 m1 00"}]}, { "name": "70 unsolicited mid 0", "msgs": [{"type":"send", "payload":"70 r2 m0"}]}, { "name": "70 unsolicited short 0", "msgs": [{"type":"send", "payload":"70 r0"}]}, { "name": "70 unsolicited short 1", "msgs": [{"type":"send", "payload":"70 r1 01"}]}, { "name": "70 unsolicited", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"70 r2 m1"}]}, { "name": "71 unsolicited", "msgs": [{"type":"send", "payload":"71 r2 m1"}]}, { "name": "72 unsolicited", "msgs": [{"type":"send", "payload":"72 r2 m1"}]}, { "name": "74 unsolicited", "msgs": [{"type":"send", "payload":"74 r2 m1"}]}, { "name": "78 unsolicited", "msgs": [{"type":"send", "payload":"78 r2 m1"}]} ] }, { "group": "v5.0 PUBCOMP", "ver":5, "tests": [ { "name": "70 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"70 r2 m1"}]}, { "name": "70 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"70 r268435456"}]}, { "name": "70 unsolicited long", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 00 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 unsolicited mid 0", "msgs": [ {"type":"send", "payload":"70 r2 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 unsolicited short 0", "msgs": [ {"type":"send", "payload":"70 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 unsolicited short 1", "msgs": [ {"type":"send", "payload":"70 r1 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 unsolicited short 3", "FIXME":"strictly, a short 3 should be malformed", "msgs": [ {"type":"send", "payload":"70 r3 m1 80"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 unsolicited", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"70 r2 m1"}]}, { "name": "70 unsolicited rc", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"70 r3 m1 00"}]}, { "name": "70 unsolicited rc=92", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"70 r3 m1 92"}]}, { "name": "70 unsolicited rc=20", "msgs": [ {"type":"send", "payload":"70 r3 m1 20"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 unsolicited rc=FF", "msgs": [ {"type":"send", "payload":"70 r3 m1 FF"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 unsolicited rc,properties", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"70 r4 m1 00 00"}]}, { "name": "71 unsolicited", "msgs": [ {"type":"send", "payload":"71 r2 m1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "72 unsolicited", "msgs": [ {"type":"send", "payload":"72 r2 m1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "74 unsolicited", "msgs": [ {"type":"send", "payload":"74 r2 m1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "78 unsolicited", "msgs": [ {"type":"send", "payload":"78 r2 m1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "71 unsolicited rc", "msgs": [ {"type":"send", "payload":"71 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "72 unsolicited rc", "msgs": [ {"type":"send", "payload":"72 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "74 unsolicited rc", "msgs": [ {"type":"send", "payload":"74 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "78 unsolicited rc", "msgs": [ {"type":"send", "payload":"78 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "71 unsolicited rc,properties", "msgs": [ {"type":"send", "payload":"71 r4 m1 00 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "72 unsolicited rc,properties", "msgs": [ {"type":"send", "payload":"72 r4 m1 00 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "74 unsolicited rc,properties", "msgs": [ {"type":"send", "payload":"74 r4 m1 00 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "78 unsolicited rc,properties", "msgs": [ {"type":"send", "payload":"78 r4 m1 00 00"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] }, { "group": "v5.0 PUBCOMP ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "70 with reason-string property", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"70 r8 m1 00 04 1F s1 'p'"}]}, { "name": "70 with 2*reason-string property", "msgs": [ {"type":"send", "payload":"70 r12 m1 00 08 1F s1 'p' 1F s1 'q'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with reason-string property missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 01 1F"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with reason-string property empty", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"70 r7 m1 00 03 1F s0"} ]}, { "name": "70 with user-property", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"70 r11 m1 00 07 26 s1 'p' s1 'q'"}]}, { "name": "70 with 2*user-property", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"70 r18 m1 00 0E 26 s1 'p' s1 'q' 26 s1 'p' s1 'q'"}]}, { "name": "70 with user-property missing value", "msgs": [ {"type":"send", "payload":"70 r8 m1 00 04 26 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with user-property missing key,value", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 01 26"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with user-property empty key", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"70 r10 m1 00 06 26 s0 s1 'p'"} ]}, { "name": "70 with user-property empty value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"70 r10 m1 00 06 26 s1 'p' s0"} ]}, { "name": "70 with user-property empty key,value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"70 r9 m1 00 05 26 s0 s0"} ]} ] }, { "group": "v5.0 PUBCOMP DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "70 with payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 01 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 17 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 24 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with retain-available (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 25 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 28 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 29 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 2A i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 17"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 24"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 25"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 28"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 29"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 2A"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with message-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"70 r9 m1 00 v5 02 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"70 r9 m1 00 v5 11 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"70 r9 m1 00 v5 18 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"70 r9 m1 00 v5 27 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with message-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 02"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with session-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 11"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with will-delay-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 18"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with maximum-packet-size (four byte integer) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 27"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"70 r8 m1 00 v4 03 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"70 r8 m1 00 v4 08 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"70 r8 m1 00 v4 12 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"70 r8 m1 00 v4 15 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"70 r8 m1 00 v4 1A s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"70 r8 m1 00 v4 1C s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with content-type (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 03"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with response-topic (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 08"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with assigned-client-identifier (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 12"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 15"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with response-information (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 1A"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with server-reference (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 1C"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"70 r8 m1 00 v4 09 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"70 r8 m1 00 v4 16 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with correlation-data (binary data) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 09"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with authentication-data (binary data) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 16"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with subscription-identifier (variable byte integer)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 0B v1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 0B"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"70 r7 m1 00 v3 13 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"70 r7 m1 00 v3 21 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"70 r7 m1 00 v3 22 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"70 r7 m1 00 v3 23 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "70 with server-keep-alive (two byte integer) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 13"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 21"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 22"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with topic-alias (two byte integer) missing", "msgs": [ {"type":"send", "payload":"70 r5 m1 00 v1 23"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 00 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 04 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 05 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 06 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 07 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 0A i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 0C i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 0D i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 0E i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 0F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 10 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 14 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 1B i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 1D i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 1E i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 20 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"70 r6 m1 00 v2 7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"70 r7 m1 00 v3 8000 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"70 r7 m1 00 v3 8001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"70 r7 m1 00 v3 FF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"70 r8 m1 00 v4 808001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"70 r8 m1 00 v4 FFFF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"70 r9 m1 00 v5 80808001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "70 with unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"70 r9 m1 00 v5 FFFFFF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] } ] ================================================ FILE: test/broker/data/PUBLISH.json ================================================ [ { "group": "v3.1.1 PUBLISH", "ver":4, "tests": [ { "name": "30 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"30 r14 s5 'topic' 'payload'"}]}, { "name": "30 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"30 r268435456"}]}, { "name": "30", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"30 r14 s5 'topic' 'payload'"}]}, { "name": "31 retain 1", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"31 r14 s5 'topic' 'payload'"}]}, { "name": "31 retain 1 zero length", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"31 r7 s5 'topic'"}]}, { "name": "30 topic 0", "msgs": [{"type":"send", "payload":"30 r9 s0 'payload'"}]}, { "name": "38 QoS 0 Dup 1", "msgs": [{"type":"send", "payload":"38 r14 s5 'topic' 'payload'"}]}, { "name": "36 QoS 3 (no mid) [MQTT-3.3.1-4]", "msgs": [{"type":"send", "payload":"36 r14 s5 'topic' 'payload'"}]}, { "name": "36 QoS 3 (with mid) [MQTT-3.3.1-4]", "msgs": [{"type":"send", "payload":"36 r16 s5 'topic' m1234 'payload'"}]}, { "name": "32 QoS 1 Mid 0", "msgs": [{"type":"send", "payload":"32 r16 s5 'topic' m0 'payload'"}]}, { "name": "34 QoS 2 Mid 0", "msgs": [{"type":"send", "payload":"34 r16 s5 'topic' m0 'payload'"}]}, { "name": "32 QoS 1 Dup 0", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r16 s5 'topic' m1234 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "3A QoS 1 Dup 1", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"3A r16 s5 'topic' m1234 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "34 QoS 2 Dup 0", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"34 r16 s5 'topic' m1234 'payload'"}, {"type":"recv", "payload":"50 r2 m1234"}, {"type":"send", "payload":"62 r2 m1234"}, {"type":"recv", "payload":"70 r2 m1234"} ]}, { "name": "3C QoS 2 Dup 1", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"3C r16 s5 'topic' m1234 'payload'"}, {"type":"recv", "payload":"50 r2 m1234"}, {"type":"send", "payload":"62 r2 m1234"}, {"type":"recv", "payload":"70 r2 m1234"} ]}, { "name": "30 topic with 0x0000", "msgs": [{"type":"send", "payload":"30 r14 s5 746F700000 'payload'"}]}, { "name": "30 topic with U+D800", "msgs": [{"type":"send", "payload":"30 r14 s5 746FEDA080 'payload'"}]}, { "name": "30 topic with U+0001", "msgs": [{"type":"send", "payload":"30 r14 s5 746F700170 'payload'"}]}, { "name": "30 topic with U+001F", "msgs": [{"type":"send", "payload":"30 r14 s5 746F701F70 'payload'"}]}, { "name": "30 topic with U+007F", "msgs": [{"type":"send", "payload":"30 r14 s5 746F707F70 'payload'"}]}, { "name": "30 topic with U+009F", "msgs": [{"type":"send", "payload":"30 r14 s5 746FC29F70 'payload'"}]}, { "name": "30 topic with U+FFFF", "msgs": [{"type":"send", "payload":"30 r14 s5 746FEDBFBF 'payload'"}]}, { "name": "30 topic with U+2A6D4 (section 1.5.3.1)", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"30 r14 s5 41F0AA9B94 'payload'"}]}, { "name": "30 topic with + [MQTT-3.3.2-2]", "msgs": [{"type":"send", "payload":"30 r14 s5 '+opic' 'payload'"}]}, { "name": "30 topic with # [MQTT-3.3.2-2]", "msgs": [{"type":"send", "payload":"30 r14 s5 '#opic' 'payload'"}]}, { "name": "34 QoS 2 repeated with/without 'payload'", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"34 r9 s5 'topic' m1234"}, {"type":"recv", "payload":"50 r2 m1234"}, {"type":"send", "payload":"34 r10 s5 'topic' m1234 'p'"}, {"type":"recv", "payload":"50 r2 m1234"}, {"type":"send", "payload":"34 r9 s5 'topic' m1234"}, {"type":"recv", "payload":"50 r2 m1234"} ]} ] }, { "group": "v5.0 PUBLISH", "ver":5, "tests": [ { "name": "30 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"30 r15 s5 'topic' 00 'payload'"}]}, { "name": "30 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"30 r268435456"}]}, { "name": "30", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"30 r15 s5 'topic' 00 'payload'"}]}, { "name": "31 retain 1", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"31 r15 s5 'topic' v0 'payload'"}]}, { "name": "31 retain 1 zero length", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"31 r8 s5 'topic' v0"}]}, { "name": "30 topic 0", "msgs": [ {"type":"send", "payload":"30 r10 s0 v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "38 QoS 0 Dup 1", "msgs": [ {"type":"send", "payload":"38 r15 s5 'topic' v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "36 QoS 3 (no mid) [MQTT-3.3.1-4]", "msgs": [ {"type":"send", "payload":"36 r15 s5 'topic' v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "36 QoS 3 (with mid) [MQTT-3.3.1-4]", "msgs": [ {"type":"send", "payload":"3611 s5 'topic' m1234 v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "32 QoS 1 Mid 0", "msgs": [ {"type":"send", "payload":"32 r17 s5 'topic' m0 v0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "34 QoS 2 Mid 0", "msgs": [ {"type":"send", "payload":"34 r17 s5 'topic' m0 v0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "32 QoS 1 Dup 0", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r17 s5 'topic' m1234 v0 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "3A QoS 1 Dup 1", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"3A r17 s5 'topic' m1234 v0 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "34 QoS 2 Dup 0", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"34 r17 s5 'topic' m1234 v0 'payload'"}, {"type":"recv", "payload":"50 r2 m1234"}, {"type":"send", "payload":"62 r2 m1234"}, {"type":"recv", "payload":"70 r2 m1234"} ]}, { "name": "3C QoS 2 Dup 1", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"3C r17 s5 'topic' m1234 v0 'payload'"}, {"type":"recv", "payload":"50 r2 m1234"}, {"type":"send", "payload":"62 r2 m1234"}, {"type":"recv", "payload":"70 r2 m1234"} ]}, { "name": "30 topic with 0x0000", "msgs": [ {"type":"send", "payload":"30 r15 s5 746F700000 v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+D800", "msgs": [ {"type":"send", "payload":"30 r15 s5 746FEDA080 v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+0001", "msgs": [ {"type":"send", "payload":"30 r15 s5 746F700170 v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+001F", "msgs": [ {"type":"send", "payload":"30 r15 s5 746F701F70 v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+007F", "msgs": [ {"type":"send", "payload":"30 r15 s5 746F707F70 v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+009F", "msgs": [ {"type":"send", "payload":"30 r15 s5 746FC29F70 v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+FFFF", "msgs": [ {"type":"send", "payload":"30 r15 s5 746FEDBFBF v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+2A6D4 (section 1.5.3.1)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"30 r15 s5 41F0AA9B94 v0 'payload'"} ]}, { "name": "30 topic with + [MQTT-3.3.2-2]", "msgs": [ {"type":"send", "payload":"30 r15 s5 '+opic' v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with # [MQTT-3.3.2-2]", "msgs": [ {"type":"send", "payload":"30 r15 s5 '#opic' v0 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] }, { "group": "v5.0 PUBLISH ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "maximum packet size", "connect":false, "expect_disconnect":false, "msgs":[ {"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 v5 2700000014 s1 'p'", "comment":"CONNECT with max-packet-size 20"}, {"type":"recv", "payload":"20 r14 00000B 22 H10 27 L2000000 21 H20", "comment": "CONNACK"}, {"type":"send", "payload":"82 r11 m1234 v0 s5 'topic' 00", "comment":"SUBSCRIBE topic"}, {"type":"recv", "payload":"90 r4 m1234 v0 00", "comment":"SUBACK"}, {"type":"send", "payload":"30 r22 s5 'topic' v0 'payloadpayload'", "comment":"PUBLISH with size > 20"}, {"type":"send", "payload":"30 r15 s5 'topic' v0 'payload'", "comment":"PUBLISH with size < 20"}, {"type":"recv", "payload":"30 r15 s5 'topic' v0 'payload'", "comment":"PUBLISH with size < 20, returned"} ]}, { "name": "payload-format-indicator=0 (byte)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 01 i0 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "payload-format-indicator=1 (byte)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 01 i1 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "payload-format-indicator=2 (byte, invalid)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 01 i2 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "2*payload-format-indicator=1 (byte)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 01 i1 01 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 01 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "message-expiry-interval=0 (four byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 02 L0 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "message-expiry-interval=1 (four byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 02 L1 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "2*message-expiry-interval=1 (four byte integer)", "msgs": [ {"type":"send", "payload":"32 r27 s5 'topic' m1234 v10 02 L1 02 L1 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "message-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 02 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "topic alias > max topic alias", "msgs": [ {"type":"send", "payload":"30 r18 s5 'topic' v3 23 H11 'payload'", "comment":"PUBLISH with topic alias 11 (server has set max topic alias=10)"}, {"type":"recv", "payload":"E0 r1 94"} ]}, { "name": "topic-alias (two byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 23 H1 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "2*topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 23 H1 23 H1 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "2*topic-alias different (two byte integer)", "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 23 H1 23 H2 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "topic-alias (two byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 23 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "response-topic (UTF-8 string)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 08 s1 'p' 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "response-topic (UTF-8 string, with wildcard)", "ver":5, "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 08 s1 '#' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "2*response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r25 s5 'topic' m1234 v8 08 s1 'p' 08 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "response-topic (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 08 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "response-topic (UTF-8 string) empty", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 08 s0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "correlation-data (binary data)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 09 s1 'p' 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "2*correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"32 r25 s5 'topic' m1234 v8 09 s1 'p' 09 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "correlation-data (binary data) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 09 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "correlation-data (binary data) empty", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 09 H0 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r24 s5 'topic' m1234 v7 26 s1 'p' s1 'q' 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "2*user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r31 s5 'topic' m1234 v14 26 s1 'p' s1 'q' 26 s1 'p' s1 'q' 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "user-property missing value", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 26 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "user-property missing key,value", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 26 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "user-property empty key", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 26 s0 s1 'p' 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "user-property empty value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 26 s1 'p' s0 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "user-property empty key,value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 26 s0 s0 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "content-type (UTF-8 string)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 03 s1 'p' 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]}, { "name": "2*content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r25 s5 'topic' m1234 v8 03 s1 'p' 03 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "content-type (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 03 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "content-type (UTF-8 string) empty", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 03 s0 'payload'"}, {"type":"recv", "payload":"40 r3 m1234 10"} ]} ] }, { "group": "v5.0 PUBLISH DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "subscription-identifier=0 (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0B v0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier=0x7F (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0B 7F 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier=0x8000 (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 0B 8000 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "subscription-identifier=0x8001 (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 0B 8001 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier=0xFF7F (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 0B FF7F 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier=0x808001 (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 0B 808001 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier=0xFFFF7F (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 0B FFFF7F 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier=0x80808001 (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 0B 80808001 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier=0xFFFFFF7F (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 0B FFFFFF7F 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier=0x8080808001 (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 0B 8080808001 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "2*subscription-identifier=1 (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 0B v1 0B v1 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 0B 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "reason-string property", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 1F s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 1700 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 2400 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "retain-available (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 2500 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 2800 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 2900 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 2A00 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 17 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 24 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 25 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 28 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 29 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 2A 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 1100000001 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 1800000001 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 2700000001 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "session-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v4 11 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "will-delay-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v4 18 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "maximum-packet-size (four byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v4 27 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 12 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 15 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 1A s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 1C s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "assigned-client-identifier (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 12 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 15 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "response-information (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 1A 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "server-reference (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 1C 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 16 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "authentication-data (binary data) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 16 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 13 H5 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 21 H5 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 22 H5 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "server-keep-alive (two byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 13 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 21 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 22 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 00 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 04 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 05 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 06 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 07 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0A i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0C i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0D i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0E i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0F i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 10 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 14 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 1B i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 1D i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 1E i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 20 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 7F i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 8000 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 8001 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 FF7F i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 808001 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 FFFF7F i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 80808001 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 FFFFFF7F i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x8080808001 (byte)", "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 8080808001 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] } ] ================================================ FILE: test/broker/data/PUBREC.json ================================================ [ { "group": "v3.1.1 PUBREC", "ver":4, "tests": [ { "name": "50 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"50 r2 m1"}]}, { "name": "50 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"50 r268435456"}]}, { "name": "50 unsolicited", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r2 m1"}, {"type":"recv", "payload":"62 r2 m1"} ] }, { "name": "50 unsolicited long", "msgs": [{"type":"send", "payload":"50 r3 m1 00"}]}, { "name": "50 unsolicited mid 0", "msgs": [{"type":"send", "payload":"50 r2 m0"}]}, { "name": "50 unsolicited short 0", "msgs": [{"type":"send", "payload":"50 r0"}]}, { "name": "50 unsolicited short 1", "msgs": [{"type":"send", "payload":"50 r1 01"}]}, { "name": "51 unsolicited", "msgs": [{"type":"send", "payload":"51 r2 m1"}]}, { "name": "52 unsolicited", "msgs": [{"type":"send", "payload":"52 r2 m1"}]}, { "name": "54 unsolicited", "msgs": [{"type":"send", "payload":"54 r2 m1"}]}, { "name": "58 unsolicited", "msgs": [{"type":"send", "payload":"58 r2 m1"}]} ] }, { "group": "v5.0 PUBREC", "ver":5, "tests": [ { "name": "50 [MQTT-3.1.0-1] (no reason code)", "connect":false, "msgs": [{"type":"send", "payload":"50 r2 m1"}]}, { "name": "50 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"50 r268435456"}]}, { "name": "50 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"50 r3 m1 00"}]}, { "name": "50 unsolicited long", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 00 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 unsolicited mid 0", "msgs": [ {"type":"send", "payload":"50 r3 m0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 unsolicited short 0", "msgs": [ {"type":"send", "payload":"50 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 unsolicited short 1", "msgs": [ {"type":"send", "payload":"50 r1 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 unsolicited len=2", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r2 m1"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 unsolicited len=3", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r3 m1 00"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 unsolicited len=3 fail", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"50 r3 m1 80"}]}, { "name": "50 unsolicited len=4 ok", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r4 m1 00 00"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 unsolicited len=4 rc=fail", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"50 r4 m1 80 00"}]}, { "name": "50 unsolicited len=4 rc=unknown", "msgs": [ {"type":"send", "payload":"50 r4 m1 FF 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 unsolicited len=4 short", "msgs": [ {"type":"send", "payload":"50 r4 m1 00 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "51 unsolicited", "msgs": [ {"type":"send", "payload":"51 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "52 unsolicited", "msgs": [ {"type":"send", "payload":"52 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "54 unsolicited", "msgs": [ {"type":"send", "payload":"54 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "58 unsolicited", "msgs": [ {"type":"send", "payload":"58 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] }, { "group": "v5.0 PUBREC ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "50 with reason-string property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 1F s1 'p'"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 with 2*reason-string property", "msgs": [ {"type":"send", "payload":"50 r12 m1 00 v8 1F s1 'p' 1F s1 'q'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with reason-string property missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 1F"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with reason-string property empty", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r7 m1 00 v3 1F s0"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 with user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r11 m1 00 v7 26 s1 'p' s1 'q'"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 with 2*user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r18 m1 00 v14 26 s1 'p' s1 'q' 26 s1 'p' s1 'q'"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 with user-property missing value", "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 26 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with user-property missing key,value", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 26"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with user-property empty key", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r10 m1 00 v6 26 s0 s1 'p'"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 with user-property empty value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r10 m1 00 v6 26 s1 'p' s0"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 with user-property empty key,value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r9 m1 00 v5 26 s0 s0"}, {"type":"recv", "payload":"62 r2 m1"} ]} ] }, { "group": "v5.0 PUBREC DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "50 with payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 01 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 17 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 24 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with retain-available (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 25 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 28 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 29 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 2A i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 17"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 24"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 25"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 28"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 29"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 2A"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with message-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"50 r9 m1 00 v5 02 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"50 r9 m1 00 v5 11 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"50 r9 m1 00 v5 18 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"50 r9 m1 00 v5 27 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with message-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 02"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with session-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 11"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with will-delay-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 18"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with maximum-packet-size (four byte integer) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 27"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 03 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 08 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 12 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 15 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 1A s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 1C s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with content-type (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 03"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with response-topic (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 08"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with assigned-client-identifier (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 12"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 15"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with response-information (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 1A"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with server-reference (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 1C"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 09 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 16 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with correlation-data (binary data) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 09"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with authentication-data (binary data) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 16"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with subscription-identifier (variable byte integer)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 0B v1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 0B"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"50 r7 m1 00 v3 13 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"50 r7 m1 00 v3 21 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"50 r7 m1 00 v3 22 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"50 r7 m1 00 v3 23 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "50 with server-keep-alive (two byte integer) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 13"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 21"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 22"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with topic-alias (two byte integer) missing", "msgs": [ {"type":"send", "payload":"50 r5 m1 00 v1 23"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 00 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 04 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 05 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 06 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 07 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 0A i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 0C i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 0D i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 0E i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 0F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 10 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 14 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 1B i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 1D i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 1E i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 20 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"50 r6 m1 00 v2 7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"50 r7 m1 00 v3 8000 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"50 r7 m1 00 v3 8001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"50 r7 m1 00 v3 FF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 808001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 FFFF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"50 r9 m1 00 v5 80808001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "50 with unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"50 r9 m1 00 v5 FFFFFF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] } ] ================================================ FILE: test/broker/data/PUBREL.json ================================================ [ { "group": "v3.1.1 PUBREL", "ver":4, "tests": [ { "name": "62 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"62 r2 m1"}]}, { "name": "62 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"62 r268435456"}]}, { "name": "62 unsolicited", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r2 m1"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 unsolicited long", "msgs": [{"type":"send", "payload":"62 r3 m1 00"}]}, { "name": "62 unsolicited mid 0", "msgs": [{"type":"send", "payload":"62 r2 m0"}]}, { "name": "62 unsolicited short 0", "msgs": [{"type":"send", "payload":"62 r0"}]}, { "name": "62 unsolicited short 1", "msgs": [{"type":"send", "payload":"62 r1 01"}]}, { "name": "63 unsolicited [MQTT-3.6.1-1]", "msgs": [{"type":"send", "payload":"63 r2 m1"}]}, { "name": "64 unsolicited [MQTT-3.6.1-1]", "msgs": [{"type":"send", "payload":"64 r2 m1"}]}, { "name": "66 unsolicited [MQTT-3.6.1-1]", "msgs": [{"type":"send", "payload":"66 r2 m1"}]}, { "name": "6A unsolicited [MQTT-3.6.1-1]", "msgs": [{"type":"send", "payload":"6A r2 m1"}]} ] }, { "group": "v5.0 PUBREL", "ver":5, "tests": [ { "name": "62 [MQTT-3.1.0-1] (no reason code)", "connect":false, "msgs": [{"type":"send", "payload":"62 r2 m1"}]}, { "name": "62 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"62 r268435456"}]}, { "name": "62 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"62 r3 m1 00"}]}, { "name": "62 unsolicited long", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 00 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 unsolicited mid 0", "msgs": [ {"type":"send", "payload":"62 r3 m0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 unsolicited short 0", "msgs": [ {"type":"send", "payload":"62 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 unsolicited short 1", "msgs": [ {"type":"send", "payload":"62 r1 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 unsolicited len=2", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r2 m1"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 unsolicited len=3", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r3 m1 00"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 unsolicited len=3 fail", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r3 m1 92"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 unsolicited len=4 ok", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r4 m1 00 00"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 unsolicited len=4 rc=fail", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r4 m1 92 00"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 unsolicited len=4 rc=unknown", "msgs": [ {"type":"send", "payload":"62 r4 m1 FF 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 unsolicited len=4 short", "msgs": [ {"type":"send", "payload":"62 r4 m1 00 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "63 unsolicited", "msgs": [ {"type":"send", "payload":"63 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "64 unsolicited", "msgs": [ {"type":"send", "payload":"64 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "66 unsolicited", "msgs": [ {"type":"send", "payload":"66 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "6A unsolicited", "msgs": [ {"type":"send", "payload":"6A r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] }, { "group": "v5.0 PUBREL ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "62 with reason-string property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r8 m1 00 04 1F s1 'p'"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 with 2*reason-string property", "msgs": [ {"type":"send", "payload":"62 r12 m1 00 08 1F s1 'p' 1F s1 'q'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with reason-string property missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 01 1F"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with reason-string property empty", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r7 m1 00 03 1F s0"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 with user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r11 m1 00 07 26 s1 'p' s1 'q'"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 with 2*user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r18 m1 00 0E 26 s1 'p' s1 'q' 26 s1 'p' s1 'q'"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 with user-property missing value", "msgs": [ {"type":"send", "payload":"62 r8 m1 00 04 26 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with user-property missing key,value", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 01 26"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with user-property empty key", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r10 m1 00 06 26 s0 s1 'p'"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 with user-property empty value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r10 m1 00 06 26 s1 'p' s0"}, {"type":"recv", "payload":"70 r2 m1"} ]}, { "name": "62 with user-property empty key,value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"62 r9 m1 00 05 26 s0 s0"}, {"type":"recv", "payload":"70 r2 m1"} ]} ] }, { "group": "v5.0 PUBREL DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "62 with payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 01 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 17 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 24 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with retain-available (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 25 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 28 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 29 i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 2A i0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 17"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 24"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 25"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 28"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 29"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 2A"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with message-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"62 r9 m1 00 v5 02 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"62 r9 m1 00 v5 11 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"62 r9 m1 00 v5 18 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"62 r9 m1 00 v5 27 L1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with message-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 02"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with session-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 11"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with will-delay-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 18"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with maximum-packet-size (four byte integer) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 27"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"62 r8 m1 00 v4 03 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"62 r8 m1 00 v4 08 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"62 r8 m1 00 v4 12 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"62 r8 m1 00 v4 15 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"62 r8 m1 00 v4 1A s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"62 r8 m1 00 v4 1C s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with content-type (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 03"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with response-topic (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 08"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with assigned-client-identifier (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 12"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 15"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with response-information (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 1A"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with server-reference (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 1C"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"62 r8 m1 00 v4 09 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"62 r8 m1 00 v4 16 s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with correlation-data (binary data) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 09"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with authentication-data (binary data) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 16"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with subscription-identifier (variable byte integer)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 0B v1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 0B"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"62 r7 m1 00 v3 13 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"62 r7 m1 00 v3 21 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"62 r7 m1 00 v3 22 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"62 r7 m1 00 v3 23 H5"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "62 with server-keep-alive (two byte integer) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 13"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 21"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 22"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with topic-alias (two byte integer) missing", "msgs": [ {"type":"send", "payload":"62 r5 m1 00 v1 23"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 00 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 04 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 05 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 06 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 07 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 0A i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 0C i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 0D i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 0E i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 0F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 10 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 14 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 1B i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 1D i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 1E i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 20 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"62 r6 m1 00 v2 7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"62 r7 m1 00 v3 8000 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"62 r7 m1 00 v3 8001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"62 r7 m1 00 v3 FF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"62 r8 m1 00 v4 808001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"62 r8 m1 00 v4 FFFF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"62 r9 m1 00 v5 80808001 i1"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "62 with unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"62 r9 m1 00 v5 FFFFFF7F i1"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] } ] ================================================ FILE: test/broker/data/REGRESSION.json ================================================ [ { "group": "REGRESSIONS", "tests": [ { "name": "subscribe-unsubscribe-crash part 1", "ver":4, "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r38 m1234 s9 'drash/1/#' 00 s9 'erash/2/#' 00 s9 'crash/3/#' 00"}, {"type":"recv", "payload":"90 r5 m1234 00 00 00"}, {"type":"send", "payload":"A2 r13 m1234 s9 'drash/1/#'"}, {"type":"recv", "payload":"B0 r2 m1234"} ], "comment": "Must be used with part 2 immediately after", "comment2": "Requires WITH_ASAN=yes"}, { "name": "subscribe-unsubscribe-crash part 2", "ver":4, "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r14 m1234 s9 'crash/3/#' 00"}, {"type":"recv", "payload":"90 r3 m1234 00"} ], "comment": "https://github.com/eclipse/mosquitto/issues/2885"} ] }, { "group": "REGRESSIONS", "tests": [ { "name": "mismatched-shared-normal-subscribe-unsubscribe-leak", "ver":4, "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r26 m1 s21 '$share/sharename/test' 01"}, {"type":"recv", "payload":"90 r3 m1 01"}, {"type":"send", "payload":"82 r9 m2 s4 'test' 00"}, {"type":"recv", "payload":"90 r3 m2 00"}, {"type":"send", "payload":"A2 r8 m7 s4 'test'"}, {"type":"recv", "payload":"B0 r2 m7"} ], "comment": "Also part one of the next two tests" }, { "name": "acl-check-uaf", "ver":4, "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"30 r13 s4 'test' 'payload'"} ] }, { "name": "shared-sub-uaf", "ver":4, "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r26 m1 s21 '$share/sharename/test' 01"}, {"type":"recv", "payload":"90 r3 m1 01"}, {"type":"send", "payload":"82 r9 m2 s4 'test' 00"}, {"type":"recv", "payload":"90 r3 m2 00"}, {"type":"send", "payload":"A2 r8 m7 s4 'test'"}, {"type":"recv", "payload":"B0 r2 m7"} ] } ] } ] ================================================ FILE: test/broker/data/SUBACK.json ================================================ [ { "group": "v3.1.1 SUBACK", "ver":4, "tests": [ { "name": "90 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"90 r3 m1 00"}]}, { "name": "90 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"90 r268435456"}]}, { "name": "90 mid 0", "msgs": [{"type":"send", "payload":"90 r3 m0 00"}]}, { "name": "90", "msgs": [{"type":"send", "payload":"90 r3 m1 00"}]}, { "name": "90 short 0", "msgs": [{"type":"send", "payload":"90 r0"}]}, { "name": "90 short 1", "msgs": [{"type":"send", "payload":"90 r1 01"}]}, { "name": "90 short 2", "msgs": [{"type":"send", "payload":"90 r2 m1"}]}, { "name": "91", "msgs": [{"type":"send", "payload":"91 r3 m1 00"}]}, { "name": "92", "msgs": [{"type":"send", "payload":"92 r3 m1 00"}]}, { "name": "94", "msgs": [{"type":"send", "payload":"94 r3 m1 00"}]}, { "name": "98", "msgs": [{"type":"send", "payload":"98 r3 m1 00"}]} ] }, { "group": "v5.0 SUBACK", "ver":5, "tests": [ { "name": "90 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"90 r3 m1 00"}]}, { "name": "90 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"90 r268435456"}]}, { "name": "90 long", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 short 0", "msgs": [ {"type":"send", "payload":"90 r0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 short 1", "msgs": [ {"type":"send", "payload":"90 r1 01"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 short 2", "msgs": [ {"type":"send", "payload":"90 r2 m1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 short 3", "msgs": [ {"type":"send", "payload":"90 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90", "msgs": [ {"type":"send", "payload":"90 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "91", "msgs": [ {"type":"send", "payload":"91 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "92", "msgs": [ {"type":"send", "payload":"92 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "94", "msgs": [ {"type":"send", "payload":"94 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "98", "msgs": [ {"type":"send", "payload":"98 r3 m1 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "90 with property", "msgs": [ {"type":"send", "payload":"90 r8 m1 04 1F s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0x01 qos 1", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 01"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0x02 qos 2", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 02"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0x11 no sub", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 11"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0x80 unspecified error", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 80"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0x83 implementation specific error", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 83"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0x87 not authorised", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 87"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0x8F topic filter invalid", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 8F"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0x91 packet identifier in use", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 91"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0x97 quota exceeded", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 97"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0x9E shared subs not supported", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 9E"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0xA1 sub ids not supported", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 A1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0xA2 wildcards not supported", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 A2"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 reason code 0xFF unknown", "msgs": [ {"type":"send", "payload":"90 r4 m1 00 FF"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] }, { "group": "v5.0 SUBACK ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "90 with reason-string property", "msgs": [ {"type":"send", "payload":"90 r8 m1 04 1F s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with 2*reason-string property", "msgs": [ {"type":"send", "payload":"90 r12 m1 0008 1F s1 'p' 1F s1 'q'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with reason-string property missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 01 1F 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with user-property", "msgs": [ {"type":"send", "payload":"90 r11 m1 07 26 s1 'p' s1 'q' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with user-property missing value", "msgs": [ {"type":"send", "payload":"90 r8 m1 04 26 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with user-property missing key,value", "msgs": [ {"type":"send", "payload":"90 r5 m1 01 26 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with user-property empty key", "msgs": [ {"type":"send", "payload":"90 r10 m1 06 26 s0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with user-property empty value", "msgs": [ {"type":"send", "payload":"90 r10 m1 06 26 s1 'p' s0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with user-property empty key,value", "msgs": [ {"type":"send", "payload":"90 r9 m1 05 26 s0 s0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] }, { "group": "v5.0 SUBACK DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "90 with payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 01 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 17 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 24 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with retain-available (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 25 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 28 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 29 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 2A i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 01 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 17 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 24 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 25 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 28 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 29 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 2A 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with message-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"90 r9 m1 v5 02 L1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"90 r9 m1 v5 11 L1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"90 r9 m1 v5 18 L1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"90 r9 m1 v5 27 L1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with message-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 02 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with session-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 11 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with will-delay-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 18 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with maximum-packet-size (four byte integer) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 27 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"90 r8 m1 v4 03 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"90 r8 m1 v4 08 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"90 r8 m1 v4 12 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"90 r8 m1 v4 15 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"90 r8 m1 v4 1A s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"90 r8 m1 v4 1C s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with content-type (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 03 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with response-topic (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 08 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with assigned-client-identifier (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 12 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 15 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with response-information (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 1A00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with server-reference (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 1C00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"90 r8 m1 v4 09 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"90 r8 m1 v4 16 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with correlation-data (binary data) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 09 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with authentication-data (binary data) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 16 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with subscription-identifier (variable byte integer)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 0B v1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 0B 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"90 r7 m1 v3 13 H5 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"90 r7 m1 v3 21 H5 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"90 r7 m1 v3 22 H5 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"90 r7 m1 v3 23 H5 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with server-keep-alive (two byte integer) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 13 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 21 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 22 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with topic-alias (two byte integer) missing", "msgs": [ {"type":"send", "payload":"90 r5 m1 v1 23 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 00 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 04 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 05 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 06 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 07 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 0A i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 0C i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 0D i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 0E i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 0F i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 10 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 14 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 19 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 1D i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 1E i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 20 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"90 r6 m1 v2 7F i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"90 r7 m1 v3 8000 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"90 r7 m1 v3 8001 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"90 r7 m1 v3 FF7F i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"90 r8 m1 v4 808001 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"90 r8 m1 v4 FFFF7F i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"90 r9 m1 v5 80808001 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "90 with unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"90 r9 m1 v5 FFFFFF7F i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] } ] ================================================ FILE: test/broker/data/SUBSCRIBE.json ================================================ [ { "group": "v3.1.1 SUBSCRIBE", "ver":4, "tests": [ { "name": "82 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 00"}]}, { "name": "82 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"82 r268435456"}]}, { "name": "80", "msgs": [{"type":"send", "payload":"80061234 s1 'p' 00"}]}, { "name": "83 [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"83 r6 m1234 s1 'p' 00"}]}, { "name": "84 [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"84 r6 m1234 s1 'p' 00"}]}, { "name": "86 [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"86 r6 m1234 s1 'p' 00"}]}, { "name": "8A [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"8A r6 m1234 s1 'p' 00"}]}, { "name": "82 QoS 3 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 03"}]}, { "name": "82 QoS 0x04 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 04"}]}, { "name": "82 QoS 0x08 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 08"}]}, { "name": "82 QoS 0x10 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 10"}]}, { "name": "82 QoS 0x20 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 20"}]}, { "name": "82 QoS 0x40 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 40"}]}, { "name": "82 QoS 0x80 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 80"}]}, { "name": "82 topic with 0x0000", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746F700000 00"} ] }, { "name": "82 topic with U+D800", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746FEDA080 00"} ] }, { "name": "82 topic with U+0001", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746F700170 00"} ] }, { "name": "82 topic with U+001F", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746F701F70 00"} ] }, { "name": "82 topic with U+007F", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746F707F70 00"} ] }, { "name": "82 topic with U+009F", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746FC29F70 00"} ] }, { "name": "82 topic with U+FFFF", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746FEDBFBF 00"} ] }, { "name": "82 long", "msgs": [{"type":"send", "payload":"82 r7 m1234 s1 'p' 00 00"}]}, { "name": "82 short 5 [MQTT-3.8.3-3]", "msgs": [{"type":"send", "payload":"82 r5 m1234 s1 'p'"}]}, { "name": "82 short 4", "msgs": [{"type":"send", "payload":"82 r4 m1234 0000"}]}, { "name": "82 short 3", "msgs": [{"type":"send", "payload":"82 r3 m1234 00"}]}, { "name": "82 short 2", "msgs": [{"type":"send", "payload":"82 r2 1234"}]}, { "name": "82 short 1", "msgs": [{"type":"send", "payload":"82 r1 12"}]}, { "name": "82 short 0", "msgs": [{"type":"send", "payload":"82 r0"}]}, { "name": "82 single topic len 0", "msgs": [{"type":"send", "payload":"82 r5 m1234 s0 00"}]}, { "name": "82 multiple topic 1 len 0", "msgs": [{"type":"send", "payload":"82 r9 m1234 s0 00 s1 'q' 00"}]}, { "name": "82 multiple topic 2 len 0", "msgs": [{"type":"send", "payload":"82 r9 m1234 s1 'q' 00 s0 00"}]}, { "name": "82 multiple topic 1,2 len 0", "msgs": [{"type":"send", "payload":"82 r8 m1234 s0 00 s0 00"}]}, { "name": "82 mid 0", "msgs": [{"type":"send", "payload":"82 r6 m0 s1 'p' 00"}]}, { "name": "82 single ok QoS 0 [MQTT-3.8.4-1]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 00"}, {"type":"recv", "payload":"90 r3 m1234 00"} ]}, { "name": "82 single ok QoS 1 [MQTT-3.8.4-1]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 01"}, {"type":"recv", "payload":"90 r3 m1234 01"} ]}, { "name": "82 single ok QoS 2 [MQTT-3.8.4-1]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 02"}, {"type":"recv", "payload":"90 r3 m1234 02"} ]}, { "name": "82 multiple ok [MQTT-3.8.4-4]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r10 m1234 s1 'p' 00 s1 'q' 00"}, {"type":"recv", "payload":"90 r4 m1234 00 00"} ]} ] }, { "group": "v5.0 SUBSCRIBE", "ver":5, "tests": [ { "name": "82 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 00"}]}, { "name": "82 single ok QoS 0 [MQTT-3.8.4-1]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1234 v0 00"} ]}, { "name": "82 single ok QoS 1 [MQTT-3.8.4-1]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 01"}, {"type":"recv", "payload":"90 r4 m1234 v0 01"} ]}, { "name": "82 single ok QoS 2 [MQTT-3.8.4-1]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 02"}, {"type":"recv", "payload":"90 r4 m1234 v0 02"} ]}, { "name": "80", "msgs": [ {"type":"send", "payload":"80 r7 m1234 v0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "83 [MQTT-3.8.1-1]", "msgs": [ {"type":"send", "payload":"83 r7 m1234 v0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "84 [MQTT-3.8.1-1]", "msgs": [ {"type":"send", "payload":"84 r7 m1234 v0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "86 [MQTT-3.8.1-1]", "msgs": [ {"type":"send", "payload":"86 r7 m1234 v0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "8A [MQTT-3.8.1-1]", "msgs": [ {"type":"send", "payload":"8A r7 m1234 v0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 QoS 3 [MQTT-3-8.3-2] (no qos)", "ver":5, "msgs": [ {"type":"send", "payload":"82 r6 m1234 v0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 QoS 3 [MQTT-3-8.3-2] (no topic or qos)", "ver":5, "msgs": [ {"type":"send", "payload":"82 r3 m1234 v0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 QoS 3 [MQTT-3-8.3-4]", "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 03"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 QoS 0 no local 0x04", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 04"}, {"type":"recv", "payload":"90 r4 m1234 v0 00"} ]}, { "name": "82 QoS 0 retain as published 0x08", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 08"}, {"type":"recv", "payload":"90 r4 m1234 v0 00"} ]}, { "name": "82 QoS 0 retain handling=1 0x10", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 10"}, {"type":"recv", "payload":"90 r4 m1234 v0 00"} ]}, { "name": "82 QoS 0 retain handling=2 0x20", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 20"}, {"type":"recv", "payload":"90 r4 m1234 v0 00"} ]}, { "name": "82 QoS 0 retain handling=3 0x30 [MQTT-3-8.3-4]", "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 30"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 QoS 0 options=0x40 [MQTT-3-8.3-5]", "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 40"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 QoS 0 options=0x80 [MQTT-3-8.3-5]", "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 80"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 QoS 0 options=0xF0 [MQTT-3-8.3-5]", "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' F0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 topic with 0x0000", "msgs": [ {"type":"send", "payload":"82 r18 m1234 v0 s5 746F700000 'payload' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 topic with U+D800", "msgs": [ {"type":"send", "payload":"82 r18 m1234 v0 s5 746FEDA080 'payload' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 topic with U+0001", "msgs": [ {"type":"send", "payload":"82 r18 m1234 v0 s5 746F700170 'payload' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 topic with U+001F", "msgs": [ {"type":"send", "payload":"82 r18 m1234 v0 s5 746F701F70 'payload' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 topic with U+007F", "msgs": [ {"type":"send", "payload":"82 r18 m1234 v0 s5 746F707F70 'payload' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 topic with U+009F", "msgs": [ {"type":"send", "payload":"82 r18 m1234 v0 s5 746FC29F70 'payload' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 topic with U+FFFF", "msgs": [ {"type":"send", "payload":"82 r18 m1234 v0 s5 746FEDBFBF 'payload' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 long", "msgs": [ {"type":"send", "payload":"82 r8 m1234 v0 s1 'p' 00 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 short 5 [MQTT-3.8.3-3]", "msgs": [ {"type":"send", "payload":"82 r6 m1234 v0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 short 5", "msgs": [ {"type":"send", "payload":"82 r5 m1234 v0 0000"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 short 4", "msgs": [ {"type":"send", "payload":"82 r4 m1234 v0 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 short 3", "msgs": [ {"type":"send", "payload":"82 r3 m1234 v0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 short 2", "msgs": [ {"type":"send", "payload":"82 r2 1234"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 short 1", "msgs": [ {"type":"send", "payload":"82 r1 12"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 short 0", "msgs": [ {"type":"send", "payload":"82 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 single topic len 0", "msgs": [ {"type":"send", "payload":"82 r6 m1234 v0 s0 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 multiple topic 1 len 0", "msgs": [ {"type":"send", "payload":"82 r10 m1234 v0 s0 00 s1 'q' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 multiple topic 2 len 0", "msgs": [ {"type":"send", "payload":"82 r10 m1234 v0 s1 'q' 00 s0 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 multiple topic 1,2 len 0", "msgs": [ {"type":"send", "payload":"82 r9 m1234 v0 s0 00 s0 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 single ok QoS 0 [MQTT-3.8.4-1]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1234 v0 00"} ]}, { "name": "82 single ok QoS 1 [MQTT-3.8.4-1]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 01"}, {"type":"recv", "payload":"90 r4 m1234 v0 01"} ]}, { "name": "82 single ok QoS 2 [MQTT-3.8.4-1]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 02"}, {"type":"recv", "payload":"90 r4 m1234 v0 02"} ]}, { "name": "82 multiple ok [MQTT-3.8.4-4]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r11 m1234 v0 s1 'p' 00 s1 'q' 00"}, {"type":"recv", "payload":"90 r5 m1234 v0 00 00"} ]}, { "name": "82 mid 0", "msgs": [ {"type":"send", "payload":"82 r7 m0 00 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 shared sub with + in sharename", "ver":5, "msgs": [ {"type":"send", "payload":"82 r16 m1234 v0 s10 '$share/+/p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "82 shared sub with # in sharename", "ver":5, "msgs": [ {"type":"send", "payload":"82 r16 m1234 v0 s10 '$share/#/p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 shared sub with no topic part 1", "ver":5, "msgs": [ {"type":"send", "payload":"82 r15 m1234 v0 s9 '$share/p/' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "82 shared sub with no topic part 2", "ver":5, "msgs": [ {"type":"send", "payload":"82 r14 m1234 v0 s8 '$share/p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "82 shared sub with no local set", "ver":5, "msgs": [ {"type":"send", "payload":"82 r16 m1234 v0 s10 '$share/p/p' 04"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] }, { "group": "v5.0 SUBSCRIBE ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "82 with user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r14 m1 v7 26 s1 'p' s1 'q' s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with 2*user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r21 m1 v14 26 s1 'p' s1 'q' 26 s1 'p' s1 'q' s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with user-property missing value", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 26 s1 'p' s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with user-property missing key,value", "msgs": [ {"type":"send", "payload":"82 r8 m1 v1 26 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with user-property empty key", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r13 m1 v6 26 s0 s1 'p' s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with user-property empty value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r13 m1 v6 26 s1 'p' s0 s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with user-property empty key,value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r12 m1 v5 26 s0 s0 s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with subscription-identifier missing (variable byte integer)", "msgs": [ {"type":"send", "payload":"82 r8 m1 v1 0B s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with subscription-identifier=0 (variable byte integer)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 0B v0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with subscription-identifier=1 (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 0B v1 s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with 2*subscription-identifier=1 (variable byte integer)", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 0B v1 0B v1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "82 with subscription-identifier=0x7F (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 0B 7F s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with subscription-identifier=0x8000 (variable byte integer)", "msgs": [ {"type":"send", "payload":"82 r10 m1 v3 0B 8000 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with subscription-identifier=0x8001 (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r10 m1 v3 0B 8001 s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with subscription-identifier=0xFF7F (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r10 m1 v3 0B FF7F s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with subscription-identifier=0x808001 (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 0B 808001 s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with subscription-identifier=0xFFFF7F (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 0B FFFF7F s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with subscription-identifier=0x80808001 (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r12 m1 v5 0B 80808001 s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with subscription-identifier=0xFFFFFF7F (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r12 m1 v5 0B FFFFFF7F s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1 00 00"} ]}, { "name": "82 with subscription-identifier=0x8080808001 (variable byte integer)", "msgs": [ {"type":"send", "payload":"82 r13 m1 v6 0B 8080808001 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] }, { "group": "v5.0 SUBSCRIBE DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "82 with payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 01 i0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 17 i0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 24 i0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with retain-available (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 25 i0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 28 i0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 29 i0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 2A i0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with message-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"82 r12 m1 v5 02 L1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"82 r12 m1 v5 11 L1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"82 r12 m1 v5 18 L1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"82 r12 m1 v5 27 L1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 03 s1 'p' s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 08 s1 'p' s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 12 s1 'p' s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 15 s1 'p' s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 1A s1 'p' s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 1C s1 'p' s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 09 s1 'p' s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 16 s1 'p' s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"82 r10 m1 v3 13 H5 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"82 r10 m1 v3 21 H5 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"82 r10 m1 v3 22 H5 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"82 r10 m1 v3 23 H5 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 00 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 04 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 05 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 06 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 07 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 0A i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 0C i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 0D i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 0E i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 0F i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 10 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 14 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 1B i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 1D i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 1E i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 20 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"82 r9 m1 v2 7F i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"82 r10 m1 v3 8000 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"82 r10 m1 v3 8001 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"82 r10 m1 v3 FF7F i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 808001 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"82 r11 m1 v4 FFFF7F i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"82 r12 m1 v5 80808001 i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "82 with unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"82 r12 m1 v5 FFFFFF7F i1 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] } ] ================================================ FILE: test/broker/data/UNSUBACK.json ================================================ [ { "group": "v3.1.1 UNSUBACK", "ver":4, "tests": [ { "name": "B0 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"B0 r2 m1"}]}, { "name": "B0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"B0 r268435456"}]}, { "name": "B0 multi", "msgs": [{"type":"send", "payload":"B0 r3 m1 00"}]}, { "name": "B0 short 0", "msgs": [{"type":"send", "payload":"B0 r0"}]}, { "name": "B0 short 1", "msgs": [{"type":"send", "payload":"B0 r1 01"}]}, { "name": "B0", "msgs": [{"type":"send", "payload":"B0 r2 m1"}]}, { "name": "B1", "msgs": [{"type":"send", "payload":"B1 r2 m1"}]}, { "name": "B2", "msgs": [{"type":"send", "payload":"B2 r2 m1"}]}, { "name": "B4", "msgs": [{"type":"send", "payload":"B4 r2 m1"}]}, { "name": "B8", "msgs": [{"type":"send", "payload":"B8 r2 m1"}]} ] }, { "group": "v5.0 UNSUBACK", "ver":5, "tests": [ { "name": "B0 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"B0 r3 m1 00"}]}, { "name": "B0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"B0 r268435456"}]}, { "name": "B0 multi", "msgs": [ {"type":"send", "payload":"B0 r4 m1 v0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 short 0", "msgs": [ {"type":"send", "payload":"B0 r0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 short 1", "msgs": [ {"type":"send", "payload":"B0 r1 01"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 short 2", "msgs": [ {"type":"send", "payload":"B0 r2 m1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0", "msgs": [ {"type":"send", "payload":"B0 r3 m1 v0"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B1", "msgs": [ {"type":"send", "payload":"B1 r3 m1 v0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "B2", "msgs": [ {"type":"send", "payload":"B2 r3 m1 v0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "B4", "msgs": [ {"type":"send", "payload":"B4 r3 m1 v0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "B8", "msgs": [ {"type":"send", "payload":"B8 r3 m1 v0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "B0 with property", "msgs": [ {"type":"send", "payload":"B0 r7 m1 04 1F s1 'p'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 reason code 0x11 no sub", "msgs": [ {"type":"send", "payload":"B0 r4 m1 v0 11"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 reason code 0x80 unspecified error", "msgs": [ {"type":"send", "payload":"B0 r4 m1 v0 80"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 reason code 0x83 implementation specific error", "msgs": [ {"type":"send", "payload":"B0 r4 m1 v0 83"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 reason code 0x87 not authorised", "msgs": [ {"type":"send", "payload":"B0 r4 m1 v0 87"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 reason code 0x8F topic filter invalid", "msgs": [ {"type":"send", "payload":"B0 r4 m1 v0 8F"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 reason code 0x91 packet identifier in use", "msgs": [ {"type":"send", "payload":"B0 r4 m1 v0 91"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 reason code 0xFF unknown", "msgs": [ {"type":"send", "payload":"B0 r4 m1 v0 FF"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] }, { "group": "v5.0 UNSUBACK ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "B0 with reason-string property", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 1F s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with reason-string property missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 1F 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with user-property", "msgs": [ {"type":"send", "payload":"B0 r11 m1 v7 26 s1 'p' s1 'q' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with user-property missing value", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 26 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with user-property missing key,value", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 26 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with user-property empty key", "msgs": [ {"type":"send", "payload":"B0 r10 m1 v6 26 s0 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with user-property empty value", "msgs": [ {"type":"send", "payload":"B0 r10 m1 v6 26 s1 'p' s0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with user-property empty key,value", "msgs": [ {"type":"send", "payload":"B0 r9 m1 v5 26 s0 s0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] }, { "group": "v5.0 UNSUBACK DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "B0 with payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 01 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 17 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 24 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with retain-available (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 25 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 28 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 29 i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 2A i0 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 01 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 17 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 24 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 25 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 28 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 29 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 2A 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with message-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"B0 r9 m1 v5 02 L1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"B0 r9 m1 v5 11 L1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"B0 r9 m1 v5 18 L1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"B0 r9 m1 v5 27 L1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with message-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 02 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with session-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 11 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with will-delay-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 18 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with maximum-packet-size (four byte integer) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 27 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 03 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 08 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 12 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 15 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 1A s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 1C s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with content-type (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 03 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with response-topic (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 08 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with assigned-client-identifier (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 12 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 15 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with response-information (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 1A 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with server-reference (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 1C 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 09 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 16 s1 'p' 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with correlation-data (binary data) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 09 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with authentication-data (binary data) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 16 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with subscription-identifier (variable byte integer)", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v2 0B v1"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"B0 r4 m1 v1 0B"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"B0 r7 m1 v3 13 H5 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"B0 r7 m1 v3 21 H5 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"B0 r7 m1 v3 22 H5 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"B0 r7 m1 v3 23 H5 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with server-keep-alive (two byte integer) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 13 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 21 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 22 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with topic-alias (two byte integer) missing", "msgs": [ {"type":"send", "payload":"B0 r5 m1 v1 23 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 00 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 04 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 05 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 06 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 07 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 0A i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 0C i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 0D i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 0E i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 0F i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 10 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 14 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 1B i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 1D i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 1E i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 20 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"B0 r6 m1 v2 7F i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"B0 r7 m1 v3 8000 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"B0 r7 m1 v3 8001 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"B0 r7 m1 v3 FF7F i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 808001 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"B0 r8 m1 v4 FFFF7F i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"B0 r9 m1 v5 80808001 i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "B0 with unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"B0 r9 m1 v5 FFFFFF7F i1 00"}, {"type":"recv", "payload":"E0 r1 82"} ]} ] } ] ================================================ FILE: test/broker/data/UNSUBSCRIBE.json ================================================ [ { "group": "v3.1.1 UNSUBSCRIBE", "ver":4, "tests": [ { "name": "A2 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"A2 r5 m1234 s1 'p'"}]}, { "name": "A2 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"A2 r268435456"}]}, { "name": "A2 (no subscribe) [MQTT-3.10.4-5]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"A2 r5 m1234 s1 'p'"}, {"type":"recv", "payload":"B0 r2 m1234"} ]}, { "name": "A2 (with subscribe) [MQTT-3.10.4-5]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r6 m1234 s1 'p' 00"}, {"type":"recv", "payload":"90 r3 m1234 00"}, {"type":"send", "payload":"A2 r5 m1234 s1 'p'"}, {"type":"recv", "payload":"B0 r2 m1234"} ]}, { "name": "A2 multiple [MQTT-3.10.4-6]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"A2 r8 m1234 s1 'p' s1 'q'"}, {"type":"recv", "payload":"B0 r2 m1234"} ]}, { "name": "A2 multiple zero 1st", "msgs": [{"type":"send", "payload":"A2 r7 m1234 0000 s1 'q'"}]}, { "name": "A2 multiple zero 2nd", "msgs": [{"type":"send", "payload":"A2 r7 m1234 s1 'q' 0000"}]}, { "name": "A2 short 4", "msgs": [{"type":"send", "payload":"A2 r4 m1234 0001"}]}, { "name": "A2 short 3", "msgs": [{"type":"send", "payload":"A2 r3 m1234 01"}]}, { "name": "A2 short 2 [MQTT-3.10.3-2]", "msgs": [{"type":"send", "payload":"A2 r2 m1234"}]}, { "name": "A2 short 1", "msgs": [{"type":"send", "payload":"A2 r1 12"}]}, { "name": "A2 short 0", "msgs": [{"type":"send", "payload":"A2 r0"}]}, { "name": "A0 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A0 r5 m1234 s1 'p'"}]}, { "name": "A3 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A3 r5 m1234 s1 'p'"}]}, { "name": "A4 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A4 r5 m1234 s1 'p'"}]}, { "name": "A6 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A6 r5 m1234 s1 'p'"}]}, { "name": "AA [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"AA r5 m1234 s1 'p'"}]}, { "name": "A2 topic with 0x0000", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746F700000"}]}, { "name": "A2 topic with U+D800", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746FEDA080"}]}, { "name": "A2 topic with U+0001", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746F700170"}]}, { "name": "A2 topic with U+001F", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746F701F70"}]}, { "name": "A2 topic with U+007F", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746F707F70"}]}, { "name": "A2 topic with U+009F", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746FC29F70"}]}, { "name": "A2 topic with U+FFFF", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746FEDBFBF"}]}, { "name": "A2 zero mid", "msgs": [ {"type":"send", "payload":"A2 r8 0000 s1 'p' s1 'q'"}]} ] }, { "group": "v5.0 UNSUBSCRIBE", "ver":5, "tests": [ { "name": "A2 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"A2 r6 m1234 00 s1 'p'"}]}, { "name": "A2 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"A2 r268435456"}]}, { "name": "A2 (no subscribe) [MQTT-3.10.4-5]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"A2 r6 m1234 v0 s1 'p'"}, {"type":"recv", "payload":"B0 r4 m1234 v0 11"} ]}, { "name": "A2 (with subscribe) [MQTT-3.10.4-5]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 00"}, {"type":"recv", "payload":"90 r4 m1234 v0 00"}, {"type":"send", "payload":"A2 r6 m1234 v0 s1 'p'"}, {"type":"recv", "payload":"B0 r4 m1234 v0 00"} ]}, { "name": "A2 multiple zero 1st", "msgs": [ {"type":"send", "payload":"A2 r8 m1234 v0 0000 s1 'q'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 multiple zero 2nd", "msgs": [ {"type":"send", "payload":"A2 r8 m1234 v0 s1 'q' 0000"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 short 5", "msgs": [ {"type":"send", "payload":"A2 r5 m1234 v0 0001"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 short 4", "msgs": [ {"type":"send", "payload":"A2 r4 m1234 v0 01"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 short 3 [MQTT-3.10.3-2]", "msgs": [ {"type":"send", "payload":"A2 r3 m1234 v0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 short 2", "msgs": [ {"type":"send", "payload":"A2 r1 1234"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 short 1", "msgs": [ {"type":"send", "payload":"A2 r1 12"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 short 0", "msgs": [ {"type":"send", "payload":"A2 r0"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A0 [MQTT-3.10.1-1]", "msgs": [ {"type":"send", "payload":"A0 r6 m1234 v0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A3 [MQTT-3.10.1-1]", "msgs": [ {"type":"send", "payload":"A3 r6 m1234 v0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A4 [MQTT-3.10.1-1]", "msgs": [ {"type":"send", "payload":"A4 r6 m1234 v0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A6 [MQTT-3.10.1-1]", "msgs": [ {"type":"send", "payload":"A6 r6 m1234 v0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "AA [MQTT-3.10.1-1]", "msgs": [ {"type":"send", "payload":"AA r6 m1234 v0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 topic with 0x0000", "msgs": [ {"type":"send", "payload":"A2 r10 m1234 v0 s5 746F700000"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 topic with U+D800", "msgs": [ {"type":"send", "payload":"A2 r10 m1234 v0 s5 746FEDA080"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 topic with U+0001", "msgs": [ {"type":"send", "payload":"A2 r10 m1234 v0 s5 746F700170"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 topic with U+001F", "msgs": [ {"type":"send", "payload":"A2 r10 m1234 v0 s5 746F701F70"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 topic with U+007F", "msgs": [ {"type":"send", "payload":"A2 r10 m1234 v0 s5 746F707F70"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 topic with U+009F", "msgs": [ {"type":"send", "payload":"A2 r10 m1234 v0 s5 746FC29F70"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 topic with U+FFFF", "msgs": [ {"type":"send", "payload":"A2 r10 m1234 v0 s5 746FEDBFBF"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 multiple [MQTT-3.10.4-6]", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"A2 r9 m1234 v0 s1 'p' s1 'q'"}, {"type":"recv", "payload":"B0 r5 m1234 v0 11 11"} ]}, { "name": "A2 zero mid", "msgs": [ {"type":"send", "payload":"A2 r6 m0 00 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] }, { "group": "v5.0 UNSUBSCRIBE ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "A2 with user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"A2 r13 m1 v7 26 s1 'p' s1 'q' s1 'p'"}, {"type":"recv", "payload":"B0 r4 m1 00 11"} ]}, { "name": "A2 with 2*user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"A2 r20 m1 v14 26 s1 'p' s1 'q' 26 s1 'p' s1 'q' s1 'p'"}, {"type":"recv", "payload":"B0 r4 m1 00 11"} ]}, { "name": "A2 with user-property missing value", "msgs": [ {"type":"send", "payload":"A2 r10 m1 v4 26 s1 'p' s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with user-property missing key,value", "msgs": [ {"type":"send", "payload":"A2 r7 m1 v1 26 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with user-property empty key", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"A2 r12 m1 v6 26 s0 s1 'p' s1 'p'"}, {"type":"recv", "payload":"B0 r4 m1 00 11"} ]}, { "name": "A2 with user-property empty value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"A2 r12 m1 v6 26 s1 'p' s0 s1 'p'"}, {"type":"recv", "payload":"B0 r4 m1 00 11"} ]}, { "name": "A2 with user-property empty key,value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"A2 r11 m1 v5 26 s0 s0 s1 'p'"}, {"type":"recv", "payload":"B0 r4 m1 00 11"} ]} ] }, { "group": "v5.0 UNSUBSCRIBE DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "A2 with payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 01 i0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 17 i0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 24 i0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with retain-available (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 25 i0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 28 i0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 29 i0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 2A i0 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with message-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"A2 r11 m1 v5 02 L1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"A2 r11 m1 v5 11 L1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"A2 r11 m1 v5 18 L1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"A2 r11 m1 v5 27 L1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"A2 r10 m1 v4 03 s1 'p' s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"A2 r10 m1 v4 08 s1 'p' s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"A2 r10 m1 v4 12 s1 'p' s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"A2 r10 m1 v4 15 s1 'p' s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"A2 r10 m1 v4 1A s1 'p' s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"A2 r10 m1 v4 1C s1 'p' s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"A2 r10 m1 v4 09 s1 'p' s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"A2 r10 m1 v4 16 s1 'p' s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with subscription-identifier (variable byte integer)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 0B v1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"A2 r9 m1 v3 13 H5 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"A2 r9 m1 v3 21 H5 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"A2 r9 m1 v3 22 H5 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"A2 r9 m1 v3 23 H5 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 00 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 04 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 05 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 06 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 07 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 0A i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 0C i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 0D i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 0E i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 0F i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 10 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 14 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 1B i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 1D i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 1E i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 20 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"A2 r8 m1 v2 7F i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"A2 r9 m1 v3 8000 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"A2 r9 m1 v3 8001 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"A2 r9 m1 v3 FF7F i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"A2 r10 m1 v4 808001 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"A2 r10 m1 v4 FFFF7F i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"A2 r11 m1 v5 80808001 i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "A2 with unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"A2 r11 m1 v5 FFFFFF7F i1 s1 'p'"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] } ] ================================================ FILE: test/broker/data/ZZ-broker-check.json ================================================ [ { "group": "BROKER CHECK", "tests": [ { "name": "END OF TEST", "ver":4, "expect_disconnect": false, "msgs": []} ] } ] ================================================ FILE: test/broker/dynamic-security-init.json ================================================ { "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 } } ================================================ FILE: test/broker/dynsec_helper.py ================================================ import json import mosq_test 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: if msg != "": print(msg) print(expected_response) print(response) raise ValueError(response) def check_details(sock, client_count, group_count, role_count, change_index): command = {"commands":[{ "command": "getDetails"}]} response = {'responses': [{'command': 'getDetails', 'data':{ 'clientCount':client_count, 'groupCount':group_count, 'roleCount':role_count, 'changeIndex': change_index }}]} command_check(sock, command, response) ================================================ FILE: test/broker/mosq_test_helper.py ================================================ import 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 from pathlib import Path source_dir = Path(__file__).resolve().parent ssl_dir = source_dir.parent / "ssl" import importlib def persist_module(): if len(sys.argv) > 1: mod = sys.argv.pop(1).replace(".py", "") else: raise RuntimeError("Not enough command line arguments - need persist module") return importlib.import_module(mod) def do_test_broker_failure( conf_file: str, config: list, port: int, rc_expected: int, error_log_entry: str = None, stdout_entry: str = None, cmd_args: list = [], with_test_config: bool = True, ): rc = 1 use_conf_file = len(conf_file) > 0 cmd_args = cmd_args.copy() if with_test_config and use_conf_file: cmd_args.insert(0, "--test-config") create_conf_file = use_conf_file and len(config) if create_conf_file: with open(conf_file, "w") as f: f.write("\n".join(config)) f.write("\n") try: broker = None broker = mosq_test.start_broker( conf_file, port=port, use_conf=use_conf_file, expect_fail=True, cmd_args=cmd_args, ) (stdo, stde) = broker.communicate() if broker.returncode != rc_expected: print(f"Expected broker return code {rc_expected}, got {broker.returncode}") print(stde.decode("utf-8")) return rc if error_log_entry is not None: error_log = stde.decode("utf-8") if error_log_entry not in error_log: print( f"Error log entry: '{error_log_entry}' not found in '{error_log}'" ) return rc if stdout_entry is not None: stdout_log = stdo.decode("utf-8") if stdout_entry not in stdout_log: print( f"Error stdout entry: '{stdout_entry}' not found in '{stdout_log}'" ) return rc rc = 0 except subprocess.TimeoutExpired: if broker is not None: mosq_test.wait_for_subprocess(broker, timeout=1) return rc except Exception as e: print(e) return rc finally: if create_conf_file: try: os.remove(conf_file) except FileNotFoundError: pass if rc: print( f"While testing 'config {chr(10).join(config) if len(config) else ''}'{', args '+ ' '.join(cmd_args) if cmd_args is not None else ''}" ) exit(rc) return rc ================================================ FILE: test/broker/msg_sequence_test.py ================================================ #!/usr/bin/env python3 # Test whether a valid CONNECT results in the correct CONNACK packet. from mosq_test_helper import * import importlib from os import walk import socket import json from collections import deque import mosq_test send = 1 recv = 2 disconnected_check = 3 connected_check = 4 publish = 5 class SingleMsg(object): __slots__ = 'action', 'message', 'comment' def __init__(self, action, message, comment=''): self.action = action self.message = message self.comment = comment class MsgSequence(object): __slots__ = 'name', 'msgs', 'msgs_all', 'expect_disconnect', 'port', 'protocol' def __init__(self, name, default_connect=True, port=1888, protocol='mqtt', proto_ver=4, expect_disconnect=True): self.name = name self.msgs_all = deque() self.expect_disconnect = expect_disconnect self.port = port self.protocol = protocol if default_connect: self.add_default_connect(proto_ver=proto_ver) def add_default_connect(self, proto_ver): self.add_send(mosq_test.gen_connect(self.name, proto_ver=proto_ver)) self.add_recv(mosq_test.gen_connack(rc=0, proto_ver=proto_ver), "default connack") def add_send(self, message): self._add(send, message) def add_recv(self, message, comment): self._add(recv, message, comment) def add_publish(self, message, comment): self._add(publish, message, comment) def add_connected_check(self): self._add(connected_check, b"") def add_disconnected_check(self): self._add(disconnected_check, b"") def _add(self, action, message, comment=""): msg = SingleMsg(action, message, comment) self.msgs_all.append(msg) def _connected_check(self, sock): try: mosq_test.do_ping(sock) except (BrokenPipeError, mosq_test.TestError): raise ValueError("connection failed") def _send_message(self, sock, msg): sock.send(msg.message) def _publish_message(self, msg): sock = mosq_test.client_connect_only(hostname="localhost", port=self.port, timeout=2, protocol=self.protocol) sock.send(mosq_test.gen_connect("helper")) mosq_test.expect_packet(sock, "connack", mosq_test.gen_connack(rc=0)) m = msg.message if m['qos'] == 0: sock.send(mosq_test.gen_publish(topic=m['topic'], payload=m['payload'])) elif m['qos'] == 1: sock.send(mosq_test.gen_publish(mid=1, qos=1, topic=m['topic'], payload=m['payload'])) mosq_test.expect_packet(sock, "helper puback", mosq_test.gen_puback(mid=1)) elif m['qos'] == 2: sock.send(mosq_test.gen_publish(mid=1, qos=2, topic=m['topic'], payload=m['payload'])) mosq_test.expect_packet(sock, "helper pubrec", mosq_test.gen_pubrec(mid=1)) sock.send(mosq_test.gen_pubrel(mid=1)) mosq_test.expect_packet(sock, "helper pubcomp", mosq_test.gen_pubcomp(mid=1)) sock.close() def _recv_message(self, sock, msg): data = sock.recv(len(msg.message)) if data != msg.message: raise ValueError("Receive message %s | rec:%s | exp:%s" % (msg.comment, data, msg.message)) def _disconnected_check(self, sock): try: data = sock.recv(1) if len(data) == 1 and self.expect_disconnect: raise ValueError("Still connected") except (ConnectionResetError, BlockingIOError): if self.expect_disconnect: pass else: raise def _process_message(self, sock, msg): if msg.action == send: self._send_message(sock, msg) elif msg.action == recv: self._recv_message(sock, msg) elif msg.action == publish: self._publish_message(msg) elif msg.action == disconnected_check: self._disconnected_check(sock) elif msg.action == connected_check: self._connected_check(sock) def process_next(self, sock): msg = self.msgs.popleft() self._process_message(sock, msg) def process_all(self, sock): self.msgs = self.msgs_all.copy() while len(self.msgs): self.process_next(sock) if self.expect_disconnect: self._disconnected_check(sock) else: self._connected_check(sock) def parse_message(message): b = bytes() parts = message.split(" ") for i in range(0, len(parts)): if len(parts[i]) == 0: continue elif parts[i][0] in ['i']: # General 8-bit unsigned decimal b += int(parts[i][1:]).to_bytes(length=1, byteorder='big', signed=False) elif parts[i][0] in ['H', 'k', 'm', 's']: # General 16-bit unsigned decimal # Or 'k' keepalive specific # Or 'm' mid specific # Or 's' string specific b += int(parts[i][1:]).to_bytes(length=2, byteorder='big', signed=False) elif parts[i][0] == "L": # 32-bit unsigned decimal b += int(parts[i][1:]).to_bytes(length=4, byteorder='big', signed=False) elif parts[i][0] == "'": s = parts[i][1:] while s[-1] != "'" and i < len(parts)-1: i += 1 s += " " + parts[i] if s[-1] != "'": raise ValueError(f"message {message} has incomplete string type") b += bytes(s[0:-1].encode('utf-8')) elif parts[i][0] in ['v', 'r']: # General variable length integer # Or 'r' remaining length v = int(parts[i][1:]) # This allows non-compliant values >=2^28 while True: byte = v % 128 v = v // 128 if v > 0: byte = byte | 0x80 b += byte.to_bytes(length=1, byteorder='big', signed=False) if v == 0: break else: # hex try: b += bytes.fromhex(parts[i]) except ValueError: raise ValueError(f"message {message} has invalid hex bytes") return b def do_test(hostname, port, protocol): data_path=Path(__file__).resolve().parent/"data" rc = 0 sequences = [] for (_, _, filenames) in walk(data_path): sequences.extend(filenames) break total = 0 succeeded = 0 test = None failed_tests = [] for seq in sorted(sequences): if seq[-5:] != ".json": continue with open(data_path/seq, "r") as f: test_file = json.load(f) for g in test_file: group_name = g["group"] try: disabled = g["disable"] if disabled: continue except KeyError: pass try: g_proto_ver = g["ver"] except KeyError: g_proto_ver = 4 try: g_connect = g["connect"] except KeyError: g_connect = True try: g_expect_disconnect = g["expect_disconnect"] except KeyError: g_expect_disconnect = True tests = g["tests"] for t in tests: tname = group_name + " " + t["name"] try: proto_ver = t["ver"] except KeyError: proto_ver = g_proto_ver try: connect = t["connect"] except KeyError: connect = g_connect try: expect_disconnect = t["expect_disconnect"] except KeyError: expect_disconnect = g_expect_disconnect this_test = MsgSequence(tname, port=port, protocol=protocol, proto_ver=proto_ver, expect_disconnect=expect_disconnect, default_connect=connect) for m in t["msgs"]: try: c = m["comment"] except KeyError: c = "" if m["type"] == "send": this_test.add_send(parse_message(m["payload"])) elif m["type"] == "recv": this_test.add_recv(parse_message(m["payload"]), c) elif m["type"] == "publish": this_test.add_publish(m, c) total += 1 try: failed_tests.append(this_test) sock = mosq_test.client_connect_only(hostname=hostname, port=port, timeout=2, protocol=protocol) this_test.process_all(sock) #print("\033[32m" + tname + "\033[0m") succeeded += 1 sock.close() failed_tests.pop() except ValueError as e: print("\033[31m" + tname + " failed: " + str(e) + "\033[0m") rc = 1 sock.close() except ConnectionResetError as e: print("\033[31m" + tname + " failed: " + str(e) + "\033[0m") rc = 1 sock.close() except socket.timeout as e: print("\033[31m" + tname + " failed: " + str(e) + "\033[0m") rc = 1 sock.close() exit() except mosq_test.TestError as e: print("\033[31m" + tname + " failed: " + str(e) + "\033[0m") rc = 1 sock.close() # Option to replay failed tests to make them easier to analyse. if False: for t in failed_tests: try: sock = mosq_test.client_connect_only(hostname=hostname, port=port, timeout=2, protocol=protocol) t.process_all(sock) length = len(data) print("\033[32m" + t.name + "\033[0m") sock.close() except ValueError as e: print("\033[31m" + t.name + " failed: " + str(e) + "\033[0m") rc = 1 sock.close() except ConnectionResetError as e: print("\033[31m" + t.name + " failed: " + str(e) + "\033[0m") rc = 1 sock.close() except socket.timeout as e: print("\033[31m" + t.name + " failed: " + str(e) + "\033[0m") rc = 1 sock.close() except mosq_test.TestError as e: print("\033[31m" + t.name + " failed: " + str(e) + "\033[0m") rc = 1 sock.close() print("%d tests total\n%d tests succeeded" % (total, succeeded)) return rc def write_config(filename, port, protocol): with open(filename, 'w') as f: f.write(f'listener {port}\n') f.write(f'protocol {protocol}\n') f.write("allow_anonymous true\n") f.write("log_type all\n") def main(protocol): hostname = "localhost" port = mosq_test.get_port() conf_file = 'msg_sequence_test.conf' write_config(conf_file, port, protocol) broker = mosq_test.start_broker(filename=conf_file, port=port, use_conf=True, nolog=True) rc = 0 try: rc = do_test(hostname=hostname, port=port, protocol=protocol) finally: broker.terminate() os.remove(conf_file) if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 if broker.returncode != 0: rc = broker.returncode print(f"Broker exited with code {rc}. If there are no obvious errors this may be due to an ASAN build having leaks, which must be fixed.") print("The easiest way to reproduce this is to run the broker with `mosquitto -p 1888`, rerun the test, then quit the broker.") (stdo, stde) = broker.communicate() if rc: #print(stde.decode('utf-8')) exit(rc) if __name__ == "__main__": #main(protocol="websockets") main(protocol="mqtt") ================================================ FILE: test/broker/ntest.py ================================================ #!/usr/bin/env python3 import mosq_test_helper import mosq_test import os import ptest import threading import importlib import time tests = [ '01-connect-bad-packet', '01-connect-disconnect-v5', '01-connect-duplicate', '01-connect-invalid-id-0', '01-connect-invalid-id-missing', '01-connect-invalid-id-utf8', '01-connect-invalid-protonum', '01-connect-invalid-reserved', '01-connect-success', '01-connect-uname-invalid-utf8', '01-connect-uname-no-flag', '01-connect-uname-pwd-no-flag', '02-shared-nolocal', '02-shared-qos0-v5', '02-subhier-crash', '02-subpub-b2c-topic-alias', '02-subpub-qos0-long-topic', '02-subpub-qos0-retain-as-publish', '02-subpub-qos0-send-retain', '02-subpub-qos0-subscription-id', '02-subpub-qos0-topic-alias-unknown', '02-subpub-qos0-topic-alias', '02-subpub-qos0', '02-subpub-qos1-bad-pubcomp', '02-subpub-qos1-bad-pubrec', '02-subpub-qos1-message-expiry-retain', '02-subpub-qos1-message-expiry-will', '02-subpub-qos1-message-expiry', '02-subpub-qos1-nolocal', '02-subpub-qos1', '02-subpub-qos2-1322', '02-subpub-qos2-bad-puback-1', '02-subpub-qos2-bad-puback-2', '02-subpub-qos2-bad-pubcomp', '02-subpub-qos2-pubrec-error', '02-subpub-qos2-receive-maximum-1', '02-subpub-qos2-receive-maximum-2', '02-subpub-qos2', '02-subscribe-dollar-v5', '02-subscribe-invalid-utf8', '02-subscribe-long-topic', '02-subscribe-persistence-flipflop', '02-subscribe-qos0', '02-subscribe-qos1', '02-subscribe-qos2', '02-unsubscribe-invalid-no-topic', '02-unsubscribe-qos0', '02-unsubscribe-qos1', '02-unsubscribe-qos2-multiple', '02-unsubscribe-qos2', ##'03-pattern-matching', '03-publish-b2c-disconnect-qos1', '03-publish-b2c-disconnect-qos2', '03-publish-b2c-qos1-len', '03-publish-b2c-qos2-len', '03-publish-c2b-disconnect-qos2', '03-publish-c2b-qos2-len', '03-publish-dollar-v5', '03-publish-dollar', '03-publish-invalid-utf8', '03-publish-long-topic', '03-publish-qos1-no-subscribers-v5', '03-publish-qos1', '03-publish-qos2', '04-retain-qos0-clear', '04-retain-qos0-fresh', '04-retain-qos0-repeated', '04-retain-qos0', '04-retain-qos1-qos0', '05-clean-session-qos1', '05-session-expiry-v5', '06-bridge-no-local', '07-will-delay', '07-will-delay-reconnect', '07-will-delay-recover', '07-will-delay-session-expiry', '07-will-delay-session-expiry2', '07-will-disconnect-with-will', '07-will-invalid-utf8', '07-will-no-flag', '07-will-null', '07-will-null-topic', '07-will-properties', '07-will-qos0', '07-will-reconnect-1273', '07-will-takeover', '09-auth-bad-method', '09-extended-auth-unsupported', '12-prop-assigned-client-identifier', '12-prop-maximum-packet-size-connect', '12-prop-maximum-packet-size-publish', '12-prop-maximum-packet-size-publish-qos1', '12-prop-maximum-packet-size-publish-qos2', '12-prop-response-topic', '12-prop-response-topic-correlation-data', '12-prop-session-expiry-invalid', '12-prop-subpub-content-type', '12-prop-subpub-payload-format', '12-prop-topic-alias-invalid', '13-malformed-subscribe-v5', '13-malformed-unsubscribe-v5', ] def single_test(name): start_time = time.time() try: mod = importlib.import_module(name) except ModuleNotFoundError: print("------ : \033[31m%s\033[0m test not found" % (name)) return 1 rc = mod.all_tests() runtime = time.time() - start_time if rc: print("%0.3fs : \033[31m%s\033[0m" % (runtime, name)) else: print("%0.3fs : \033[32m%s\033[0m" % (runtime, name)) return rc port = mosq_test.get_port() broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port, nolog=True) rc = 0 try: # FIXME - use Queue instead to limit max threads threads = [] for test in tests: t = threading.Thread(target=single_test, args=(test,), name=test) threads.append(t) t.start() # FIXME - return code for t in threads: t.join() finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) ================================================ FILE: test/broker/persist_module_helper.py ================================================ #!/usr/bin/env python3 import socket import mosq_test import mqtt5_props from typing import Any, Optional from types import ModuleType def connect_client( port: int, client_id: str, username: str, proto_ver: int, session_expiry: int, session_present: bool = False, subscribe_topic: Optional[str] = None, qos: int = 1, **connect_params: Any, ): connect_packet = mosq_test.gen_connect( client_id=client_id, username=username, proto_ver=proto_ver, clean_session=session_expiry == 0, session_expiry=session_expiry, **connect_params, ) connack_packet = mosq_test.gen_connack( rc=0, proto_ver=proto_ver, flags=1 if session_present else 0 ) sock = mosq_test.do_client_connect( connect_packet, connack_packet, timeout=5, port=port ) if subscribe_topic is not None: mid = 1 subscribe_packet = mosq_test.gen_subscribe( mid, subscribe_topic, qos, proto_ver=proto_ver ) suback_packet = mosq_test.gen_suback(mid, qos=qos, proto_ver=proto_ver) mosq_test.do_send_receive(sock, subscribe_packet, suback_packet, "suback") return sock def publish_messages( sock: socket, proto_ver: int, topic: str, start: int, end: int, retain_end=0, message_expiry: int = 0, qos: int = 1, ): for i in range(start, end): payload = f"queued message {i:3}" mid = 10 + i props = ( mqtt5_props.gen_uint32_prop( mqtt5_props.MESSAGE_EXPIRY_INTERVAL, message_expiry ) if message_expiry > 0 else b"" ) publish_packet = mosq_test.gen_publish( topic, mid=mid, qos=qos, payload=payload.encode("UTF-8"), retain=True if i < retain_end else False, proto_ver=proto_ver, properties=props, ) puback_packet = mosq_test.gen_puback(mid=mid, proto_ver=proto_ver) mosq_test.do_send_receive(sock, publish_packet, puback_packet, "puback") def check_db( persist_help: ModuleType, port: int, username: str, subscription_topic: str, client_msg_counts: dict[str, int], publisher_id: str, num_published_msgs: int, retain_end: int = 0, message_expiry: int = 0, qos: int = 1, check_session_expiry_time: bool = True, ): count_list = [v for v in client_msg_counts.values() if v is not None] + [0] num_base_msgs = max(count_list) num_subscriptions = sum(1 for c in client_msg_counts.values() if c is not None) num_client_msgs_out = sum(count_list) persist_help.check_counts( port, clients=len(client_msg_counts), client_msgs_out=num_client_msgs_out, base_msgs=num_base_msgs if num_base_msgs > 0 or retain_end == 0 else 1, retain_msgs=1 if retain_end > 0 else 0, subscriptions=num_subscriptions, ) # Check client for client_id, num_messages_for_client in client_msg_counts.items(): persist_help.check_client( port, client_id, username=username, will_delay_time=0, session_expiry_time=60 if check_session_expiry_time else None, listener_port=None, # persist-lmdb reset listener port to 0 on disconnect max_packet_size=0, max_qos=2, retain_available=1, session_expiry_interval=60, will_delay_interval=0, ) # Check subscription if num_messages_for_client is not None: persist_help.check_subscription(port, client_id, subscription_topic, qos, 0) # Check stored message for i in range(num_base_msgs): msg_id = num_published_msgs - num_base_msgs + i payload = f"queued message {msg_id:3}" payload_b = payload.encode("UTF-8") mid = 10 + msg_id store_id = persist_help.check_base_msg( port, message_expiry, subscription_topic, payload_b, publisher_id, username, len(payload_b), mid, port, qos, retain=1 if i < retain_end else 0, idx=i, ) # Check client msg for client_id, num_messages_for_client in client_msg_counts.items(): if num_messages_for_client is None: continue client_msg_start = num_published_msgs - num_messages_for_client if msg_id < client_msg_start: continue cmsg_id = 1 + msg_id - client_msg_start subscriber_mid = cmsg_id persist_help.check_client_msg( port, client_id, cmsg_id, store_id, 0, persist_help.dir_out, subscriber_mid, qos, 0, persist_help.ms_queued, ) ================================================ FILE: test/broker/persist_sqlite.py ================================================ import os from pathlib import Path import sqlite3 import mosq_test dir_in = 0 dir_out = 1 ms_invalid = 0 ms_publish_qos0 = 1 ms_publish_qos1 = 2 ms_wait_for_puback = 3 ms_publish_qos2 = 4 ms_wait_for_pubrec = 5 ms_resend_pubrel = 6 ms_wait_for_pubrel = 7 ms_resend_pubcomp = 8 ms_wait_for_pubcomp = 9 ms_send_pubrec = 10 ms_queued = 11 def write_config(filename, port, additional_config_entries: dict = {}): with open(filename, "w") as f: f.write("listener %d\n" % (port)) f.write("allow_anonymous true\n") f.write( f"plugin {mosq_test.get_build_root()}/plugins/persist-sqlite/mosquitto_persist_sqlite.so\n" ) f.write("plugin_opt_db_file %d/mosquitto.sqlite3\n" % (port)) for entry, value in additional_config_entries.items(): f.write(f"{entry} {value}\n") # The create_db_of_version contains the database schema version introduced with Pro Mosquitto 2.8. # The list of supported version includes artificial versions, which are used for databases created # prior to the current version # 0.9.0: DB from Mosquitto without version info table # 1.0.0: DB created with latest version of plugin def init(port, create_db_of_version: list[int] = None): try: os.mkdir(str(port)) except FileExistsError: try: os.remove(f"{port}/mosquitto.sqlite3") except FileNotFoundError: pass if create_db_of_version is not None: con = sqlite3.connect(f"{port}/mosquitto.sqlite3") cursor = con.cursor() for statement in [ "PRAGMA page_size=4096;", "PRAGMA journal_mode=WAL;", "PRAGMA foreign_keys = ON;", "PRAGMA synchronous=1;", "CREATE TABLE base_msgs (store_id INT64 PRIMARY KEY,expiry_time INT64,topic STRING NOT NULL,payload BLOB,source_id STRING,source_username STRING,payloadlen INTEGER,source_mid INTEGER,source_port INTEGER,qos INTEGER,retain INTEGER,properties STRING);", "CREATE TABLE retains (topic STRING PRIMARY KEY,store_id INT64);", "CREATE TABLE clients (client_id TEXT PRIMARY KEY,username TEXT,connection_time INT64,will_delay_time INT64,session_expiry_time INT64,listener_port INT,max_packet_size INT,max_qos INT,retain_available INT,session_expiry_interval INT,will_delay_interval INT);", "CREATE TABLE subscriptions (client_id TEXT NOT NULL,topic TEXT NOT NULL,subscription_options INTEGER,subscription_identifier INTEGER,PRIMARY KEY (client_id, topic) );", ]: cursor.execute(statement) if create_db_of_version[0] == 0 and create_db_of_version[1] == 9: for statement in [ "CREATE TABLE client_msgs (client_id TEXT NOT NULL,cmsg_id INT64,store_id INT64,dup INTEGER,direction INTEGER,mid INTEGER,qos INTEGER,retain INTEGER,state INTEGER,subscription_identifier INTEGER);", ]: cursor.execute(statement) elif create_db_of_version[0] >= 1: for statement in [ "CREATE TABLE client_msgs (client_id TEXT NOT NULL,cmsg_id INT64,store_id INT64,dup INTEGER,direction INTEGER,mid INTEGER,qos INTEGER,retain INTEGER,state INTEGER,subscription_identifier INTEGER);", "CREATE TABLE version_info (component TEXT NOT NULL,major INTEGER NOT NULL,minor INTEGER NOT NULL,patch INTEGER NOT NULL);", f"INSERT INTO version_info(component,major,minor,patch) VALUES ('database_schema',{','.join([str(i) for i in create_db_of_version])});", ]: cursor.execute(statement) if create_db_of_version[1] >= 1: for statement in [ "CREATE TABLE wills(client_id TEXT PRIMARY KEY,payload BLOB,topic STRING NOT NULL,payloadlen INTEGER,qos INTEGER,retain INTEGER,properties STRING);" ]: cursor.execute(statement) cursor.close() con.commit() con.close() # We need to set write permission to everybody as broker will start with privilege drop os.chmod(f"{port}/mosquitto.sqlite3", 0o666) def cleanup(port): rc = 1 try: os.remove(f"{port}/mosquitto.sqlite3") except FileNotFoundError: pass try: os.rmdir(f"{port}") rc = 0 except OSError as e: if Path(str(port), "mosquitto.sqlite3-wal").stat().st_size == 0: # some versions of sqlite3 do not remove the wal file # thus we make sure that the file is at least empty (no pending db transactions) rc = 0 else: print(f"ERROR sqlite3 file not removed after shutdown") try: os.remove(f"{port}/mosquitto.sqlite3-shm") except FileNotFoundError: pass try: os.remove(f"{port}/mosquitto.sqlite3-wal") except FileNotFoundError: pass os.rmdir(f"{port}") return rc def check_version_infos(port, database_schema_version): con = sqlite3.connect(f"{port}/mosquitto.sqlite3") cur = con.cursor() cur.execute( "SELECT major,minor,patch FROM version_info WHERE component = 'database_schema';" ) row = cur.fetchone() if len(row) != len(database_schema_version): raise ValueError("Could not fetch db version info from DB") for i in range(len(row)): if row[i] != database_schema_version[i]: raise ValueError( f"DB version info {'.'.join([str(v) for v in row])} != expected {'.'.join([str(v) for v in database_schema_version])}" ) con.close() def check_counts( port, clients=0, client_msgs_in=0, client_msgs_out=0, base_msgs=0, retain_msgs=0, subscriptions=0, wills=None ): con = sqlite3.connect(f"{port}/mosquitto.sqlite3") cur = con.cursor() cur.execute("SELECT COUNT(*) FROM clients") row = cur.fetchone() if row[0] != clients: raise ValueError("Found %d clients, expected %d" % (row[0], clients)) cur.execute("SELECT COUNT(*) FROM client_msgs WHERE direction=0") row = cur.fetchone() if row[0] != client_msgs_in: raise ValueError( "Found %d client_msgs_in, expected %d" % (row[0], client_msgs_in) ) cur.execute("SELECT COUNT(*) FROM client_msgs WHERE direction=1") row = cur.fetchone() if row[0] != client_msgs_out: raise ValueError( "Found %d client_msgs_out, expected %d" % (row[0], client_msgs_out) ) cur.execute("SELECT COUNT(*) FROM subscriptions") row = cur.fetchone() if row[0] != subscriptions: raise ValueError( "Found %d subscriptions, expected %d" % (row[0], subscriptions) ) cur.execute("SELECT COUNT(*) FROM base_msgs") row = cur.fetchone() if row[0] != base_msgs: raise ValueError("Found %d base_msgs, expected %d" % (row[0], base_msgs)) cur.execute("SELECT COUNT(*) FROM retains") row = cur.fetchone() if row[0] != retain_msgs: raise ValueError("Found %d retain_msgs, expected %d" % (row[0], retain_msgs)) if wills is not None: cur.execute("SELECT COUNT(*) FROM wills") row = cur.fetchone() if row[0] != wills: raise ValueError("Found %d wills, expected %d" % (row[0], wills)) con.close() def check_client( port, client_id, username, will_delay_time, session_expiry_time, listener_port, max_packet_size, max_qos, retain_available, session_expiry_interval, will_delay_interval, ): # "Fix" the infinite session expiry interval as mangled by an int32 conversion. if session_expiry_interval == 4294967295: session_expiry_interval = -1 con = sqlite3.connect(f"{port}/mosquitto.sqlite3") cur = con.cursor() cur.execute( "SELECT client_id, username, will_delay_time, session_expiry_time, " + "listener_port, max_packet_size, max_qos, retain_available, " + "session_expiry_interval, will_delay_interval " + "FROM clients " + f"WHERE client_id = '{client_id}'" ) row = cur.fetchone() if row is None: raise ValueError(f"Cannot find client {client_id} in db") if row[0] != client_id: raise ValueError("Invalid client_id %s / %s" % (row[0], client_id)) if username is not None and row[1] != username: raise ValueError("Invalid username %s / %s" % (row[1], username)) if (will_delay_time == 0 and row[2] != 0) or (will_delay_time != 0 and row[2] == 0): raise ValueError("Invalid will_delay_time %d / %d" % (row[2], will_delay_time)) if session_expiry_time and ( (session_expiry_time == 0 and row[3] != 0) or (session_expiry_time != 0 and row[3] == 0) ): raise ValueError( "Invalid session_expiry_time %d / %d for client %s" % (row[3], session_expiry_time, client_id) ) if listener_port is not None and row[4] != listener_port: raise ValueError("Invalid listener_port %d / %d" % (row[4], listener_port)) if row[5] != max_packet_size: raise ValueError("Invalid max_packet_size %d / %d" % (row[5], max_packet_size)) if row[6] != max_qos: raise ValueError("Invalid max_qos %d / %d" % (row[6], max_qos)) if row[7] != retain_available: raise ValueError( "Invalid retain_available %d / %d" % (row[7], retain_available) ) if row[8] != session_expiry_interval: raise ValueError( "Invalid session_expiry_interval %d / %d" % (row[8], session_expiry_interval) ) if row[9] != will_delay_interval: raise ValueError( "Invalid will_delay_interval %d / %d" % (row[9], will_delay_interval) ) con.close() def modify_client(port: int, client_id: str, sub_expiry_time: int): num_modified_rows = 0 con = sqlite3.connect(f"{port}/mosquitto.sqlite3") try: cur = con.cursor() cur.execute( "UPDATE clients" + f" SET session_expiry_time = session_expiry_time - {sub_expiry_time}" + f" WHERE client_id = ?", (client_id,), ) num_modified_rows = cur.rowcount con.commit() finally: con.close() return num_modified_rows def check_subscription( port, client_id, topic, subscription_options, subscription_identifier ): con = sqlite3.connect(f"{port}/mosquitto.sqlite3") cur = con.cursor() cur.execute( "SELECT client_id, topic, subscription_options, subscription_identifier " + "FROM subscriptions " + f"WHERE client_id = '{client_id}'" ) row = cur.fetchone() if row is None: raise ValueError(f"Cannot find client {client_id} in db") if row[0] != client_id: raise ValueError("Invalid client_id %s / %s" % (row[0], client_id)) if row[1] != topic: raise ValueError("Invalid topic %s / %s" % (row[1], topic)) if row[2] != subscription_options: raise ValueError( "Invalid subscription_options %d / %d" % (row[2], subscription_options) ) if row[3] != subscription_identifier: raise ValueError( "Invalid subscription_identifier %d / %d" % (row[3], subscription_identifier) ) con.close() def check_client_msg( port, client_id, cmsg_id, store_id, dup, direction, mid, qos, retain, state ): con = sqlite3.connect(f"{port}/mosquitto.sqlite3") try: cur = con.cursor() cur.execute( "SELECT client_id,cmsg_id,store_id,dup,direction,mid,qos,retain,state " + "FROM client_msgs " + f"WHERE client_id = '{client_id}' AND cmsg_id = {cmsg_id}" ) row = cur.fetchone() msg_id = f"client_id={client_id},cmsg_id={cmsg_id}" if row is None: raise ValueError( f"Cannot find client message client_id = {client_id} cmsg_id = {msg_id} in db." ) if row[0] != client_id: raise ValueError( "Invalid client_id %s / %s for message %s" % (row[0], client_id, msg_id) ) if row[1] != cmsg_id: raise ValueError( "Invalid cmsg_id %s / %s for message %s" % (row[1], cmsg_id, msg_id) ) if row[2] != store_id: raise ValueError( "Invalid store_id %d / %d for message %s" % (row[2], store_id, msg_id) ) if row[3] != dup: raise ValueError( "Invalid dup %d / %d for message %s" % (row[3], dup, msg_id) ) if row[4] != direction: raise ValueError( "Invalid direction %d / %d for message %s" % (row[4], direction, msg_id) ) if row[5] != mid: raise ValueError( "Invalid mid %d / %d for message %s" % (row[5], mid, msg_id) ) if row[6] != qos: raise ValueError( "Invalid qos %d / %d for message %s" % (row[6], qos, msg_id) ) if row[7] != retain: raise ValueError( "Invalid retain %d / %d for message %s" % (row[7], retain, msg_id) ) if row[8] != state: raise ValueError( "Invalid state %d / %d for message %s" % (row[8], state, msg_id) ) finally: con.close() def check_base_msg( port, expiry_time, topic, payload, source_id, source_username, payloadlen, source_mid, source_port, qos, retain, idx=0, ): con = sqlite3.connect(f"{port}/mosquitto.sqlite3") try: cur = con.cursor() cur.execute( "SELECT store_id,expiry_time,topic,payload,source_id,source_username, " + "payloadlen, source_mid, source_port, qos, retain " + "FROM base_msgs " ) for i in range(0, idx + 1): row = cur.fetchone() if row is None: raise ValueError(f"no base messages") if row[0] == 0: raise ValueError("Invalid store_id %d / %d" % (row[0], store_id)) if (expiry_time == 0 and row[1] != 0) or (expiry_time != 0 and row[1] == 0): raise ValueError("Invalid expiry_time %d / %d" % (row[1], expiry_time)) if row[2] != topic: raise ValueError("Invalid topic %s / %s" % (row[2], topic)) if row[3] != payload: raise ValueError("Invalid payload %s / %s" % (row[3], payload)) if row[4] != source_id: raise ValueError("Invalid source_id %s / %s" % (row[4], source_id)) if row[5] != source_username: raise ValueError( "Invalid source_username %s / %s" % (row[5], source_username) ) if row[6] != payloadlen or (payloadlen != 0 and row[6] != len(row[3])): raise ValueError("Invalid payloadlen %d / %d" % (row[6], payloadlen)) if row[7] != source_mid: raise ValueError("Invalid source_mid %d / %d" % (row[7], source_mid)) if row[8] != source_port: raise ValueError("Invalid source_port %d / %d" % (row[8], source_port)) if row[9] != qos: raise ValueError("Invalid qos %d / %d" % (row[9], qos)) if row[10] != retain: raise ValueError("Invalid retain %d / %d" % (row[10], retain)) except ValueError as err: raise ValueError(str(err) + f" at index {idx}") from err finally: con.close() return row[0] def modify_base_msgs( port: int, sub_expiry_time: int, ): num_modified_rows = 0 con = sqlite3.connect(f"{port}/mosquitto.sqlite3") try: cur = con.cursor() cur.execute( "UPDATE base_msgs" + f" SET expiry_time = expiry_time - {sub_expiry_time}" ) num_modified_rows = cur.rowcount con.commit() finally: con.close() return num_modified_rows def check_retain(port, topic, store_id): con = sqlite3.connect(f"{port}/mosquitto.sqlite3") cur = con.cursor() cur.execute("SELECT store_id FROM retains WHERE topic=?", (topic,)) row = cur.fetchone() if row[0] != store_id: raise ValueError("Invalid store_id %d / %d" % (row[0], store_id)) con.close() def check_will( port, client_id: str, payload: bytes, topic: str, qos: int, retain: int, properties: str, idx=0, ): con = sqlite3.connect(f"{port}/mosquitto.sqlite3") try: cur = con.cursor() cur.execute( "SELECT client_id,topic,payload,payloadlen,qos,retain,properties " "FROM wills", ) for i in range(0, idx + 1): row = cur.fetchone() if row is None: raise ValueError(f"no will at index {idx}") if row[0] != client_id: raise ValueError(f"Invalid client_id {row[0]} / {client_id}") if row[1] != topic: raise ValueError("Invalid topic %s / %s" % (row[2], topic)) if row[2] != payload: raise ValueError("Invalid payload %s / %s" % (row[2], payload)) if row[3] != len(payload): raise ValueError("Invalid payloadlen %d / %d" % (row[3], len(payload))) if row[4] != qos: raise ValueError("Invalid qos %d / %d" % (row[4], qos)) if row[5] != retain: raise ValueError("Invalid retain %d / %d" % (row[5], retain)) if row[6] != properties: raise ValueError("Invalid properties %s / %s" % (row[6], properties)) except ValueError as err: raise ValueError(str(err) + f" at index {idx}") from err finally: con.close() return row[0] ================================================ FILE: test/broker/prop_subpub_helper.py ================================================ #!/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(start_broker, test_name, props_out, props_in, expect_proto_error=False): rc = 1 mid = 53 connect_packet = mosq_test.gen_connect(test_name, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet = mosq_test.gen_subscribe(mid, "%s/subpub/qos0" % (test_name), 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) publish_packet_out = mosq_test.gen_publish("%s/subpub/qos0" % (test_name), qos=0, payload="message", proto_ver=5, properties=props_out) publish_packet_expected = mosq_test.gen_publish("%s/subpub/qos0" % (test_name), qos=0, payload="message", proto_ver=5, properties=props_in) disconnect_packet = mosq_test.gen_disconnect(reason_code=mqtt5_rc.PROTOCOL_ERROR, proto_ver=5) port = mosq_test.get_port() if start_broker: 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") if expect_proto_error: mosq_test.do_send_receive(sock, publish_packet_out, disconnect_packet, "publish") else: mosq_test.do_send_receive(sock, publish_packet_out, publish_packet_expected, "publish") rc = 0 sock.close() except mosq_test.TestError: pass finally: if start_broker: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) else: return rc ================================================ FILE: test/broker/proxy_helper.py ================================================ import socket PROXY_VER = 0x20 PROXY_CMD_LOCAL = 0x00 PROXY_CMD_PROXY = 0x01 PROXY_FAM_UNSPEC = 0x00 PROXY_FAM_IPV4 = 0x10 PROXY_FAM_IPV6 = 0x20 PROXY_FAM_UNIX = 0x30 PROXY_PROTO_UNSPEC = 0x00 PROXY_PROTO_TCP = 0x01 PROXY_PROTO_UDP = 0x02 def do_connect(port, data): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(5) sock.connect(("localhost", port)) sock.send(data) return sock def do_proxy_v2_connect(port, ver, cmd, fam, data): proxy_header = b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a" l = len(data) proxy_header += bytes([ver | cmd, fam, (l&0xFF00)>>8, l&0xFF]) proxy_header += data return do_connect(port, proxy_header) def do_proxy_v1_connect(port, data): return do_connect(port, data) ================================================ FILE: test/broker/readme.txt ================================================ ----- 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 13: Malformed tests 14: Dynamic security tests ================================================ FILE: test/broker/test.py ================================================ #!/usr/bin/env python3 import sys sys.path.insert(0, "..") import ptest tests = [ #(ports required, 'path'), (1, './msg_sequence_test.py'), (1, './01-bad-initial-packets.py'), (1, './01-connect-575314.py'), (1, './01-connect-accept-protocol.py'), (1, './01-connect-allow-anonymous.py'), (2, './01-connect-auto-id.py'), (1, './01-connect-disconnect-v5.py'), (1, './01-connect-global-max-clients.py'), (1, './01-connect-global-max-connections.py'), (2, './01-connect-listener-allow-anonymous.py'), (1, './01-connect-max-connections.py'), (1, './01-connect-max-keepalive.py'), (1, './01-connect-take-over.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-unix-socket.py'), (1, './01-connect-windows-line-endings.py'), (2, './01-connect-zero-length-id.py'), (1, './01-plugin-connect-uname-password-denied.py'), (1, './02-shared-nolocal.py'), (1, './02-shared-qos0-v5.py'), (1, './02-subhier-crash.py'), (1, './02-subpub-b2c-topic-alias.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-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-max-inflight-bytes.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-subpub-recover-subscriptions.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, './03-publish-qos1-queued-bytes.py'), (1, './03-pattern-matching.py'), (1, './03-publish-bad-flags.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-dup.py'), #(1, './03-publish-qos2-max-inflight-exceeded.py'), (1, './03-publish-qos2-max-inflight.py'), (1, './03-publish-qos2-reuse-mid.py'), (1, './03-publish-qos2.py'), (1, './04-retain-check-source-persist.py'), (1, './04-retain-check-source.py'), (1, './04-retain-clear-multiple.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'), (1, './05-session-expiry-kick.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-csF-lcsF.py'), (2, './06-bridge-clean-session-csF-lcsN.py'), (2, './06-bridge-clean-session-csF-lcsT.py'), (2, './06-bridge-clean-session-csT-lcsF.py'), (2, './06-bridge-clean-session-csT-lcsN.py'), (2, './06-bridge-clean-session-csT-lcsT.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'), (2, './06-bridge-per-listener-settings.py'), (2, './06-bridge-reconnect-local-out.py'), (2, './06-bridge-remote-shutdown.py'), (2, './06-bridge-config-reload.py'), (2, './06-bridge-remap-receive-wildcard.py'), (1, './07-will-control.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-0.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-per-listener.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-expired-allowed.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-dhparam.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-reauth.py'), (1, './09-extended-auth-single.py'), (1, './09-plugin-acl-access-variants.py'), (1, './09-plugin-acl-change.py'), (1, './09-plugin-auth-acl-pub.py'), (1, './09-plugin-auth-acl-pub-prop.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-auth-v3-unpwd-fail.py'), (1, './09-plugin-auth-v3-unpwd-success.py'), (1, './09-plugin-auth-v4-unpwd-fail.py'), (1, './09-plugin-auth-v4-unpwd-success.py'), (1, './09-plugin-auth-v5-unpwd-fail.py'), (1, './09-plugin-auth-v5-unpwd-success.py'), (1, './09-plugin-bad.py'), (1, './09-plugin-change-id.py'), (1, './09-plugin-evt-client-offline.py'), (1, './09-plugin-evt-message-in.py'), (1, './09-plugin-evt-message-out.py'), (1, './09-plugin-evt-psk-key.py'), (1, './09-plugin-evt-reload.py'), (1, './09-plugin-evt-subscribe.py'), (1, './09-plugin-evt-tick.py'), (1, './09-plugin-evt-unsubscribe.py'), (1, './09-plugin-delayed-auth.py'), (2, './09-plugin-load-acl.py'), (3, './09-plugin-load-basic-auth.py'), (2, './09-plugin-load-extended-auth.py'), (1, './09-plugin-publish.py'), (1, './09-plugin-unsupported.py'), (1, './09-pwfile-parse-invalid.py'), (2, './10-listener-mount-point.py'), (1, './11-message-expiry.py'), (1, './11-persistence-autosave-changes.py'), (1, './11-persistent-subscription.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-publish-qos1.py'), (1, './12-prop-maximum-packet-size-publish-qos2.py'), (1, './12-prop-response-topic-correlation-data.py'), (1, './12-prop-response-topic.py'), (1, './12-prop-server-keepalive.py'), (1, './12-prop-subpub-content-type.py'), (1, './12-prop-subpub-payload-format.py'), (1, './13-websocket-bad-origin.py'), (1, './14-dynsec-acl.py'), (1, './14-dynsec-allow-wildcard.py'), (1, './14-dynsec-anon-group.py'), (1, './14-dynsec-auth.py'), (1, './14-dynsec-client-invalid.py'), (1, './14-dynsec-client.py'), (1, './14-dynsec-config-init-env.py'), (1, './14-dynsec-config-init-file.py'), (1, './14-dynsec-config-init-random.py'), (1, './14-dynsec-default-access.py'), (1, './14-dynsec-disable-client.py'), (1, './14-dynsec-group-invalid.py'), (1, './14-dynsec-group.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-invalid.py'), (1, './14-dynsec-role.py'), (2, './15-persist-bridge-queue.py', 'persist_sqlite'), (1, './15-persist-client-msg-in-v3-1-1.py', 'persist_sqlite'), (1, './15-persist-client-msg-in-v5-0.py', 'persist_sqlite'), (1, './15-persist-client-msg-out-clear-v3-1-1.py', 'persist_sqlite'), (1, './15-persist-client-msg-out-dup-v3-1-1.py', 'persist_sqlite'), (1, './15-persist-client-msg-out-queue-v3-1-1.py', 'persist_sqlite'), (1, './15-persist-client-msg-out-v3-1-1-db.py', 'persist_sqlite'), (1, './15-persist-client-msg-out-v3-1-1.py', 'persist_sqlite'), (1, './15-persist-client-msg-out-v5-0.py', 'persist_sqlite'), (1, './15-persist-client-v3-1-1.py', 'persist_sqlite'), (1, './15-persist-client-v5-0.py', 'persist_sqlite'), (1, './15-persist-publish-properties-v5-0.py', 'persist_sqlite'), (1, './15-persist-retain-clear.py', 'persist_sqlite'), (1, './15-persist-retain-v3-1-1.py', 'persist_sqlite'), (1, './15-persist-retain-v5-0.py', 'persist_sqlite'), (1, './15-persist-subscription-v3-1-1.py', 'persist_sqlite'), (1, './15-persist-subscription-v5-0.py', 'persist_sqlite'), (1, './16-cmd-args.py'), (4, './16-config-huge.py'), (1, './16-config-includedir.py'), (1, './16-config-missing.py'), (1, './16-config-parse-errors-tls.py'), (1, './16-config-parse-errors-tls-psk.py'), (1, './16-config-parse-errors-without-tls.py'), (4, './17-control-list-listeners.py'), (1, './17-control-list-plugins.py'), (1, './17-control-missing-endpoint.py'), (1, './20-sparkplug-compliance.py'), (1, './20-sparkplug-aware.py'), (1, './21-proxy-bad-version.py'), (1, './21-proxy-v1-bad.py'), (1, './21-proxy-v1-success.py'), (1, './21-proxy-v2-bad-config.py'), (1, './21-proxy-v2-bad-header.py'), (1, './21-proxy-v2-local.py'), (1, './21-proxy-v2-ipv4.py'), (1, './21-proxy-v2-ipv6.py'), (1, './21-proxy-v2-unix.py'), (1, './21-proxy-v2-websockets.py'), (1, './21-proxy-v2-long-tlv.py'), (1, './21-proxy-v2-ssl-require-cert-failure.py'), (1, './21-proxy-v2-ssl-require-cert-success.py'), (1, './21-proxy-v2-ssl-common-name-failure.py'), (1, './21-proxy-v2-ssl-common-name-success.py'), (1, './21-proxy-v2-lost-connection.py'), (1, './21-proxy-v2-ssl-cipher.py'), (1, './21-proxy-v2-ssl-require-tls-failure.py'), (1, './21-proxy-v2-ssl-require-tls-success.py'), (2, './22-http-api-acl.py'), (3, './22-http-api-api.py'), (2, './22-http-api-auth.py'), (2, './22-http-api-file.py'), (2, './22-http-api-tls.py'), (2, './23-security-acl-file-reload.py'), ] if __name__ == "__main__": test = ptest.PTest() if len(sys.argv) == 2 and sys.argv[1] == "--rerun-failed": test.run_failed_tests() else: test.run_tests(tests) ================================================ FILE: test/broker/test.supp ================================================ { openssl_CRYPTO_get_ex_new_index Memcheck:Leak match-leak-kinds: reachable ... fun:CRYPTO_get_ex_new_index ... } { dl_reachable_leaks Memcheck:Leak match-leak-kinds: reachable ... fun:_dl_catch_error } { openssl_CRYPTO_THREAD_run_once Memcheck:Leak match-leak-kinds: reachable ... fun:CRYPTO_THREAD_run_once ... } { dl_open_reachable Memcheck:Leak match-leak-kinds: reachable ... fun:_dl_open ... } { MHD_quick_close CoreError:FdBadClose fun:__syscall_cancel fun:close fun:MHD_start_daemon_va fun:MHD_start_daemon ... } { openssl_LH_new Memcheck:Leak match-leak-kinds: reachable fun:malloc fun:CRYPTO_zalloc fun:OPENSSL_LH_new ... fun:__pthread_once_slow } { openssl_THREAD_lock_new Memcheck:Leak match-leak-kinds: reachable fun:malloc fun:CRYPTO_zalloc fun:CRYPTO_THREAD_lock_new ... fun:__pthread_once_slow } { openssl_CRYPTO_set_ex_data Memcheck:Leak match-leak-kinds: reachable fun:malloc fun:CRYPTO_zalloc ... fun:CRYPTO_set_ex_data ... fun:__pthread_once_slow } ================================================ FILE: test/client/02-subscribe-argv-errors-tls-psk.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(args, stderr_expected, rc_expected): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub'] + args sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) if mosq_test.wait_for_subprocess(sub): print("sub not terminated") raise mosq_test.TestError(1) (stdo, stde) = sub.communicate() if sub.returncode != rc_expected: raise mosq_test.TestError(sub.returncode) if stderr_expected is not None and stde.decode('utf-8') != stderr_expected: raise mosq_test.TestError(stde) if __name__ == '__main__': helps = "\nUse 'mosquitto_sub --help' to see usage.\n" # Missing args for TLS-PSK related options do_test(['--psk'], "Error: --psk argument given but no key specified.\n\n" + helps, 1) do_test(['--psk-identity'], "Error: --psk-identity argument given but no identity specified.\n\n" + helps, 1) ================================================ FILE: test/client/02-subscribe-argv-errors-tls.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(args, stderr_expected, rc_expected): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub'] + args sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) if mosq_test.wait_for_subprocess(sub): print("sub not terminated") raise mosq_test.TestError(1) (stdo, stde) = sub.communicate() if sub.returncode != rc_expected: raise mosq_test.TestError(sub.returncode) if stderr_expected is not None and stde.decode('utf-8') != stderr_expected: raise mosq_test.TestError(stde) if __name__ == '__main__': helps = "\nUse 'mosquitto_sub --help' to see usage.\n" # Missing args for TLS related options do_test(['--cafile'], "Error: --cafile argument given but no file specified.\n\n" + helps, 1) do_test(['--capath'], "Error: --capath argument given but no directory specified.\n\n" + helps, 1) do_test(['--cert'], "Error: --cert argument given but no file specified.\n\n" + helps, 1) do_test(['--ciphers'], "Error: --ciphers argument given but no ciphers specified.\n\n" + helps, 1) do_test(['--key'], "Error: --key argument given but no file specified.\n\n" + helps, 1) do_test(['--keyform'], "Error: --keyform argument given but no keyform specified.\n\n" + helps, 1) do_test(['--tls-alpn'], "Error: --tls-alpn argument given but no protocol specified.\n\n" + helps, 1) do_test(['--tls-engine'], "Error: --tls-engine argument given but no engine_id specified.\n\n" + helps, 1) do_test(['--tls-engine-kpass-sha1'], "Error: --tls-engine-kpass-sha1 argument given but no kpass sha1 specified.\n\n" + helps, 1) do_test(['--tls-version'], "Error: --tls-version argument given but no version specified.\n\n" + helps, 1) do_test(['--tls-keylog'], "Error: --tls-keylog argument given but no file specified.\n\n" + helps, 1) ================================================ FILE: test/client/02-subscribe-argv-errors-without-tls.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(args, stderr_expected, rc_expected): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub'] + args sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) if mosq_test.wait_for_subprocess(sub): print("sub not terminated") raise mosq_test.TestError(1) (stdo, stde) = sub.communicate() if sub.returncode != rc_expected: raise mosq_test.TestError(sub.returncode) if stderr_expected is not None and stde.decode('utf-8') != stderr_expected: raise mosq_test.TestError(stde) if __name__ == '__main__': helps = "\nUse 'mosquitto_sub --help' to see usage.\n" # Usage and version, ignore actual text though. do_test(['--help'], None, 1) do_test(['--version'], None, 1) # Missing args do_test(['-A'], "Error: -A argument given but no address specified.\n\n" + helps, 1) do_test(['-C'], "Error: -C argument given but no count specified.\n\n" + helps, 1) do_test(['-h'], "Error: -h argument given but no host specified.\n\n" + helps, 1) do_test(['-i'], "Error: -i argument given but no id specified.\n\n" + helps, 1) do_test(['-I'], "Error: -I argument given but no id prefix specified.\n\n" + helps, 1) do_test(['-k'], "Error: -k argument given but no keepalive specified.\n\n" + helps, 1) do_test(['-L'], "Error: -L argument given but no URL specified.\n\n" + helps, 1) do_test(['-M'], "Error: -M argument given but max_inflight not specified.\n\n" + helps, 1) do_test(['-o'], "Error: -o argument given but no options file specified.\n\n" + helps, 1) do_test(['-p'], "Error: -p argument given but no port specified.\n\n" + helps, 1) do_test(['-P'], "Error: -P argument given but no password specified.\n\n" + helps, 1) do_test(['--proxy'], "Error: --proxy argument given but no proxy url specified.\n\n" + helps, 1) do_test(['--random-filter'], "Error: --random-filter argument given but no chance specified.\n\n" + helps, 1) do_test(['-q'], "Error: -q argument given but no QoS specified.\n\n" + helps, 1) do_test(['-t'], "Error: -t argument given but no topic specified.\n\n" + helps, 1) do_test(['-u'], "Error: -u argument given but no username specified.\n\n" + helps, 1) do_test(['--unix'], "Error: --unix argument given but no socket path specified.\n\n" + helps, 1) do_test(['-V'], "Error: --protocol-version argument given but no version specified.\n\n" + helps, 1) do_test(['--will-payload'], "Error: --will-payload argument given but no will payload specified.\n\n" + helps, 1) do_test(['--will-qos'], "Error: --will-qos argument given but no will QoS specified.\n\n" + helps, 1) do_test(['--will-topic'], "Error: --will-topic argument given but no will topic specified.\n\n" + helps, 1) do_test(['-x'], "Error: -x argument given but no session expiry interval specified.\n\n" + helps, 1) do_test(['-F'], "Error: -F argument given but no format specified.\n\n" + helps, 1) do_test(['-o'], "Error: -o argument given but no options file specified.\n\n" + helps, 1) do_test(['-T'], "Error: -T argument given but no topic filter specified.\n\n" + helps, 1) do_test(['-U'], "Error: -U argument given but no unsubscribe topic specified.\n\n" + helps, 1) do_test(['-W'], "Error: -W argument given but no timeout specified.\n\n" + helps, 1) do_test(['--will-payload', 'payload'], "Error: Will payload given, but no will topic given.\n" + helps, 1) # No -t or -U do_test([], "Error: You must specify a topic to subscribe to (-t) or unsubscribe from (-U).\n" + helps, 1) # Invalid combinations do_test(['-i', 'id', '-I', 'id-prefix'], "Error: -i and -I argument cannot be used together.\n\n" + helps, 1) do_test(['-I', 'id-prefix', '-i', 'id'], "Error: -i and -I argument cannot be used together.\n\n" + helps, 1) # Duplicate options do_test(['-o', 'file1', '-o', 'file2'], "Error: Duplicate -o argument given.\n\n" + helps, 1) # Invalid output format do_test(['-F', '%'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%0'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%-'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%1'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%.'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%.1'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%Z'], "Error: Invalid format specifier 'Z'.\n" + helps, 1) do_test(['-F', '@'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '\\'], "Error: Incomplete escape specifier.\n" + helps, 1) do_test(['-F', '\\Z'], "Error: Invalid escape specifier 'Z'.\n" + helps, 1) # Invalid values do_test(['-k', '-1'], "Error: Invalid keepalive given, it must be between 5 and 65535 inclusive.\n\n" + helps, 1) do_test(['-k', '65536'], "Error: Invalid keepalive given, it must be between 5 and 65535 inclusive.\n\n" + helps, 1) do_test(['-M', '0'], "Error: Maximum inflight messages must be greater than 0.\n\n" + helps, 1) do_test(['-p', '-1'], "Error: Invalid port given: -1\n" + helps, 1) do_test(['-p', '65536'], "Error: Invalid port given: 65536\n" + helps, 1) do_test(['-q', '-1'], "Error: Invalid QoS given: -1\n" + helps, 1) do_test(['-q', '3'], "Error: Invalid QoS given: 3\n" + helps, 1) do_test(['-C', '0'], "Error: Invalid message count \"0\".\n\n" + helps, 1) do_test(['-L', 'invalid://'], "Error: Unsupported URL scheme.\n\n" + helps, 1) do_test(['-L', 'mqtt://localhost'], "Error: Invalid URL for -L argument specified - topic missing.\n" + helps, 1) do_test(['-L', 'mqtts://localhost'], "Error: Invalid URL for -L argument specified - topic missing.\n" + helps, 1) do_test(['-L', 'ws://localhost'], "Error: Invalid URL for -L argument specified - topic missing.\n" + helps, 1) do_test(['-L', 'wss://localhost'], "Error: Invalid URL for -L argument specified - topic missing.\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'request-problem-information', '-1'], "Error: Property value (-1) out of range for property request-problem-information.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'request-problem-information', '256'], "Error: Property value (256) out of range for property request-problem-information.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'receive-maximum', '-1'], "Error: Property value (-1) out of range for property receive-maximum.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'receive-maximum', '65536'], "Error: Property value (65536) out of range for property receive-maximum.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'session-expiry-interval', '-1'], "Error: Property value (-1) out of range for property session-expiry-interval.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'session-expiry-interval', '4294967296'], "Error: Property value (4294967296) out of range for property session-expiry-interval.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'subscribe', 'subscription-identifier', '-1'], "Error: Property value (-1) out of range for property subscription-identifier.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'subscribe', 'subscription-identifier', '4294967296'], "Error: Property value (4294967296) out of range for property subscription-identifier.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'subscribe', 'topic-alias', '1'], "Error: topic-alias property not allowed for subscribe in --property argument.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'auth', 'authentication-method', '1'], "Error: authentication-method property not supported for auth in --property argument.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'puback', 'reason-string', '1'], "Error: reason-string property not supported for puback in --property argument.\n\n" + helps, 1) do_test(['-t', '++'], "Error: Invalid subscription topic '++', are all '+' and '#' wildcards correct?\n" + helps, 1) do_test(['-T', '++'], "Error: Invalid filter topic '++', are all '+' and '#' wildcards correct?\n" + helps, 1) do_test(['-U', '++'], "Error: Invalid unsubscribe topic '++', are all '+' and '#' wildcards correct?\n" + helps, 1) do_test(['-V', '0'], "Error: Invalid protocol version argument given.\n\n" + helps, 1) do_test(['-W', '0'], "Error: Invalid timeout \"0\".\n\n" + helps, 1) do_test(['--will-qos', '-1'], "Error: Invalid will QoS -1.\n\n" + helps, 1) do_test(['--will-qos', '3'], "Error: Invalid will QoS 3.\n\n" + helps, 1) do_test(['--will-topic', '+'], "Error: Invalid will topic '+', does it contain '+' or '#'?\n" + helps, 1) do_test(['-x', 'A'], "Error: session-expiry-interval not a number.\n\n" + helps, 1) do_test(['-x', '-2'], "Error: session-expiry-interval out of range.\n\n" + helps, 1) do_test(['-x', '4294967296'], "Error: session-expiry-interval out of range.\n\n" + helps, 1) do_test(['--retain-handling', 'invalid'], "Error: Unknown value 'invalid' for --retain-handling.\n\n" + helps, 1) # Unknown options do_test(['--unknown'], "Error: Unknown option '--unknown'.\n" + helps, 1) do_test(['-l'], "Error: Unknown option '-l'.\n" + helps, 1) do_test(['-m'], "Error: Unknown option '-m'.\n" + helps, 1) do_test(['-n'], "Error: Unknown option '-n'.\n" + helps, 1) do_test(['-r'], "Error: Unknown option '-r'.\n" + helps, 1) do_test(['--repeat'], "Error: Unknown option '--repeat'.\n" + helps, 1) do_test(['--repeat-delay'], "Error: Unknown option '--repeat-delay'.\n" + helps, 1) do_test(['-s'], "Error: Unknown option '-s'.\n" + helps, 1) ================================================ FILE: test/client/02-subscribe-env.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver, env): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = mosq_test.env_add_ld_library_path(env) cmd = [mosq_test.get_build_root() + '/client/mosquitto_sub', '-p', str(port), '-q', '1', '-V', V, '-C', '1' ] payload = "message" publish_packet_s = mosq_test.gen_publish("env/config/file/sub", qos=1, mid=1, payload=payload, proto_ver=proto_ver) publish_packet_r = mosq_test.gen_publish("env/config/file/sub", qos=1, mid=2, payload=payload, proto_ver=proto_ver) puback_packet_s = mosq_test.gen_puback(1, proto_ver=proto_ver) puback_packet_r = mosq_test.gen_puback(2, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.pub_helper(port=port, proto_ver=proto_ver) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) time.sleep(0.1) sock.send(publish_packet_s) mosq_test.expect_packet(sock, "puback", puback_packet_s) sub_terminate_rc = 0 if mosq_test.wait_for_subprocess(sub): print("sub not terminated") sub_terminate_rc = 1 (stdo, stde) = sub.communicate() if stdo.decode('utf-8') == payload + '\n': rc = sub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (_, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) env = {'HOME': str(source_dir / 'data')} do_test(proto_ver=3, env=env) do_test(proto_ver=4, env=env) do_test(proto_ver=5, env=env) env = {'XDG_CONFIG_HOME': str(source_dir / 'data/.config')} do_test(proto_ver=3, env=env) do_test(proto_ver=4, env=env) do_test(proto_ver=5, env=env) ================================================ FILE: test/client/02-subscribe-filter-out.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub', '-p', str(port), '-q', '0', '-t', '02/sub/filter-out/#', '-T', '02/sub/filter-out/filtered', '-V', V, '-C', '2' ] publish_packet1 = mosq_test.gen_publish("02/sub/filter-out/recv", qos=0, payload="recv", proto_ver=proto_ver) publish_packet2 = mosq_test.gen_publish("02/sub/filter-out/filtered", qos=0, payload="filtered", proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.pub_helper(port=port, proto_ver=proto_ver) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) time.sleep(0.1) sock.send(publish_packet1) sock.send(publish_packet2) sock.send(publish_packet1) sock.send(publish_packet2) sub_terminate_rc = 0 if mosq_test.wait_for_subprocess(sub): print("sub not terminated") sub_terminate_rc = 1 (stdo, stde) = sub.communicate() if stdo.decode('utf-8') == 'recv\nrecv\n': rc = sub_terminate_rc else: print(stdo.decode('utf-8')) sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/02-subscribe-format-json-properties.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * import json def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub', '-p', str(port), '-q', '1', '-F', '%j', '-t', '02/sub/format/json/properties/test', '-V', V, '-C', '1', '-D', 'subscribe', 'subscription-identifier', '99', '-D', 'connect', 'topic-alias-maximum', '100' ] props = mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 1) props += mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "plain/text") props += mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "/dev/null") props += mqtt5_props.gen_string_prop(mqtt5_props.CORRELATION_DATA, "2357289375902345") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name", "value4") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name", "value3") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name", "value1") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name", "value2") publish_packet = mosq_test.gen_publish("02/sub/format/json/properties/test", mid=1, qos=1, payload="message", proto_ver=proto_ver, properties=props) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) expected = { "tst": "", "topic": "02/sub/format/json/properties/test", "qos": 1, "retain": 0, "payloadlen": 7, "mid": 1, "properties": { "payload-format-indicator": 1, "content-type": "plain/text", "response-topic": "/dev/null", "correlation-data": "2357289375902345", "user-properties": [ {"name": "value4"}, {"name": "value3"}, {"name": "value1"}, {"name": "value2"} ], "topic-alias": 1, "subscription-identifier": 99 }, "payload": "message" } try: sock = mosq_test.pub_helper(port=port, proto_ver=proto_ver) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) time.sleep(0.1) sock.send(publish_packet) sub_terminate_rc = 0 if mosq_test.wait_for_subprocess(sub): print("sub not terminated") sub_terminate_rc = 1 (stdo, stde) = sub.communicate() j = json.loads(stdo.decode('utf-8')) j['tst'] = "" if j == expected: rc = sub_terminate_rc else: print(json.dumps(j)) print(json.dumps(expected)) sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=5) ================================================ FILE: test/client/02-subscribe-format-json-qos0.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * import json def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub', '-p', str(port), '-F', '%j', '-t', '02/sub/format/json/test', '-V', V, '-C', '1' ] publish_packet = mosq_test.gen_publish("02/sub/format/json/test", qos=0, payload="message", proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) expected = {"tst": "", "topic": "02/sub/format/json/test", "qos": 0, "retain": 0, "payloadlen": 7, "payload": "message"} try: sock = mosq_test.pub_helper(port=port, proto_ver=proto_ver) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) time.sleep(0.1) sock.send(publish_packet) sub_terminate_rc = 0 if mosq_test.wait_for_subprocess(sub): print("sub not terminated") sub_terminate_rc = 1 (stdo, stde) = sub.communicate() j = json.loads(stdo.decode('utf-8')) j['tst'] = "" if j == expected: rc = sub_terminate_rc else: print(json.dumps(j)) sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/02-subscribe-format-json-qos1.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * import json def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub', '-p', str(port), '-q', '1', '-F', '%j', '-t', '02/sub/format/json/qos1/test', '-V', V, '-C', '1' ] publish_packet = mosq_test.gen_publish("02/sub/format/json/qos1/test", mid=1, qos=1, payload="message", proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) expected = {"tst": "", "topic": "02/sub/format/json/qos1/test", "qos": 1, "mid": 1, "retain": 0, "payloadlen": 7, "payload": "message"} try: sock = mosq_test.pub_helper(port=port, proto_ver=proto_ver) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) time.sleep(0.1) sock.send(publish_packet) sub_terminate_rc = 0 if mosq_test.wait_for_subprocess(sub): print("sub not terminated") sub_terminate_rc = 1 (stdo, stde) = sub.communicate() j = json.loads(stdo.decode('utf-8')) j['tst'] = "" if j == expected: rc = sub_terminate_rc else: print(json.dumps(expected)) print(json.dumps(j)) sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/02-subscribe-format-json-retain.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * import json def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub', '-p', str(port), '-F', '%j', '-t', '02/sub/format/json/retain/test', '-V', V, '-C', '1' ] publish_packet = mosq_test.gen_publish("02/sub/format/json/retain/test", qos=0, payload="message", proto_ver=proto_ver, retain=True) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) expected = {"tst": "", "topic": "02/sub/format/json/retain/test", "qos": 0, "retain": 1, "payloadlen": 7, "payload": "message"} try: sock = mosq_test.pub_helper(port=port, proto_ver=proto_ver) sock.send(publish_packet) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) sub_terminate_rc = 0 if mosq_test.wait_for_subprocess(sub): print("sub not terminated") sub_terminate_rc = 1 (stdo, stde) = sub.communicate() j = json.loads(stdo.decode('utf-8')) j['tst'] = "" if j == expected: rc = sub_terminate_rc else: print(json.dumps(j)) sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/02-subscribe-format.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * import platform def do_test(format_str, expected_output, proto_ver=4, payload="message"): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub', '-p', str(port), '-q', '1', '-t', '02/sub/format/test', '-C', '1', '-V', V, '-F', format_str ] if proto_ver == 5: cmd += ['-D', 'subscribe', 'subscription-identifier', '56'] props = mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 1) props += mqtt5_props.gen_uint32_prop(mqtt5_props.MESSAGE_EXPIRY_INTERVAL, 3600) props += mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "plain/text") props += mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "/dev/null") #props += mqtt5_props.gen_string_prop(mqtt5_props.CORRELATION_DATA, "2357289375902345") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name1", "value1") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name2", "value2") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name3", "value3") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "name4", "value4") if proto_ver == 5: publish_packet = mosq_test.gen_publish("02/sub/format/test", qos=0, payload=payload, properties=props, proto_ver=proto_ver) else: publish_packet = mosq_test.gen_publish("02/sub/format/test", qos=0, payload=payload, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.pub_helper(port=port, proto_ver=proto_ver) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) time.sleep(0.1) sock.send(publish_packet) sub_terminate_rc = 0 if mosq_test.wait_for_subprocess(sub): print("sub not terminated") sub_terminate_rc = 1 (stdo, stde) = sub.communicate() if stdo.decode('utf-8') == expected_output: rc = sub_terminate_rc else: print("expected: (%d) %s" % (len(expected_output), expected_output)) print("actual: (%d) %s" % (len(stdo.decode('utf-8')), stdo.decode('utf-8'))) sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) exit(rc) do_test('%%', '%\n') do_test('%A', '\n') # missing do_test('%C', '\n') # missing do_test('%2C', ' \n') # missing do_test('%C', 'plain/text\n', proto_ver=5) do_test('%D', '\n') # missing do_test('%E', '\n') # missing do_test('%E', '3600\n', proto_ver=5) do_test('%F', '\n') # missing do_test('%F', '1\n', proto_ver=5) do_test('%l', '7\n') # strlen("message") do_test('%02l', '07\n') # strlen("message") do_test('%2l', ' 7\n') # strlen("message") do_test('%-2l', '7 \n') # strlen("message") do_test('%m', '0\n') do_test('%P', '\n') # missing do_test('%P', 'name1:value1 name2:value2 name3:value3 name4:value4\n', proto_ver=5) do_test('%p', 'message\n') do_test('%-12p', 'message \n') do_test('%q', '0\n') do_test('%R', '\n') # missing do_test('%r', '0\n') do_test('%S', '\n') # missing do_test('%S', '56\n', proto_ver=5) do_test('%t', '02/sub/format/test\n') do_test('%.20t', '02/sub/format/test\n') do_test('%-.20t', '02/sub/format/test\n') do_test('%20t', ' 02/sub/format/test\n') do_test('%-20t', '02/sub/format/test \n') do_test('%10.10t', '02/sub/for\n') do_test('%20.10t', ' 02/sub/for\n') do_test('%-20.10t', '02/sub/for \n') do_test('%x', '6d657373616765\n') do_test('%.1x', '6 d 6 5 7 3 7 3 6 1 6 7 6 5\n') do_test('%.2x', '6d 65 73 73 61 67 65\n') do_test('%.2:x', '6d:65:73:73:61:67:65\n') do_test('%18x', ' 6d657373616765\n') do_test('%-18x', '6d657373616765 \n') do_test('%X', '6D657373616765\n') do_test('\\\\', '\\\n') do_test('\\a', '\a\n') #do_test('\\e', '\e\n') do_test('\\n', '\n\n') do_test('\\r', '\r\n') do_test('\\t', '\t\n') do_test('\\v', '\v\n') do_test('@@', '@\n') do_test('text', 'text\n') if platform.system() != 'Darwin': do_test('%.3d', '2.718\n', payload=struct.pack('BBBBBBBB', 0x58, 0x39, 0xB4, 0xC8, 0x76, 0xBE, 0x05, 0x40)) do_test('%.3f', '0.707\n', payload=struct.pack('BBBB', 0xF4, 0xFD, 0x34, 0x3F)) ================================================ FILE: test/client/02-subscribe-null.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub', '-p', str(port), '-q', '1', '-t', '02/sub/null/test', '-V', V, '-C', '1', '-v' ] topic = "02/sub/null/test" payload = "" publish_packet_s = mosq_test.gen_publish(topic, qos=1, mid=1, payload=payload, proto_ver=proto_ver) publish_packet_r = mosq_test.gen_publish(topic, qos=1, mid=2, payload=payload, proto_ver=proto_ver) puback_packet_s = mosq_test.gen_puback(1, proto_ver=proto_ver) puback_packet_r = mosq_test.gen_puback(2, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.pub_helper(port=port, proto_ver=proto_ver) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) time.sleep(0.1) sock.send(publish_packet_s) mosq_test.expect_packet(sock, "puback", puback_packet_s) sub_terminate_rc = 0 if mosq_test.wait_for_subprocess(sub): print("sub not terminated") sub_terminate_rc = 1 (stdo, stde) = sub.communicate() expected_output = topic + ' (null)\n' if stdo.decode('utf-8') == expected_output: rc = sub_terminate_rc else: print("expected: %s" % expected_output) print("actual: %s" % stdo.decode('utf-8')) sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/02-subscribe-qos1-ws.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write(f"listener {port1}\n") f.write("protocol websockets\n") f.write(f"listener {port2}\n") def do_test(proto_ver): rc = 1 ports = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub', '-p', str(ports[0]), '-q', '1', '-t', '02/sub/qos1/test', '-V', V, '-C', '1', '--ws' ] payload = "message" publish_packet_s = mosq_test.gen_publish("02/sub/qos1/test", qos=1, mid=1, payload=payload, proto_ver=proto_ver) puback_packet_s = mosq_test.gen_puback(1, proto_ver=proto_ver) write_config(conf_file, ports[0], ports[1]) try: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=ports[1], use_conf=True) sock = mosq_test.pub_helper(port=ports[1], proto_ver=proto_ver) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) time.sleep(0.1) sock.send(publish_packet_s) mosq_test.expect_packet(sock, "puback", puback_packet_s) sub_terminate_rc = 0 if mosq_test.wait_for_subprocess(sub): print("sub not terminated") sub_terminate_rc = 1 (stdo, stde) = sub.communicate() if stdo.decode('utf-8') == payload + '\n': rc = sub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() os.remove(conf_file) if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/02-subscribe-qos1.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub', '-p', str(port), '-q', '1', '-t', '02/sub/qos1/test', '-V', V, '-C', '1' ] payload = "message" publish_packet_s = mosq_test.gen_publish("02/sub/qos1/test", qos=1, mid=1, payload=payload, proto_ver=proto_ver) publish_packet_r = mosq_test.gen_publish("02/sub/qos1/test", qos=1, mid=2, payload=payload, proto_ver=proto_ver) puback_packet_s = mosq_test.gen_puback(1, proto_ver=proto_ver) puback_packet_r = mosq_test.gen_puback(2, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.pub_helper(port=port, proto_ver=proto_ver) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) time.sleep(0.1) sock.send(publish_packet_s) mosq_test.expect_packet(sock, "puback", puback_packet_s) sub_terminate_rc = 0 if mosq_test.wait_for_subprocess(sub): print("sub not terminated") sub_terminate_rc = 1 (stdo, stde) = sub.communicate() if stdo.decode('utf-8') == payload + '\n': rc = sub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/02-subscribe-retain-handling.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub', '-p', str(port), '-q', '0', '-t', 'retain-handling', '-V', '5', '-C', '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) props = mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 1) connect_packet = mosq_test.gen_connect("", proto_ver=5, properties=props) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet_always = mosq_test.gen_subscribe(mid=1, topic="retain-handling", qos=0x00, proto_ver=5) subscribe_packet_new = mosq_test.gen_subscribe(mid=1, topic="retain-handling", qos=0x10, proto_ver=5) subscribe_packet_never = mosq_test.gen_subscribe(mid=1, topic="retain-handling", qos=0x20, proto_ver=5) suback_packet = mosq_test.gen_suback(mid=1, qos=0) publish_packet = mosq_test.gen_publish("retain-handling", qos=0, payload="m", proto_ver=5) client_terminate_rc = 0 try: for subscribe_packet, handling in [ (subscribe_packet_always, 'always'), (subscribe_packet_new, 'new'), (subscribe_packet_never, 'never')]: client_cmd = cmd + ['--retain-handling', handling] client = subprocess.Popen(client_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) (conn, address) = sock.accept() conn.settimeout(5) mosq_test.expect_packet(conn, "connect", connect_packet) conn.send(connack_packet) mosq_test.expect_packet(conn, f"subscribe {handling}", subscribe_packet) conn.send(suback_packet) conn.send(publish_packet) if mosq_test.wait_for_subprocess(client): print("client not terminated") client_terminate_rc = 1 sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: sock.close() client.terminate() exit(client_terminate_rc) do_test() ================================================ FILE: test/client/02-subscribe-verbose.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_sub', '-p', str(port), '-q', '1', '-t', '02/sub/verbose/test', '-V', V, '-C', '1', '-v' ] topic = "02/sub/verbose/test" payload = "message" publish_packet_s = mosq_test.gen_publish(topic, qos=1, mid=1, payload=payload, proto_ver=proto_ver) publish_packet_r = mosq_test.gen_publish(topic, qos=1, mid=2, payload=payload, proto_ver=proto_ver) puback_packet_s = mosq_test.gen_puback(1, proto_ver=proto_ver) puback_packet_r = mosq_test.gen_puback(2, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.pub_helper(port=port, proto_ver=proto_ver) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) time.sleep(0.1) sock.send(publish_packet_s) mosq_test.expect_packet(sock, "puback", puback_packet_s) sub_terminate_rc = 0 if mosq_test.wait_for_subprocess(sub): print("sub not terminated") sub_terminate_rc = 1 (stdo, stde) = sub.communicate() expected_output = topic + ' ' + payload + '\n' if stdo.decode('utf-8') == expected_output: rc = sub_terminate_rc else: print("expected: %s" % expected_output) print("actual: %s" % stdo.decode('utf-8')) sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/03-publish-argv-errors-tls-psk.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(args, stderr_expected, rc_expected): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub'] + args pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) if mosq_test.wait_for_subprocess(pub): print("pub not terminated") raise mosq_test.TestError(1) (stdo, stde) = pub.communicate() if pub.returncode != rc_expected: raise mosq_test.TestError(pub.returncode) if stderr_expected is not None and stde.decode('utf-8') != stderr_expected: raise mosq_test.TestError(stde) if __name__ == '__main__': helps = "\nUse 'mosquitto_pub --help' to see usage.\n" # Missing args do_test(['--psk'], "Error: --psk argument given but no key specified.\n\n" + helps, 1) do_test(['--psk-identity'], "Error: --psk-identity argument given but no identity specified.\n\n" + helps, 1) # Invalid combinations do_test(['--cafile', 'file', '--psk', 'key'], "Error: Only one of --psk or --cafile/--capath may be used at once.\n" + helps, 1) do_test(['--capath', 'dir', '--psk', 'key'], "Error: Only one of --psk or --cafile/--capath may be used at once.\n" + helps, 1) do_test(['--psk', 'key'], "Error: --psk-identity required if --psk used.\n" + helps, 1) ================================================ FILE: test/client/03-publish-argv-errors-tls.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(args, stderr_expected, rc_expected): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub'] + args pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) if mosq_test.wait_for_subprocess(pub): print("pub not terminated") raise mosq_test.TestError(1) (stdo, stde) = pub.communicate() if pub.returncode != rc_expected: raise mosq_test.TestError(pub.returncode) if stderr_expected is not None and stde.decode('utf-8') != stderr_expected: raise mosq_test.TestError(stde.decode('utf-8')) if __name__ == '__main__': helps = "\nUse 'mosquitto_pub --help' to see usage.\n" # Missing args do_test(['--cafile'], "Error: --cafile argument given but no file specified.\n\n" + helps, 1) do_test(['--capath'], "Error: --capath argument given but no directory specified.\n\n" + helps, 1) do_test(['--cert'], "Error: --cert argument given but no file specified.\n\n" + helps, 1) do_test(['--ciphers'], "Error: --ciphers argument given but no ciphers specified.\n\n" + helps, 1) do_test(['--key'], "Error: --key argument given but no file specified.\n\n" + helps, 1) do_test(['--keyform'], "Error: --keyform argument given but no keyform specified.\n\n" + helps, 1) do_test(['--tls-alpn'], "Error: --tls-alpn argument given but no protocol specified.\n\n" + helps, 1) do_test(['--tls-engine'], "Error: --tls-engine argument given but no engine_id specified.\n\n" + helps, 1) do_test(['--tls-engine-kpass-sha1'], "Error: --tls-engine-kpass-sha1 argument given but no kpass sha1 specified.\n\n" + helps, 1) do_test(['--tls-version'], "Error: --tls-version argument given but no version specified.\n\n" + helps, 1) # Invalid combinations do_test(['--cert', 'file'], "Error: Both certfile and keyfile must be provided if one of them is set.\n" + helps, 1) do_test(['--key', 'file'], "Error: Both certfile and keyfile must be provided if one of them is set.\n" + helps, 1) do_test(['--keyform', 'file'], "Error: If keyform is set, keyfile must be also specified.\n" + helps, 1) do_test(['--tls-engine-kpass-sha1', 'hash'], "Error: when using tls-engine-kpass-sha1, both tls-engine and keyform must also be provided.\n" + helps, 1) # Invalid values do_test(['--tls-keylog', 'keylog', '-t','topic','-m','1', '--cafile', 'missing'], "Error: Problem setting TLS options: File not found.\n", 1) ================================================ FILE: test/client/03-publish-argv-errors-without-tls.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(args, stderr_expected, rc_expected): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub'] + args pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) if mosq_test.wait_for_subprocess(pub): print("pub not terminated") raise mosq_test.TestError(1) (stdo, stde) = pub.communicate() if pub.returncode != rc_expected: raise mosq_test.TestError(pub.returncode) if stderr_expected is not None and stde.decode('utf-8') != stderr_expected: raise mosq_test.TestError(stde) if __name__ == '__main__': helps = "\nUse 'mosquitto_pub --help' to see usage.\n" # Usage, version, ignore actual text though. do_test(['--help'], None, 1) do_test(['--version'], None, 1) # Missing args do_test(['-A'], "Error: -A argument given but no address specified.\n\n" + helps, 1) do_test(['-f'], "Error: -f argument given but no file specified.\n\n" + helps, 1) do_test(['-h'], "Error: -h argument given but no host specified.\n\n" + helps, 1) do_test(['-i'], "Error: -i argument given but no id specified.\n\n" + helps, 1) do_test(['-I'], "Error: -I argument given but no id prefix specified.\n\n" + helps, 1) do_test(['-k'], "Error: -k argument given but no keepalive specified.\n\n" + helps, 1) do_test(['-L'], "Error: -L argument given but no URL specified.\n\n" + helps, 1) do_test(['-M'], "Error: -M argument given but max_inflight not specified.\n\n" + helps, 1) do_test(['-m'], "Error: -m argument given but no message specified.\n\n" + helps, 1) do_test(['-o'], "Error: -o argument given but no options file specified.\n\n" + helps, 1) do_test(['-p'], "Error: -p argument given but no port specified.\n\n" + helps, 1) do_test(['-P'], "Error: -P argument given but no password specified.\n\n" + helps, 1) do_test(['--proxy'], "Error: --proxy argument given but no proxy url specified.\n\n" + helps, 1) do_test(['-q'], "Error: -q argument given but no QoS specified.\n\n" + helps, 1) do_test(['--repeat'], "Error: --repeat argument given but no count specified.\n\n" + helps, 1) do_test(['--repeat-delay'], "Error: --repeat-delay argument given but no time specified.\n\n" + helps, 1) do_test(['-t'], "Error: -t argument given but no topic specified.\n\n" + helps, 1) do_test(['-u'], "Error: -u argument given but no username specified.\n\n" + helps, 1) do_test(['--unix'], "Error: --unix argument given but no socket path specified.\n\n" + helps, 1) do_test(['-V'], "Error: --protocol-version argument given but no version specified.\n\n" + helps, 1) do_test(['--will-payload'], "Error: --will-payload argument given but no will payload specified.\n\n" + helps, 1) do_test(['--will-qos'], "Error: --will-qos argument given but no will QoS specified.\n\n" + helps, 1) do_test(['--will-topic'], "Error: --will-topic argument given but no will topic specified.\n\n" + helps, 1) do_test(['-x'], "Error: -x argument given but no session expiry interval specified.\n\n" + helps, 1) do_test(['-V', '5', '-D'], "Error: --property argument given but not enough arguments specified.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect'], "Error: --property argument given but not enough arguments specified.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'receive-maximum'], "Error: --property argument given but not enough arguments specified.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'invalid', 'receive-maximum', '1'], "Error: Invalid command invalid given in --property argument.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'invalid', '1'], "Error: Invalid property name invalid given in --property argument.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'will-delay-interval', '1'], "Error: will-delay-interval property not allowed for connect in --property argument.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'user-property', 'key'], "Error: --property argument given but not enough arguments specified.\n\n" + helps, 1) # Invalid combinations do_test(['-i', 'id', '-I', 'id-prefix'], "Error: -i and -I argument cannot be used together.\n\n" + helps, 1) do_test(['-I', 'id-prefix', '-i', 'id'], "Error: -i and -I argument cannot be used together.\n\n" + helps, 1) do_test(['--will-payload', 'payload'], "Error: Will payload given, but no will topic given.\n" + helps, 1) do_test(['--will-retain'], "Error: Will retain given, but no will topic given.\n" + helps, 1) do_test(['-V', 'mqttv5', '-x', '-1'], "Error: You must provide a client id if you are using an infinite session expiry interval.\n" + helps, 1) do_test(['-V', 'mqttv311', '-c'], "Error: You must provide a client id if you are using the -c option.\n" + helps, 1) # Mixed message types do_test(['-m', 'message', '-f', 'file'], "Error: Only one type of message can be sent at once.\n\n" + helps, 1) do_test(['-m', 'message', '-l'], "Error: Only one type of message can be sent at once.\n\n" + helps, 1) do_test(['-l', '-m', 'message'], "Error: Only one type of message can be sent at once.\n\n" + helps, 1) do_test(['-l', '-n'], "Error: Only one type of message can be sent at once.\n\n" + helps, 1) do_test(['-l', '-s'], "Error: Only one type of message can be sent at once.\n\n" + helps, 1) # Invalid values do_test(['-t', 'topic', '-f', 'missing'], "Error: Unable to read file \"missing\": No such file or directory.\nError loading input file \"missing\".\n", 1) do_test(['-k', '-1'], "Error: Invalid keepalive given, it must be between 5 and 65535 inclusive.\n\n" + helps, 1) do_test(['-k', '65536'], "Error: Invalid keepalive given, it must be between 5 and 65535 inclusive.\n\n" + helps, 1) do_test(['-M', '0'], "Error: Maximum inflight messages must be greater than 0.\n\n" + helps, 1) do_test(['-p', '-1'], "Error: Invalid port given: -1\n" + helps, 1) do_test(['-p', '65536'], "Error: Invalid port given: 65536\n" + helps, 1) do_test(['-q', '-1'], "Error: Invalid QoS given: -1\n" + helps, 1) do_test(['-q', '3'], "Error: Invalid QoS given: 3\n" + helps, 1) do_test(['--repeat-delay', '-1'], "Error: --repeat-delay argument must be >=0.0.\n\n" + helps, 1) do_test(['-t', 'topic/+'], "Error: Invalid publish topic 'topic/+', does it contain '+' or '#'?\n" + helps, 1) do_test(['-t', 'topic/#'], "Error: Invalid publish topic 'topic/#', does it contain '+' or '#'?\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'request-problem-information', '-1'], "Error: Property value (-1) out of range for property request-problem-information.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'request-problem-information', '256'], "Error: Property value (256) out of range for property request-problem-information.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'receive-maximum', '-1'], "Error: Property value (-1) out of range for property receive-maximum.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'receive-maximum', '65536'], "Error: Property value (65536) out of range for property receive-maximum.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'session-expiry-interval', '-1'], "Error: Property value (-1) out of range for property session-expiry-interval.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'session-expiry-interval', '4294967296'], "Error: Property value (4294967296) out of range for property session-expiry-interval.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'subscription-identifier', '1'], "Error: subscription-identifier property not allowed for connect in --property argument.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'publish', 'subscription-identifier', '1'], "Error: subscription-identifier property not supported for publish in --property argument.\n\n" + helps, 1) # Unknown options do_test(['--unknown'], "Error: Unknown option '--unknown'.\n" + helps, 1) do_test(['-C', '1'], "Error: Unknown option '-C'.\n" + helps, 1) do_test(['-e', 'response-topic'], "Error: Unknown option '-e'.\n" + helps, 1) do_test(['-E'], "Error: Unknown option '-E'.\n" + helps, 1) do_test(['-F', '%p'], "Error: Unknown option '-F'.\n" + helps, 1) do_test(['-N'], "Error: Unknown option '-N'.\n" + helps, 1) do_test(['--pretty'], "Error: Unknown option '--pretty'.\n" + helps, 1) do_test(['-R'], "Error: Unknown option '-R'.\n" + helps, 1) do_test(['--random-filter'], "Error: Unknown option '--random-filter'.\n" + helps, 1) do_test(['--remove-retained'], "Error: Unknown option '--remove-retained'.\n" + helps, 1) do_test(['--retain-as-published'], "Error: Unknown option '--retain-as-published'.\n" + helps, 1) do_test(['--retain-handling', 'invalid'], "Error: Unknown option '--retain-handling'.\n" + helps, 1) do_test(['--retained-only'], "Error: Unknown option '--retained-only'.\n" + helps, 1) do_test(['-T'], "Error: Unknown option '-T'.\n" + helps, 1) do_test(['-U'], "Error: Unknown option '-U'.\n" + helps, 1) do_test(['-v'], "Error: Unknown option '-v'.\n" + helps, 1) do_test(['-W'], "Error: Unknown option '-W'.\n" + helps, 1) do_test(['-w'], "Error: Unknown option '-w'.\n" + helps, 1) ================================================ FILE: test/client/03-publish-env.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver, env): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = mosq_test.env_add_ld_library_path(env) cmd = [mosq_test.get_build_root() + '/client/mosquitto_pub', '-p', str(port), '-q', '1', '-V', V ] mid = 1 publish_packet = mosq_test.gen_publish("env/config/file/pub", 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.NO_MATCHING_SUBSCRIBERS) else: puback_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.sub_helper(port=port, topic="#", qos=1, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) env = {'HOME': str(source_dir / 'data')} do_test(proto_ver=3, env=env) do_test(proto_ver=4, env=env) do_test(proto_ver=5, env=env) env = {'XDG_CONFIG_HOME': str(source_dir / 'data/.config')} do_test(proto_ver=3, env=env) do_test(proto_ver=4, env=env) do_test(proto_ver=5, env=env) ================================================ FILE: test/client/03-publish-file-empty.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def write_file(filename): with open(filename, 'w') as f: pass def do_test(proto_ver): rc = 1 port = mosq_test.get_port() data_file = os.path.basename(__file__).replace('.py', '.data') if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-p', str(port), '-q', '1', '-t', '03/pub/file/empty/test', '-f', data_file, '-V', V ] publish_packet = mosq_test.gen_publish("03/pub/file/empty/test", qos=0, payload="", proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) write_file(data_file) try: sock = mosq_test.sub_helper(port=port, topic="#", qos=0, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: os.remove(data_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/03-publish-file.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def write_file(filename): with open(filename, 'w') as f: f.write("line1\n") f.write("line2\n") def do_test(proto_ver): rc = 1 port = mosq_test.get_port() data_file = os.path.basename(__file__).replace('.py', '.data') if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-p', str(port), '-q', '1', '-t', '03/pub/file/test', '-f', data_file, '-V', V ] publish_packet = mosq_test.gen_publish("03/pub/file/test", qos=0, payload="line1\nline2\n", proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) write_file(data_file) try: sock = mosq_test.sub_helper(port=port, topic="#", qos=0, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: os.remove(data_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/03-publish-options-file.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def write_config(filename, port, V): with open(filename, 'w') as f: f.write("-p %d\n" % (port)) f.write("-V %s\n" % (V)) f.write("-q 1\n") f.write("-t 03/pub/qos1/test\n") f.write("-m message\n") def do_test(proto_ver): rc = 1 port = mosq_test.get_port() conf_file = os.path.basename(__file__).replace('.py', '.conf') if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-o', conf_file ] write_config(conf_file, port, V) mid = 1 publish_packet = mosq_test.gen_publish("03/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.NO_MATCHING_SUBSCRIBERS) else: puback_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.sub_helper(port=port, topic="#", qos=1, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: os.remove(conf_file) broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/03-publish-qos0-empty.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-p', str(port), '-q', '0', '-t', '03/pub/qos0/test', '-n', '-V', V ] mid = 1 publish_packet = mosq_test.gen_publish("03/pub/qos0/test", qos=0, mid=mid, payload="", proto_ver=proto_ver) if proto_ver == 5: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver, reason_code=mqtt5_rc.NO_MATCHING_SUBSCRIBERS) else: puback_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.sub_helper(port=port, topic="#", qos=0, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/03-publish-qos1-properties.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-p', str(port), '-q', '1', '-t', '03/pub/qos1/test/properties', '-m', 'message', '-V', V, '-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' ] mid = 1 props = mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "application/json") props += mqtt5_props.gen_string_prop(mqtt5_props.CORRELATION_DATA, "some-data") props += mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 1) props += mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "/dev/null") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "publish", "up") props += mqtt5_props.gen_uint32_prop(mqtt5_props.MESSAGE_EXPIRY_INTERVAL, 59) publish_packet = mosq_test.gen_publish("03/pub/qos1/test/properties", qos=1, mid=mid, payload="message", proto_ver=proto_ver, properties=props) puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver, reason_code=mqtt5_rc.NO_MATCHING_SUBSCRIBERS) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.sub_helper(port=port, topic="#", qos=1, proto_ver=5) pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=5) ================================================ FILE: test/client/03-publish-qos1-ws-large.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write(f"listener {port1}\n") f.write("protocol websockets\n") f.write(f"listener {port2}\n") def do_test(proto_ver): rc = 1 ports = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) payload = "abcdefghijklmnopqrstuvwxyz0123456789"*1821 cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-p', str(ports[0]), '-q', '1', '-t', '03/pub/qos1/test', '-m', payload, '-V', V, '--ws' ] mid = 1 publish_packet = mosq_test.gen_publish("03/pub/qos1/test", qos=1, mid=mid, payload=payload, proto_ver=proto_ver) if proto_ver == 5: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver, reason_code=mqtt5_rc.NO_MATCHING_SUBSCRIBERS) else: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) write_config(conf_file, ports[0], ports[1]) try: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=ports[1], use_conf=True) sock = mosq_test.sub_helper(port=ports[1], topic="#", qos=1, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() os.remove(conf_file) if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/03-publish-qos1-ws.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write(f"listener {port1}\n") f.write("protocol websockets\n") f.write(f"listener {port2}\n") def do_test(proto_ver): rc = 1 ports = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-p', str(ports[0]), '-q', '1', '-t', '03/pub/qos1/test', '-m', 'message', '-V', V, '--ws' ] mid = 1 publish_packet = mosq_test.gen_publish("03/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.NO_MATCHING_SUBSCRIBERS) else: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) write_config(conf_file, ports[0], ports[1]) try: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=ports[1], use_conf=True) sock = mosq_test.sub_helper(port=ports[1], topic="#", qos=1, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() os.remove(conf_file) if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/03-publish-qos1.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-p', str(port), '-q', '1', '-t', '03/pub/qos1/test', '-m', 'message', '-V', V ] mid = 1 publish_packet = mosq_test.gen_publish("03/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.NO_MATCHING_SUBSCRIBERS) else: puback_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.sub_helper(port=port, topic="#", qos=1, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/03-publish-repeat.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-p', str(port), '-q', '1', '-t', '03/pub/repeat/test', '-m', 'message', '-V', V, '--repeat', '2', '--repeat-delay', '0.1', ] mid = 1 publish_packet = mosq_test.gen_publish("03/pub/repeat/test", qos=0, mid=mid, payload="message", proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.sub_helper(port=port, topic="#", qos=0, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 mosq_test.expect_packet(sock, "publish 1", publish_packet) mosq_test.expect_packet(sock, "publish 2", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/03-publish-socks-auth-failed.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver, host): rc = 1 (port1, port2) = mosq_test.get_port(2) cmd = ['microsocks', '-?'] try: proxy = subprocess.run(cmd, capture_output=True) except FileNotFoundError: print("microsocks not found, skipping test") sys.exit(0) cmd = ['microsocks', '-1', '-i', host, '-u', 'user', '-P', 'pass:word', '-p', str(port1)] if b"bindaddr" in proxy.stderr: cmd += ['-b', host] else: cmd += ['-b'] try: proxy = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except FileNotFoundError: print("microsocks not found, skipping test") sys.exit(0) if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [ f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-h', host, '-p', str(port2), '-q', '1', '-t', '03/pub/proxy/test', '-m', 'message', '-V', V, '--proxy', f'socks5h://wrong:auth@{host}:{port1}' ] broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, checkhost=host) try: pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() if stde.decode('utf-8') == 'Error: Authorisation failed\n': rc = 0 else: rc = pub_terminate_rc except mosq_test.TestError: pass except Exception as e: print(e) finally: proxy.terminate() broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=3, host="localhost") do_test(proto_ver=4, host="localhost") do_test(proto_ver=5, host="localhost") ================================================ FILE: test/client/03-publish-socks-no-auth.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver, host): rc = 1 (port1, port2) = mosq_test.get_port(2) cmd = ['microsocks', '-?'] try: proxy = subprocess.run(cmd, capture_output=True) except FileNotFoundError: print("microsocks not found, skipping test") sys.exit(0) cmd = ['microsocks', '-i', host, '-p', str(port1)] if b"bindaddr" in proxy.stderr: cmd += ['-b', host] else: cmd += ['-b'] try: proxy = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except FileNotFoundError: print("microsocks not found, skipping test") sys.exit(0) if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [ f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-h', host, '-p', str(port2), '-q', '1', '-t', '03/pub/proxy/test', '-m', 'message', '-V', V, '--proxy', f'socks5h://{host}:{port1}' ] mid = 1 publish_packet = mosq_test.gen_publish("03/pub/proxy/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.NO_MATCHING_SUBSCRIBERS) else: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, checkhost=host) try: sock = mosq_test.sub_helper(port=port2, topic="#", qos=1, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: proxy.terminate() broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=3, host="localhost") do_test(proto_ver=4, host="localhost") do_test(proto_ver=5, host="localhost") do_test(proto_ver=5, host="ip6-localhost") do_test(proto_ver=5, host="127.0.0.1") #do_test(proto_ver=5, host="::1") ================================================ FILE: test/client/03-publish-socks.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver, host): rc = 1 (port1, port2) = mosq_test.get_port(2) cmd = ['microsocks', '-?'] try: proxy = subprocess.run(cmd, capture_output=True) except FileNotFoundError: print("microsocks not found, skipping test") sys.exit(0) cmd = ['microsocks', '-1', '-i', host, '-u', 'user', '-P', 'pass:word', '-p', str(port1)] if b"bindaddr" in proxy.stderr: cmd += ['-b', host] else: cmd += ['-b'] try: proxy = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except FileNotFoundError: print("microsocks not found, skipping test") sys.exit(0) if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [ f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-h', host, '-p', str(port2), '-q', '1', '-t', '03/pub/proxy/test', '-m', 'message', '-V', V, '--proxy', f'socks5h://user:pass%3Aword@{host}:{port1}' ] mid = 1 publish_packet = mosq_test.gen_publish("03/pub/proxy/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.NO_MATCHING_SUBSCRIBERS) else: puback_packet = mosq_test.gen_puback(mid, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port2, checkhost=host) try: sock = mosq_test.sub_helper(port=port2, topic="#", qos=1, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: proxy.terminate() broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) do_test(proto_ver=3, host="localhost") do_test(proto_ver=4, host="localhost") do_test(proto_ver=5, host="localhost") do_test(proto_ver=5, host="ip6-localhost") do_test(proto_ver=5, host="127.0.0.1") #do_test(proto_ver=5, host="::1") ================================================ FILE: test/client/03-publish-stdin-file.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-p', str(port), '-q', '1', '-t', '03/pub/stdin/file/test', '-s', '-V', V ] publish_packet = mosq_test.gen_publish("03/pub/stdin/file/test", qos=0, payload="message1\nmessage2", proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.sub_helper(port=port, topic="#", qos=0, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) pub.stdin.write(b'message1\nmessage2') pub.stdin.close() pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/03-publish-stdin-line.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-p', str(port), '-q', '2', '-t', '03/pub/stdin/line/test', '-l', '-V', V ] publish_packet1 = mosq_test.gen_publish("03/pub/stdin/line/test", qos=0, payload="message1", proto_ver=proto_ver) publish_packet2 = mosq_test.gen_publish("03/pub/stdin/line/test", qos=0, payload="message2", proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.sub_helper(port=port, topic="#", qos=0, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) pub.stdin.write(b'message1\nmessage2') pub.stdin.close() pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 mosq_test.expect_packet(sock, "publish", publish_packet1) mosq_test.expect_packet(sock, "publish", publish_packet2) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/03-publish-tls.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * source_dir = Path(__file__).resolve().parent ssl_dir = source_dir.parent / "ssl" def do_test(address, insecure_option, expect_ssl_fail): rc = 1 port = mosq_test.get_port() port = 8883 env = { 'XDG_CONFIG_HOME':'/tmp/missing', 'SSLKEYLOGFILE':'/home/roger/keylog' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '--cafile', f"{ssl_dir}/all-ca.crt", '-d', '-h', address, '-p', str(port), '-t', '03/pub/tls/test', '-m', 'message', ] if insecure_option is not None: cmd.append(insecure_option) connect_packet = mosq_test.gen_connect("", clean_session=True) connack_packet = mosq_test.gen_connack(rc=0) publish_packet = mosq_test.gen_publish("03/pub/tls/test", qos=0, payload="message") broker = socket.socket(socket.AF_INET, socket.SOCK_STREAM) broker.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=f"{ssl_dir}/all-ca.crt") context.minimum_version = ssl.TLSVersion.TLSv1_2 context.load_cert_chain(certfile=f"{ssl_dir}/server-san.crt", keyfile=f"{ssl_dir}/server-san.key") sbroker = context.wrap_socket(broker, server_side=True) sbroker.settimeout(20) sbroker.bind(('', port)) sbroker.listen(5) try: pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) (pub_sock, address) = sbroker.accept() pub_sock.settimeout(5) mosq_test.expect_packet(pub_sock, "connect", connect_packet) pub_sock.send(connack_packet) mosq_test.expect_packet(pub_sock, "publish", publish_packet) if expect_ssl_fail: raise mosq_test.TestError pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() rc = pub_terminate_rc pub_sock.close() except mosq_test.TestError: pass except ssl.SSLError as e: if expect_ssl_fail and e.reason == "SSLV3_ALERT_BAD_CERTIFICATE": rc = 0 pass else: raise mosq_test.TestError except Exception as e: print(e) finally: broker.close() if rc: print(stde.decode('utf-8')) exit(rc) do_test("127.0.0.1", None, False) do_test(mosq_test.get_non_loopback_ip(), None, True) do_test(mosq_test.get_non_loopback_ip(), "--insecure", False) ================================================ FILE: test/client/03-publish-url.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_pub', '-L', f'mqtt://localhost:{port}/03/pub/url/test', '-m', 'message', '-V', V ] publish_packet = mosq_test.gen_publish("03/pub/url/test", qos=0, payload="message", proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.sub_helper(port=port, topic="#", qos=0, proto_ver=proto_ver) pub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) pub_terminate_rc = 0 if mosq_test.wait_for_subprocess(pub): print("pub not terminated") pub_terminate_rc = 1 (stdo, stde) = pub.communicate() mosq_test.expect_packet(sock, "publish", publish_packet) rc = pub_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/04-rr-argv-errors-tls-psk.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(args, stderr_expected, rc_expected): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_rr'] + args sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) sub.wait() (stdo, stde) = sub.communicate() if sub.returncode != rc_expected: raise mosq_test.TestError(sub.returncode) if stderr_expected is not None and stde.decode('utf-8') != stderr_expected: raise mosq_test.TestError(stde) if __name__ == '__main__': helps = "\nUse 'mosquitto_rr --help' to see usage.\n" # Missing args for TLS-PSK related options do_test(['--psk'], "Error: --psk argument given but no key specified.\n\n" + helps, 1) do_test(['--psk-identity'], "Error: --psk-identity argument given but no identity specified.\n\n" + helps, 1) ================================================ FILE: test/client/04-rr-argv-errors-tls.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(args, stderr_expected, rc_expected): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_rr'] + args sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) sub.wait() (stdo, stde) = sub.communicate() if sub.returncode != rc_expected: raise mosq_test.TestError(sub.returncode) if stderr_expected is not None and stde.decode('utf-8') != stderr_expected: raise mosq_test.TestError(stde) if __name__ == '__main__': helps = "\nUse 'mosquitto_rr --help' to see usage.\n" # Missing args for TLS related options do_test(['--cafile'], "Error: --cafile argument given but no file specified.\n\n" + helps, 1) do_test(['--capath'], "Error: --capath argument given but no directory specified.\n\n" + helps, 1) do_test(['--cert'], "Error: --cert argument given but no file specified.\n\n" + helps, 1) do_test(['--ciphers'], "Error: --ciphers argument given but no ciphers specified.\n\n" + helps, 1) do_test(['--key'], "Error: --key argument given but no file specified.\n\n" + helps, 1) do_test(['--keyform'], "Error: --keyform argument given but no keyform specified.\n\n" + helps, 1) do_test(['--tls-alpn'], "Error: --tls-alpn argument given but no protocol specified.\n\n" + helps, 1) do_test(['--tls-engine'], "Error: --tls-engine argument given but no engine_id specified.\n\n" + helps, 1) do_test(['--tls-engine-kpass-sha1'], "Error: --tls-engine-kpass-sha1 argument given but no kpass sha1 specified.\n\n" + helps, 1) do_test(['--tls-version'], "Error: --tls-version argument given but no version specified.\n\n" + helps, 1) ================================================ FILE: test/client/04-rr-argv-errors-without-tls.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(args, stderr_expected, rc_expected): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_rr'] + args sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) sub.wait() (stdo, stde) = sub.communicate() if sub.returncode != rc_expected: raise mosq_test.TestError(sub.returncode) if stderr_expected is not None and stde.decode('utf-8') != stderr_expected: raise mosq_test.TestError(stde) if __name__ == '__main__': helps = "\nUse 'mosquitto_rr --help' to see usage.\n" # Usage, version, ignore actual text though. do_test(['--help'], None, 1) do_test(['--version'], None, 1) # Missing args do_test(['-A'], "Error: -A argument given but no address specified.\n\n" + helps, 1) do_test(['-e'], "Error: -e argument given but no response topic specified.\n\n" + helps, 1) do_test(['-h'], "Error: -h argument given but no host specified.\n\n" + helps, 1) do_test(['-i'], "Error: -i argument given but no id specified.\n\n" + helps, 1) do_test(['-I'], "Error: -I argument given but no id prefix specified.\n\n" + helps, 1) do_test(['-k'], "Error: -k argument given but no keepalive specified.\n\n" + helps, 1) do_test(['-L'], "Error: -L argument given but no URL specified.\n\n" + helps, 1) do_test(['-M'], "Error: -M argument given but max_inflight not specified.\n\n" + helps, 1) do_test(['-m'], "Error: -m argument given but no message specified.\n\n" + helps, 1) do_test(['-o'], "Error: -o argument given but no options file specified.\n\n" + helps, 1) do_test(['-p'], "Error: -p argument given but no port specified.\n\n" + helps, 1) do_test(['-P'], "Error: -P argument given but no password specified.\n\n" + helps, 1) do_test(['--proxy'], "Error: --proxy argument given but no proxy url specified.\n\n" + helps, 1) do_test(['-q'], "Error: -q argument given but no QoS specified.\n\n" + helps, 1) do_test(['-t'], "Error: -t argument given but no topic specified.\n\n" + helps, 1) do_test(['-u'], "Error: -u argument given but no username specified.\n\n" + helps, 1) do_test(['--unix'], "Error: --unix argument given but no socket path specified.\n\n" + helps, 1) do_test(['-V'], "Error: --protocol-version argument given but no version specified.\n\n" + helps, 1) do_test(['--will-payload'], "Error: --will-payload argument given but no will payload specified.\n\n" + helps, 1) do_test(['--will-qos'], "Error: --will-qos argument given but no will QoS specified.\n\n" + helps, 1) do_test(['--will-topic'], "Error: --will-topic argument given but no will topic specified.\n\n" + helps, 1) do_test(['-x'], "Error: -x argument given but no session expiry interval specified.\n\n" + helps, 1) do_test(['-F'], "Error: -F argument given but no format specified.\n\n" + helps, 1) do_test(['-o'], "Error: -o argument given but no options file specified.\n\n" + helps, 1) do_test(['-W'], "Error: -W argument given but no timeout specified.\n\n" + helps, 1) do_test(['--will-payload', 'payload'], "Error: Will payload given, but no will topic given.\n" + helps, 1) # No -t or -U do_test([], "Error: All of topic, message, and response topic must be supplied.\n" + helps, 1) # Invalid combinations do_test(['-i', 'id', '-I', 'id-prefix'], "Error: -i and -I argument cannot be used together.\n\n" + helps, 1) do_test(['-I', 'id-prefix', '-i', 'id'], "Error: -i and -I argument cannot be used together.\n\n" + helps, 1) # Invalid output format do_test(['-F', '%'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%0'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%-'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%1'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%.'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%.1'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '%Z'], "Error: Invalid format specifier 'Z'.\n" + helps, 1) do_test(['-F', '@'], "Error: Incomplete format specifier.\n" + helps, 1) do_test(['-F', '\\'], "Error: Incomplete escape specifier.\n" + helps, 1) do_test(['-F', '\\Z'], "Error: Invalid escape specifier 'Z'.\n" + helps, 1) # Invalid values do_test(['-e', 'topic/+'], "Error: Invalid response topic 'topic/+', does it contain '+' or '#'?\n" + helps, 1) do_test(['-k', '-1'], "Error: Invalid keepalive given, it must be between 5 and 65535 inclusive.\n\n" + helps, 1) do_test(['-k', '65536'], "Error: Invalid keepalive given, it must be between 5 and 65535 inclusive.\n\n" + helps, 1) do_test(['-M', '0'], "Error: Maximum inflight messages must be greater than 0.\n\n" + helps, 1) do_test(['-p', '-1'], "Error: Invalid port given: -1\n" + helps, 1) do_test(['-p', '65536'], "Error: Invalid port given: 65536\n" + helps, 1) do_test(['-q', '-1'], "Error: Invalid QoS given: -1\n" + helps, 1) do_test(['-q', '3'], "Error: Invalid QoS given: 3\n" + helps, 1) do_test(['-L', 'invalid://'], "Error: Unsupported URL scheme.\n\n" + helps, 1) do_test(['-L', 'mqtt://localhost'], "Error: Invalid URL for -L argument specified - topic missing.\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'request-problem-information', '-1'], "Error: Property value (-1) out of range for property request-problem-information.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'request-problem-information', '256'], "Error: Property value (256) out of range for property request-problem-information.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'receive-maximum', '-1'], "Error: Property value (-1) out of range for property receive-maximum.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'receive-maximum', '65536'], "Error: Property value (65536) out of range for property receive-maximum.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'session-expiry-interval', '-1'], "Error: Property value (-1) out of range for property session-expiry-interval.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'connect', 'session-expiry-interval', '4294967296'], "Error: Property value (4294967296) out of range for property session-expiry-interval.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'subscribe', 'subscription-identifier', '-1'], "Error: Property value (-1) out of range for property subscription-identifier.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'subscribe', 'subscription-identifier', '4294967296'], "Error: Property value (4294967296) out of range for property subscription-identifier.\n\n" + helps, 1) do_test(['-V', '5', '-D', 'subscribe', 'topic-alias', '1'], "Error: topic-alias property not allowed for subscribe in --property argument.\n\n" + helps, 1) do_test(['-V', '0'], "Error: Invalid protocol version argument given.\n\n" + helps, 1) do_test(['-W', '0'], "Error: Invalid timeout \"0\".\n\n" + helps, 1) do_test(['--will-qos', '-1'], "Error: Invalid will QoS -1.\n\n" + helps, 1) do_test(['--will-qos', '3'], "Error: Invalid will QoS 3.\n\n" + helps, 1) do_test(['--will-topic', '+'], "Error: Invalid will topic '+', does it contain '+' or '#'?\n" + helps, 1) do_test(['-x', 'A'], "Error: session-expiry-interval not a number.\n\n" + helps, 1) do_test(['-x', '-2'], "Error: session-expiry-interval out of range.\n\n" + helps, 1) do_test(['-x', '4294967296'], "Error: session-expiry-interval out of range.\n\n" + helps, 1) do_test(['--retain-handling', 'invalid'], "Error: Unknown value 'invalid' for --retain-handling.\n\n" + helps, 1) # Mixed message types do_test(['-m', 'message', '-f', 'file'], "Error: Only one type of message can be sent at once.\n\n" + helps, 1) # Unknown options do_test(['--unknown'], "Error: Unknown option '--unknown'.\n" + helps, 1) do_test(['-l'], "Error: Unknown option '-l'.\n" + helps, 1) do_test(['-r'], "Error: Unknown option '-r'.\n" + helps, 1) do_test(['--repeat'], "Error: Unknown option '--repeat'.\n" + helps, 1) do_test(['--repeat-delay'], "Error: Unknown option '--repeat-delay'.\n" + helps, 1) ================================================ FILE: test/client/04-rr-env.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver, env): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = mosq_test.env_add_ld_library_path(env) payload = "message" cmd = [mosq_test.get_build_root() + '/client/mosquitto_rr', '-p', str(port), '-q', '1', '-t', '04/rr/qos1/test/request', '-e', '04/rr/qos1/test/response', '-V', V, '-m', payload ] if proto_ver == 5: props = mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "04/rr/qos1/test/response") else: props = None publish_packet_req = mosq_test.gen_publish("04/rr/qos1/test/request", qos=1, mid=1, payload=payload, proto_ver=proto_ver, properties=props) payload = "the response" publish_packet_resp = mosq_test.gen_publish("04/rr/qos1/test/response", qos=1, mid=2, payload=payload, proto_ver=proto_ver) puback_packet_req = mosq_test.gen_puback(1, proto_ver=proto_ver) puback_packet_resp = mosq_test.gen_puback(2, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.sub_helper(port=port, topic="04/rr/qos1/test/request", qos=1, proto_ver=proto_ver) rr = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) mosq_test.expect_packet(sock, "publish", publish_packet_req) sock.send(puback_packet_req) sock.send(publish_packet_resp) mosq_test.expect_packet(sock, "puback", puback_packet_resp) time.sleep(0.1) rr_terminate_rc = 0 if mosq_test.wait_for_subprocess(rr): print("rr not terminated") rr_terminate_rc = 1 (stdo, stde) = rr.communicate() if stdo.decode('utf-8') == payload + '\n': rc = rr_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (stdo, stde) = broker.communicate() if rc: print(stde.decode('utf-8')) print("proto_ver=%d" % (proto_ver)) exit(rc) env = {'HOME': str(source_dir / 'data')} do_test(proto_ver=3, env=env) do_test(proto_ver=4, env=env) do_test(proto_ver=5, env=env) env = {'XDG_CONFIG_HOME': str(source_dir / 'data/.config')} do_test(proto_ver=3, env=env) do_test(proto_ver=4, env=env) do_test(proto_ver=5, env=env) ================================================ FILE: test/client/04-rr-qos1-ws.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def write_config(filename, port1, port2): with open(filename, 'w') as f: f.write("allow_anonymous true\n") f.write(f"listener {port1}\n") f.write("protocol websockets\n") f.write(f"listener {port2}\n") def do_test(proto_ver): rc = 1 ports = mosq_test.get_port(2) conf_file = os.path.basename(__file__).replace('.py', '.conf') if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) payload = "message" cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_rr', '-p', str(ports[0]), '-q', '1', '-t', '04/rr/qos1/test/request', '-e', '04/rr/qos1/test/response', '-V', V, '-m', payload, '--ws' ] if proto_ver == 5: props = mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "04/rr/qos1/test/response") else: props = None publish_packet_req = mosq_test.gen_publish("04/rr/qos1/test/request", qos=1, mid=1, payload=payload, proto_ver=proto_ver, properties=props) payload = "the response" publish_packet_resp = mosq_test.gen_publish("04/rr/qos1/test/response", qos=1, mid=2, payload=payload, proto_ver=proto_ver) puback_packet_req = mosq_test.gen_puback(1, proto_ver=proto_ver) puback_packet_resp = mosq_test.gen_puback(2, proto_ver=proto_ver) write_config(conf_file, ports[0], ports[1]) try: broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=ports[1], use_conf=True) sock = mosq_test.sub_helper(port=ports[1], topic="04/rr/qos1/test/request", qos=1, proto_ver=proto_ver) rr = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) mosq_test.expect_packet(sock, "publish", publish_packet_req) sock.send(puback_packet_req) sock.send(publish_packet_resp) mosq_test.expect_packet(sock, "puback", puback_packet_resp) time.sleep(0.1) rr_terminate_rc = 0 if mosq_test.wait_for_subprocess(rr): print("rr not terminated") rr_terminate_rc = 1 (stdo, stde) = rr.communicate() if stdo.decode('utf-8') == payload + '\n': rc = rr_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() os.remove(conf_file) if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/04-rr-qos1.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(proto_ver): rc = 1 port = mosq_test.get_port() if proto_ver == 5: V = 'mqttv5' elif proto_ver == 4: V = 'mqttv311' else: V = 'mqttv31' env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) payload = "message" cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_rr', '-p', str(port), '-q', '1', '-t', '04/rr/qos1/test/request', '-e', '04/rr/qos1/test/response', '-V', V, '-m', payload ] if proto_ver == 5: props = mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "04/rr/qos1/test/response") else: props = None publish_packet_req = mosq_test.gen_publish("04/rr/qos1/test/request", qos=1, mid=1, payload=payload, proto_ver=proto_ver, properties=props) payload = "the response" publish_packet_resp = mosq_test.gen_publish("04/rr/qos1/test/response", qos=1, mid=2, payload=payload, proto_ver=proto_ver) puback_packet_req = mosq_test.gen_puback(1, proto_ver=proto_ver) puback_packet_resp = mosq_test.gen_puback(2, proto_ver=proto_ver) broker = mosq_test.start_broker(filename=os.path.basename(__file__), port=port) try: sock = mosq_test.sub_helper(port=port, topic="04/rr/qos1/test/request", qos=1, proto_ver=proto_ver) rr = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) mosq_test.expect_packet(sock, "publish", publish_packet_req) sock.send(puback_packet_req) sock.send(publish_packet_resp) mosq_test.expect_packet(sock, "puback", puback_packet_resp) time.sleep(0.1) rr_terminate_rc = 0 if mosq_test.wait_for_subprocess(rr): print("rr not terminated") rr_terminate_rc = 1 (stdo, stde) = rr.communicate() if stdo.decode('utf-8') == payload + '\n': rc = rr_terminate_rc sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: broker.terminate() if mosq_test.wait_for_subprocess(broker): print("broker not terminated") if rc == 0: rc=1 (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) ================================================ FILE: test/client/04-rr-retain-handling.py ================================================ #!/usr/bin/env python3 # from mosq_test_helper import * def do_test(): rc = 1 port = mosq_test.get_port() env = { 'XDG_CONFIG_HOME':'/tmp/missing' } env = mosq_test.env_add_ld_library_path(env) cmd = [f'{mosq_test.get_build_root()}/client/mosquitto_rr', '-p', str(port), '-q', '0', '-e', 'retain-handling', '-t', 'retain-handling', '-m', 'm', '-V', '5', ] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(5) sock.bind(('', port)) sock.listen(5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 1) connect_packet = mosq_test.gen_connect("", proto_ver=5, properties=props) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) subscribe_packet_always = mosq_test.gen_subscribe(mid=1, topic="retain-handling", qos=0x00, proto_ver=5) subscribe_packet_new = mosq_test.gen_subscribe(mid=1, topic="retain-handling", qos=0x10, proto_ver=5) subscribe_packet_never = mosq_test.gen_subscribe(mid=1, topic="retain-handling", qos=0x20, proto_ver=5) suback_packet = mosq_test.gen_suback(mid=1, qos=0, proto_ver=5) props = mqtt5_props.gen_string_prop(mqtt5_props.RESPONSE_TOPIC, "retain-handling") publish_packet_in = mosq_test.gen_publish("retain-handling", qos=0, payload="m", proto_ver=5, properties=props) publish_packet_out = mosq_test.gen_publish("retain-handling", qos=0, payload="m", proto_ver=5) client_terminate_rc = 0 try: for subscribe_packet, handling in [ (subscribe_packet_always, 'always'), (subscribe_packet_new, 'new'), (subscribe_packet_never, 'never')]: client_cmd = cmd + ['--retain-handling', handling] client = subprocess.Popen(client_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) (conn, address) = sock.accept() conn.settimeout(5) mosq_test.expect_packet(conn, "connect", connect_packet) conn.send(connack_packet) mosq_test.expect_packet(conn, f"subscribe {handling}", subscribe_packet) conn.send(suback_packet) mosq_test.expect_packet(conn, "publish}", publish_packet_in) conn.send(publish_packet_out) if mosq_test.wait_for_subprocess(client): print("client not terminated") client_terminate_rc = 1 sock.close() except mosq_test.TestError: pass except Exception as e: print(e) finally: sock.close() client.terminate() exit(client_terminate_rc) do_test() ================================================ FILE: test/client/CMakeLists.txt ================================================ file(GLOB PY_TEST_FILES [0-9][0-9]-*.py) set(EXCLUDE_LIST # none ) foreach(PY_TEST_FILE ${PY_TEST_FILES}) get_filename_component(PY_TEST_NAME ${PY_TEST_FILE} NAME_WE) if(${PY_TEST_NAME} IN_LIST EXCLUDE_LIST) continue() endif() add_test(NAME client-${PY_TEST_NAME} COMMAND ${PY_TEST_FILE} ) set_tests_properties(client-${PY_TEST_NAME} PROPERTIES ENVIRONMENT "BUILD_ROOT=${CMAKE_BINARY_DIR}" ) endforeach() ================================================ FILE: test/client/Makefile ================================================ R=../.. include ${R}/config.mk .PHONY: all check test test-compile ptest clean .NOTPARALLEL: all : check : test test : 02 03 04 ./test.sh ./test-ws.sh test-compile: 02 : ./02-subscribe-argv-errors-without-tls.py ifeq ($(WITH_TLS),yes) ./02-subscribe-argv-errors-tls.py ifeq ($(WITH_TLS_PSK),yes) ./02-subscribe-argv-errors-tls-psk.py endif endif ./02-subscribe-env.py ./02-subscribe-filter-out.py ./02-subscribe-format.py ./02-subscribe-format-json-qos0.py ./02-subscribe-format-json-qos1.py ./02-subscribe-format-json-properties.py ./02-subscribe-format-json-retain.py ./02-subscribe-qos1.py ifeq ($(WITH_WEBSOCKETS),yes) ./02-subscribe-qos1-ws.py endif ./02-subscribe-retain-handling.py ./02-subscribe-format.py ./02-subscribe-null.py ./02-subscribe-verbose.py 03 : ./03-publish-argv-errors-without-tls.py ifeq ($(WITH_TLS),yes) ./03-publish-argv-errors-tls.py ifeq ($(WITH_TLS_PSK),yes) ./03-publish-argv-errors-tls-psk.py endif endif ./03-publish-env.py ./03-publish-file-empty.py ./03-publish-file.py ./03-publish-options-file.py ./03-publish-qos0-empty.py ./03-publish-qos1-properties.py ./03-publish-qos1.py ifeq ($(WITH_WEBSOCKETS),yes) ./03-publish-qos1-ws.py ./03-publish-qos1-ws-large.py endif ./03-publish-repeat.py ./03-publish-socks.py ./03-publish-socks-auth-failed.py ./03-publish-socks-no-auth.py ./03-publish-stdin-file.py ./03-publish-stdin-line.py ./03-publish-tls.py ./03-publish-url.py 04 : ./04-rr-argv-errors-without-tls.py ifeq ($(WITH_TLS),yes) ./04-rr-argv-errors-tls.py ifeq ($(WITH_TLS_PSK),yes) ./04-rr-argv-errors-tls-psk.py endif endif ./04-rr-env.py ./04-rr-qos1.py ifeq ($(WITH_WEBSOCKETS),yes) ./04-rr-qos1-ws.py endif ./04-rr-retain-handling.py ptest : ./test.sh ./test-ws.sh ./test.py clean: ================================================ FILE: test/client/data/.config/mosquitto_pub ================================================ -t env/config/file/pub -m message ================================================ FILE: test/client/data/.config/mosquitto_sub ================================================ -t env/config/file/sub ================================================ FILE: test/client/mosq_test_helper.py ================================================ import 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 from pathlib import Path source_dir = Path(__file__).resolve().parent ================================================ FILE: test/client/test-ws.sh ================================================ #!/bin/bash # Very basic client testing. set -e export BASE_PATH=../../ export LD_LIBRARY_PATH=${BASE_PATH}/lib export CONFIG=ws.conf export PORT=1888 export SUB_TIMEOUT=1 # Start broker ../../src/mosquitto -c ${CONFIG} 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 --ws -p ${PORT} -W ${SUB_TIMEOUT} -C 1 -t '$SYS/broker/version' >/dev/null echo "Simple subscribe ok" # Simple publish/subscribe test - single message from mosquitto_pub ${BASE_PATH}/client/mosquitto_sub --ws -p ${PORT} -W ${SUB_TIMEOUT} -C 1 -t 'single/test' >/dev/null & export SUB_PID=$! ${BASE_PATH}/client/mosquitto_pub --ws -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 --ws -p ${PORT} -W ${SUB_TIMEOUT} -C ${TEST_LINES} -t 'file-publish' >/dev/null & export SUB_PID=$! ${BASE_PATH}/client/mosquitto_pub --ws -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 --ws -p ${PORT} -W ${SUB_TIMEOUT} -C ${TEST_LINES} -t 'file-publish' >/dev/null & export SUB_PID=$! ${BASE_PATH}/client/mosquitto_pub --ws -p ${PORT} -t 'file-publish' -l < ./test.sh kill ${SUB_PID} 2>/dev/null || true echo "stdin publish ok" ================================================ FILE: test/client/test.py ================================================ #!/usr/bin/env python3 import sys sys.path.insert(0, "..") import ptest tests = [ #(ports required, 'path'), (1, './02-subscribe-argv-errors-tls-psk.py'), (1, './02-subscribe-argv-errors-tls.py'), (1, './02-subscribe-argv-errors-without-tls.py'), (1, './02-subscribe-env.py'), (1, './02-subscribe-filter-out.py'), (1, './02-subscribe-format.py'), (1, './02-subscribe-format-json-qos0.py'), (1, './02-subscribe-format-json-qos1.py'), (1, './02-subscribe-format-json-properties.py'), (1, './02-subscribe-format-json-retain.py'), (1, './02-subscribe-null.py'), (1, './02-subscribe-qos1.py'), (2, './02-subscribe-qos1-ws.py'), (1, './02-subscribe-retain-handling.py'), (1, './02-subscribe-verbose.py'), (1, './03-publish-argv-errors-tls-psk.py'), (1, './03-publish-argv-errors-tls.py'), (1, './03-publish-argv-errors-without-tls.py'), (1, './03-publish-env.py'), (1, './03-publish-file-empty.py'), (1, './03-publish-file.py'), (1, './03-publish-options-file.py'), (1, './03-publish-qos0-empty.py'), (1, './03-publish-qos1-properties.py'), (1, './03-publish-qos1.py'), (2, './03-publish-qos1-ws.py'), (2, './03-publish-qos1-ws-large.py'), (1, './03-publish-repeat.py'), (1, './03-publish-url.py'), (1, './03-publish-tls.py'), (2, './03-publish-socks.py'), (2, './03-publish-socks-auth-failed.py'), (2, './03-publish-socks-no-auth.py'), (1, './03-publish-stdin-file.py'), (1, './03-publish-stdin-line.py'), (1, './04-rr-argv-errors-tls-psk.py'), (1, './04-rr-argv-errors-tls.py'), (1, './04-rr-argv-errors-without-tls.py'), (1, './04-rr-env.py'), (1, './04-rr-qos1.py'), (2, './04-rr-qos1-ws.py'), (1, './04-rr-retain-handling.py'), ] if __name__ == "__main__": test = ptest.PTest() test.run_tests(tests) ================================================ FILE: test/client/test.sh ================================================ #!/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/version' >/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" ================================================ FILE: test/client/ws.conf ================================================ listener 1888 protocol websockets allow_anonymous true ================================================ FILE: test/lib/01-con-discon-success-v5.py ================================================ #!/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 * def do_test(conn, data): props = mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 1000) props += mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) connect_packet = mosq_test.gen_connect("01-con-discon-success-v5", proto_ver=5, properties=props) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) mosq_test.client_test("c/01-con-discon-success-v5.test", [], do_test, None) mosq_test.client_test("cpp/01-con-discon-success-v5.test", [], do_test, None) ================================================ FILE: test/lib/01-con-discon-success.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("01-con-discon-success") connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) mosq_test.client_test("c/01-con-discon-success.test", [], do_test, None) mosq_test.client_test("cpp/01-con-discon-success.test", [], do_test, None) ================================================ FILE: test/lib/01-con-discon-will-clear.py ================================================ #!/usr/bin/env python3 # Test whether a client produces a correct connect and subsequent disconnect, with setting a will then clearing it. from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("01-con-discon-will") connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) mosq_test.client_test("c/01-con-discon-will-clear.test", [], do_test, None) mosq_test.client_test("cpp/01-con-discon-will-clear.test", [], do_test, None) ================================================ FILE: test/lib/01-con-discon-will-v5.py ================================================ #!/usr/bin/env python3 # Test whether a client produces a correct connect and subsequent disconnect, with a will, MQTT v5 from mosq_test_helper import * def do_test(conn, data): props = mqtt5_props.gen_byte_prop(mqtt5_props.PAYLOAD_FORMAT_INDICATOR, 0x01) connect_packet = mosq_test.gen_connect("01-con-discon-will", will_topic="will/topic", will_payload=b"will-payload", will_qos=1, will_retain=True, will_properties=props, proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect() mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) mosq_test.client_test("c/01-con-discon-will-v5.test", [], do_test, None) mosq_test.client_test("cpp/01-con-discon-will-v5.test", [], do_test, None) ================================================ FILE: test/lib/01-con-discon-will.py ================================================ #!/usr/bin/env python3 # Test whether a client produces a correct connect and subsequent disconnect, with a will. from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("01-con-discon-will", will_topic="will/topic", will_payload=b"will-payload", will_qos=1, will_retain=True) connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) mosq_test.client_test("c/01-con-discon-will.test", [], do_test, None) mosq_test.client_test("cpp/01-con-discon-will.test", [], do_test, None) ================================================ FILE: test/lib/01-extended-auth-continue.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import mqtt5_rc def do_test(conn, data): props = mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 1000) props += mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) connect_packet = mosq_test.gen_connect("01-extended-auth", proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "test-method") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "test-request") # This is really a binary property auth_continue_b2c = mosq_test.gen_auth(reason_code=mqtt5_rc.CONTINUE_AUTHENTICATION, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "test-method") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "test-reply") # This is really a binary property auth_continue_c2b = mosq_test.gen_auth(reason_code=mqtt5_rc.CONTINUE_AUTHENTICATION, properties=props) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) mosq_test.do_receive_send(conn, connect_packet, auth_continue_b2c, "auth_b2c") mosq_test.do_receive_send(conn, auth_continue_c2b, connack_packet, "connack") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) mosq_test.client_test("c/01-extended-auth-continue.test", [], do_test, None) mosq_test.client_test("cpp/01-extended-auth-continue.test", [], do_test, None) ================================================ FILE: test/lib/01-extended-auth-failure.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * import mqtt5_rc def do_test(conn, data): props = mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 1000) props += mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) connect_packet = mosq_test.gen_connect("01-extended-auth", proto_ver=5, properties=props) props = mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_METHOD, "test-method") props += mqtt5_props.gen_string_prop(mqtt5_props.AUTHENTICATION_DATA, "test-request") # This is really a binary property auth_continue_b2c = mosq_test.gen_auth(reason_code=mqtt5_rc.CONTINUE_AUTHENTICATION, properties=props) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) mosq_test.do_receive_send(conn, connect_packet, auth_continue_b2c, "auth_b2c") p = conn.recv(1) if len(p) == 1: exit(1) mosq_test.client_test("c/01-extended-auth-failure.test", [], do_test, None) mosq_test.client_test("cpp/01-extended-auth-failure.test", [], do_test, None) ================================================ FILE: test/lib/01-keepalive-pingreq.py ================================================ #!/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 * def do_test(conn, data): 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() 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) mosq_test.client_test("c/01-keepalive-pingreq.test", [], do_test, None) mosq_test.client_test("cpp/01-keepalive-pingreq.test", [], do_test, None) ================================================ FILE: test/lib/01-no-clean-session.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("01-no-clean-session", clean_session=False) mosq_test.expect_packet(conn, "connect", connect_packet) mosq_test.client_test("c/01-no-clean-session.test", [], do_test, None) mosq_test.client_test("cpp/01-no-clean-session.test", [], do_test, None) ================================================ FILE: test/lib/01-pre-connect-callback.py ================================================ #!/usr/bin/env python3 # Test whether the pre-connect callback is triggered and allows us to set a username and password. # The client should connect to port 1888 with keepalive=60, clean session set, # client id 01-pre-connect, username set to uname and password set to ;'[08gn=# from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("01-pre-connect", username="uname", password=";'[08gn=#") mosq_test.expect_packet(conn, "connect", connect_packet) mosq_test.client_test("c/01-pre-connect-callback.test", [], do_test, None) mosq_test.client_test("cpp/01-pre-connect-callback.test", [], do_test, None) ================================================ FILE: test/lib/01-server-keepalive-pingreq.py ================================================ #!/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 * def do_test(conn, data): 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.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() 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) mosq_test.client_test("c/01-server-keepalive-pingreq.test", [], do_test, None) mosq_test.client_test("cpp/01-server-keepalive-pingreq.test", [], do_test, None) ================================================ FILE: test/lib/01-unpwd-set.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("01-unpwd-set", username="uname", password=";'[08gn=#") mosq_test.expect_packet(conn, "connect", connect_packet) mosq_test.client_test("c/01-unpwd-set.test", [], do_test, None) mosq_test.client_test("cpp/01-unpwd-set.test", [], do_test, None) ================================================ FILE: test/lib/01-will-set.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("01-will-set", will_topic="topic/on/unexpected/disconnect", will_qos=1, will_retain=True, will_payload=b"will message") mosq_test.expect_packet(conn, "connect", connect_packet) mosq_test.client_test("c/01-will-set.test", [], do_test, None) mosq_test.client_test("cpp/01-will-set.test", [], do_test, None) ================================================ FILE: test/lib/01-will-unpwd-set.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("01-will-unpwd-set", username="oibvvwqw", password="#'^2hg9a&nm38*us", will_topic="will-topic", will_qos=2, will_payload=b"will message") mosq_test.expect_packet(conn, "connect", connect_packet) mosq_test.client_test("c/01-will-unpwd-set.test", [], do_test, None) mosq_test.client_test("cpp/01-will-unpwd-set.test", [], do_test, None) ================================================ FILE: test/lib/02-subscribe-helper-qos2.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("subscribe-qos2-test") 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) publish_packet = mosq_test.gen_publish("qos2/test", 0, "message") mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, subscribe_packet, suback_packet, "subscribe") conn.send(publish_packet) mosq_test.expect_packet(conn, "disconnect", disconnect_packet) mosq_test.client_test("c/02-subscribe-helper-simple-qos2.test", [], do_test, None) mosq_test.client_test("cpp/02-subscribe-helper-simple-qos2.test", [], do_test, None) mosq_test.client_test("c/02-subscribe-helper-callback-qos2.test", [], do_test, None) mosq_test.client_test("cpp/02-subscribe-helper-callback-qos2.test", [], do_test, None) ================================================ FILE: test/lib/02-subscribe-qos0.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("subscribe-qos0-test") 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) 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) mosq_test.client_test("c/02-subscribe-qos0.test", [], do_test, None) mosq_test.client_test("cpp/02-subscribe-qos0.test", [], do_test, None) ================================================ FILE: test/lib/02-subscribe-qos1.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("subscribe-qos1-test") 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) 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) mosq_test.client_test("c/02-subscribe-qos1.test", [], do_test, None) mosq_test.client_test("c/02-subscribe-qos1-async1.test", [], do_test, None) mosq_test.client_test("c/02-subscribe-qos1-async2.test", [], do_test, None) mosq_test.client_test("cpp/02-subscribe-qos1.test", [], do_test, None) mosq_test.client_test("cpp/02-subscribe-qos1-async1.test", [], do_test, None) # FIXME - CI fails here, connection refused mosq_test.client_test("cpp/02-subscribe-qos1-async2.test", [], do_test, None) ================================================ FILE: test/lib/02-subscribe-qos2.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("subscribe-qos2-test") 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) 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) mosq_test.client_test("c/02-subscribe-qos2.test", [], do_test, None) mosq_test.client_test("cpp/02-subscribe-qos2.test", [], do_test, None) ================================================ FILE: test/lib/02-unsubscribe-multiple-v5.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("unsubscribe-test", 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) 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) mosq_test.client_test("c/02-unsubscribe-multiple-v5.test", [], do_test, None) # FIXME - missing func in lib mosq_test.client_test("cpp/02-unsubscribe-multiple-v5.test", [], do_test, None) ================================================ FILE: test/lib/02-unsubscribe-v5.py ================================================ #!/usr/bin/env python3 # Test whether a v5 client sends a correct UNSUBSCRIBE packet, and handles the UNSUBACK. from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("unsubscribe-test", 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 props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key", "value") unsubscribe_packet = mosq_test.gen_unsubscribe(mid, "unsubscribe/test", proto_ver=5, properties=props) unsuback_packet = mosq_test.gen_unsuback(mid, proto_ver=5) 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) mosq_test.client_test("c/02-unsubscribe-v5.test", [], do_test, None) mosq_test.client_test("cpp/02-unsubscribe-v5.test", [], do_test, None) # FIXME - missing lib function mosq_test.client_test("c/02-unsubscribe2-v5.test", [], do_test, None) # FIXME - missing lib function mosq_test.client_test("cpp/02-unsubscribe2-v5.test", [], do_test, None) ================================================ FILE: test/lib/02-unsubscribe.py ================================================ #!/usr/bin/env python3 # Test whether a client sends a correct UNSUBSCRIBE packet. from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("unsubscribe-test") 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) 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) mosq_test.client_test("c/02-unsubscribe.test", [], do_test, None) mosq_test.client_test("cpp/02-unsubscribe.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-b2c-qos1-unexpected-puback.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(conn, data): 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() mosq_test.expect_packet(conn, "connect", connect_packet) conn.send(connack_packet) conn.send(puback_packet) mosq_test.expect_packet(conn, "pingreq", pingreq_packet) mosq_test.client_test("c/03-publish-b2c-qos1-unexpected-puback.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-b2c-qos1-unexpected-puback.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-b2c-qos1.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos1-test") 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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_send_receive(conn, publish_packet, puback_packet, "puback") mosq_test.client_test("c/03-publish-b2c-qos1.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-b2c-qos1.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-b2c-qos2-len.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos2-test", 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=data['mid'], payload="message", proto_ver=5) pubrec_packet = mosq_test.gen_pubrec(data['mid'], proto_ver=5) pubcomp_packet = mosq_test.gen_pubcomp(data['mid'], proto_ver=5) 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, data['pubrel_packet'], pubcomp_packet, "pubcomp") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) data = {} data['mid'] = 56 # No reason code, no properties data['pubrel_packet'] = mosq_test.gen_pubrel(data['mid']) data['label'] = "qos2 len 2" mosq_test.client_test("c/03-publish-b2c-qos2-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-b2c-qos2-len.test", [], do_test, data) # Reason code, no properties data['pubrel_packet'] = mosq_test.gen_pubrel(data['mid'], proto_ver=5, reason_code=0x00) data['label'] = "qos2 len 3" mosq_test.client_test("c/03-publish-b2c-qos2-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-b2c-qos2-len.test", [], do_test, data) # Reason code, empty properties data['pubrel_packet'] = mosq_test.gen_pubrel(data['mid'], proto_ver=5, reason_code=0x00, properties="") data['label'] = "qos2 len 4" mosq_test.client_test("c/03-publish-b2c-qos2-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-b2c-qos2-len.test", [], do_test, data) # Reason code, one property props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key", "value") data['pubrel_packet'] = mosq_test.gen_pubrel(data['mid'], proto_ver=5, reason_code=0x00, properties=props) data['label'] = "qos2 len >5" mosq_test.client_test("c/03-publish-b2c-qos2-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-b2c-qos2-len.test", [], do_test, data) ================================================ FILE: test/lib/03-publish-b2c-qos2-unexpected-pubcomp.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(conn, data): 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() mosq_test.expect_packet(conn, "connect", connect_packet) conn.send(connack_packet) conn.send(pubcomp_packet) mosq_test.expect_packet(conn, "pingreq", pingreq_packet) mosq_test.client_test("c/03-publish-b2c-qos2-unexpected-pubcomp.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-b2c-qos2-unexpected-pubcomp.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-b2c-qos2-unexpected-pubrel.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos2-test") 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") mosq_test.expect_packet(conn, "connect", connect_packet) conn.send(connack_packet) conn.send(pubrel_unexpected) mosq_test.expect_packet(conn, "pubcomp", pubcomp_unexpected) conn.send(publish_packet) mosq_test.expect_packet(conn, "pubrec", pubrec_packet) conn.send(pubrel_packet) mosq_test.expect_packet(conn, "pubcomp", pubcomp_packet) conn.send(publish_quit_packet) conn.close() mosq_test.client_test("c/03-publish-b2c-qos2-unexpected-pubrel.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-b2c-qos2-unexpected-pubrel.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-b2c-qos2.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos2-test") 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) 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.client_test("c/03-publish-b2c-qos2.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-b2c-qos2.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-c2b-qos1-disconnect.py ================================================ #!/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 * def do_test(client_cmd): port = mosq_test.get_port() rc = 1 connect_packet = mosq_test.gen_connect("publish-qos1-test") 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 = [client_cmd, str(port)] env = mosq_test.env_add_ld_library_path() client = mosq_test.start_client(filename=client_cmd.replace('/', '-'), cmd=client_args, env=env) 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: sock.close() if mosq_test.wait_for_subprocess(client): print("test client not finished") rc=1 exit(1) do_test("c/03-publish-c2b-qos1-disconnect.test") do_test("cpp/03-publish-c2b-qos1-disconnect.test") ================================================ FILE: test/lib/03-publish-c2b-qos1-len.py ================================================ #!/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 do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos1-test", 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("pub/qos1/test", qos=1, mid=data['mid'], payload="message", proto_ver=5) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, publish_packet, data['puback_packet'], "publish") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) data = {} data['mid'] = 1 # No reason code, no properties data['puback_packet'] = mosq_test.gen_puback(data['mid']) data['label'] = "qos1 len 2" mosq_test.client_test("c/03-publish-c2b-qos1-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-c2b-qos1-len.test", [], do_test, data) # Reason code, no properties data['puback_packet'] = mosq_test.gen_puback(data['mid'], proto_ver=5, reason_code=0x00) data['label'] = "qos1 len 3" mosq_test.client_test("c/03-publish-c2b-qos1-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-c2b-qos1-len.test", [], do_test, data) # Reason code, empty properties data['puback_packet'] = mosq_test.gen_puback(data['mid'], proto_ver=5, reason_code=0x00, properties="") data['label'] = "qos1 len 4" mosq_test.client_test("c/03-publish-c2b-qos1-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-c2b-qos1-len.test", [], do_test, data) # Reason code, one property props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key", "value") data['puback_packet'] = mosq_test.gen_puback(data['mid'], proto_ver=5, reason_code=0x00, properties=props) data['label'] = "qos1 len >5" mosq_test.client_test("c/03-publish-c2b-qos1-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-c2b-qos1-len.test", [], do_test, data) ================================================ FILE: test/lib/03-publish-c2b-qos1-receive-maximum.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos1-test", proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.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) 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) mosq_test.client_test("c/03-publish-c2b-qos1-receive-maximum.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-c2b-qos1-receive-maximum.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-c2b-qos2-disconnect.py ================================================ #!/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 * def do_test(client_cmd): port = mosq_test.get_port() rc = 1 connect_packet = mosq_test.gen_connect("publish-qos2-test") 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 = [client_cmd, str(port)] env = mosq_test.env_add_ld_library_path() client = mosq_test.start_client(filename=client_cmd.replace('/', '-'), cmd=client_args, env=env) 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: sock.close() if mosq_test.wait_for_subprocess(client): print("test client not finished") rc=1 exit(1) do_test("c/03-publish-c2b-qos2-disconnect.test") do_test("cpp/03-publish-c2b-qos2-disconnect.test") ================================================ FILE: test/lib/03-publish-c2b-qos2-len.py ================================================ #!/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 do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos2-test", 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("pub/qos2/test", qos=2, mid=data['mid'], payload="message", proto_ver=5) pubrel_packet = mosq_test.gen_pubrel(data['mid'], proto_ver=5) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, publish_packet, data['pubrec_packet'], "publish") mosq_test.do_receive_send(conn, pubrel_packet, data['pubcomp_packet'], "pubrel") mosq_test.expect_packet(conn, "disconnect", disconnect_packet) data = {} data['mid'] = 1 # No reason code, no properties data['pubrec_packet'] = mosq_test.gen_pubrec(data['mid']) data['pubcomp_packet'] = mosq_test.gen_pubcomp(data['mid']) mosq_test.client_test("c/03-publish-c2b-qos2-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-c2b-qos2-len.test", [], do_test, data) # Reason code, no properties data['pubrec_packet'] = mosq_test.gen_pubrec(data['mid'], proto_ver=5, reason_code=0x00) data['pubcomp_packet'] = mosq_test.gen_pubcomp(data['mid'], proto_ver=5, reason_code=0x00) mosq_test.client_test("c/03-publish-c2b-qos2-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-c2b-qos2-len.test", [], do_test, data) # Reason code, empty properties data['pubrec_packet'] = mosq_test.gen_pubrec(data['mid'], proto_ver=5, reason_code=0x00, properties="") data['pubcomp_packet'] = mosq_test.gen_pubcomp(data['mid'], proto_ver=5, reason_code=0x00, properties="") mosq_test.client_test("c/03-publish-c2b-qos2-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-c2b-qos2-len.test", [], do_test, data) # Reason code, one property props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key", "value") data['pubrec_packet'] = mosq_test.gen_pubrec(data['mid'], proto_ver=5, reason_code=0x00, properties=props) props = mqtt5_props.gen_string_pair_prop(mqtt5_props.USER_PROPERTY, "key", "value") data['pubcomp_packet'] = mosq_test.gen_pubcomp(data['mid'], proto_ver=5, reason_code=0x00, properties=props) mosq_test.client_test("c/03-publish-c2b-qos2-len.test", [], do_test, data) mosq_test.client_test("cpp/03-publish-c2b-qos2-len.test", [], do_test, data) ================================================ FILE: test/lib/03-publish-c2b-qos2-maximum-qos-0.py ================================================ #!/usr/bin/env python3 # Test whether a client correctly handles sending a message with QoS > maximum QoS. from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos2-test", proto_ver=5) props = mqtt5_props.gen_byte_prop(mqtt5_props.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) 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) conn.close() mosq_test.client_test("c/03-publish-c2b-qos2-maximum-qos-0.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-c2b-qos2-maximum-qos-0.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-c2b-qos2-maximum-qos-1.py ================================================ #!/usr/bin/env python3 # Test whether a client correctly handles sending a message with QoS > maximum QoS. from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos2-test", proto_ver=5) props = mqtt5_props.gen_byte_prop(mqtt5_props.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) 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) conn.close() mosq_test.client_test("c/03-publish-c2b-qos2-maximum-qos-1.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-c2b-qos2-maximum-qos-1.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-c2b-qos2-pubrec-error.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos2-test", proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.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) 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") conn.close() mosq_test.client_test("c/03-publish-c2b-qos2-pubrec-error.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-c2b-qos2-pubrec-error.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-c2b-qos2-receive-maximum-1.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos2-test", proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.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) 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") conn.close() mosq_test.client_test("c/03-publish-c2b-qos2-receive-maximum.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-c2b-qos2-receive-maximum.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-c2b-qos2-receive-maximum-2.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos2-test", proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.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) 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) conn.close() mosq_test.client_test("c/03-publish-c2b-qos2-receive-maximum.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-c2b-qos2-receive-maximum.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-c2b-qos2.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos2-test") 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) 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) conn.close() mosq_test.client_test("c/03-publish-c2b-qos2.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-c2b-qos2.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-loop.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("loop-test", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 subscribe_packet = mosq_test.gen_subscribe(mid, "loop/test", 0, proto_ver=5) suback_packet = mosq_test.gen_suback(mid, 0, proto_ver=5) disconnect_packet = mosq_test.gen_disconnect(proto_ver=5) publish_packet = mosq_test.gen_publish("loop/test", qos=0, payload="message", proto_ver=5) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_receive_send(conn, subscribe_packet, suback_packet, "subscribe") conn.send(publish_packet) mosq_test.expect_packet(conn, "publish", publish_packet) mosq_test.expect_packet(conn, "disconnect", disconnect_packet) mosq_test.client_test("c/03-publish-loop.test", [], do_test, None) mosq_test.client_test("c/03-publish-loop-forever.test", [], do_test, None) mosq_test.client_test("c/03-publish-loop-manual.test", [], do_test, None) mosq_test.client_test("c/03-publish-loop-start.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-loop.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-loop-forever.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-loop-manual.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-loop-start.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-qos0-no-payload.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos0-test-np") 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() 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) conn.close() mosq_test.client_test("c/03-publish-qos0-no-payload.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-qos0-no-payload.test", [], do_test, None) ================================================ FILE: test/lib/03-publish-qos0.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos0-test") 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() 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) conn.close() mosq_test.client_test("c/03-publish-qos0.test", [], do_test, None) mosq_test.client_test("cpp/03-publish-qos0.test", [], do_test, None) ================================================ FILE: test/lib/03-request-response-correlation.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(testdir): port = mosq_test.get_port() resp_topic = "response/topic" pub_topic = "request/topic" rc = 1 connect1_packet = mosq_test.gen_connect("request-test", proto_ver=5) connect2_packet = mosq_test.gen_connect("response-test", 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.RESPONSE_TOPIC, resp_topic) props += mqtt5_props.gen_string_prop(mqtt5_props.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.RESPONSE_TOPIC, resp_topic) props += mqtt5_props.gen_string_prop(mqtt5_props.CORRELATION_DATA, "corridor") props += mqtt5_props.gen_string_pair_prop(mqtt5_props.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.CORRELATION_DATA, "corridor") publish2_packet = mosq_test.gen_publish(resp_topic, qos=0, payload="a response", proto_ver=5, properties=props) publish2_packet_outgoing = mosq_test.gen_publish(pub_topic, qos=0, payload="action", proto_ver=5, properties=props) sock = mosq_test.listen_sock(port); env = dict(os.environ) client1 = mosq_test.start_client(filename=f"{testdir}-03-request-response-correlation-1.log", cmd=[f"{testdir}/03-request-response-correlation-1.test", str(port)]) try: (conn1, address) = sock.accept() conn1.settimeout(10) client2 = mosq_test.start_client(filename=f"{testdir}-03-request-response-2.log", cmd=[f"{testdir}/03-request-response-2.test", str(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) conn1.send(publish2_packet_outgoing) rc = 0 conn1.close() conn2.close() except mosq_test.TestError: pass if mosq_test.wait_for_subprocess(client1): print("client1 not terminated") if rc == 0: rc=1 if mosq_test.wait_for_subprocess(client2): print("client2 not terminated") if rc == 0: rc=1 if rc: (stdo, stde) = client1.communicate() print(stde) (stdo, stde) = client2.communicate() print(stde) exit(1) do_test("c") do_test("cpp") ================================================ FILE: test/lib/03-request-response.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(testdir): port = mosq_test.get_port() resp_topic = "response/topic" pub_topic = "request/topic" rc = 1 connect1_packet = mosq_test.gen_connect("request-test", proto_ver=5) connect2_packet = mosq_test.gen_connect("response-test", 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.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 = mosq_test.listen_sock(port); client1 = mosq_test.start_client(filename=f"{testdir}-03-request-response-1.log", cmd=[f"{testdir}/03-request-response-1.test", str(port)]) try: (conn1, address) = sock.accept() conn1.settimeout(10) client2 = mosq_test.start_client(filename=f"{testdir}-03-request-response-2.log", cmd=[f"{testdir}/03-request-response-2.test", str(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) conn1.send(publish2_packet) rc = 0 conn1.close() conn2.close() except mosq_test.TestError: pass finally: sock.close() if mosq_test.wait_for_subprocess(client1): print("client1 not terminated") if rc == 0: rc=1 if mosq_test.wait_for_subprocess(client2): print("client2 not terminated") if rc == 0: rc=1 if rc: (stdo, stde) = client1.communicate() print(stde) (stdo, stde) = client2.communicate() print(stde) exit(1) do_test("c") do_test("cpp") ================================================ FILE: test/lib/04-retain-qos0.py ================================================ #!/usr/bin/env python3 # Test whether a client sends a correct retained PUBLISH to a topic with QoS 0. from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("retain-qos0-test") connack_packet = mosq_test.gen_connack(rc=0) mid = 16 publish_packet = mosq_test.gen_publish("retain/qos0/test", qos=0, payload="retained message", retain=True) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.expect_packet(conn, "publish", publish_packet) conn.close() mosq_test.client_test("c/04-retain-qos0.test", [], do_test, None) mosq_test.client_test("cpp/04-retain-qos0.test", [], do_test, None) ================================================ FILE: test/lib/08-ssl-bad-cacert.py ================================================ #!/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 do_test(client_cmd): rc = 1 port = mosq_test.get_port() client_args = [mosq_test.get_build_root() + "/test/lib/" + client_cmd, str(port)] client = mosq_test.start_client(filename=client_cmd.replace('/', '-'), cmd=client_args) if mosq_test.wait_for_subprocess(client): print("test client not finished") rc=1 else: rc=client.returncode if rc: (o, e) = client.communicate() print(o) print(e) exit(rc) do_test("c/08-ssl-bad-cacert.test") do_test("cpp/08-ssl-bad-cacert.test") ================================================ FILE: test/lib/08-ssl-connect-cert-auth-enc.py ================================================ #!/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 * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def do_test(client_cmd): rc = 1 connect_packet = mosq_test.gen_connect("08-ssl-connect-crt-auth-enc") connack_packet = mosq_test.gen_connack(rc=0) disconnect_packet = mosq_test.gen_disconnect() port = mosq_test.get_port() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=f"{ssl_dir}/all-ca.crt") context.load_cert_chain(certfile=f"{ssl_dir}/server.crt", keyfile=f"{ssl_dir}/server.key") context.verify_mode = ssl.CERT_REQUIRED ssock = context.wrap_socket(sock, server_side=True) ssock.settimeout(10) ssock.bind(('', port)) ssock.listen(5) client_args = [mosq_test.get_build_root() + "/test/lib/" + client_cmd, str(port)] client = mosq_test.start_client(filename=client_cmd.replace('/', '-'), cmd=client_args) 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: if mosq_test.wait_for_subprocess(client): print("test client not finished") rc=1 ssock.close() if rc: (stdo, stde) = client.communicate() print(stde.decode('utf-8')) exit(rc) do_test('c/08-ssl-connect-cert-auth-enc.test') do_test('cpp/08-ssl-connect-cert-auth-enc.test') ================================================ FILE: test/lib/08-ssl-connect-cert-auth.py ================================================ #!/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 * def do_test(client_cmd): port = mosq_test.get_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) context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=f"{ssl_dir}/all-ca.crt") context.load_cert_chain(certfile=f"{ssl_dir}/server.crt", keyfile=f"{ssl_dir}/server.key") context.verify_mode = ssl.CERT_REQUIRED ssock = context.wrap_socket(sock, server_side=True) ssock.settimeout(10) ssock.bind(('', port)) ssock.listen(5) client_args = [mosq_test.get_build_root() + "/test/lib/" + client_cmd, str(port)] client = mosq_test.start_client(filename=client_cmd.replace('/', '-'), cmd=client_args) 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: if mosq_test.wait_for_subprocess(client): print("test client not finished") rc=1 ssock.close() if rc: print(f"Fail: {client}") exit(rc) do_test("c/08-ssl-connect-cert-auth.test") do_test("c/08-ssl-connect-cert-auth-custom-ssl-ctx.test") do_test("c/08-ssl-connect-cert-auth-custom-ssl-ctx-default.test") do_test("cpp/08-ssl-connect-cert-auth.test") do_test("cpp/08-ssl-connect-cert-auth-custom-ssl-ctx.test") do_test("cpp/08-ssl-connect-cert-auth-custom-ssl-ctx-default.test") ================================================ FILE: test/lib/08-ssl-connect-no-auth.py ================================================ #!/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 * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def do_test(client_cmd): port = mosq_test.get_port() rc = 1 connect_packet = mosq_test.gen_connect("08-ssl-connect-no-auth") 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) context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=f"{ssl_dir}/all-ca.crt") context.load_cert_chain(certfile=f"{ssl_dir}/server.crt", keyfile=f"{ssl_dir}/server.key") ssock = context.wrap_socket(sock, server_side=True) ssock.settimeout(10) ssock.bind(('', port)) ssock.listen(5) client_args = [mosq_test.get_build_root() + "/test/lib/" + client_cmd, str(port)] client = mosq_test.start_client(filename=client_cmd.replace('/', '-'), cmd=client_args) 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: if mosq_test.wait_for_subprocess(client): print("test client not finished") rc=1 ssock.close() if rc: exit(rc) do_test("c/08-ssl-connect-no-auth.test") do_test("cpp/08-ssl-connect-no-auth.test") ================================================ FILE: test/lib/08-ssl-connect-san.py ================================================ #!/usr/bin/env python3 # Test whether a client produces a correct connect and subsequent disconnect when using SSL. # Certificate uses subjectAltName # The client should connect to port 1888 with keepalive=60, clean session set, # and client id 08-ssl-connect-san # 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 * if sys.version < '2.7': print("WARNING: SSL not supported on Python 2.6") exit(0) def do_test(client_cmd, host): port = mosq_test.get_port() rc = 1 connect_packet = mosq_test.gen_connect("08-ssl-connect-san") 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) context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=f"{ssl_dir}/all-ca.crt") context.load_cert_chain(certfile=f"{ssl_dir}/server-san.crt", keyfile=f"{ssl_dir}/server-san.key") ssock = context.wrap_socket(sock, server_side=True) ssock.settimeout(10) ssock.bind(('', port)) ssock.listen(5) client_args = [mosq_test.get_build_root() + "/test/lib/" + client_cmd, str(port), host] client = mosq_test.start_client(filename=client_cmd.replace('/', '-'), cmd=client_args) 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: if mosq_test.wait_for_subprocess(client): print("test client not finished") rc=1 ssock.close() if rc: exit(rc) do_test("c/08-ssl-connect-san.test", "localhost") do_test("cpp/08-ssl-connect-san.test", "localhost") do_test("c/08-ssl-connect-san.test", "127.0.0.1") do_test("cpp/08-ssl-connect-san.test", "127.0.0.1") ================================================ FILE: test/lib/08-ssl-fake-cacert.py ================================================ #!/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 do_test(client_cmd): port = mosq_test.get_port() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=f"{ssl_dir}/all-ca.crt") context.load_cert_chain(certfile=f"{ssl_dir}/server.crt", keyfile=f"{ssl_dir}/server.key") context.verify_mode = ssl.CERT_REQUIRED ssock = context.wrap_socket(sock, server_side=True) ssock.settimeout(10) ssock.bind(('', port)) ssock.listen(5) client_args = [mosq_test.get_build_root() + "/test/lib/" + client_cmd, str(port)] client = mosq_test.start_client(filename=client_cmd.replace('/', '-'), cmd=client_args) 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) if mosq_test.wait_for_subprocess(client): print("test client not finished") rc=1 ssock.close() if client.returncode == 0: exit(0) else: exit(1) do_test("c/08-ssl-fake-cacert.test") do_test("cpp/08-ssl-fake-cacert.test") ================================================ FILE: test/lib/09-util-topic-tokenise.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(client): port = mosq_test.get_port() rc = 1 client_args = [client, str(port)] client = mosq_test.start_client(filename=client.replace('/', '-'), cmd=client_args) if mosq_test.wait_for_subprocess(client): print("test client not finished") rc=1 else: rc=client.returncode if rc: print(f"Fail: {client}") exit(rc) do_test("c/09-util-topic-tokenise.test") do_test("cpp/09-util-topic-tokenise.test") ================================================ FILE: test/lib/11-prop-oversize-packet.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("publish-qos0-test", proto_ver=5) props = mqtt5_props.gen_uint16_prop(mqtt5_props.TOPIC_ALIAS_MAXIMUM, 10) props += mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 30) props += mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5, properties=props, property_helper=False) bad_publish_packet = mosq_test.gen_publish("pub/test", qos=0, payload="123456789012345678", proto_ver=5) publish_packet = mosq_test.gen_publish("pub/test", qos=0, payload="12345678901234567", proto_ver=5) disconnect_packet = mosq_test.gen_disconnect() 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) conn.close() mosq_test.client_test("c/11-prop-oversize-packet.test", [], do_test, None) mosq_test.client_test("cpp/11-prop-oversize-packet.test", [], do_test, None) ================================================ FILE: test/lib/11-prop-recv-qos0.py ================================================ #!/usr/bin/env python3 # Check whether the v5 message callback gets the properties from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("prop-test", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "plain/text") props += mqtt5_props.gen_string_prop(mqtt5_props.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) mosq_test.do_receive_send(conn, connect_packet, connack_packet, "connect") mosq_test.do_send_receive(conn, publish_packet, ok_packet, "ok") conn.close() mosq_test.client_test("c/11-prop-recv.test", ["0"], do_test, None) mosq_test.client_test("cpp/11-prop-recv.test", ["0"], do_test, None) ================================================ FILE: test/lib/11-prop-recv-qos1.py ================================================ #!/usr/bin/env python3 # Check whether the v5 message callback gets the properties from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("prop-test", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 props = mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "plain/text") props += mqtt5_props.gen_string_prop(mqtt5_props.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) 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) conn.close() mosq_test.client_test("c/11-prop-recv.test", ["1"], do_test, None) mosq_test.client_test("cpp/11-prop-recv.test", ["1"], do_test, None) ================================================ FILE: test/lib/11-prop-recv-qos2.py ================================================ #!/usr/bin/env python3 # Check whether the v5 message callback gets the properties from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("prop-test", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) mid = 1 props = mqtt5_props.gen_string_prop(mqtt5_props.CONTENT_TYPE, "plain/text") props += mqtt5_props.gen_string_prop(mqtt5_props.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) 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) conn.close() mosq_test.client_test("c/11-prop-recv.test", ["2"], do_test, None) mosq_test.client_test("cpp/11-prop-recv.test", ["2"], do_test, None) ================================================ FILE: test/lib/11-prop-send-content-type.py ================================================ #!/usr/bin/env python3 from mosq_test_helper import * def do_test(conn, data): connect_packet = mosq_test.gen_connect("prop-test", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_string_prop(mqtt5_props.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) 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) conn.close() mosq_test.client_test("c/11-prop-send-content-type.test", [], do_test, None) mosq_test.client_test("cpp/11-prop-send-content-type.test", [], do_test, None) ================================================ FILE: test/lib/11-prop-send-payload-format.py ================================================ #!/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 * def do_test(conn, data): connect_packet = mosq_test.gen_connect("prop-test", proto_ver=5) connack_packet = mosq_test.gen_connack(rc=0, proto_ver=5) props = mqtt5_props.gen_byte_prop(mqtt5_props.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) 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) conn.close() mosq_test.client_test("c/11-prop-send-payload-format.test", [], do_test, None) mosq_test.client_test("cpp/11-prop-send-payload-format.test", [], do_test, None) ================================================ FILE: test/lib/CMakeLists.txt ================================================ add_subdirectory(c) add_subdirectory(cpp) file(GLOB PY_TEST_FILES [0-9][0-9]-*.py) list(APPEND PY_TEST_FILES "${CMAKE_CURRENT_SOURCE_DIR}/msg_sequence_test.py") set(EXCLUDE_LIST 03-publish-c2b-qos1-timeout 03-publish-c2b-qos2-timeout ) foreach(PY_TEST_FILE ${PY_TEST_FILES}) get_filename_component(PY_TEST_NAME ${PY_TEST_FILE} NAME_WE) if(${PY_TEST_NAME} IN_LIST EXCLUDE_LIST) continue() endif() add_test(NAME lib-${PY_TEST_NAME} COMMAND ${PY_TEST_FILE} ) set_tests_properties(lib-${PY_TEST_NAME} PROPERTIES ENVIRONMENT "BUILD_ROOT=${CMAKE_BINARY_DIR}" ) endforeach() ================================================ FILE: test/lib/Makefile ================================================ R=../.. include ${R}/config.mk .PHONY: all check test test-compile test-compile-c test-compile-cpp .NOTPARALLEL: LD_LIBRARY_PATH=${R}/lib all : check : test ptest : test-compile ./test.py msg_sequence_test: test-compile-c ./msg_sequence_test.py test-compile : test-compile-c test-compile-cpp test-compile-c : $(MAKE) -C c test-compile-cpp : $(MAKE) -C cpp test : test-compile ./01-con-discon-success.py ./01-con-discon-success-v5.py ./01-con-discon-will.py ./01-con-discon-will-v5.py ./01-con-discon-will-clear.py ./01-extended-auth-continue.py ./01-extended-auth-failure.py ./01-keepalive-pingreq.py ./01-no-clean-session.py ./01-server-keepalive-pingreq.py ./01-pre-connect-callback.py ./01-unpwd-set.py ./01-will-set.py ./01-will-unpwd-set.py ./02-subscribe-qos0.py ./02-subscribe-qos1.py ./02-subscribe-qos2.py ./02-subscribe-helper-qos2.py ./02-unsubscribe-multiple-v5.py ./02-unsubscribe-v5.py ./02-unsubscribe.py ./03-publish-b2c-qos1.py ./03-publish-b2c-qos1-unexpected-puback.py ./03-publish-b2c-qos2-len.py ./03-publish-b2c-qos2.py ./03-publish-b2c-qos2-unexpected-pubrel.py ./03-publish-b2c-qos2-unexpected-pubcomp.py ./03-publish-c2b-qos1-disconnect.py ./03-publish-c2b-qos1-len.py ./03-publish-c2b-qos1-receive-maximum.py ./03-publish-c2b-qos2-disconnect.py ./03-publish-c2b-qos2-len.py ./03-publish-c2b-qos2-maximum-qos-0.py ./03-publish-c2b-qos2-maximum-qos-1.py ./03-publish-c2b-qos2-pubrec-error.py ./03-publish-c2b-qos2-receive-maximum-1.py ./03-publish-c2b-qos2-receive-maximum-2.py ./03-publish-c2b-qos2.py ./03-publish-loop.py ./03-publish-qos0-no-payload.py ./03-publish-qos0.py ./03-request-response-correlation.py ./03-request-response.py ./04-retain-qos0.py ifeq ($(WITH_TLS),yes) ./08-ssl-fake-cacert.py ./08-ssl-bad-cacert.py ./08-ssl-connect-cert-auth-enc.py ./08-ssl-connect-cert-auth.py ./08-ssl-connect-no-auth.py ./08-ssl-connect-san.py endif ./09-util-topic-tokenise.py ./11-prop-oversize-packet.py ./11-prop-send-content-type.py ./11-prop-send-payload-format.py ./11-prop-recv-qos0.py ./11-prop-recv-qos1.py ./11-prop-recv-qos2.py clean : $(MAKE) -C c clean $(MAKE) -C cpp clean ================================================ FILE: test/lib/c/01-con-discon-success-v5.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { (void)obj; (void)rc; (void)flags; (void)properties; /* FIXME - should verify flags and all properties here. */ if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc, const mosquitto_property *properties) { (void)mosq; (void)obj; (void)properties; /* FIXME - should verify flags and all properties here. */ run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; mosquitto_property *props = NULL; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-con-discon-success-v5", true, NULL); if(mosq == NULL){ return 1; } mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, 5); mosquitto_connect_v5_callback_set(mosq, on_connect); mosquitto_disconnect_v5_callback_set(mosq, on_disconnect); mosquitto_property_add_int32(&props, MQTT_PROP_MAXIMUM_PACKET_SIZE, 1000); rc = mosquitto_connect_bind_v5(mosq, "localhost", port, 60, NULL, props); mosquitto_property_free_all(&props); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-con-discon-success.c ================================================ #include #include #include #include static int run = -1; static int mydata = 42; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { int *obj_i = obj; if(rc || obj_i != &mydata || *obj_i != mydata || obj != mosquitto_userdata(mosq)){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-con-discon-success", true, NULL); if(mosq == NULL){ return 1; } mosquitto_user_data_set(mosq, &mydata); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-con-discon-will-clear.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-con-discon-will", true, NULL); if(mosq == NULL){ return 1; } mosquitto_will_set(mosq, "will/topic", strlen("will-payload"), "will-payload", 1, true); mosquitto_will_clear(mosq); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-con-discon-will-v5.c ================================================ #include #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; mosquitto_property *proplist = NULL; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-con-discon-will", true, NULL); if(mosq == NULL){ return 1; } mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); rc = mosquitto_property_add_byte(&proplist, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); if(rc != MOSQ_ERR_SUCCESS){ abort(); } /* Set twice, so it has to clear the old settings */ mosquitto_will_set_v5(mosq, "will/topic", strlen("will-payload"), "will-payload", 1, true, proplist); proplist = NULL; rc = mosquitto_property_add_byte(&proplist, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); if(rc != MOSQ_ERR_SUCCESS){ abort(); } mosquitto_will_set_v5(mosq, "will/topic", strlen("will-payload"), "will-payload", 1, true, proplist); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-con-discon-will.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-con-discon-will", true, NULL); if(mosq == NULL){ return 1; } /* Set twice, so it has to clear the old settings */ mosquitto_will_set(mosq, "will/topic", strlen("will-payload"), "will-payload", 1, true); mosquitto_will_set(mosq, "will/topic", strlen("will-payload"), "will-payload", 1, true); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-extended-auth-continue.c ================================================ #include #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { (void)obj; (void)rc; (void)flags; (void)properties; /* FIXME - should verify flags and all properties here. */ if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static int on_ext_auth(struct mosquitto *mosq, void *obj, const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *properties) { (void)obj; (void)auth_data; (void)auth_data_len; (void)properties; if(strcmp(auth_method, "test-method")){ run = 1; return MOSQ_ERR_AUTH; } if(auth_data_len == 0 || (!auth_data || strcmp(auth_data, "test-request"))){ run = 1; return MOSQ_ERR_AUTH; } return mosquitto_ext_auth_continue(mosq, auth_method, strlen("test-reply"), "test-reply", NULL); } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc, const mosquitto_property *properties) { (void)mosq; (void)obj; (void)properties; /* FIXME - should verify flags and all properties here. */ run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; mosquitto_property *props = NULL; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-extended-auth", true, NULL); if(mosq == NULL){ return 1; } mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, 5); mosquitto_connect_v5_callback_set(mosq, on_connect); mosquitto_ext_auth_callback_set(mosq, on_ext_auth); mosquitto_disconnect_v5_callback_set(mosq, on_disconnect); mosquitto_property_add_int32(&props, MQTT_PROP_MAXIMUM_PACKET_SIZE, 1000); rc = mosquitto_connect_bind_v5(mosq, "localhost", port, 60, NULL, props); mosquitto_property_free_all(&props); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-extended-auth-failure.c ================================================ #include #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { (void)obj; (void)rc; (void)flags; (void)properties; /* FIXME - should verify flags and all properties here. */ if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static int on_ext_auth(struct mosquitto *mosq, void *obj, const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *properties) { (void)mosq; (void)obj; (void)auth_method; (void)auth_data; (void)auth_data_len; (void)properties; return MOSQ_ERR_AUTH; } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc, const mosquitto_property *properties) { (void)mosq; (void)obj; (void)properties; /* FIXME - should verify flags and all properties here. */ run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; mosquitto_property *props = NULL; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-extended-auth", true, NULL); if(mosq == NULL){ return 1; } mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, 5); mosquitto_connect_v5_callback_set(mosq, on_connect); mosquitto_ext_auth_callback_set(mosq, on_ext_auth); mosquitto_disconnect_v5_callback_set(mosq, on_disconnect); mosquitto_property_add_int32(&props, MQTT_PROP_MAXIMUM_PACKET_SIZE, 1000); rc = mosquitto_connect_bind_v5(mosq, "localhost", port, 60, NULL, props); mosquitto_property_free_all(&props); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-keepalive-pingreq.c ================================================ #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; if(rc){ exit(1); } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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 != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); if(rc != 0){ break; } } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-no-clean-session.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-no-clean-session", false, 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-pre-connect-callback.c ================================================ #include #include #include #include #include static void on_pre_connect(struct mosquitto *mosq, void *userdata) { (void)userdata; mosquitto_username_pw_set(mosq, "uname", ";'[08gn=#"); } static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-pre-connect", true, NULL); if(mosq == NULL){ return 1; } mosquitto_pre_connect_callback_set(mosq, on_pre_connect); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-server-keepalive-pingreq.c ================================================ #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; if(rc){ exit(1); } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); if(rc){ break; } } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-unpwd-set.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; printf("conn %d\n", rc); if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-unpwd-set", true, NULL); if(mosq == NULL){ return 1; } mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_username_pw_set(mosq, "uname", ";'[08gn=#"); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-will-set.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-will-set", true, NULL); if(mosq == NULL){ return 1; } mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_will_set(mosq, "topic/on/unexpected/disconnect", strlen("will message"), "will message", 1, true); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/01-will-unpwd-set.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("01-will-unpwd-set", true, NULL); if(mosq == NULL){ return 1; } mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/02-subscribe-helper-callback-qos2.c ================================================ #include #include #include #include #include #define QOS 2 int cb(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *msg) { (void)mosq; (void)userdata; assert(msg); assert(!strcmp(msg->topic, "qos2/test")); return 1; } int main(int argc, char *argv[]) { int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosquitto_subscribe_callback( cb, NULL, "qos2/test", QOS, "localhost", port, "subscribe-qos2-test", 60, true, NULL, NULL, NULL, NULL); mosquitto_lib_cleanup(); return 0; } ================================================ FILE: test/lib/c/02-subscribe-helper-simple-qos2.c ================================================ #include #include #include #include #define QOS 2 int main(int argc, char *argv[]) { int port; struct mosquitto_message *messages; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosquitto_subscribe_simple(&messages, 1, true, "qos2/test", QOS, "localhost", port, "subscribe-qos2-test", 60, true, NULL, NULL, NULL, NULL); mosquitto_message_free(&messages); mosquitto_lib_cleanup(); return 0; } ================================================ FILE: test/lib/c/02-subscribe-qos0.c ================================================ #include #include #include #include #define QOS 0 static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "qos0/test", QOS); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } static void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { (void)obj; (void)mid; if(qos_count != 1 || granted_qos[0] != QOS){ abort(); } mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/02-subscribe-qos1-async1.c ================================================ #include #include #include #include #include /* mosquitto_connect_async() test, with mosquitto_loop_start() called before mosquitto_connect_async(). */ #define QOS 1 static int run = -1; static bool should_run = true; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "qos1/test", QOS); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } static void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { (void)mosq; (void)obj; (void)mid; if(qos_count != 1 || granted_qos[0] != QOS){ abort(); } should_run = false; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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; } ================================================ FILE: test/lib/c/02-subscribe-qos1-async2.c ================================================ #include #include #include #include #include /* mosquitto_connect_async() test, with mosquitto_loop_start() called after mosquitto_connect_async(). */ #define QOS 1 static int run = -1; static bool should_run = true; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "qos1/test", QOS); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } static void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { (void)mosq; (void)obj; (void)mid; if(qos_count != 1 || granted_qos[0] != QOS){ abort(); } should_run = false; } static const char *loglevel_as_str(int level) { switch(level){ case MOSQ_LOG_INFO: return "INFO"; case MOSQ_LOG_NOTICE: return "NOTICE"; case MOSQ_LOG_WARNING: return "WARNING"; case MOSQ_LOG_ERR: return "ERROR"; case MOSQ_LOG_DEBUG: return "DEBUG"; } return "UNKNOWN"; } static void on_log(struct mosquitto *mosq, void *user_data, int level, const char *msg) { (void)mosq; (void)user_data; fprintf(stderr, "%s: %s\n", loglevel_as_str(level), msg); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("subscribe-qos1-test", true, NULL); if(mosq == NULL){ return 1; } mosquitto_log_callback_set(mosq, &on_log); 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; } ================================================ FILE: test/lib/c/02-subscribe-qos1.c ================================================ #include #include #include #include #define QOS 1 static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "qos1/test", QOS); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } static void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { (void)obj; (void)mid; if(qos_count != 1 || granted_qos[0] != QOS){ abort(); } mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/02-subscribe-qos2.c ================================================ #include #include #include #include #define QOS 2 static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "qos2/test", QOS); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } static void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { (void)obj; (void)mid; if(qos_count != 1 || granted_qos[0] != QOS){ abort(); } mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/02-unsubscribe-multiple-v5.c ================================================ #include #include #include #include #define QOS 2 static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_subscribe_v5(mosq, NULL, "unsubscribe/test", QOS, 0, NULL); } } static void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int sub_count, const int *subs) { char *const unsubs[] = {"unsubscribe/test", "no-sub"}; (void)obj; (void)mid; if(sub_count != 1 || subs[0] != QOS){ abort(); } mosquitto_unsubscribe_multiple(mosq, NULL, 2, unsubs, NULL); } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } static void on_unsubscribe(struct mosquitto *mosq, void *obj, int mid) { (void)obj; (void)mid; mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/02-unsubscribe-v5.c ================================================ #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { int rc2; mosquitto_property *proplist = NULL; (void)obj; if(rc){ exit(1); }else{ rc2 = mosquitto_property_add_string_pair(&proplist, MQTT_PROP_USER_PROPERTY, "key", "value"); if(rc2 != MOSQ_ERR_SUCCESS){ abort(); } mosquitto_unsubscribe_v5(mosq, NULL, "unsubscribe/test", proplist); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } static void on_unsubscribe(struct mosquitto *mosq, void *obj, int mid, const mosquitto_property *props) { (void)obj; (void)mid; (void)props; mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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_v5_callback_set(mosq, on_unsubscribe); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/02-unsubscribe.c ================================================ #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_unsubscribe(mosq, NULL, "unsubscribe/test"); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } static void on_unsubscribe(struct mosquitto *mosq, void *obj, int mid) { (void)obj; (void)mid; mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/02-unsubscribe2-v5.c ================================================ #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { int rc2; mosquitto_property *proplist = NULL; (void)obj; if(rc){ exit(1); }else{ rc2 = mosquitto_property_add_string_pair(&proplist, MQTT_PROP_USER_PROPERTY, "key", "value"); if(rc2 != MOSQ_ERR_SUCCESS){ abort(); } mosquitto_unsubscribe_v5(mosq, NULL, "unsubscribe/test", proplist); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } static void on_unsubscribe(struct mosquitto *mosq, void *obj, int mid, int reason_code_count, const int *reason_codes, const mosquitto_property *props) { (void)obj; (void)mid; (void)props; for(int i=0; i #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; if(rc){ printf("Connect error: %d\n", rc); exit(1); } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ rc = mosquitto_loop(mosq, 300, 1); if(rc){ exit(0); } } mosquitto_lib_cleanup(); return 0; } ================================================ FILE: test/lib/c/03-publish-b2c-qos1.c ================================================ #include #include #include #include #include static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; if(rc){ exit(1); } } static void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { (void)mosq; (void)obj; 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; if(argc < 2){ return 1; } 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); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(1){ if(mosquitto_loop(mosq, 300, 1)){ break; } } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return 1; } ================================================ FILE: test/lib/c/03-publish-b2c-qos2-len.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; if(rc){ exit(1); } } static void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { (void)obj; 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); } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; (void)rc; run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 100, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-b2c-qos2-unexpected-pubcomp.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; if(rc){ printf("Connect error: %d\n", rc); exit(1); } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ rc = mosquitto_loop(mosq, 300, 1); if(rc){ exit(0); } } mosquitto_lib_cleanup(); return 0; } ================================================ FILE: test/lib/c/03-publish-b2c-qos2-unexpected-pubrel.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; if(rc){ exit(1); } } static void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { (void)mosq; (void)obj; 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; if(argc < 2){ return 1; } 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); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } 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; } ================================================ FILE: test/lib/c/03-publish-b2c-qos2.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; if(rc){ exit(1); } } static void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { (void)mosq; (void)obj; 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; if(argc < 2){ return 1; } 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); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-c2b-qos1-disconnect.c ================================================ #include #include #include #include #include static int run = -1; static int first_connection = 1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ if(first_connection == 1){ mosquitto_publish(mosq, NULL, "pub/qos1/test", strlen("message"), "message", 1, false); first_connection = 0; } } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; (void)mid; mosquitto_disconnect(mosq); } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ mosquitto_reconnect(mosq); }else{ run = 0; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-c2b-qos1-len.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_publish(mosq, NULL, "pub/qos1/test", strlen("message"), "message", 1, false); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; (void)mid; mosquitto_disconnect(mosq); } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; (void)rc; run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-c2b-qos1-receive-maximum.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { int i; (void)obj; (void)flags; (void)properties; if(rc){ exit(1); } for(i=0; i<6; i++){ mosquitto_publish_v5(mosq, NULL, "topic", 5, "12345", 1, false, NULL); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { (void)obj; (void)reason_code; (void)properties; if(mid == 6){ mosquitto_disconnect(mosq); run = 0; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-c2b-qos2-disconnect.c ================================================ #include #include #include #include #include static int run = -1; static int first_connection = 1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ if(first_connection == 1){ mosquitto_publish(mosq, NULL, "pub/qos2/test", strlen("message"), "message", 2, false); first_connection = 0; } } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; (void)mid; mosquitto_disconnect(mosq); } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ mosquitto_reconnect(mosq); }else{ run = 0; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-c2b-qos2-len.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_publish(mosq, NULL, "pub/qos2/test", strlen("message"), "message", 2, false); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { (void)obj; (void)mid; (void)reason_code; (void)properties; mosquitto_disconnect(mosq); } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; (void)rc; run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-c2b-qos2-maximum-qos-0.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; 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; } } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; if(mid == 1){ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; (void)rc; run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 50, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-c2b-qos2-maximum-qos-1.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; 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; } } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; if(mid == 2){ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; (void)rc; run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 50, 1); } mosquitto_loop(mosq, 50, 1); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-c2b-qos2-pubrec-error.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { (void)obj; (void)flags; (void)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); } static void on_publish(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { (void)mosq; (void)obj; (void)reason_code; (void)properties; if(mid == 2){ run = 0; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 100, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-c2b-qos2-receive-maximum.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { int i; (void)obj; (void)flags; (void)properties; if(rc){ exit(1); } for(i=0; i<5; i++){ mosquitto_publish_v5(mosq, NULL, "topic", 5, "12345", 2, false, NULL); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties) { (void)obj; (void)reason_code; (void)properties; if(mid == 5){ mosquitto_disconnect(mosq); run = 0; } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-c2b-qos2.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_publish(mosq, NULL, "pub/qos2/test", strlen("message"), "message", 2, false); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; (void)mid; mosquitto_disconnect(mosq); } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; (void)rc; run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-loop-forever.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect_v5(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { (void)obj; (void)flags; (void)properties; if(rc){ exit(1); }else{ mosquitto_subscribe_v5(mosq, NULL, "loop/test", 0, 0, NULL); } } static void on_disconnect_v5(struct mosquitto *mosq, void *obj, int rc, const mosquitto_property *properties) { (void)mosq; (void)obj; (void)properties; run = rc; } static void on_subscribe_v5(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos, const mosquitto_property *props) { (void)obj; (void)mid; (void)qos_count; (void)granted_qos; (void)props; mosquitto_publish_v5(mosq, NULL, "loop/test", strlen("message"), "message", 0, false, NULL); } static void on_message_v5(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *properties) { (void)obj; (void)msg; (void)properties; mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("loop-test", true, NULL); if(mosq == NULL){ return 1; } mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_v5_callback_set(mosq, on_connect_v5); mosquitto_disconnect_v5_callback_set(mosq, on_disconnect_v5); mosquitto_subscribe_v5_callback_set(mosq, on_subscribe_v5); mosquitto_message_v5_callback_set(mosq, on_message_v5); rc = mosquitto_connect_bind_v5(mosq, "localhost", port, 60, NULL, NULL); if(rc != MOSQ_ERR_SUCCESS){ return rc; } mosquitto_loop_forever(mosq, -1, 1); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return 1; } ================================================ FILE: test/lib/c/03-publish-loop-manual.c ================================================ #include #include #include #include #include #include static int run = -1; static void do_loop(struct mosquitto *mosq) { int sock; struct timeval tv; fd_set readfds, writefds; int fdcount; sock = mosquitto_socket(mosq); if(sock < 0){ exit(1); } FD_ZERO(&readfds); FD_ZERO(&writefds); FD_SET(sock, &readfds); while(run == -1){ tv.tv_sec = 0; tv.tv_usec = 100000; FD_SET(sock, &readfds); if(mosquitto_want_write(mosq)){ FD_SET(sock, &writefds); }else{ FD_CLR(sock, &writefds); } fdcount = select(sock+1, &readfds, &writefds, NULL, &tv); if(fdcount < 0){ exit(1); } if(FD_ISSET(sock, &readfds)){ mosquitto_loop_read(mosq, 1); } if(FD_ISSET(sock, &writefds)){ mosquitto_loop_write(mosq, 1); } mosquitto_loop_misc(mosq); } } static void on_connect_v5(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { (void)mosq; (void)obj; (void)flags; (void)properties; if(rc){ exit(1); }else{ mosquitto_subscribe_v5(mosq, NULL, "loop/test", 0, 0, NULL); } } static void on_disconnect_v5(struct mosquitto *mosq, void *obj, int rc, const mosquitto_property *properties) { (void)mosq; (void)obj; (void)properties; run = rc; } static void on_subscribe_v5(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos, const mosquitto_property *props) { (void)obj; (void)mid; (void)qos_count; (void)granted_qos; (void)props; mosquitto_publish_v5(mosq, NULL, "loop/test", strlen("message"), "message", 0, false, NULL); } static void on_message_v5(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *properties) { (void)mosq; (void)obj; (void)msg; (void)properties; mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("loop-test", true, NULL); if(mosq == NULL){ return 1; } mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_v5_callback_set(mosq, on_connect_v5); mosquitto_disconnect_v5_callback_set(mosq, on_disconnect_v5); mosquitto_subscribe_v5_callback_set(mosq, on_subscribe_v5); mosquitto_message_v5_callback_set(mosq, on_message_v5); rc = mosquitto_connect_bind_v5(mosq, "localhost", port, 60, NULL, NULL); if(rc != MOSQ_ERR_SUCCESS){ return rc; } do_loop(mosq); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return 1; } ================================================ FILE: test/lib/c/03-publish-loop-start.c ================================================ #include #include #include #include #include #include static int run = -1; static void on_connect_v5(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { (void)obj; (void)flags; (void)properties; if(rc){ exit(1); }else{ mosquitto_subscribe_v5(mosq, NULL, "loop/test", 0, 0, NULL); } } static void on_disconnect_v5(struct mosquitto *mosq, void *obj, int rc, const mosquitto_property *properties) { (void)mosq; (void)obj; (void)properties; run = rc; } static void on_subscribe_v5(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos, const mosquitto_property *props) { (void)obj; (void)mid; (void)qos_count; (void)granted_qos; (void)props; mosquitto_publish_v5(mosq, NULL, "loop/test", strlen("message"), "message", 0, false, NULL); } static void on_message_v5(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *properties) { (void)obj; (void)msg; (void)properties; mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("loop-test", true, NULL); if(mosq == NULL){ return 1; } mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_v5_callback_set(mosq, on_connect_v5); mosquitto_disconnect_v5_callback_set(mosq, on_disconnect_v5); mosquitto_subscribe_v5_callback_set(mosq, on_subscribe_v5); mosquitto_message_v5_callback_set(mosq, on_message_v5); rc = mosquitto_connect_bind_v5(mosq, "localhost", port, 60, NULL, NULL); if(rc != MOSQ_ERR_SUCCESS){ return rc; } mosquitto_loop_start(mosq); struct timespec tv = { 0, 50e6 }; while(run == -1){ nanosleep(&tv, NULL); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return 1; } ================================================ FILE: test/lib/c/03-publish-loop.c ================================================ #include #include #include #include #include static int run = -1; static void on_connect_v5(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *properties) { (void)obj; (void)flags; (void)properties; if(rc){ exit(1); }else{ mosquitto_subscribe_v5(mosq, NULL, "loop/test", 0, 0, NULL); } } static void on_disconnect_v5(struct mosquitto *mosq, void *obj, int rc, const mosquitto_property *properties) { (void)mosq; (void)obj; (void)properties; run = rc; } static void on_subscribe_v5(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos, const mosquitto_property *props) { (void)obj; (void)mid; (void)qos_count; (void)granted_qos; (void)props; mosquitto_publish_v5(mosq, NULL, "loop/test", strlen("message"), "message", 0, false, NULL); } static void on_message_v5(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *properties) { (void)obj; (void)msg; (void)properties; mosquitto_disconnect(mosq); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("loop-test", true, NULL); if(mosq == NULL){ return 1; } mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosquitto_connect_v5_callback_set(mosq, on_connect_v5); mosquitto_disconnect_v5_callback_set(mosq, on_disconnect_v5); mosquitto_subscribe_v5_callback_set(mosq, on_subscribe_v5); mosquitto_message_v5_callback_set(mosq, on_message_v5); rc = mosquitto_connect_bind_v5(mosq, "localhost", port, 60, NULL, NULL); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, 300, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return 1; } ================================================ FILE: test/lib/c/03-publish-qos0-no-payload.c ================================================ #include #include #include #include #include static int run = -1; static int sent_mid = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_publish(mosq, &sent_mid, "pub/qos0/no-payload/test", 0, NULL, 0, false); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; 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; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-publish-qos0.c ================================================ #include #include #include #include #include static int sent_mid = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_publish(mosq, &sent_mid, "pub/qos0/test", strlen("message"), "message", 0, false); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; if(mid == sent_mid){ mosquitto_disconnect(mosq); }else{ exit(1); } } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } rc = mosquitto_loop_forever(mosq, -1, 1); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return rc; } ================================================ FILE: test/lib/c/03-request-response-1.c ================================================ #include #include #include #include #include #include #define QOS 0 static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "response/topic", QOS); } } static void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { mosquitto_property *props = NULL; (void)obj; (void)mid; if(qos_count != 1 || granted_qos[0] != QOS){ abort(); } if(mosquitto_property_add_string(&props, MQTT_PROP_RESPONSE_TOPIC, "response/topic")){ abort(); } mosquitto_publish_v5(mosq, NULL, "request/topic", 6, "action", 0, 0, props); mosquitto_property_free_all(&props); } static void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { (void)mosq; (void)obj; 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; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-request-response-2.c ================================================ #include #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "request/topic", 0); } } static 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; (void)obj; 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); if(rc != MOSQ_ERR_SUCCESS){ abort(); } free(resp_topic); } } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)mosq; (void)obj; (void)mid; run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int ver = PROTOCOL_VERSION_v5; int port; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/03-request-response-correlation-1.c ================================================ #include #include #include #include #include #include #define QOS 0 static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_subscribe(mosq, NULL, "response/topic", QOS); } } static void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { mosquitto_property *props = NULL; int rc; (void)obj; (void)mid; if(qos_count != 1 || granted_qos[0] != QOS){ abort(); } if(mosquitto_property_add_string(&props, MQTT_PROP_RESPONSE_TOPIC, "response/topic") || mosquitto_property_add_binary(&props, MQTT_PROP_CORRELATION_DATA, "corridor", 8)){ abort(); } rc = mosquitto_publish_v5(mosq, NULL, "request/topic", 6, "action", QOS, 0, props); if(rc != MOSQ_ERR_SUCCESS){ abort(); } mosquitto_property_free_all(&props); } static void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { (void)mosq; (void)obj; 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; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/04-retain-qos0.c ================================================ #include #include #include #include #include #define UNUSED(A) (void)(A) static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { UNUSED(obj); if(rc){ exit(1); }else{ mosquitto_publish(mosq, NULL, "retain/qos0/test", strlen("retained message"), "retained message", 0, true); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { UNUSED(mosq); UNUSED(obj); UNUSED(mid); run = 0; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } 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); mosquitto_publish_callback_set(mosq, on_publish); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/08-ssl-bad-cacert.c ================================================ #include #include #include #include #include int main(int argc, char *argv[]) { int rc = 1; struct mosquitto *mosq; (void)argc; (void)argv; 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; } ================================================ FILE: test/lib/c/08-ssl-connect-cert-auth-custom-ssl-ctx-default.c ================================================ #include #include #include #include #include #include #include #include #include "path_helper.h" static int run = -1; void handle_sigint(int signal) { (void)signal; run = 0; } void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { struct mosquitto *mosq; SSL_CTX *ssl_ctx; assert(argc == 2); int port = atoi(argv[1]); mosquitto_lib_init(); OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \ | OPENSSL_INIT_ADD_ALL_DIGESTS \ | OPENSSL_INIT_LOAD_CONFIG, NULL); ssl_ctx = SSL_CTX_new(TLS_client_method()); mosq = mosquitto_new("08-ssl-connect-crt-auth", true, NULL); if(mosq == NULL){ return 1; } mosquitto_int_option(mosq, MOSQ_OPT_SSL_CTX_WITH_DEFAULTS, 1); mosquitto_void_option(mosq, MOSQ_OPT_SSL_CTX, ssl_ctx); char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-root-ca.crt"); char capath[4096]; cat_sourcedir_with_relpath(capath, "/../../ssl/certs"); char certfile[4096]; cat_sourcedir_with_relpath(certfile, "/../../ssl/client.crt"); char keyfile[4096]; cat_sourcedir_with_relpath(keyfile, "/../../ssl/client.key"); mosquitto_tls_set(mosq, cafile, capath, certfile, keyfile, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); int rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc){ return rc; } signal(SIGINT, handle_sigint); while(run == -1){ mosquitto_loop(mosq, -1, 1); } SSL_CTX_free(ssl_ctx); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/08-ssl-connect-cert-auth-custom-ssl-ctx.c ================================================ #include #include #include #include #include #include #include #include #include "path_helper.h" static int run = -1; void handle_sigint(int signal) { (void)signal; run = 0; } void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { struct mosquitto *mosq; SSL_CTX *ssl_ctx; assert(argc == 2); int port = atoi(argv[1]); mosquitto_lib_init(); OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \ | OPENSSL_INIT_ADD_ALL_DIGESTS \ | OPENSSL_INIT_LOAD_CONFIG, NULL); ssl_ctx = SSL_CTX_new(TLS_client_method()); char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-root-ca.crt"); char capath[4096]; cat_sourcedir_with_relpath(capath, "/../../ssl/certs"); char certfile[4096]; cat_sourcedir_with_relpath(certfile, "/../../ssl/client.crt"); char keyfile[4096]; cat_sourcedir_with_relpath(keyfile, "/../../ssl/client.key"); SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); SSL_CTX_use_certificate_chain_file(ssl_ctx, certfile); SSL_CTX_use_PrivateKey_file(ssl_ctx, keyfile, SSL_FILETYPE_PEM); SSL_CTX_load_verify_locations(ssl_ctx, cafile, capath); 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); mosquitto_int_option(mosq, MOSQ_OPT_SSL_CTX_WITH_DEFAULTS, 0); mosquitto_void_option(mosq, MOSQ_OPT_SSL_CTX, ssl_ctx); int rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc){ return rc; } signal(SIGINT, handle_sigint); while(run == -1){ mosquitto_loop(mosq, -1, 1); } SSL_CTX_free(ssl_ctx); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/08-ssl-connect-cert-auth-enc.c ================================================ #include #include #include #include #include #include #include "path_helper.h" static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } static int password_callback(char *buf, int size, int rwflag, void *userdata) { (void)rwflag; (void)userdata; strncpy(buf, "password", (size_t)size); buf[size-1] = '\0'; return (int)strlen(buf); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("08-ssl-connect-crt-auth-enc", true, NULL); if(mosq == NULL){ return 1; } char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-root-ca.crt"); char capath[4096]; cat_sourcedir_with_relpath(capath, "/../../ssl/certs"); char certfile[4096]; cat_sourcedir_with_relpath(certfile, "/../../ssl/client-encrypted.crt"); char keyfile[4096]; cat_sourcedir_with_relpath(keyfile, "/../../ssl/client-encrypted.key"); mosquitto_tls_set(mosq, cafile, capath, certfile, keyfile, password_callback); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/08-ssl-connect-cert-auth.c ================================================ #include "path_helper.h" #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("08-ssl-connect-crt-auth", true, NULL); if(mosq == NULL){ return 1; } char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-root-ca.crt"); char capath[4096]; cat_sourcedir_with_relpath(capath, "/../../ssl/certs"); char certfile[4096]; cat_sourcedir_with_relpath(certfile, "/../../ssl/client.crt"); char keyfile[4096]; cat_sourcedir_with_relpath(keyfile, "/../../ssl/client.key"); mosquitto_tls_set(mosq, cafile, capath, certfile, keyfile, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/08-ssl-connect-no-auth.c ================================================ #include "path_helper.h" #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("08-ssl-connect-no-auth", true, NULL); if(mosq == NULL){ return 1; } char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-root-ca.crt"); mosquitto_tls_set(mosq, cafile, 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/08-ssl-connect-san.c ================================================ #include "path_helper.h" #include #include #include #include #include static int run = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; if(rc){ exit(1); }else{ mosquitto_disconnect(mosq); } } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; run = rc; } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; char *host; if(argc < 2){ return 1; } port = atoi(argv[1]); host = argv[2]; mosquitto_lib_init(); mosq = mosquitto_new("08-ssl-connect-san", true, NULL); if(mosq == NULL){ return 1; } char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-root-ca.crt"); mosquitto_tls_set(mosq, cafile, NULL, NULL, NULL, NULL); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); rc = mosquitto_connect(mosq, host, port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosquitto_loop(mosq, -1, 1); } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/08-ssl-fake-cacert.c ================================================ #include #include #include #include #include #include "path_helper.h" static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; (void)rc; exit(1); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosquitto_lib_init(); mosq = mosquitto_new("08-ssl-connect-crt-auth", true, NULL); if(mosq == NULL){ return 1; } char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-fake-root-ca.crt"); char certfile[4096]; cat_sourcedir_with_relpath(certfile, "/../../ssl/client.crt"); char keyfile[4096]; cat_sourcedir_with_relpath(keyfile, "/../../ssl/client.key"); mosquitto_tls_set(mosq, cafile, NULL, certfile, keyfile, NULL); mosquitto_connect_callback_set(mosq, on_connect); rc = mosquitto_connect(mosq, "localhost", port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } 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; } } ================================================ FILE: test/lib/c/09-util-topic-tokenise.c ================================================ #include #include #include static 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 static int run = -1; static int sent_mid = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)obj; 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("123456789012345678"), "123456789012345678", 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("12345678901234567"), "12345678901234567", 0, false); if(rc != MOSQ_ERR_SUCCESS){ printf("Fail on publish 2\n"); exit(1); } } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; 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; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); if(rc != MOSQ_ERR_SUCCESS){ return rc; } } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/11-prop-recv.c ================================================ #include #include #include #include #include #include static int run = -1; static int qos = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { (void)mosq; (void)obj; if(rc){ exit(1); } } static void on_message_v5(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *properties) { int rc; char *str; (void)obj; 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 == qos){ mosquitto_publish(mosq, NULL, "ok", 2, "ok", 0, 0); return; } } } } } } /* No matching message, so quit with an error */ exit(1); } int main(int argc, char *argv[]) { int rc; struct mosquitto *mosq; int port; if(argc < 2){ return 1; } port = atoi(argv[1]); qos = atoi(argv[2]); 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); if(rc != MOSQ_ERR_SUCCESS){ return rc; } } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/11-prop-send-content-type.c ================================================ #include #include #include #include #include #include static int run = -1; static int sent_mid = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { int rc2; mosquitto_property *proplist = NULL; (void)obj; if(rc){ exit(1); }else{ rc2 = mosquitto_property_add_string(&proplist, MQTT_PROP_CONTENT_TYPE, "application/json"); if(rc2 != MOSQ_ERR_SUCCESS){ abort(); } mosquitto_publish_v5(mosq, &sent_mid, "prop/qos0", strlen("message"), "message", 0, false, proplist); mosquitto_property_free_all(&proplist); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; 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; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); if(rc != MOSQ_ERR_SUCCESS){ return rc; } } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/11-prop-send-payload-format.c ================================================ #include #include #include #include #include #include static int run = -1; static int sent_mid = -1; static void on_connect(struct mosquitto *mosq, void *obj, int rc) { int rc2; mosquitto_property *proplist = NULL; (void)obj; if(rc){ exit(1); }else{ rc2 = mosquitto_property_add_byte(&proplist, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); if(rc2 != MOSQ_ERR_SUCCESS){ abort(); } mosquitto_publish_v5(mosq, &sent_mid, "prop/qos0", strlen("message"), "message", 0, false, proplist); mosquitto_property_free_all(&proplist); } } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { (void)obj; 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; if(argc < 2){ return 1; } 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); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ rc = mosquitto_loop(mosq, -1, 1); if(rc != MOSQ_ERR_SUCCESS){ return rc; } } mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return run; } ================================================ FILE: test/lib/c/CMakeLists.txt ================================================ set(BINARIES 01-con-discon-success 01-con-discon-success-v5 01-con-discon-will 01-con-discon-will-clear 01-con-discon-will-v5 01-extended-auth-continue 01-extended-auth-failure 01-keepalive-pingreq 01-no-clean-session 01-pre-connect-callback 01-server-keepalive-pingreq 01-unpwd-set 01-will-set 01-will-unpwd-set 02-subscribe-helper-callback-qos2 02-subscribe-helper-simple-qos2 02-subscribe-qos0 02-subscribe-qos1-async1 02-subscribe-qos1-async2 02-subscribe-qos1 02-subscribe-qos2 02-unsubscribe2-v5 02-unsubscribe 02-unsubscribe-multiple-v5 02-unsubscribe-v5 03-publish-b2c-qos1 03-publish-b2c-qos1-unexpected-puback 03-publish-b2c-qos2 03-publish-b2c-qos2-len 03-publish-b2c-qos2-unexpected-pubcomp 03-publish-b2c-qos2-unexpected-pubrel 03-publish-c2b-qos1-disconnect 03-publish-c2b-qos1-len 03-publish-c2b-qos1-receive-maximum 03-publish-c2b-qos2 03-publish-c2b-qos2-disconnect 03-publish-c2b-qos2-len 03-publish-c2b-qos2-maximum-qos-0 03-publish-c2b-qos2-maximum-qos-1 03-publish-c2b-qos2-pubrec-error 03-publish-c2b-qos2-receive-maximum 03-publish-loop 03-publish-loop-forever 03-publish-loop-manual 03-publish-loop-start 03-publish-qos0 03-publish-qos0-no-payload 03-request-response-1 03-request-response-2 03-request-response-correlation-1 04-retain-qos0 08-ssl-bad-cacert 08-ssl-connect-cert-auth 08-ssl-connect-cert-auth-custom-ssl-ctx 08-ssl-connect-cert-auth-custom-ssl-ctx-default 08-ssl-connect-cert-auth-enc 08-ssl-connect-no-auth 08-ssl-connect-san 08-ssl-fake-cacert 09-util-topic-tokenise 11-prop-oversize-packet 11-prop-recv 11-prop-send-content-type 11-prop-send-payload-format fuzzish ) foreach(BINARY ${BINARIES}) add_executable(${BINARY} ${BINARY}.c) target_compile_definitions(${BINARY} PRIVATE TEST_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}") target_include_directories(${BINARY} PRIVATE ${CMAKE_SOURCE_DIR}/test) set_property(TARGET ${BINARY} PROPERTY SUFFIX .test) target_link_libraries(${BINARY} PRIVATE common-options libmosquitto OpenSSL::SSL) endforeach() ================================================ FILE: test/lib/c/Makefile ================================================ R=../../.. include ${R}/config.mk .PHONY: all clean reallyclean LOCAL_CPPFLAGS+=-I${R}/test LOCAL_CFLAGS+=-Werror -ggdb LOCAL_LIBADD+=${LIBMOSQ} SRC = \ 01-con-discon-success.c \ 01-con-discon-success-v5.c \ 01-con-discon-will.c \ 01-con-discon-will-v5.c \ 01-con-discon-will-clear.c \ 01-extended-auth-continue.c \ 01-extended-auth-failure.c \ 01-keepalive-pingreq.c \ 01-no-clean-session.c \ 01-pre-connect-callback.c \ 01-server-keepalive-pingreq.c \ 01-unpwd-set.c \ 01-will-set.c \ 01-will-unpwd-set.c \ 02-subscribe-helper-callback-qos2.c \ 02-subscribe-helper-simple-qos2.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-unsubscribe2-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.c \ 03-publish-c2b-qos2.c \ 03-publish-loop.c \ 03-publish-loop-forever.c \ 03-publish-loop-manual.c \ 03-publish-loop-start.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-connect-san.c \ 08-ssl-fake-cacert.c \ 09-util-topic-tokenise.c \ 11-prop-oversize-packet.c \ 11-prop-recv.c \ 11-prop-send-payload-format.c \ 11-prop-send-content-type.c \ fuzzish.c ifeq ($(WITH_TLS),yes) SRC += \ 08-ssl-connect-cert-auth-custom-ssl-ctx.c \ 08-ssl-connect-cert-auth-custom-ssl-ctx-default.c LOCAL_LIBADD+=-lssl -lcrypto endif TESTS = ${SRC:.c=.test} all : ${TESTS} ${TESTS} : %.test: %.c ${R}/test/path_helper.h $(CC) $< -o $@ -D TEST_SOURCE_DIR='"$(realpath .)"' $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) $(LOCAL_LIBADD) $(LOCAL_LDFLAGS) reallyclean : clean -rm -f *.orig clean : rm -f *.test ================================================ FILE: test/lib/c/fuzzish.c ================================================ #include #include #include #include #include #include #include #define UNUSED(A) (void)(A) static int run = -1; static int proto_ver; #ifndef UNUSED # define UNUSED(A) (void)(A) #endif static void signal_handler(int s) { UNUSED(s); run = 0; } static void prop_test(const mosquitto_property *props) { mosquitto_property *dest = NULL; int rc; rc = mosquitto_property_copy_all(&dest, props); if(rc){ printf("bad prop_test: %s\n", mosquitto_strerror(rc)); exit(1); } mosquitto_property_free_all(&dest); } static void msg_test(const struct mosquitto_message *msg) { struct mosquitto_message dest; int rc; memset(&dest, 0, sizeof(dest)); rc = mosquitto_message_copy(&dest, msg); if(rc){ printf("bad msg_test: %s\n", mosquitto_strerror(rc)); exit(1); } mosquitto_message_free_contents(&dest); } static void on_pre_connect(struct mosquitto *mosq, void *obj) { UNUSED(mosq); UNUSED(obj); } static void on_connect(struct mosquitto *mosq, void *obj, int rc) { char *command = obj; int mid; mosquitto_property *props = NULL; UNUSED(mosq); UNUSED(obj); if(command){ if(proto_ver == 5){ if(!strncmp(command, "subscribe", strlen("subscribe"))){ rc = mosquitto_property_add_varint(&props, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, 268435455); if(rc){ printf("bad on_connect prop add: %s\n", mosquitto_strerror(rc)); goto error; } rc = mosquitto_property_add_string_pair(&props, MQTT_PROP_USER_PROPERTY, "key", "value"); if(rc){ printf("bad on_connect prop add: %s\n", mosquitto_strerror(rc)); goto error; } }else if(!strncmp(command, "unsubscribe", strlen("unsubscribe"))){ rc = mosquitto_property_add_string_pair(&props, MQTT_PROP_USER_PROPERTY, "key", "value"); if(rc){ printf("bad on_connect prop add: %s\n", mosquitto_strerror(rc)); goto error; } }else if(!strncmp(command, "publish", strlen("publish"))){ rc = mosquitto_property_add_byte(&props, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); if(rc){ printf("bad on_connect prop add: %s\n", mosquitto_strerror(rc)); goto error; } rc = mosquitto_property_add_int32(&props, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, UINT32_MAX); if(rc){ printf("bad on_connect prop add: %s\n", mosquitto_strerror(rc)); goto error; } rc = mosquitto_property_add_int16(&props, MQTT_PROP_TOPIC_ALIAS, UINT16_MAX); if(rc){ printf("bad on_connect prop add: %s\n", mosquitto_strerror(rc)); goto error; } rc = mosquitto_property_add_string(&props, MQTT_PROP_RESPONSE_TOPIC, "response/topic"); if(rc){ printf("bad on_connect prop add: %s\n", mosquitto_strerror(rc)); goto error; } rc = mosquitto_property_add_binary(&props, MQTT_PROP_CORRELATION_DATA, "7deac5c5-8802-44ff-86ce-11479f337419", strlen("7deac5c5-8802-44ff-86ce-11479f337419")); if(rc){ printf("bad on_connect prop add: %s\n", mosquitto_strerror(rc)); goto error; } rc = mosquitto_property_add_string(&props, MQTT_PROP_CONTENT_TYPE, "text/plain"); if(rc){ printf("bad on_connect prop add: %s\n", mosquitto_strerror(rc)); goto error; } rc = mosquitto_property_add_string_pair(&props, MQTT_PROP_USER_PROPERTY, "key", "value"); if(rc){ printf("bad on_connect prop add: %s\n", mosquitto_strerror(rc)); goto error; } } } if(!strcmp(command, "subscribe-2")){ rc = mosquitto_subscribe_v5(mosq, &mid, "test/subscribe", 2, 0, props); if(rc || mid != 1){ printf("bad on_connect subscribe-2 %d || %d\n", rc, mid); goto error; } }else if(!strcmp(command, "subscribe-1")){ rc = mosquitto_subscribe_v5(mosq, &mid, "test/subscribe", 1, 0, props); if(rc || mid != 1){ printf("bad on_connect subscribe-1 %d || %d\n", rc, mid); goto error; } }else if(!strcmp(command, "subscribe-0")){ rc = mosquitto_subscribe_v5(mosq, &mid, "test/subscribe", 0, 0, props); if(rc || mid != 1){ printf("bad on_connect subscribe-0 %d || %d\n", rc, mid); goto error; } }else if(!strcmp(command, "subscribe-multiple")){ char *subs[] = {"test/subscribe1", "test/subscribe2"}; rc = mosquitto_subscribe_multiple(mosq, &mid, 2, subs, 2, 0, props); if(rc || mid != 1){ printf("bad on_connect subscribe-multiple %d || %d\n", rc, mid); goto error; } }else if(!strcmp(command, "unsubscribe")){ rc = mosquitto_unsubscribe_v5(mosq, &mid, "test/subscribe", props); if(rc || mid != 1){ printf("bad on_connect unsubscribe %d || %d\n", rc, mid); goto error; } }else if(!strcmp(command, "unsubscribe-multiple")){ char *subs[] = {"test/subscribe1", "test/subscribe2"}; rc = mosquitto_unsubscribe_multiple(mosq, &mid, 2, subs, props); if(rc || mid != 1){ printf("bad on_connect unsubscribe-multiple %d || %d\n", rc, mid); goto error; } }else if(!strcmp(command, "publish-2")){ rc = mosquitto_publish_v5(mosq, &mid, "test/publish", strlen("message"), "message", 2, 0, props); if(rc || mid != 1){ printf("bad on_connect publish-2 %d || %d\n", rc, mid); goto error; } }else if(!strcmp(command, "publish-1")){ rc = mosquitto_publish_v5(mosq, &mid, "test/publish", strlen("message"), "message", 1, 0, props); if(rc || mid != 1){ printf("bad on_connect publish-1 %d || %d\n", rc, mid); goto error; } }else if(!strcmp(command, "publish-0")){ rc = mosquitto_publish_v5(mosq, &mid, "test/publish", strlen("message"), "message", 0, 0, props); if(rc || mid != 1){ printf("bad on_connect publish-0 %d || %d\n", rc, mid); goto error; } }else{ printf("bad on_connect command '%s'\n", command); goto error; } } mosquitto_property_free_all(&props); return; error: mosquitto_property_free_all(&props); exit(1); } static void on_connect_with_flags(struct mosquitto *mosq, void *obj, int rc, int flags) { UNUSED(mosq); UNUSED(obj); UNUSED(rc); UNUSED(flags); } static void on_connect_v5(struct mosquitto *mosq, void *obj, int rc, int flags, const mosquitto_property *props) { UNUSED(mosq); UNUSED(obj); UNUSED(rc); UNUSED(flags); prop_test(props); } static void on_disconnect(struct mosquitto *mosq, void *obj, int rc) { UNUSED(mosq); UNUSED(obj); run = rc; } static void on_disconnect_v5(struct mosquitto *mosq, void *obj, int rc, const mosquitto_property *props) { UNUSED(mosq); UNUSED(obj); prop_test(props); run = rc; } static void on_publish(struct mosquitto *mosq, void *obj, int mid) { UNUSED(mosq); UNUSED(obj); UNUSED(mid); } static void on_publish_v5(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *props) { UNUSED(mosq); UNUSED(obj); UNUSED(mid); UNUSED(reason_code); prop_test(props); } static void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg) { UNUSED(mosq); UNUSED(obj); msg_test(msg); } static void on_message_v5(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *props) { UNUSED(mosq); UNUSED(obj); msg_test(msg); prop_test(props); } static void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { UNUSED(mosq); UNUSED(mid); int tot = 0; UNUSED(mosq); UNUSED(obj); UNUSED(mid); for(int i=0; i #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect_v5(int rc, int flags, const mosquitto_property *props); void on_disconnect_v5(int rc, const mosquitto_property *props); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect_v5(int rc, int flags, const mosquitto_property *props) { assert(flags == 0); assert(props); assert(mosqpp::property_check_all(CMD_CONNACK, props) == MOSQ_ERR_SUCCESS); if(rc){ exit(1); }else{ disconnect(); } } void mosquittopp_test::on_disconnect_v5(int rc, const mosquitto_property *props) { assert(props == NULL); run = rc; } int main(int argc, char *argv[]) { mosquittopp_test *mosq; mosquitto_property *props = NULL; int rc; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-con-discon-success-v5"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, 5); mosquitto_property_add_int32(&props, MQTT_PROP_MAXIMUM_PACKET_SIZE, 1000); rc = mosq->connect_v5("localhost", port, 60, NULL, props); mosquitto_property_free_all(&props); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-con-discon-success.cpp ================================================ #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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; } ================================================ FILE: test/lib/cpp/01-con-discon-will-clear.cpp ================================================ #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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-con-discon-will"); /* Set twice, so it has to clear the old settings */ mosq->will_set("will/topic", strlen("will-payload"), "will-payload", 1, true); mosq->will_clear(); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-con-discon-will-v5.cpp ================================================ #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[]) { mosquittopp_test *mosq; mosquitto_property *proplist = NULL; int rc; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-con-discon-will"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); rc = mosquitto_property_add_byte(&proplist, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); if(rc != MOSQ_ERR_SUCCESS){ abort(); } /* Set twice, so it has to clear the old settings */ mosq->will_set_v5("will/topic", strlen("will-payload"), "will-payload", 1, true, proplist); proplist = NULL; rc = mosquitto_property_add_byte(&proplist, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); if(rc != MOSQ_ERR_SUCCESS){ abort(); } mosq->will_set_v5("will/topic", strlen("will-payload"), "will-payload", 1, true, proplist); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-con-discon-will.cpp ================================================ #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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-con-discon-will"); /* Set twice, so it has to clear the old settings */ mosq->will_set("will/topic", strlen("will-payload"), "will-payload", 1, true); mosq->will_set("will/topic", strlen("will-payload"), "will-payload", 1, true); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-extended-auth-continue.cpp ================================================ #include #include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect_v5(int rc, int flags, const mosquitto_property *props); void on_disconnect_v5(int rc, const mosquitto_property *props); int on_ext_auth(const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *props); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect_v5(int rc, int flags, const mosquitto_property *props) { assert(flags == 0); assert(props); assert(mosqpp::property_check_all(CMD_CONNACK, props) == MOSQ_ERR_SUCCESS); if(rc){ exit(1); }else{ disconnect(); } } void mosquittopp_test::on_disconnect_v5(int rc, const mosquitto_property *props) { assert(props == NULL); run = rc; } int mosquittopp_test::on_ext_auth(const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *props) { assert(props != NULL); if(strcmp(auth_method, "test-method")){ run = 1; return MOSQ_ERR_AUTH; } if(auth_data_len == 0 || (!auth_data || strcmp((const char *)auth_data, "test-request"))){ run = 1; return MOSQ_ERR_AUTH; } return ext_auth_continue(auth_method, strlen("test-reply"), "test-reply", NULL); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; mosquitto_property *props = NULL; int rc; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-extended-auth"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, 5); mosquitto_property_add_int32(&props, MQTT_PROP_MAXIMUM_PACKET_SIZE, 1000); rc = mosq->connect_v5("localhost", port, 60, NULL, props); mosquitto_property_free_all(&props); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-extended-auth-failure.cpp ================================================ #include #include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect_v5(int rc, int flags, const mosquitto_property *props); void on_disconnect_v5(int rc, const mosquitto_property *props); int on_ext_auth(const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *props); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect_v5(int rc, int flags, const mosquitto_property *props) { assert(flags == 0); assert(props); assert(mosqpp::property_check_all(CMD_CONNACK, props) == MOSQ_ERR_SUCCESS); if(rc){ exit(1); }else{ disconnect(); } } void mosquittopp_test::on_disconnect_v5(int rc, const mosquitto_property *props) { assert(props == NULL); run = rc; } int mosquittopp_test::on_ext_auth(const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *props) { (void)auth_method; (void)auth_data_len; (void)auth_data; (void)props; return MOSQ_ERR_AUTH; } int main(int argc, char *argv[]) { mosquittopp_test *mosq; mosquitto_property *props = NULL; int rc; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-extended-auth"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, 5); mosquitto_property_add_int32(&props, MQTT_PROP_MAXIMUM_PACKET_SIZE, 1000); rc = mosq->connect_v5("localhost", port, 60, NULL, props); mosquitto_property_free_all(&props); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-keepalive-pingreq.cpp ================================================ #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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); int rc; mosqpp::lib_init(); mosq = new mosquittopp_test("01-keepalive-pingreq"); mosq->connect("localhost", port, 5); while(run == -1){ rc = mosq->loop(); if(rc){ break; } } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-no-clean-session.cpp ================================================ #include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id, bool clean_session); void on_connect(int rc); void on_disconnect(int rc); }; mosquittopp_test::mosquittopp_test(const char *id, bool clean_session) : mosqpp::mosquittopp(id, clean_session) { } 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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-pre-connect-callback.cpp ================================================ #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_pre_connect(); void on_connect(int rc); void on_disconnect(int rc); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_pre_connect() { username_pw_set("uname", ";'[08gn=#"); } 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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("01-pre-connect"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-server-keepalive-pingreq.cpp ================================================ #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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); int rc; mosqpp::lib_init(); mosq = new mosquittopp_test("01-server-keepalive-pingreq"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ rc = mosq->loop(); if(rc){ break; } } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-unpwd-set.cpp ================================================ #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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-will-set.cpp ================================================ #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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/01-will-unpwd-set.cpp ================================================ #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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/02-subscribe-helper-callback-qos2.cpp ================================================ #include #include #include #include #define QOS 2 static int mydata = 1; int cb(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *msg) { assert(mosq); assert(userdata == &mydata); assert(msg); assert(!strcmp(msg->topic, "qos2/test")); return 1; } int main(int argc, char *argv[]) { int port; if(argc < 2){ return 1; } port = atoi(argv[1]); mosqpp::lib_init(); mosqpp::subscribe_callback( cb, &mydata, "qos2/test", QOS, "localhost", port, "subscribe-qos2-test", 60, true, NULL, NULL, NULL, NULL); mosqpp::lib_cleanup(); return 0; } ================================================ FILE: test/lib/cpp/02-subscribe-helper-simple-qos2.cpp ================================================ #include #include #define QOS 2 int main(int argc, char *argv[]) { int port; struct mosquitto_message *messages; if(argc < 2){ return 1; } port = atoi(argv[1]); mosqpp::lib_init(); mosqpp::subscribe_simple(&messages, 1, true, "qos2/test", QOS, "localhost", port, "subscribe-qos2-test", 60, true, NULL, NULL, NULL, NULL); /* FIXME - this should be in the wrapper */ mosquitto_message_free(&messages); mosqpp::lib_cleanup(); return 0; } ================================================ FILE: test/lib/cpp/02-subscribe-qos0.cpp ================================================ #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_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) { assert(mid == 1); assert(qos_count == 1); assert(granted_qos[0] == 0); disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/02-subscribe-qos1-async1.cpp ================================================ #include #include #include #include /* mosquitto_connect_async() test, with mosquitto_loop_start() called before mosquitto_connect_async(). */ #define QOS 1 static int run = -1; static bool should_run = true; 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", QOS); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_subscribe(int mid, int qos_count, const int *granted_qos) { assert(mid == 1); assert(qos_count == 1); assert(granted_qos[0] == QOS); should_run = false; } int main(int argc, char *argv[]) { mosquittopp_test *mosq; int rc; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("subscribe-qos1-test"); rc = mosq->loop_start(); if(rc){ printf("loop_start failed: %s\n", mosquitto_strerror(rc)); return rc; } rc = mosq->connect_async("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, (long)50e6 }; while(should_run){ nanosleep(&tv, NULL); } mosq->disconnect(); mosq->loop_stop(); delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/02-subscribe-qos1-async2.cpp ================================================ #include #include #include #include /* mosquitto_connect_async() test, with mosquitto_loop_start() called after mosquitto_connect_async(). */ #define QOS 1 static int run = -1; static bool should_run = true; 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", QOS); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_subscribe(int mid, int qos_count, const int *granted_qos) { assert(mid == 1); assert(qos_count == 1); assert(granted_qos[0] == QOS); should_run = false; } int main(int argc, char *argv[]) { mosquittopp_test *mosq; int rc; struct timespec tv = { 0, (long)100e6 }; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("subscribe-qos1-test"); /* Help with possible race condition on CI */ nanosleep(&tv, NULL); rc = mosq->connect_async("localhost", port, 60, NULL); if(rc){ printf("connect_async failed: %s\n", mosquitto_strerror(rc)); return rc; } rc = mosq->loop_start(); if(rc){ printf("loop_start failed: %s\n", mosquitto_strerror(rc)); return rc; } /* 50 millis to be system polite */ tv.tv_nsec = (long)50e6; while(should_run){ nanosleep(&tv, NULL); } mosq->disconnect(); mosq->loop_stop(); delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/02-subscribe-qos1.cpp ================================================ #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_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) { assert(mid == 1); assert(qos_count == 1); assert(granted_qos[0] == 1); disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; } ================================================ FILE: test/lib/cpp/02-subscribe-qos2.cpp ================================================ #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_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_v5(NULL, "qos2/test", 2, 2, NULL); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_subscribe(int mid, int qos_count, const int *granted_qos) { assert(mid == 1); assert(qos_count == 1); assert(granted_qos[0] == 2); disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/02-unsubscribe-v5.cpp ================================================ #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_unsubscribe_v5(int mid, const mosquitto_property *props); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { int rc2; mosquitto_property *proplist = NULL; if(rc){ exit(1); }else{ rc2 = mosquitto_property_add_string_pair(&proplist, MQTT_PROP_USER_PROPERTY, "key", "value"); if(rc2 != MOSQ_ERR_SUCCESS){ abort(); } unsubscribe_v5(NULL, "unsubscribe/test", proplist); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_unsubscribe_v5(int mid, const mosquitto_property *props) { assert(mid == 1); assert(props == NULL); disconnect_v5(0, NULL); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("unsubscribe-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/02-unsubscribe.cpp ================================================ #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_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) { assert(mid == 1); disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; } ================================================ FILE: test/lib/cpp/03-publish-b2c-qos1-unexpected-puback.cpp ================================================ #include #include #include #include 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[]) { mosquittopp_test *mosq; int rc = 1; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos1-test"); mosq->connect("localhost", port, 5); while(1){ if(mosq->loop(300, 1)){ rc = 0; break; } } delete mosq; mosqpp::lib_cleanup(); return rc; } ================================================ FILE: test/lib/cpp/03-publish-b2c-qos1.cpp ================================================ #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[]) { mosquittopp_test *mosq; int rc = 1; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos1-test"); mosq->connect("localhost", port, 60); while(1){ if(mosq->loop()){ rc = 0; break; } } delete mosq; mosqpp::lib_cleanup(); return rc; } ================================================ FILE: test/lib/cpp/03-publish-b2c-qos2-len.cpp ================================================ #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); 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_disconnect(int rc) { run = rc; } void mosquittopp_test::on_message(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((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); } disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos2-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(100, 1); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-b2c-qos2-unexpected-pubcomp.cpp ================================================ #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); }; 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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos2-test"); mosq->connect("localhost", port, 5); while(run == -1){ int rc = mosq->loop(300, 1); if(rc){ exit(0); } } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-b2c-qos2-unexpected-pubrel.cpp ================================================ #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(!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((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); } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos2-test"); mosq->connect("localhost", port, 60); while(run == -1){ int rc = mosq->loop(300, 1); if(rc){ exit(1); } } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-b2c-qos2.cpp ================================================ #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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; } ================================================ FILE: test/lib/cpp/03-publish-c2b-qos1-disconnect.cpp ================================================ #include #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) { assert(mid == 1); disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos1-test"); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-c2b-qos1-len.cpp ================================================ #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); 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/qos1/test", strlen("message"), "message", 1, false); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_publish(int mid) { assert(mid == 1); disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos1-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(300, 1); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-c2b-qos1-receive-maximum.cpp ================================================ #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_publish_v5(int mid, int reason_code, const mosquitto_property *properties); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); } for(int i=0; i<6; i++){ publish_v5(NULL, "topic", 5, "12345", 1, false, NULL); } } void mosquittopp_test::on_publish_v5(int mid, int reason_code, const mosquitto_property *properties) { assert(reason_code == 0); assert(properties == NULL); if(mid == 6){ disconnect(); run = 0; } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos1-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect_v5("localhost", port, 60, NULL, NULL); while(run == -1){ mosq->loop(300, 1); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-c2b-qos2-disconnect.cpp ================================================ #include #include #include #include static int run = -1; static int first_connection = 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_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(&sent_mid, "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) { assert(mid == sent_mid); disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; } ================================================ FILE: test/lib/cpp/03-publish-c2b-qos2-len.cpp ================================================ #include #include #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_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(&sent_mid, "pub/qos2/test", strlen("message"), "message", 2, false); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_publish(int mid) { assert(mid == sent_mid); disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos2-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-c2b-qos2-maximum-qos-0.cpp ================================================ #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{ rc = publish(NULL, "maximum/qos/qos2", strlen("message"), "message", 2, false); if(rc != MOSQ_ERR_QOS_NOT_SUPPORTED){ run = 1; } rc = publish(NULL, "maximum/qos/qos1", strlen("message"), "message", 1, false); if(rc != MOSQ_ERR_QOS_NOT_SUPPORTED){ run = 1; } rc = publish(NULL, "maximum/qos/qos0", strlen("message"), "message", 0, false); if(rc != MOSQ_ERR_SUCCESS){ run = 1; } } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_publish(int mid) { if(mid == 1){ disconnect(); } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos2-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(50, 1); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-c2b-qos2-maximum-qos-1.cpp ================================================ #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{ rc = publish(NULL, "maximum/qos/qos2", strlen("message"), "message", 2, false); if(rc != MOSQ_ERR_QOS_NOT_SUPPORTED){ run = 1; } rc = publish(NULL, "maximum/qos/qos1", strlen("message"), "message", 1, false); if(rc != MOSQ_ERR_SUCCESS){ run = 1; } rc = publish(NULL, "maximum/qos/qos0", strlen("message"), "message", 0, false); if(rc != MOSQ_ERR_SUCCESS){ run = 1; } } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_publish(int mid) { if(mid == 2){ disconnect(); } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos2-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(50, 1); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-c2b-qos2-pubrec-error.cpp ================================================ #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_v5(NULL, "topic", strlen("rejected"), "rejected", 2, false, NULL); publish_v5(NULL, "topic", strlen("accepted"), "accepted", 2, false, NULL); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_publish(int mid) { if(mid == 2){ run = 0; } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos2-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-c2b-qos2-receive-maximum.cpp ================================================ #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); } for(int i=0; i<5; i++){ publish_v5(NULL, "topic", 5, "12345", 2, false, NULL); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_publish(int mid) { if(mid == 5){ disconnect(); run = 0; } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos2-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-c2b-qos2.cpp ================================================ #include #include #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_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(&sent_mid, "pub/qos2/test", strlen("message"), "message", 2, false); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } void mosquittopp_test::on_publish(int mid) { assert(mid == sent_mid); disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; } ================================================ FILE: test/lib/cpp/03-publish-loop-forever.cpp ================================================ #include #include #include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect_v5(int rc, int flags, const mosquitto_property *properties); void on_disconnect_v5(int rc, const mosquitto_property *properties); void on_subscribe_v5(int mid, int qos_count, const int *granted_qos, const mosquitto_property *props); void on_message_v5(const struct mosquitto_message *msg, const mosquitto_property *properties); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect_v5(int rc, int flags, const mosquitto_property *properties) { (void)flags; (void)properties; if(rc){ exit(1); }else{ subscribe_v5(NULL, "loop/test", 0, 0, NULL); } } void mosquittopp_test::on_disconnect_v5(int rc, const mosquitto_property *properties) { (void)properties; run = rc; } void mosquittopp_test::on_subscribe_v5(int mid, int qos_count, const int *granted_qos, const mosquitto_property *props) { (void)mid; (void)qos_count; (void)granted_qos; (void)props; publish_v5(NULL, "loop/test", strlen("message"), "message", 0, false, NULL); } void mosquittopp_test::on_message_v5(const struct mosquitto_message *msg, const mosquitto_property *properties) { (void)msg; (void)properties; disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("loop-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect_v5("localhost", port, 60, NULL, NULL); mosq->loop_forever(); delete mosq; mosqpp::lib_cleanup(); return 1; } ================================================ FILE: test/lib/cpp/03-publish-loop-manual.cpp ================================================ #include #include #include #include #include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect_v5(int rc, int flags, const mosquitto_property *properties); void on_disconnect_v5(int rc, const mosquitto_property *properties); void on_subscribe_v5(int mid, int qos_count, const int *granted_qos, const mosquitto_property *props); void on_message_v5(const struct mosquitto_message *msg, const mosquitto_property *properties); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect_v5(int rc, int flags, const mosquitto_property *properties) { (void)flags; (void)properties; if(rc){ exit(1); }else{ subscribe_v5(NULL, "loop/test", 0, 0, NULL); } } void mosquittopp_test::on_disconnect_v5(int rc, const mosquitto_property *properties) { (void)properties; run = rc; } void mosquittopp_test::on_subscribe_v5(int mid, int qos_count, const int *granted_qos, const mosquitto_property *props) { (void)mid; (void)qos_count; (void)granted_qos; (void)props; publish_v5(NULL, "loop/test", strlen("message"), "message", 0, false, NULL); } void mosquittopp_test::on_message_v5(const struct mosquitto_message *msg, const mosquitto_property *properties) { (void)msg; (void)properties; mosqpp::validate_utf8(msg->topic, (int)strlen(msg->topic)); disconnect(); } void do_loop(mosquittopp_test *mosq) { int sock; struct timeval tv; fd_set readfds, writefds; sock = mosq->socket(); if(sock < 0){ exit(1); } FD_ZERO(&readfds); FD_ZERO(&writefds); FD_SET(sock, &readfds); while(run == -1){ tv.tv_sec = 0; tv.tv_usec = 100000; FD_SET(sock, &readfds); if(mosq->want_write()){ FD_SET(sock, &writefds); }else{ FD_CLR(sock, &writefds); } int fdcount = select(sock+1, &readfds, &writefds, NULL, &tv); if(fdcount < 0){ exit(1); } if(FD_ISSET(sock, &readfds)){ mosq->loop_read(); } if(FD_ISSET(sock, &writefds)){ mosq->loop_write(); } mosq->loop_misc(); } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("loop-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect_v5("localhost", port, 60, NULL, NULL); do_loop(mosq); delete mosq; mosqpp::lib_cleanup(); return 1; } ================================================ FILE: test/lib/cpp/03-publish-loop-start.cpp ================================================ #include #include #include #include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect_v5(int rc, int flags, const mosquitto_property *properties); void on_disconnect_v5(int rc, const mosquitto_property *properties); void on_subscribe_v5(int mid, int qos_count, const int *granted_qos, const mosquitto_property *props); void on_message_v5(const struct mosquitto_message *msg, const mosquitto_property *properties); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect_v5(int rc, int flags, const mosquitto_property *properties) { (void)flags; (void)properties; if(rc){ exit(1); }else{ subscribe_v5(NULL, "loop/test", 0, 0, NULL); } } void mosquittopp_test::on_disconnect_v5(int rc, const mosquitto_property *properties) { (void)properties; run = rc; } void mosquittopp_test::on_subscribe_v5(int mid, int qos_count, const int *granted_qos, const mosquitto_property *props) { (void)mid; (void)qos_count; (void)granted_qos; (void)props; publish_v5(NULL, "loop/test", strlen("message"), "message", 0, false, NULL); } void mosquittopp_test::on_message_v5(const struct mosquitto_message *msg, const mosquitto_property *properties) { (void)msg; (void)properties; disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("loop-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect_v5("localhost", port, 60, NULL, NULL); mosq->loop_start(); struct timespec tv = { 0, (long)50e6 }; while(run == -1){ nanosleep(&tv, NULL); } delete mosq; mosqpp::lib_cleanup(); return 1; } ================================================ FILE: test/lib/cpp/03-publish-loop.cpp ================================================ #include #include #include #include static int run = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect_v5(int rc, int flags, const mosquitto_property *properties); void on_disconnect_v5(int rc, const mosquitto_property *properties); void on_subscribe_v5(int mid, int qos_count, const int *granted_qos, const mosquitto_property *props); void on_message_v5(const struct mosquitto_message *msg, const mosquitto_property *properties); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect_v5(int rc, int flags, const mosquitto_property *properties) { (void)flags; (void)properties; if(rc){ exit(1); }else{ subscribe_v5(NULL, "loop/test", 0, 0, NULL); } } void mosquittopp_test::on_disconnect_v5(int rc, const mosquitto_property *properties) { (void)properties; run = rc; } void mosquittopp_test::on_subscribe_v5(int mid, int qos_count, const int *granted_qos, const mosquitto_property *props) { (void)mid; (void)qos_count; (void)granted_qos; (void)props; publish_v5(NULL, "loop/test", strlen("message"), "message", 0, false, NULL); } void mosquittopp_test::on_message_v5(const struct mosquitto_message *msg, const mosquitto_property *properties) { (void)msg; (void)properties; disconnect(); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("loop-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect_v5("localhost", port, 60, NULL, NULL); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return 1; } ================================================ FILE: test/lib/cpp/03-publish-qos0-no-payload.cpp ================================================ #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_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(&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); } } void mosquittopp_test::on_disconnect(int rc) { run = rc; } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/03-publish-qos0.cpp ================================================ #include #include 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[]) { mosquittopp_test *mosq; int rc; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos0-test"); mosq->connect("localhost", port, 60); rc = mosq->loop_forever(); delete mosq; mosqpp::lib_cleanup(); return rc; } ================================================ FILE: test/lib/cpp/03-request-response-1.cpp ================================================ #include #include #include #include #define QOS 0 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); 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, "response/topic", QOS); } } void mosquittopp_test::on_subscribe(int mid, int qos_count, const int *granted_qos) { mosquitto_property *props = NULL; (void)mid; if(qos_count != 1 || granted_qos[0] != QOS){ abort(); } if(mosquitto_property_add_string(&props, MQTT_PROP_RESPONSE_TOPIC, "response/topic")){ abort(); } publish_v5(NULL, "request/topic", 6, "action", 0, 0, props); mosquitto_property_free_all(&props); } void mosquittopp_test::on_message(const struct mosquitto_message *msg) { if(!strcmp((char *)msg->payload, "a response")){ run = 0; }else{ run = 1; } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("request-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, 5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return 1; } ================================================ FILE: test/lib/cpp/03-request-response-2.cpp ================================================ #include #include #include #include #include #define QOS 0 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_message_v5(const struct mosquitto_message *msg, const mosquitto_property *props); 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{ subscribe(NULL, "request/topic", QOS); } } void mosquittopp_test::on_publish(int mid) { assert(mid == sent_mid); run = 0; } void mosquittopp_test::on_message_v5(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 = publish_v5(&sent_mid, resp_topic, strlen("a response"), "a response", 0, false, p_corr); if(rc != MOSQ_ERR_SUCCESS){ abort(); } free(resp_topic); } } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("response-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, 5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return 1; } ================================================ FILE: test/lib/cpp/03-request-response-correlation-1.cpp ================================================ #include #include #include #include #define QOS 0 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); 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, "response/topic", QOS); } } void mosquittopp_test::on_subscribe(int mid, int qos_count, const int *granted_qos) { mosquitto_property *props = NULL; int rc; (void)mid; if(qos_count != 1 || granted_qos[0] != QOS){ abort(); } if(mosquitto_property_add_string(&props, MQTT_PROP_RESPONSE_TOPIC, "response/topic") || mosquitto_property_add_binary(&props, MQTT_PROP_CORRELATION_DATA, "corridor", 8)){ abort(); } rc = publish_v5(NULL, "request/topic", 6, "action", QOS, 0, props); if(rc != MOSQ_ERR_SUCCESS){ abort(); } mosquitto_property_free_all(&props); } void mosquittopp_test::on_message(const struct mosquitto_message *msg) { if(!strcmp((char *)msg->payload, "a response")){ run = 0; }else{ run = 1; } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("request-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, 5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return 1; } ================================================ FILE: test/lib/cpp/04-retain-qos0.cpp ================================================ #include #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, "retain/qos0/test", strlen("retained message"), "retained message", 0, true); } } void mosquittopp_test::on_publish(int mid) { assert(mid == sent_mid); run = 0; } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } 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; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/08-ssl-bad-cacert.cpp ================================================ #include #include "path_helper.h" 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[]) { mosquittopp_test *mosq; int rc = 1; if(argc != 2){ return 1; } (void)argv; mosqpp::lib_init(); mosq = new mosquittopp_test("08-ssl-bad-cacert"); if(mosq->tls_set("this/file/doesnt/exist") == MOSQ_ERR_INVAL){ rc = 0; } delete mosq; mosqpp::lib_cleanup(); return rc; } ================================================ FILE: test/lib/cpp/08-ssl-connect-cert-auth-custom-ssl-ctx-default.cpp ================================================ #include #include #include #include "path_helper.h" static int run = -1; void handle_sigint(int signal) { (void)signal; run = 0; } 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[]) { mosquittopp_test *mosq; SSL_CTX *ssl_ctx; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \ | OPENSSL_INIT_ADD_ALL_DIGESTS \ | OPENSSL_INIT_LOAD_CONFIG, NULL); ssl_ctx = SSL_CTX_new(TLS_client_method()); mosq = new mosquittopp_test("08-ssl-connect-crt-auth"); char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-root-ca.crt"); char capath[4096]; cat_sourcedir_with_relpath(capath, "/../../ssl/certs"); char certfile[4096]; cat_sourcedir_with_relpath(certfile, "/../../ssl/client.crt"); char keyfile[4096]; cat_sourcedir_with_relpath(keyfile, "/../../ssl/client.key"); mosq->tls_set(cafile, NULL, certfile, keyfile); mosq->int_option(MOSQ_OPT_SSL_CTX_WITH_DEFAULTS, 1); mosq->void_option(MOSQ_OPT_SSL_CTX, ssl_ctx); mosq->connect("localhost", port, 60); signal(SIGINT, handle_sigint); while(run == -1){ mosq->loop(); } SSL_CTX_free(ssl_ctx); delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/08-ssl-connect-cert-auth-custom-ssl-ctx.cpp ================================================ #include #include #include #include "path_helper.h" static int run = -1; void handle_sigint(int signal) { (void)signal; run = 0; } 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[]) { mosquittopp_test *mosq; SSL_CTX *ssl_ctx; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \ | OPENSSL_INIT_ADD_ALL_DIGESTS \ | OPENSSL_INIT_LOAD_CONFIG, NULL); ssl_ctx = SSL_CTX_new(TLS_client_method()); char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-root-ca.crt"); char capath[4096]; cat_sourcedir_with_relpath(capath, "/../../ssl/certs"); char certfile[4096]; cat_sourcedir_with_relpath(certfile, "/../../ssl/client.crt"); char keyfile[4096]; cat_sourcedir_with_relpath(keyfile, "/../../ssl/client.key"); SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); SSL_CTX_use_certificate_chain_file(ssl_ctx, certfile); SSL_CTX_use_PrivateKey_file(ssl_ctx, keyfile, SSL_FILETYPE_PEM); SSL_CTX_load_verify_locations(ssl_ctx, cafile, capath); mosq = new mosquittopp_test("08-ssl-connect-crt-auth"); mosq->tls_set(cafile, NULL, certfile, keyfile); mosq->int_option(MOSQ_OPT_SSL_CTX_WITH_DEFAULTS, 0); mosq->void_option(MOSQ_OPT_SSL_CTX, ssl_ctx); mosq->connect("localhost", port, 60); signal(SIGINT, handle_sigint); while(run == -1){ mosq->loop(); } SSL_CTX_free(ssl_ctx); delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/08-ssl-connect-cert-auth-enc.cpp ================================================ #include #include #include "path_helper.h" static int run = -1; static int password_callback(char *buf, int size, int rwflag, void *userdata) { (void)rwflag; (void)userdata; strncpy(buf, "password", (size_t )size); buf[size-1] = '\0'; return (int)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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("08-ssl-connect-crt-auth-enc"); char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-root-ca.crt"); char capath[4096]; cat_sourcedir_with_relpath(capath, "/../../ssl/certs"); char certfile[4096]; cat_sourcedir_with_relpath(certfile, "/../../ssl/client.crt"); char keyfile[4096]; cat_sourcedir_with_relpath(keyfile, "/../../ssl/client.key"); mosq->tls_set(cafile, NULL, certfile, keyfile, password_callback); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/08-ssl-connect-cert-auth.cpp ================================================ #include #include "path_helper.h" 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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("08-ssl-connect-crt-auth"); char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-root-ca.crt"); char capath[4096]; cat_sourcedir_with_relpath(capath, "/../../ssl/certs"); char certfile[4096]; cat_sourcedir_with_relpath(certfile, "/../../ssl/client.crt"); char keyfile[4096]; cat_sourcedir_with_relpath(keyfile, "/../../ssl/client.key"); mosq->tls_set(cafile, capath, certfile, keyfile); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/08-ssl-connect-no-auth.cpp ================================================ #include #include "path_helper.h" 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[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("08-ssl-connect-no-auth"); char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/all-ca.crt"); mosq->tls_set(cafile); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/08-ssl-connect-san.cpp ================================================ #include #include "path_helper.h" #include #include "path_helper.h" 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[]) { mosquittopp_test *mosq; int rc; char cafile[4096]; assert(argc == 3); int port = atoi(argv[1]); char *host = argv[2]; mosqpp::lib_init(); mosq = new mosquittopp_test("08-ssl-connect-san"); cat_sourcedir_with_relpath(cafile, "/../../ssl/test-root-ca.crt"); mosq->tls_set(cafile); rc = mosq->connect(host, port, 60); if(rc != MOSQ_ERR_SUCCESS){ return rc; } while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/08-ssl-fake-cacert.cpp ================================================ #include #include #include "path_helper.h" 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) { (void)rc; exit(1); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; int rc; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("08-ssl-fake-cacert"); char cafile[4096]; cat_sourcedir_with_relpath(cafile, "/../../ssl/test-fake-root-ca.crt"); char capath[4096]; cat_sourcedir_with_relpath(capath, "/../../ssl/certs"); char certfile[4096]; cat_sourcedir_with_relpath(certfile, "/../../ssl/client.crt"); char keyfile[4096]; cat_sourcedir_with_relpath(keyfile, "/../../ssl/client.key"); mosq->tls_set(cafile, NULL, certfile, keyfile); 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; } } ================================================ FILE: test/lib/cpp/09-util-topic-tokenise.cpp ================================================ #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 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 rc); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ rc = subscribe(NULL, "0123456789012345678901234567890", 0); if(rc != MOSQ_ERR_OVERSIZE_PACKET){ printf("Fail on subscribe\n"); exit(1); } rc = unsubscribe(NULL, "0123456789012345678901234567890"); if(rc != MOSQ_ERR_OVERSIZE_PACKET){ printf("Fail on unsubscribe\n"); exit(1); } rc = publish(&sent_mid, "pub/test", strlen("123456789012345678"), "123456789012345678", 0, false); if(rc != MOSQ_ERR_OVERSIZE_PACKET){ printf("Fail on publish 1\n"); exit(1); } rc = publish(&sent_mid, "pub/test", strlen("12345678901234567"), "12345678901234567", 0, false); if(rc != MOSQ_ERR_SUCCESS){ printf("Fail on publish 2\n"); exit(1); } } } void mosquittopp_test::on_publish(int mid) { if(mid == sent_mid){ disconnect(); run = 0; }else{ exit(1); } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("publish-qos0-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/11-prop-recv.cpp ================================================ #include #include #include #include static int run = -1; static int qos = -1; class mosquittopp_test : public mosqpp::mosquittopp { public: mosquittopp_test(const char *id); void on_connect(int rc); void on_message_v5(const struct mosquitto_message *msg, const mosquitto_property *properties); }; 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_v5(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 == qos){ publish(NULL, "ok", 2, "ok", 0, 0); return; } } } } } } /* No matching message, so quit with an error */ exit(1); } int main(int argc, char *argv[]) { mosquittopp_test *mosq; int rc; assert(argc == 3); int port = atoi(argv[1]); qos = atoi(argv[2]); mosqpp::lib_init(); mosq = new mosquittopp_test("prop-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ rc = mosq->loop(); if(rc != MOSQ_ERR_SUCCESS){ return rc; } } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/11-prop-send-content-type.cpp ================================================ #include #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 rc); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ mosquitto_property *proplist = NULL; int rc2 = mosquitto_property_add_string(&proplist, MQTT_PROP_CONTENT_TYPE, "application/json"); if(rc2 != MOSQ_ERR_SUCCESS){ abort(); } publish_v5(&sent_mid, "prop/qos0", strlen("message"), "message", 0, false, proplist); mosquitto_property_free_all(&proplist); } } void mosquittopp_test::on_publish(int mid) { if(mid == sent_mid){ disconnect(); run = 0; }else{ exit(1); } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("prop-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60, NULL); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/11-prop-send-payload-format.cpp ================================================ #include #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 rc); }; mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id) { } void mosquittopp_test::on_connect(int rc) { if(rc){ exit(1); }else{ mosquitto_property *proplist = NULL; int rc2 = mosquitto_property_add_byte(&proplist, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, 1); if(rc2 != MOSQ_ERR_SUCCESS){ abort(); } publish_v5(&sent_mid, "prop/qos0", strlen("message"), "message", 0, false, proplist); mosquitto_property_free_all(&proplist); } } void mosquittopp_test::on_publish(int mid) { if(mid == sent_mid){ disconnect(); run = 0; }else{ exit(1); } } int main(int argc, char *argv[]) { mosquittopp_test *mosq; if(argc != 2){ return 1; } int port = atoi(argv[1]); mosqpp::lib_init(); mosq = new mosquittopp_test("prop-test"); mosq->int_option(MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5); mosq->connect("localhost", port, 60); while(run == -1){ mosq->loop(); } delete mosq; mosqpp::lib_cleanup(); return run; } ================================================ FILE: test/lib/cpp/CMakeLists.txt ================================================ set(BINARIES 01-con-discon-success 01-con-discon-success-v5 01-con-discon-will-clear 01-con-discon-will 01-con-discon-will-v5 01-extended-auth-continue 01-extended-auth-failure 01-keepalive-pingreq 01-no-clean-session 01-pre-connect-callback 01-server-keepalive-pingreq 01-unpwd-set 01-will-set 01-will-unpwd-set 02-subscribe-helper-callback-qos2 02-subscribe-helper-simple-qos2 02-subscribe-qos0 02-subscribe-qos1-async1 02-subscribe-qos1-async2 02-subscribe-qos1 02-subscribe-qos2 02-unsubscribe 02-unsubscribe-v5 03-publish-b2c-qos1 03-publish-b2c-qos1-unexpected-puback 03-publish-b2c-qos2 03-publish-b2c-qos2-len 03-publish-b2c-qos2-unexpected-pubcomp 03-publish-b2c-qos2-unexpected-pubrel 03-publish-c2b-qos1-disconnect 03-publish-c2b-qos1-len 03-publish-c2b-qos1-receive-maximum 03-publish-c2b-qos2 03-publish-c2b-qos2-disconnect 03-publish-c2b-qos2-len 03-publish-c2b-qos2-maximum-qos-0 03-publish-c2b-qos2-maximum-qos-1 03-publish-c2b-qos2-pubrec-error 03-publish-c2b-qos2-receive-maximum 03-publish-loop 03-publish-loop-forever 03-publish-loop-manual 03-publish-loop-start 03-publish-qos0 03-publish-qos0-no-payload 03-request-response-1 03-request-response-2 03-request-response-correlation-1 04-retain-qos0 08-ssl-bad-cacert 08-ssl-connect-cert-auth 08-ssl-connect-cert-auth-custom-ssl-ctx 08-ssl-connect-cert-auth-custom-ssl-ctx-default 08-ssl-connect-cert-auth-enc 08-ssl-connect-no-auth 08-ssl-connect-san 08-ssl-fake-cacert 09-util-topic-tokenise 11-prop-oversize-packet 11-prop-recv 11-prop-send-content-type 11-prop-send-payload-format ) foreach(BINARY ${BINARIES}) set(TARGET "${BINARY}-cpp") add_executable(${TARGET} ${BINARY}.cpp) target_compile_definitions(${TARGET} PRIVATE TEST_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}") target_include_directories(${TARGET} PRIVATE ${CMAKE_SOURCE_DIR}/test ${CMAKE_SOURCE_DIR}/include) set_property(TARGET ${TARGET} PROPERTY SUFFIX .test) target_link_libraries(${TARGET} PRIVATE common-options mosquittopp OpenSSL::SSL) set_target_properties(${TARGET} PROPERTIES OUTPUT_NAME ${BINARY}) endforeach() ================================================ FILE: test/lib/cpp/Makefile ================================================ R=../../.. include ${R}/config.mk .PHONY: all test clean reallyclean LOCAL_CXXFLAGS+=-I${R}/include -I${R}/test -I${R}/lib/cpp -DDEBUG -Werror -W LIBS=${LIBMOSQ} ${R}/lib/cpp/libmosquittopp.so.1 SRC = \ 01-con-discon-success.cpp \ 01-con-discon-success-v5.cpp \ 01-con-discon-will-clear.cpp \ 01-con-discon-will-v5.cpp \ 01-con-discon-will.cpp \ 01-extended-auth-continue.cpp \ 01-extended-auth-failure.cpp \ 01-keepalive-pingreq.cpp \ 01-no-clean-session.cpp \ 01-pre-connect-callback.cpp \ 01-server-keepalive-pingreq.cpp \ 01-unpwd-set.cpp \ 01-will-set.cpp \ 01-will-unpwd-set.cpp \ 02-subscribe-helper-callback-qos2.cpp \ 02-subscribe-helper-simple-qos2.cpp \ 02-subscribe-qos0.cpp \ 02-subscribe-qos1-async1.cpp \ 02-subscribe-qos1-async2.cpp \ 02-subscribe-qos1.cpp \ 02-subscribe-qos2.cpp \ 02-unsubscribe.cpp \ 02-unsubscribe-v5.cpp \ 03-publish-b2c-qos1.cpp \ 03-publish-b2c-qos1-unexpected-puback.cpp \ 03-publish-b2c-qos2.cpp \ 03-publish-b2c-qos2-len.cpp \ 03-publish-b2c-qos2-unexpected-pubcomp.cpp \ 03-publish-b2c-qos2-unexpected-pubrel.cpp \ 03-publish-c2b-qos1-disconnect.cpp \ 03-publish-c2b-qos1-len.cpp \ 03-publish-c2b-qos1-receive-maximum.cpp \ 03-publish-c2b-qos2-disconnect.cpp \ 03-publish-c2b-qos2.cpp \ 03-publish-c2b-qos2-len.cpp \ 03-publish-c2b-qos2-maximum-qos-0.cpp \ 03-publish-c2b-qos2-maximum-qos-1.cpp \ 03-publish-c2b-qos2-pubrec-error.cpp \ 03-publish-c2b-qos2-receive-maximum.cpp \ 03-publish-loop.cpp \ 03-publish-loop-forever.cpp \ 03-publish-loop-manual.cpp \ 03-publish-loop-start.cpp \ 03-publish-qos0-no-payload.cpp \ 03-publish-qos0.cpp \ 03-request-response-1.cpp \ 03-request-response-2.cpp \ 03-request-response-correlation-1.cpp \ 04-retain-qos0.cpp \ 08-ssl-bad-cacert.cpp \ 08-ssl-connect-cert-auth-enc.cpp \ 08-ssl-connect-cert-auth.cpp \ 08-ssl-connect-cert-auth-custom-ssl-ctx.cpp \ 08-ssl-connect-cert-auth-custom-ssl-ctx-default.cpp \ 08-ssl-connect-no-auth.cpp \ 08-ssl-connect-san.cpp \ 08-ssl-fake-cacert.cpp \ 09-util-topic-tokenise.cpp \ 11-prop-oversize-packet.cpp \ 11-prop-send-content-type.cpp \ 11-prop-send-payload-format.cpp \ 11-prop-recv.cpp LIBS += -lssl -lcrypto TESTS = ${SRC:.cpp=.test} all : ${TESTS} ${TESTS} : %.test: %.cpp ${R}/test/path_helper.h $(CXX) -DTEST_SOURCE_DIR='"$(realpath .)"' $< -o $@ $(LOCAL_CXXFLAGS) $(LIBS) $(LOCAL_LDFLAGS) reallyclean : clean -rm -f *.orig clean : rm -f *.test ================================================ FILE: test/lib/data/AUTH.json ================================================ [ { "comment": "AUTH TESTS ARE INCOMPLETE", "group": "v3.1.1 AUTH", "ver":4, "tests": [ { "name": "F0 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"F0 r0"}]}, { "name": "F0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"F0 r268435456"}]}, { "name": "F0 long", "msgs": [{"type":"send", "payload":"F0 r1 00"}]}, { "name": "F1", "msgs": [{"type":"send", "payload":"F1 r0"}]}, { "name": "F2", "msgs": [{"type":"send", "payload":"F2 r0"}]}, { "name": "F4", "msgs": [{"type":"send", "payload":"F4 r0"}]}, { "name": "F8", "msgs": [{"type":"send", "payload":"F8 r0"}]} ] }, { "group": "v5.0 AUTH", "ver":5, "tests": [ { "name": "F0 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"F0 r0"}]}, { "name": "F0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"F0 r268435456"}]}, { "name": "F0 long", "msgs": [{"type":"send", "payload":"F0 r1 00"}]}, { "name": "F1", "msgs": [{"type":"send", "payload":"F1 r0"}]}, { "name": "F2", "msgs": [{"type":"send", "payload":"F2 r0"}]}, { "name": "F4", "msgs": [{"type":"send", "payload":"F4 r0"}]}, { "name": "F8", "msgs": [{"type":"send", "payload":"F8 r0"}]} ] } ] ================================================ FILE: test/lib/data/CONNACK.json ================================================ [ { "group": "v3.1.1 CONNACK", "connack": false, "ver":4, "tests": [ { "name": "20 [MQTT-3.1.0-1]", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"20 r2 00 00"}]}, { "name": "20 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"20 r268435456"}]}, { "name": "20 long", "msgs": [{"type":"send", "payload":"20 r3 00 00 00"}]}, { "name": "20 short 1", "msgs": [{"type":"send", "payload":"20 r1 00"}]}, { "name": "20 short 0", "msgs": [{"type":"send", "payload":"20 r0"}]}, { "name": "20", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"20 r2 00 00"}]}, { "name": "21", "msgs": [{"type":"send", "payload":"21 02 00 00"}]}, { "name": "22", "msgs": [{"type":"send", "payload":"22 02 00 00"}]}, { "name": "24", "msgs": [{"type":"send", "payload":"24 02 00 00"}]}, { "name": "28", "msgs": [{"type":"send", "payload":"28 02 00 00"}]}, { "name": "issue 2163 v3", "ver":3, "msgs": [{"type":"send", "payload":"29 02 00 01"}]}, { "name": "issue 2163 v4", "msgs": [{"type":"send", "payload":"29 02 00 01"}]}, { "name": "20 CAF=0x01", "msgs": [{"type":"send", "payload":"20 r2 01 00"}]}, { "name": "20 CAF=0x02", "msgs": [{"type":"send", "payload":"20 r2 02 00"}]}, { "name": "20 CAF=0x04", "msgs": [{"type":"send", "payload":"20 r2 04 00"}]}, { "name": "20 CAF=0x08", "msgs": [{"type":"send", "payload":"20 r2 08 00"}]}, { "name": "20 CAF=0x10", "msgs": [{"type":"send", "payload":"20 r2 10 00"}]}, { "name": "20 CAF=0x20", "msgs": [{"type":"send", "payload":"20 r2 20 00"}]}, { "name": "20 CAF=0x40", "msgs": [{"type":"send", "payload":"20 r2 40 00"}]}, { "name": "20 CAF=0x80", "msgs": [{"type":"send", "payload":"20 r2 80 00"}]} ] }, { "group": "v5.0 CONNACK", "comment": "CMD RL FLAG RC PROPLEN PROPS", "ver":5, "connack": false, "tests": [ { "name": "20 [MQTT-3.1.0-1]", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"20 r3 00 00 v0"}]}, { "name": "20 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"20 r268435456"}]}, { "name": "20 with properties", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"20 r6 00 00 v3 21 H10"}]}, { "name": "20 long", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"20 r4 00 00 00 00"}]}, { "name": "20 short 2", "msgs": [{"type":"send", "payload":"20 r2 00 00"}]}, { "name": "20 short 1", "msgs": [{"type":"send", "payload":"20 r1 00"}]}, { "name": "20 short 0", "msgs": [{"type":"send", "payload":"20 r0"}]}, { "name": "21", "msgs": [{"type":"send", "payload":"21 r3 00 00 v0"}]}, { "name": "22", "msgs": [{"type":"send", "payload":"22 r3 00 00 v0"}]}, { "name": "24", "msgs": [{"type":"send", "payload":"24 r3 00 00 v0"}]}, { "name": "28", "msgs": [{"type":"send", "payload":"28 r3 00 00 v0"}]}, { "name": "issue 2163 v5", "msgs": [{"type":"send", "payload":"29 r2 00 01"}]}, { "name": "20 CAF=0x01", "msgs": [{"type":"send", "payload":"20 r3 01 00 v0"}]}, { "name": "20 CAF=0x02", "msgs": [{"type":"send", "payload":"20 r3 02 00 v0"}]}, { "name": "20 CAF=0x04", "msgs": [{"type":"send", "payload":"20 r3 04 00 v0"}]}, { "name": "20 CAF=0x08", "msgs": [{"type":"send", "payload":"20 r3 08 00 v0"}]}, { "name": "20 CAF=0x10", "msgs": [{"type":"send", "payload":"20 r3 10 00 v0"}]}, { "name": "20 CAF=0x20", "msgs": [{"type":"send", "payload":"20 r3 20 00 v0"}]}, { "name": "20 CAF=0x40", "msgs": [{"type":"send", "payload":"20 r3 40 00 v0"}]}, { "name": "20 CAF=0x80", "msgs": [{"type":"send", "payload":"20 r3 80 00 v0"}]}, { "name": "20 RC=0x01 (invalid)", "msgs": [{"type":"send", "payload":"20 r3 00 01 v0"}]}, { "name": "20 RC=0x80 (unspecified error)", "msgs": [{"type":"send", "payload":"20 r3 00 80 v0"}]}, { "name": "20 RC=0x81 (malformed packet)", "msgs": [{"type":"send", "payload":"20 r3 00 81 v0"}]}, { "name": "20 RC=0x82 (protocol error)", "msgs": [{"type":"send", "payload":"20 r3 00 82 v0"}]}, { "name": "20 RC=0x83 (implementation specific error)", "msgs": [{"type":"send", "payload":"20 r3 00 83 v0"}]}, { "name": "20 RC=0x84 (unsupported protocol version)", "msgs": [{"type":"send", "payload":"20 r3 00 84 v0"}]}, { "name": "20 RC=0x85 (client identifier not valid)", "msgs": [{"type":"send", "payload":"20 r3 00 85 v0"}]}, { "name": "20 RC=0x86 (bad user name or password)", "msgs": [{"type":"send", "payload":"20 r3 00 86 v0"}]}, { "name": "20 RC=0x87 (not authorised)", "msgs": [{"type":"send", "payload":"20 r3 00 87 v0"}]}, { "name": "20 RC=0x88 (server unavailable)", "msgs": [{"type":"send", "payload":"20 r3 00 88 v0"}]}, { "name": "20 RC=0x89 (server busy)", "msgs": [{"type":"send", "payload":"20 r3 00 89 v0"}]}, { "name": "20 RC=0x8A (banned)", "msgs": [{"type":"send", "payload":"20 r3 00 8A v0"}]}, { "name": "20 RC=0x8C (bad authentication method)", "msgs": [{"type":"send", "payload":"20 r3 00 8C v0"}]}, { "name": "20 RC=0x90 (topic name invalid)", "msgs": [{"type":"send", "payload":"20 r3 00 90 v0"}]}, { "name": "20 RC=0x95 (packet too large)", "msgs": [{"type":"send", "payload":"20 r3 00 95 v0"}]}, { "name": "20 RC=0x97 (quota exceeded)", "msgs": [{"type":"send", "payload":"20 r3 00 97 v0"}]}, { "name": "20 RC=0x99 (payload format invalid)", "msgs": [{"type":"send", "payload":"20 r3 00 99 v0"}]}, { "name": "20 RC=0x9A (retain not supported)", "msgs": [{"type":"send", "payload":"20 r3 00 9A v0"}]}, { "name": "20 RC=0x9B (qos not supported)", "msgs": [{"type":"send", "payload":"20 r3 00 9B v0"}]}, { "name": "20 RC=0x9C (use another server)", "msgs": [{"type":"send", "payload":"20 r3 00 9C v0"}]}, { "name": "20 RC=0x9D (server moved)", "msgs": [{"type":"send", "payload":"20 r3 00 9D v0"}]}, { "name": "20 RC=0x9F (connection rate exceeded)", "msgs": [{"type":"send", "payload":"20 r3 00 9F v0"}]}, { "name": "20 RC=0xFF (invalid)", "msgs": [{"type":"send", "payload":"20 r3 00 FF v0"}]} ] }, { "group": "v5.0 CONNACK ALLOWED PROPERTIES VALID", "comment": "CMD RL FLAG RC PROPLEN PROPS", "ver":5, "connack": false, "expect_disconnect":false, "tests": [ { "name": "20 with session-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"20 r8 00 00 v5 11 L1"}]}, { "name": "20 with receive-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"20 r6 00 00 v3 21 H5"}]}, { "name": "20 with maximum-qos (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 24 i0"}]}, { "name": "20 with retain-available (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 25 i0"}]}, { "name": "20 with maximum-packet-size (four byte integer)", "msgs": [{"type":"send", "payload":"20 r8 00 00 v5 27 L1"}]}, { "name": "20 with maximum-packet-size (four byte integer)", "msgs": [{"type":"send", "payload":"20 r8 00 00 v5 27 L1"}]}, { "name": "20 with topic-alias-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"20 r6 00 00 v3 22 H5"}]}, { "name": "20 with reason-string property", "msgs": [{"type":"send", "payload":"20 r7 00 00 v4 1F s1 'p'"}]}, { "name": "20 with reason-string property empty", "msgs": [{"type":"send", "payload":"20 r6 00 00 v3 1F s0"}]}, { "name": "20 with wildcard-subscription-available (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 28 i0"}]}, { "name": "20 with subscription-identifier-available (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 29 i0"}]}, { "name": "20 with server-keep-alive (two byte integer)", "msgs": [{"type":"send", "payload":"20 r6 00 00 v3 13 H5"}]}, { "name": "20 with shared-subscription-available (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 2A i0"}]}, { "name": "20 with response-information (UTF-8 string)", "msgs": [{"type":"send", "payload":"20 r7 00 00 v4 1A s1 'p'"}]}, { "name": "20 with server-reference (UTF-8 string)", "msgs": [{"type":"send", "payload":"20 r7 00 00 v4 1C s1 'p'"}]}, { "name": "20 with authentication-method (UTF-8 string)", "msgs": [{"type":"send", "payload":"20 r7 00 00 v4 15 s1 'p'"}]}, { "name": "20 with authentication-data (binary data)", "msgs": [{"type":"send", "payload":"20 r7 00 00 v4 16 s1 'p'"}]}, { "name": "20 with user-property", "msgs": [{"type":"send", "payload":"20 r10 00 00 07 26 s1 'p' s1 'q'"}]} ] }, { "group": "v5.0 CONNACK ALLOWED PROPERTIES INVALID", "comment": "CMD RL FLAG RC PROPLEN PROPS", "ver":5, "connack": false, "expect_disconnect":true, "tests": [ { "name": "20 with session-expiry-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 11"}]}, { "name": "20 with receive-maximum (two byte integer) 0 value", "msgs": [{"type":"send", "payload":"20 r6 00 00 v3 21 H0"}]}, { "name": "20 with receive-maximum (two byte integer) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 21"}]}, { "name": "20 with assigned-client-identifier (UTF-8 string)", "msgs": [{"type":"send", "payload":"20 r7 00 00 v4 12 s1 'p'"}]}, { "name": "20 with maximum-qos (byte) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 24"}]}, { "name": "20 with maximum-qos (byte) 2 value", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 24 i2"}]}, { "name": "20 with retain-available (byte) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 25"}]}, { "name": "20 with maximum-packet-size (four byte integer) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 27"}]}, { "name": "20 with assigned-client-identifier (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 12"}]}, { "name": "20 with topic-alias-maximum (two byte integer) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 22"}]}, { "name": "20 with reason-string property missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 01 1F"}]}, { "name": "20 with wildcard-subscription-available (byte) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 28"}]}, { "name": "20 with subscription-identifier-available (byte) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 29"}]}, { "name": "20 with server-keep-alive (two byte integer) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 13"}]}, { "name": "20 with shared-subscription-available (byte) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 2A"}]}, { "name": "20 with response-information (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 01 1A"}]}, { "name": "20 with server-reference (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 1C"}]}, { "name": "20 with authentication-method (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 15"}]}, { "name": "20 with authentication-data (binary data) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 16"}]}, { "name": "20 with user-property missing value", "msgs": [{"type":"send", "payload":"20 r7 00 00 04 26 s1 'p'"}]}, { "name": "20 with user-property missing key,value", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 26"}]} ] }, { "group": "v5.0 CONNACK DISALLOWED PROPERTIES", "comment": "CMD RL FLAG RC PROPLEN PROPS", "ver":5, "connack": false, "tests": [ { "name": "20 with payload-format-indicator (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 01 i0"}]}, { "name": "20 with request-problem-information (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 17 i0"}]}, { "name": "20 with payload-format-indicator (byte) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 01"}]}, { "name": "20 with request-problem-information (byte) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 17"}]}, { "name": "20 with message-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"20 r8 00 00 v5 02 L1"}]}, { "name": "20 with will-delay-interval (four byte integer)", "msgs": [{"type":"send", "payload":"20 r8 00 00 v5 18 L1"}]}, { "name": "20 with message-expiry-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 02"}]}, { "name": "20 with will-delay-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 18"}]}, { "name": "20 with content-type (UTF-8 string)", "msgs": [{"type":"send", "payload":"20 r7 00 00 v4 03 s1 'p'"}]}, { "name": "20 with response-topic (UTF-8 string)", "msgs": [{"type":"send", "payload":"20 r7 00 00 v4 08 s1 'p'"}]}, { "name": "20 with content-type (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 03"}]}, { "name": "20 with response-topic (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 08"}]}, { "name": "20 with correlation-data (binary data)", "msgs": [{"type":"send", "payload":"20 r7 00 00 v4 09 s1 'p'"}]}, { "name": "20 with correlation-data (binary data) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 09"}]}, { "name": "20 with subscription-identifier (variable byte integer)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 0B i1"}]}, { "name": "20 with subscription-identifier (variable byte integer) missing", "msgs": [{"type":"send", "payload":"20 04 00 00 v1 0B"}]}, { "name": "20 with topic-alias (two byte integer)", "msgs": [{"type":"send", "payload":"20 r6 00 00 v3 23 H5"}]}, { "name": "20 with topic-alias (two byte integer) missing", "msgs": [{"type":"send", "payload":"20 r4 00 00 v1 23"}]}, { "name": "20 with invalid-property 0x00 (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 00 i1"}]}, { "name": "20 with unknown-property 0x04 (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 04 i1"}]}, { "name": "20 with unknown-property 0x05 (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 05 i1"}]}, { "name": "20 with unknown-property 0x06 (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 06 i1"}]}, { "name": "20 with unknown-property 0x07 (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 07 i1"}]}, { "name": "20 with unknown-property 0x0A (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 0A i1"}]}, { "name": "20 with unknown-property 0x0C (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 0C i1"}]}, { "name": "20 with unknown-property 0x0D (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 0D i1"}]}, { "name": "20 with unknown-property 0x0E (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 0E i1"}]}, { "name": "20 with unknown-property 0x0F (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 0F i1"}]}, { "name": "20 with unknown-property 0x10 (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 10 i1"}]}, { "name": "20 with unknown-property 0x14 (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 14 i1"}]}, { "name": "20 with unknown-property 0x1B (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 1B i1"}]}, { "name": "20 with unknown-property 0x1D (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 1D i1"}]}, { "name": "20 with unknown-property 0x1E (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 1E i1"}]}, { "name": "20 with unknown-property 0x20 (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 20 i1"}]}, { "name": "20 with unknown-property 0x7F (byte)", "msgs": [{"type":"send", "payload":"20 r5 00 00 v2 7F i1"}]}, { "name": "20 with invalid-property 0x8000 (byte)", "msgs": [{"type":"send", "payload":"20 r6 00 00 v3 8000 i1"}]}, { "name": "20 with unknown-property 0x8001 (byte)", "msgs": [{"type":"send", "payload":"20 r6 00 00 v3 8001 i1"}]}, { "name": "20 with unknown-property 0xFF7F (byte)", "msgs": [{"type":"send", "payload":"20 r6 00 00 v3 FF7F i1"}]}, { "name": "20 with unknown-property 0x808001 (byte)", "msgs": [{"type":"send", "payload":"20 r7 00 00 v4 808001 i1"}]}, { "name": "20 with unknown-property 0xFFFF7F (byte)", "msgs": [{"type":"send", "payload":"20 r7 00 00 v4 FFFF7F i1"}]}, { "name": "20 with unknown-property 0x80808001 (byte)", "msgs": [{"type":"send", "payload":"20 r8 00 00 v5 80808001 i1"}]}, { "name": "20 with unknown-property 0xFFFFFF7F (byte)", "msgs": [{"type":"send", "payload":"20 r8 00 00 v5 FFFFFF7F i1"}]} ] } ] ================================================ FILE: test/lib/data/CONNECT.json ================================================ [ { "group": "v3.1 CONNECT", "ver":3, "tests": [ { "name": "10 ok ", "msgs":[{"type":"send", "payload":"10 r15 s6 'MQIsdp' 03 01 k10 s1 'p'", "comment":"minimal valid CONNECT"}]}, { "name": "10 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"10 r268435456"}]}, { "name": "14 ok ", "msgs":[{"type":"send", "payload":"14 r15 s6 'MQIsdp' 03 01 k10 s1 'p'", "comment":"CONNECT with QoS=1"}]}, { "name": "10 proto ver 2", "msgs":[{"type":"send", "payload":"10 r15 s6 'MQIsdp' 02 02 k10 s1 'p'", "comment":"CONNECT"}]}, { "name": "10 proto ver 6", "msgs":[{"type":"send", "payload":"10 r15 s6 'MQIsdp' 06 02 k10 s1 'p'", "comment":"CONNECT"}]}, { "name": "10 empty client ID", "msgs":[{"type":"send", "payload":"10 r14 s6 'MQIsdp' 03 02 k10 0000", "comment":"CONNECT clean session true, no client id"}]}, { "name": "10 ok", "msgs":[{"type":"send", "payload":"10 r15 s6 'MQIsdp' 03 02 k10 s1 'p'", "comment":"CONNECT clean session true, no client id"}]} ] }, { "group": "v3.1 CONNECT instead of CONNACK", "ver":3, "connack":false, "tests": [ { "name": "10 ok ", "msgs":[{"type":"send", "payload":"10 r15 s6 'MQIsdp' 03 01 k10 s1 'p'", "comment":"minimal valid CONNECT"}]}, { "name": "10 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"10 r268435456"}]}, { "name": "14 ok ", "msgs":[{"type":"send", "payload":"14 r15 s6 'MQIsdp' 03 01 k10 s1 'p'", "comment":"CONNECT with QoS=1"}]}, { "name": "10 proto ver 2", "msgs":[{"type":"send", "payload":"10 r15 s6 'MQIsdp' 02 02 k10 s1 'p'", "comment":"CONNECT"}]}, { "name": "10 proto ver 6", "msgs":[{"type":"send", "payload":"10 r15 s6 'MQIsdp' 06 02 k10 s1 'p'", "comment":"CONNECT"}]}, { "name": "10 empty client ID", "msgs":[{"type":"send", "payload":"10 r14 s6 'MQIsdp' 03 02 k10 s0", "comment":"CONNECT clean session true, no client id"}]}, { "name": "10 ok", "msgs":[{"type":"send", "payload":"10 r15 s6 'MQIsdp' 03 02 k10 s1 'p'", "comment":"CONNECT clean session true, no client id"}]} ] }, { "group": "v3.1.1 CONNECT", "ver":4, "tests": [ { "name": "10 ok ", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 02 k10 s1 'p'", "comment":"minimal valid CONNECT"}]}, { "name": "10 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"10 r268435456"}]}, { "name": "10 missing client ID", "msgs":[{"type":"send", "payload":"10 r8 s4 'MQTT' 04 02 000A"}]}, { "name": "10 empty client ID", "msgs":[{"type":"send", "payload":"10 r12 s4 'MQTT' 04 02 k10 0000", "comment":"CONNECT clean session true, no client id"}]}, { "name": "10 empty client ID clean false [MQTT-3.1.3-7]", "msgs":[{"type":"send", "payload":"10 r12 s4 'MQTT' 04 02 k10 s0", "comment":"CONNECT clean session false, no client id"}]}, { "name": "10 proto ver 2 [MQTT-3.1.2-2]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 02 02 k10 s1 'p'", "comment":"CONNECT"}]}, { "name": "10 proto ver 6 [MQTT-3.1.2-2]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 06 02 k10 s1 'p'", "comment":"CONNECT"}]}, { "name": "10 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"10 FFFFFFFF7F s4 'MQTT' 05 02 k10 s1 'p'", "comment":"CONNECT"}]}, { "name": "11", "msgs":[{"type":"send", "payload":"11 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "12", "msgs":[{"type":"send", "payload":"12 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "14", "msgs":[{"type":"send", "payload":"14 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "18", "msgs":[{"type":"send", "payload":"18 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "10 short proto", "msgs":[{"type":"send", "payload":"10 r12 s3 'MQT' 04 02 k10 s1 'p'"}]}, { "name": "10 zero proto", "msgs":[{"type":"send", "payload":"10 r9 s0 04 02 k10 s1 'p'"}]}, { "name": "10 long proto", "msgs":[{"type":"send", "payload":"10 r14 s5 'MQTTT' 04 02 k10 s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-1]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTU' 04 02 k10 s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-3] ", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 01 k10 s1 'p'"}]}, { "name": "10 Will flag 0 Will QoS 1 [MQTT-3.1.2-11]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 0A k10 s1 'p'"}]}, { "name": "10 Will flag 0 Will retain 1 [MQTT-3.1.2-11]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 12 k10 s1 'p'"}]}, { "name": "10 Will flag 1 no Will topic no Will message [MQTT-3.1.2-9]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 06 k10 s1 'p'"}]}, { "name": "10 Will flag 1 no Will topic [MQTT-3.1.2-9]", "msgs":[{"type":"send", "payload":"10 r16 s4 'MQTT' 04 06 k10 s1 'p' s1 'p'"}]}, { "name": "10 Will flag 1 ok", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 04 06 k10 s1 'p' s1 'p' s1 'p'"}]}, { "name": "10 Will flag 1 Will Qos 3 [MQTT-3.1.2-14]", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 04 1E k10 s1 'p' s1 'p' s1 'p'"}]}, { "name": "10 Will topic with 0x0000", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F700000 s1 'p'"}]}, { "name": "10 Will topic with U+D800", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746FEDA080 s1 'p'"}]}, { "name": "10 Will topic with U+0001", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F700170 s1 'p'"}]}, { "name": "10 Will topic with U+001F", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F701F70 s1 'p'"}]}, { "name": "10 Will topic with U+007F", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F707F70 s1 'p'"}]}, { "name": "10 Will topic with U+009F", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746FC29F70 s1 'p'"}]}, { "name": "10 Will topic with U+FFFF", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746FEDBFBF s1 'p'"}]}, { "name": "10 Client ID with 0x0000", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F700000"}]}, { "name": "10 Client ID with U+D800", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746FEDA080"}]}, { "name": "10 Client ID with U+0001", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F700170"}]}, { "name": "10 Client ID with U+001F", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F701F70"}]}, { "name": "10 Client ID with U+007F", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F707F70"}]}, { "name": "10 Client ID with U+009F", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746FC29F70"}]}, { "name": "10 Client ID with U+FFFF", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746FEDBFBF"}]}, { "name": "10 [MQTT-3.1.2-18]", "msgs":[{"type":"send", "payload":"10 r16 s4 'MQTT' 04 02 k10 s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-19]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 82 k10 s1 'p'"}]}, { "name": "10 Username with 0x0000", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F700000"}]}, { "name": "10 Username with 0xD800", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746FEDA080"}]}, { "name": "10 Username with 0x0001", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F700170"}]}, { "name": "10 Username with 0x001F", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F701F70"}]}, { "name": "10 Username with 0x007F", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F707F70"}]}, { "name": "10 Username with 0x009F", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746FC29F70"}]}, { "name": "10 Username with 0xFFFF", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746FEDBFBF"}]}, { "name": "10 Username zero length ok", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 04 82 k10 s1 'p' s0"}]}, { "name": "10 Username flag 1 Password flag 1 ok", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 04 C2 k10 s1 'p' s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-20]", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 04 82 k10 s1 'p' s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-21]", "msgs":[{"type":"send", "payload":"10 r16 s4 'MQTT' 04 C2 k10 s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-22]", "msgs":[{"type":"send", "payload":"10 r16 s4 'MQTT' 04 42 k10 s1 'p' s1 'p'"}]}, { "name": "10 Password with 0x0000", "msgs":[{"type":"send", "payload":"10 r23 s4 'MQTT' 04 C2 k10 s1 'p' s1 'p' s5 746F700000"}]}, { "name": "NanoMQ CWE-119", "msgs":[{"type":"send", "payload":"10 r7 s4 'MQTT' 04 C2 k60 s11 746573742D707974686F6E s5 61646d696E s8 70617373776F7264"}]} ] }, { "group": "v3.1.1 CONNECT instead of CONNACK", "ver":4, "connack":false, "tests": [ { "name": "10 ok ", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 02 k10 s1 'p'", "comment":"minimal valid CONNECT"}]}, { "name": "10 missing client ID", "msgs":[{"type":"send", "payload":"10 r8 s4 'MQTT' 04 02 k10"}]}, { "name": "10 empty client ID", "msgs":[{"type":"send", "payload":"10 r12 s4 'MQTT' 04 02 k10 s0", "comment":"CONNECT clean session true, no client id"}]}, { "name": "10 empty client ID clean false [MQTT-3.1.3-7]", "msgs":[{"type":"send", "payload":"10 r12 s4 'MQTT' 04 02 k10 s0", "comment":"CONNECT clean session false, no client id"}]}, { "name": "10 proto ver 2 [MQTT-3.1.2-2]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 02 02 k10 s1 'p'", "comment":"CONNECT"}]}, { "name": "10 proto ver 6 [MQTT-3.1.2-2]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 06 02 k10 s1 'p'", "comment":"CONNECT"}]}, { "name": "10 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"10 FFFFFFFF7F s4 'MQTT' 05 02 k10 s1 'p'", "comment":"CONNECT"}]}, { "name": "11", "msgs":[{"type":"send", "payload":"11 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "12", "msgs":[{"type":"send", "payload":"12 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "14", "msgs":[{"type":"send", "payload":"14 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "18", "msgs":[{"type":"send", "payload":"18 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "10 short proto", "msgs":[{"type":"send", "payload":"10 r12 s3 'MQT' 04 02 k10 s1 'p'"}]}, { "name": "10 zero proto", "msgs":[{"type":"send", "payload":"10 r9 s0 04 02 k10 s1 'p'"}]}, { "name": "10 long proto", "msgs":[{"type":"send", "payload":"10 r14 s5 'MQTTT' 04 02 k10 s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-1]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 02 k10 s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-3] ", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 01 k10 s1 'p'"}]}, { "name": "10 Will flag 0 Will QoS 1 [MQTT-3.1.2-11]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 0A k10 s1 'p'"}]}, { "name": "10 Will flag 0 Will retain 1 [MQTT-3.1.2-11]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 12 k10 s1 'p'"}]}, { "name": "10 Will flag 1 no Will topic no Will message [MQTT-3.1.2-9]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 06 k10 s1 'p'"}]}, { "name": "10 Will flag 1 no Will topic [MQTT-3.1.2-9]", "msgs":[{"type":"send", "payload":"10 r16 s4 'MQTT' 04 06 k10 s1 'p' s1 'p'"}]}, { "name": "10 Will flag 1 ok", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 04 06 k10 s1 'p' s1 'p' s1 'p'"}]}, { "name": "10 Will flag 1 Will Qos 3 [MQTT-3.1.2-14]", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 04 1E k10 s1 'p' s1 'p' s1 'p'"}]}, { "name": "10 Will topic with 0x0000", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F700000 s1 'p'"}]}, { "name": "10 Will topic with U+D800", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746FEDA080 s1 'p'"}]}, { "name": "10 Will topic with U+0001", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F700170 s1 'p'"}]}, { "name": "10 Will topic with U+001F", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F701F70 s1 'p'"}]}, { "name": "10 Will topic with U+007F", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746F707F70 s1 'p'"}]}, { "name": "10 Will topic with U+009F", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746FC29F70 s1 'p'"}]}, { "name": "10 Will topic with U+FFFF", "msgs": [{"type":"send", "payload":"10 r23 s4 'MQTT' 04 06 k10 s1 'p' s5 746FEDBFBF s1 'p'"}]}, { "name": "10 Client ID with 0x0000", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F700000"}]}, { "name": "10 Client ID with U+D800", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746FEDA080"}]}, { "name": "10 Client ID with U+0001", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F700170"}]}, { "name": "10 Client ID with U+001F", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F701F70"}]}, { "name": "10 Client ID with U+007F", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746F707F70"}]}, { "name": "10 Client ID with U+009F", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746FC29F70"}]}, { "name": "10 Client ID with U+FFFF", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 04 02 k10 s5 746FEDBFBF"}]}, { "name": "10 [MQTT-3.1.2-18]", "msgs":[{"type":"send", "payload":"10 r16 s4 'MQTT' 04 02 k10 s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-19]", "msgs":[{"type":"send", "payload":"10 r13 s4 'MQTT' 04 82 k10 s1 'p'"}]}, { "name": "10 Username with 0x0000", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F700000"}]}, { "name": "10 Username with 0xD800", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746FEDA080"}]}, { "name": "10 Username with 0x0001", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F700170"}]}, { "name": "10 Username with 0x001F", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F701F70"}]}, { "name": "10 Username with 0x007F", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746F707F70"}]}, { "name": "10 Username with 0x009F", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746FC29F70"}]}, { "name": "10 Username with 0xFFFF", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 04 82 k10 s1 'p' s5 746FEDBFBF"}]}, { "name": "10 Username zero length ok", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 04 82 k10 s1 'p' 0000"}]}, { "name": "10 Username flag 1 Password flag 1 ok", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 04 C2 k10 s1 'p' s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-20]", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 04 82 k10 s1 'p' s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-21]", "msgs":[{"type":"send", "payload":"10 r16 s4 'MQTT' 04 C2 k10 s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-22]", "msgs":[{"type":"send", "payload":"10 r16 s4 'MQTT' 04 42 k10 s1 'p' s1 'p'"}]}, { "name": "10 Password with 0x0000", "msgs":[{"type":"send", "payload":"10 r23 s4 'MQTT' 04 C2 k10 s1 'p' s1 'p' s5 746F700000"}]}, { "name": "NanoMQ CWE-119", "msgs":[{"type":"send", "payload":"10 r7 s4 'MQTT' 04 C2 003C 000B 746573742D707974686F6E s5 61646d696E s8 70617373776F7264"}]} ] }, { "group": "v5.0 CONNECT", "ver":5, "tests": [ { "name": "10 ok ", "msgs":[{"type":"send", "payload":"10 r14 s4 'MQTT' 05 02 k10 00 s1 'p'", "comment":"minimal valid CONNECT"}]}, { "name": "10 Username flag 1 ok", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 82 k10 00 s1 'p' s1 'p'"}]}, { "name": "10 Client ID with 0x0000", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746F700000"}]}, { "name": "10 Client ID with U+D800", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746FEDA080"}]}, { "name": "10 Client ID with U+0001", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746F700170"}]}, { "name": "10 Client ID with U+001F", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746F701F70"}]}, { "name": "10 Client ID with U+007F", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746F707F70"}]}, { "name": "10 Client ID with U+009F", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746FC29F70"}]}, { "name": "10 Client ID with U+FFFF", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746FEDBFBF"}]}, { "name": "10 [MQTT-3.1.2-16]", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 00 0001 71 0001 71"}]}, { "name": "10 [MQTT-3.1.2-17]", "msgs":[{"type":"send", "payload":"10 r14 s4 'MQTT' 05 82 k10 00 s1 'p'"}]}, { "name": "10 Username with 0x0000", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746F700000"}]}, { "name": "10 Username with 0xD800", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746FEDA080"}]}, { "name": "10 Username with 0x0001", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746F700170"}]}, { "name": "10 Username with 0x001F", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746F701F70"}]}, { "name": "10 Username with 0x007F", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746F707F70"}]}, { "name": "10 Username with 0x009F", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746FC29F70"}]}, { "name": "10 Username with 0xFFFF", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746FEDBFBF"}]}, { "name": "10 [MQTT-3.1.2-18]", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 05 82 k10 00 s1 'p' s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-19]", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 C2 k10 00 s1 'p' s1 'p'"}]}, { "name": "10 Will flag 1 ok", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 06 k10 00 s1 'p' 00 s1 'p' s1 'p'"}]}, { "name": "tiny max packet", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 2700000002 s1 'p'"}]} ] }, { "group": "v5.0 CONNECT instead of CONNACK", "ver":5, "connack":false, "tests": [ { "name": "10 ok ", "msgs":[{"type":"send", "payload":"10 r14 s4 'MQTT' 05 02 k10 00 s1 'p'", "comment":"minimal valid CONNECT"}]}, { "name": "10 Username flag 1 ok", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 82 k10 00 s1 'p' s1 'p'"}]}, { "name": "10 Client ID with 0x0000", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746F700000"}]}, { "name": "10 Client ID with U+D800", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746FEDA080"}]}, { "name": "10 Client ID with U+0001", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746F700170"}]}, { "name": "10 Client ID with U+001F", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746F701F70"}]}, { "name": "10 Client ID with U+007F", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746F707F70"}]}, { "name": "10 Client ID with U+009F", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746FC29F70"}]}, { "name": "10 Client ID with U+FFFF", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 00 s5 746FEDBFBF"}]}, { "name": "10 [MQTT-3.1.2-16]", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 00 0001 71 0001 71"}]}, { "name": "10 [MQTT-3.1.2-17]", "msgs":[{"type":"send", "payload":"10 r14 s4 'MQTT' 05 82 k10 00 s1 'p'"}]}, { "name": "10 Username with 0x0000", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746F700000"}]}, { "name": "10 Username with 0xD800", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746FEDA080"}]}, { "name": "10 Username with 0x0001", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746F700170"}]}, { "name": "10 Username with 0x001F", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746F701F70"}]}, { "name": "10 Username with 0x007F", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746F707F70"}]}, { "name": "10 Username with 0x009F", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746FC29F70"}]}, { "name": "10 Username with 0xFFFF", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 82 k10 00 s1 'p' s5 746FEDBFBF"}]}, { "name": "10 [MQTT-3.1.2-18]", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 05 82 k10 00 s1 'p' s1 'p' s1 'p'"}]}, { "name": "10 [MQTT-3.1.2-19]", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 C2 k10 00 s1 'p' s1 'p'"}]}, { "name": "10 Will flag 1 ok", "msgs":[{"type":"send", "payload":"10 r21 s4 'MQTT' 05 06 k10 00 s1 'p' 00 s1 'p' s1 'p'"}]}, { "name": "tiny max packet", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 2700000002 s1 'p'"}]} ] }, { "group": "v5.0 CONNECT EXTENDED AUTH", "ver":5, "tests": [ { "name": "unsupported authentication method", "msgs":[ {"type":"send", "payload":"10 r35 s4 'MQTT' 05 02 k10 15 15000B756E737570706F7274656416000474657374 s1 'p'", "comment":"auth-method:unsupported, auth-data:test"} ]} ] }, { "group": "v5.0 CONNECT ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "session-expiry-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 11 L1 s1 'p'"}]}, { "name": "2*session-expiry-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 02 k10 0A 11 L1 11 L1 s1 'p'"}]}, { "name": "session-expiry-interval (four byte integer) missing", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 11 s1 'p'"}]}, { "name": "receive-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 21 0101 s1 'p'"}]}, { "name": "receive-maximum (two byte integer) 0 value", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 21 H0 s1 'p'"}]}, { "name": "2*receive-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 21 0101 21 0101 s1 'p'"}]}, { "name": "receive-maximum (two byte integer) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 21 s1 'p'"}]}, { "name": "maximum-packet-size (four byte integer)", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 27 10000001 s1 'p'"}]}, { "name": "2*maximum-packet-size (four byte integer)", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 02 k10 0A 27 10000001 27 10000001 s1 'p'"}]}, { "name": "maximum-packet-size (four byte integer) missing", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 27 s1 'p'"}]}, { "name": "maximum-packet-size (four byte integer) 0 value", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 27 L0 s1 'p'"}]}, { "name": "maximum-packet-size (four byte integer) FFFFFFFF value", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 27 FFFFFFFF s1 'p'"}]}, { "name": "topic-alias-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 22 0101 s1 'p'"}]}, { "name": "topic-alias-maximum (two byte integer) 0 value", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 22 H0 s1 'p'"}]}, { "name": "2*topic-alias-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 22 0101 22 0101 s1 'p'"}]}, { "name": "topic-alias-maximum (two byte integer) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 22 s1 'p'"}]}, { "name": "request-response-information (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 19 01 s1 'p'"}]}, { "name": "2*request-response-information (byte)", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 19 01 19 01 s1 'p'"}]}, { "name": "request-response-information (byte) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 19 s1 'p'"}]}, { "name": "request-response-information (byte) 2 value", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 19 02 s1 'p'"}]}, { "name": "request-problem-information (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 17 01 s1 'p'"}]}, { "name": "2*request-problem-information (byte)", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 17 01 17 01 s1 'p'"}]}, { "name": "request-problem-information (byte) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 17 s1 'p'"}]}, { "name": "request-problem-information (byte) 2 value", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 17 02 s1 'p'"}]}, { "name": "user-property", "msgs": [{"type":"send", "payload":"10 r21 s4 'MQTT' 05 02 k10 07 26 s1 'p' s1 'p' s1 'p'"}]}, { "name": "2*user-property", "msgs": [{"type":"send", "payload":"10 r28 s4 'MQTT' 05 02 k10 0E 26 s1 'p' s1 'p' 26 s1 'p' s1 'p' s1 'p'"}]}, { "name": "user-property missing value", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 26 s1 'p' s1 'p'"}]}, { "name": "user-property missing key,value", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 26 s1 'p'"}]}, { "name": "user-property empty key", "msgs": [{"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 26 s0 s1 'p' s1 'p'"}]}, { "name": "user-property empty value", "msgs": [{"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 26 s1 'p' s0 s1 'p'"}]}, { "name": "user-property empty key,value", "msgs": [{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 26 s0 s0 s1 'p'"}]}, { "name": "authentication-method (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 15 s1 'p'"}]}, { "name": "2*authentication-method (UTF-8 string)", "msgs": [{"type":"send", "payload":"10 r22 s4 'MQTT' 05 02 k10 08 15 s1 'p' 15 s1 'p' s1 'p'"}]}, { "name": "authentication-data (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 15 s1 'p' 16 s1 'p'"}]}, { "name": "authentication-data (UTF-8 string) no authentication-method", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 16 s1 'p' s1 'p'"}]}, { "name": "2*authentication-data (UTF-8 string)", "msgs": [{"type":"send", "payload":"10 r26 s4 'MQTT' 05 02 k10 0C 15 s1 'p' 16 s1 'p' 16 s1 'p' s1 'p'"}]} ] }, { "group": "v5.0 CONNECT DISALLOWED PROPERTIES", "ver":5, "connect":false, "tests": [ { "name": "payload-format-indicator (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 01 01 s1 'p'"}]}, { "name": "payload-format-indicator (byte) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 01 s1 'p'"}]}, { "name": "maximum-qos (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 24 01 s1 'p'"}]}, { "name": "maximum-qos (byte) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 24 01 s1 'p'"}]}, { "name": "retain-available (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 25 01 s1 'p'"}]}, { "name": "retain-available (byte) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 25 01 s1 'p'"}]}, { "name": "wildcard-subscription-available (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 28 01 s1 'p'"}]}, { "name": "wildcard-subscription-available (byte) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 28 01 s1 'p'"}]}, { "name": "subscription-identifier-available (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 29 01 s1 'p'"}]}, { "name": "subscription-identifier-available (byte) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 29 01 s1 'p'"}]}, { "name": "shared-subscription-available (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 2A 01 s1 'p'"}]}, { "name": "shared-subscription-available (byte) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 2A 01 s1 'p'"}]}, { "name": "invalid-property 0x00 (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 00 01 s1 'p'"}]}, { "name": "unknown-property 0x04 (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 04 01 s1 'p'"}]}, { "name": "unknown-property 0x05 (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 05 01 s1 'p'"}]}, { "name": "unknown-property 0x06 (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 06 01 s1 'p'"}]}, { "name": "unknown-property 0x07 (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 07 01 s1 'p'"}]}, { "name": "unknown-property 0x0A (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0A 01 s1 'p'"}]}, { "name": "unknown-property 0x0C (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0C 01 s1 'p'"}]}, { "name": "unknown-property 0x0D (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0D 01 s1 'p'"}]}, { "name": "unknown-property 0x0E (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0E 01 s1 'p'"}]}, { "name": "unknown-property 0x0F (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0F 01 s1 'p'"}]}, { "name": "unknown-property 0x10 (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 10 01 s1 'p'"}]}, { "name": "unknown-property 0x14 (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 14 01 s1 'p'"}]}, { "name": "unknown-property 0x1B (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 1B 01 s1 'p'"}]}, { "name": "unknown-property 0x1D (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 1D 01 s1 'p'"}]}, { "name": "unknown-property 0x1E (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 1E 01 s1 'p'"}]}, { "name": "unknown-property 0x20 (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 20 01 s1 'p'"}]}, { "name": "unknown-property 0x7F (byte)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 7F 01 s1 'p'"}]}, { "name": "invalid-property 0x8000 (byte)", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 8000 01 s1 'p'"}]}, { "name": "unknown-property 0x8001 (byte)", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 8001 01 s1 'p'"}]}, { "name": "unknown-property 0xFF7F (byte)", "msgs": [{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 FF7F 01 s1 'p'"}]}, { "name": "unknown-property 0x808001 (byte)", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 808001 01 s1 'p'"}]}, { "name": "unknown-property 0xFFFF7F (byte)", "msgs": [{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 FFFF7F 01 s1 'p'"}]}, { "name": "unknown-property 0x80808001 (byte)", "msgs": [{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 80808001 01 s1 'p'"}]}, { "name": "unknown-property 0xFFFFFF7F (byte)", "msgs": [{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 FFFFFF7F 01 s1 'p'"}]}, { "name": "unknown-property 0x8080808001 (byte)", "msgs": [{"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 8080808001 01 s1 'p'"}]}, { "name": "message-expiry-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 02 10000001 s1 'p'"}]}, { "name": "2*message-expiry-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 02 k10 0A 02 10000001 02 10000001 s1 'p'"}]}, { "name": "message-expiry-interval (four byte integer) missing", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 02 s1 'p'"}]}, { "name": "message-expiry-interval (four byte integer) 0 value", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 02 L0 s1 'p'"}]}, { "name": "message-expiry-interval (four byte integer) FFFFFFFF value", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 02 FFFFFFFF s1 'p'"}]}, { "name": "will-delay-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 18 10000001 s1 'p'"}]}, { "name": "2*will-delay-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 02 k10 0A 18 10000001 18 10000001 s1 'p'"}]}, { "name": "will-delay-interval (four byte integer) missing", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 18 s1 'p'"}]}, { "name": "will-delay-interval (four byte integer) 0 value", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 18 L0 s1 'p'"}]}, { "name": "will-delay-interval (four byte integer) FFFFFFFF value", "msgs":[{"type":"send", "payload":"10 r19 s4 'MQTT' 05 02 k10 05 18 FFFFFFFF s1 'p'"}]}, { "name": "server-keep-alive (two byte integer)", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 13 0001 s1 'p'"}]}, { "name": "2*server-keep-alive (two byte integer)", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 13 0001 13 0001 s1 'p'"}]}, { "name": "server-keep-alive (two byte integer) missing", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 13 s1 'p'"}]}, { "name": "topic-alias (two byte integer)", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 23 0001 s1 'p'"}]}, { "name": "2*topic-alias (two byte integer)", "msgs":[{"type":"send", "payload":"10 r20 s4 'MQTT' 05 02 k10 06 23 0001 23 0001 s1 'p'"}]}, { "name": "topic-alias (two byte integer) missing", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 23 s1 'p'"}]}, { "name": "content-type (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 03 s1 'p' s1 'p'"}]}, { "name": "content-type (UTF-8 string) missing", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 03 s1 'p'"}]}, { "name": "content-type (UTF-8 string) empty", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 03 s0 s1 'p'"}]}, { "name": "response-topic (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 08 s1 'p' s1 'p'"}]}, { "name": "response-topic (UTF-8 string) missing", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 08 s1 'p'"}]}, { "name": "response-topic (UTF-8 string) empty", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 08 s0 s1 'p'"}]}, { "name": "assigned-client-identifier (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 12 s1 'p' s1 'p'"}]}, { "name": "assigned-client-identifier (UTF-8 string) missing", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 12 s1 'p'"}]}, { "name": "assigned-client-identifier (UTF-8 string) empty", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 12 s0 s1 'p'"}]}, { "name": "response-information (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 1A s1 'p' s1 'p'"}]}, { "name": "response-information (UTF-8 string) missing", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 1A s1 'p'"}]}, { "name": "response-information (UTF-8 string) empty", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 1A s0 s1 'p'"}]}, { "name": "correlation-data (binary)", "msgs":[{"type":"send", "payload":"10 r18 s4 'MQTT' 05 02 k10 04 09 s1 'p' s1 'p'"}]}, { "name": "correlation-data (binary) missing", "msgs":[{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 09 s1 'p'"}]}, { "name": "correlation-data (binary) empty", "msgs":[{"type":"send", "payload":"10 r17 s4 'MQTT' 05 02 k10 03 09 s0 s1 'p'"}]}, {"name": "subscription-identifier (variable byte integer)", "msgs": [{"type":"send", "payload":"10 r16 s4 'MQTT' 05 02 k10 02 0B 01 s1 'p'"}]}, {"name": "subscription-identifier (variable byte integer) missing", "msgs": [{"type":"send", "payload":"10 r15 s4 'MQTT' 05 02 k10 01 0B s1 'p'"}]} ] }, { "group": "v5.0 WILL ALLOWED PROPERTIES", "ver":5, "connect":false, "tests": [ { "name": "payload-format-indicator (byte)", "msgs":[{"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 00 s1 'p' 02 01 01 s1 'p' s1 'p'"}]}, { "name": "payload-format-indicator (byte) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 01 s1 'p' s1 'p'"}]}, { "name": "2*payload-format-indicator (byte)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 01 01 01 01 s1 'p' s1 'p'"}]}, { "name": "message-expiry-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r26 s4 'MQTT' 05 06 k10 00 s1 'p' 05 02 L1 s1 'p' s1 'p'"}]}, { "name": "2*message-expiry-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r31 s4 'MQTT' 05 06 k10 00 s1 'p' 0A 02 L1 02 L1 s1 'p' s1 'p'"}]}, { "name": "message-expiry-interval (four byte integer) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 02 s1 'p' s1 'p'"}]}, { "name": "will-delay-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r26 s4 'MQTT' 05 06 k10 00 s1 'p' 05 18 L1 s1 'p' s1 'p'"}]}, { "name": "will-delay-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r31 s4 'MQTT' 05 06 k10 00 s1 'p' 0A 18 L1 18 L1 s1 'p' s1 'p'"}]}, { "name": "will-delay-interval (four byte integer) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 18 s1 'p' s1 'p'"}]}, { "name": "content-type (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 03 s1 'p' s1 'p' s1 'p'"}]}, { "name": "2*content-type (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 00 s1 'p' 08 03 s1 'p' 03 s1 'p' s1 'p' s1 'p'"}]}, { "name": "content-type (UTF-8 string) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 03 s1 'p' s1 'p'"}]}, { "name": "content-type (UTF-8 string) empty", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 03 s0 s1 'p' s1 'p'"}]}, { "name": "response-topic (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 08 s1 'p' s1 'p' s1 'p'"}]}, { "name": "2*response-topic (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 00 s1 'p' 08 08 s1 'p' 08 s1 'p' s1 'p' s1 'p'"}]}, { "name": "response-topic (UTF-8 string) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 08 s1 'p' s1 'p'"}]}, { "name": "response-topic (UTF-8 string) empty", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 08 s0 s1 'p' s1 'p'"}]}, { "name": "correlation-data (binary)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 09 s1 'p' s1 'p' s1 'p'"}]}, { "name": "2*correlation-data (binary)", "msgs":[{"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 00 s1 'p' 08 09 s1 'p' 09 s1 'p' s1 'p' s1 'p'"}]}, { "name": "correlation-data (binary) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 09 s1 'p' s1 'p'"}]}, { "name": "correlation-data (binary) empty", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 09 s0 s1 'p' s1 'p'"}]}, { "name": "user-property", "msgs":[{"type":"send", "payload":"10 r28 s4 'MQTT' 05 06 k10 00 s1 'p' 07 26 s1 'p' s1 'p' s1 'p' s1 'p'"}]}, { "name": "2*user-property", "msgs":[{"type":"send", "payload":"10 r35 s4 'MQTT' 05 06 k10 00 s1 'p' 0E 26 s1 'p' s1 'p' 26 s1 'p' s1 'p' s1 'p' s1 'p'"}]}, { "name": "user-property missing value", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 26 s1 'p' s1 'p' s1 'p'"}]}, { "name": "user-property missing key,value", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 26 s1 'p' s1 'p'"}]}, { "name": "user-property empty key", "msgs":[{"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 00 s1 'p' 06 26 s0 s1 'p' s1 'p' s1 'p'"}]}, { "name": "user-property empty value", "msgs":[{"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 00 s1 'p' 06 26 s1 'p' s0 s1 'p' s1 'p'"}]}, { "name": "user-property empty key,value", "msgs":[{"type":"send", "payload":"10 r26 s4 'MQTT' 05 06 k10 00 s1 'p' 05 26 s0 s0 s1 'p' s1 'p'"}]} ] }, { "group": "v5.0 WILL DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "request-problem-information (byte)", "msgs":[{"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 00 s1 'p' 02 17 01 s1 'p' s1 'p'"}]}, { "name": "request-problem-information (byte) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 17 s1 'p' s1 'p'"}]}, { "name": "2*request-problem-information (byte)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 17 01 17 01 s1 'p' s1 'p'"}]}, { "name": "request-response-information (byte)", "msgs":[{"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 00 s1 'p' 02 19 01 s1 'p' s1 'p'"}]}, { "name": "request-response-information (byte) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 19 s1 'p' s1 'p'"}]}, { "name": "2*request-response-information (byte)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 19 01 19 01 s1 'p' s1 'p'"}]}, { "name": "maximum-qos (byte)", "msgs":[{"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 00 s1 'p' 02 24 01 s1 'p' s1 'p'"}]}, { "name": "maximum-qos (byte) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 24 s1 'p' s1 'p'"}]}, { "name": "2*maximum-qos (byte)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 24 01 24 01 s1 'p' s1 'p'"}]}, { "name": "retain-available (byte)", "msgs":[{"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 00 s1 'p' 02 25 01 s1 'p' s1 'p'"}]}, { "name": "retain-available (byte) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 25 s1 'p' s1 'p'"}]}, { "name": "2*retain-available (byte)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 25 01 25 01 s1 'p' s1 'p'"}]}, { "name": "wildcard-subscription-available (byte)", "msgs":[{"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 00 s1 'p' 02 28 01 s1 'p' s1 'p'"}]}, { "name": "wildcard-subscription-available (byte) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 28 s1 'p' s1 'p'"}]}, { "name": "2*wildcard-subscription-available (byte)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 28 01 28 01 s1 'p' s1 'p'"}]}, { "name": "subscription-identifier-available (byte)", "msgs":[{"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 00 s1 'p' 02 29 01 s1 'p' s1 'p'"}]}, { "name": "subscription-identifier-available (byte) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 29 s1 'p' s1 'p'"}]}, { "name": "2*subscription-identifier-available (byte)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 29 01 29 01 s1 'p' s1 'p'"}]}, { "name": "shared-subscription-available (byte)", "msgs":[{"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 00 s1 'p' 02 2A 01 s1 'p' s1 'p'"}]}, { "name": "shared-subscription-available (byte) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 2A s1 'p' s1 'p'"}]}, { "name": "2*shared-subscription-available (byte)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 2A 01 2A 01 s1 'p' s1 'p'"}]}, { "name": "server-keep-alive (two byte integer)", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 13 0001 s1 'p' s1 'p'"}]}, { "name": "server-keep-alive (two byte integer) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 13 s1 'p' s1 'p'"}]}, { "name": "2*server-keep-alive (two byte integer)", "msgs":[{"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 00 s1 'p' 06 13 0001 13 0001 s1 'p' s1 'p'"}]}, { "name": "receive-maximum (two byte integer)", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 21 0001 s1 'p' s1 'p'"}]}, { "name": "receive-maximum (two byte integer) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 21 s1 'p' s1 'p'"}]}, { "name": "2*receive-maximum (two byte integer)", "msgs":[{"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 00 s1 'p' 06 21 0001 21 0001 s1 'p' s1 'p'"}]}, { "name": "topic-alias-maximum (two byte integer)", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 22 0001 s1 'p' s1 'p'"}]}, { "name": "topic-alias-maximum (two byte integer) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 22 s1 'p' s1 'p'"}]}, { "name": "2*topic-alias-maximum (two byte integer)", "msgs":[{"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 00 s1 'p' 06 22 0001 22 0001 s1 'p' s1 'p'"}]}, { "name": "topic-alias (two byte integer)", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 23 0001 s1 'p' s1 'p'"}]}, { "name": "topic-alias (two byte integer) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 23 s1 'p' s1 'p'"}]}, { "name": "2*topic-alias (two byte integer)", "msgs":[{"type":"send", "payload":"10 r27 s4 'MQTT' 05 06 k10 00 s1 'p' 06 23 0001 23 0001 s1 'p' s1 'p'"}]}, { "name": "session-expiry-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r26 s4 'MQTT' 05 06 k10 00 s1 'p' 05 11 L1 s1 'p' s1 'p'"}]}, { "name": "session-expiry-interval (four byte integer) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 11 s1 'p' s1 'p'"}]}, { "name": "2*session-expiry-interval (four byte integer)", "msgs":[{"type":"send", "payload":"10 r31 s4 'MQTT' 05 06 k10 00 s1 'p' 0A 11 L1 11 L1 s1 'p' s1 'p'"}]}, { "name": "maximum-packet-size (four byte integer)", "msgs":[{"type":"send", "payload":"10 r26 s4 'MQTT' 05 06 k10 00 s1 'p' 05 27 L1 s1 'p' s1 'p'"}]}, { "name": "maximum-packet-size (four byte integer) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 27 s1 'p' s1 'p'"}]}, { "name": "2*maximum-packet-size (four byte integer)", "msgs":[{"type":"send", "payload":"10 r31 s4 'MQTT' 05 06 k10 00 s1 'p' 0A 27 L1 27 L1 s1 'p' s1 'p'"}]}, { "name": "assigned-client-identifier (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 12 s1 'p' s1 'p' s1 'p'"}]}, { "name": "2*assigned-client-identifier (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 00 s1 'p' 08 12 s1 'p' 12 s1 'p' s1 'p' s1 'p'"}]}, { "name": "assigned-client-identifier (UTF-8 string) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 12 s1 'p' s1 'p'"}]}, { "name": "assigned-client-identifier (UTF-8 string) empty", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 12 s0 s1 'p' s1 'p'"}]}, { "name": "authentication-method (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 15 s1 'p' s1 'p' s1 'p'"}]}, { "name": "2*authentication-method (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 00 s1 'p' 08 15 s1 'p' 15 s1 'p' s1 'p' s1 'p'"}]}, { "name": "authentication-method (UTF-8 string) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 15 s1 'p' s1 'p'"}]}, { "name": "authentication-method (UTF-8 string) empty", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 15 s0 s1 'p' s1 'p'"}]}, { "name": "response-information (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 1A s1 'p' s1 'p' s1 'p'"}]}, { "name": "2*response-information (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 00 s1 'p' 08 1A s1 'p' 1A s1 'p' s1 'p' s1 'p'"}]}, { "name": "response-information (UTF-8 string) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 1A s1 'p' s1 'p'"}]}, { "name": "response-information (UTF-8 string) empty", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 1A s0 s1 'p' s1 'p'"}]}, { "name": "server-reference (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 1C s1 'p' s1 'p' s1 'p'"}]}, { "name": "2*server-reference (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 00 s1 'p' 08 1C s1 'p' 1C s1 'p' s1 'p' s1 'p'"}]}, { "name": "server-reference (UTF-8 string) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 1C s1 'p' s1 'p'"}]}, { "name": "server-reference (UTF-8 string) empty", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 1C s0 s1 'p' s1 'p'"}]}, { "name": "reason-string (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 1F s1 'p' s1 'p' s1 'p'"}]}, { "name": "2*reason-string (UTF-8 string)", "msgs":[{"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 00 s1 'p' 08 1F s1 'p' 1F s1 'p' s1 'p' s1 'p'"}]}, { "name": "reason-string (UTF-8 string) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 1F s1 'p' s1 'p'"}]}, { "name": "reason-string (UTF-8 string) empty", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 1F s0 s1 'p' s1 'p'"}]}, { "name": "authentication-data (binary)", "msgs":[{"type":"send", "payload":"10 r25 s4 'MQTT' 05 06 k10 00 s1 'p' 04 16 s1 'p' s1 'p' s1 'p'"}]}, { "name": "2*authentication-data (binary)", "msgs":[{"type":"send", "payload":"10 r29 s4 'MQTT' 05 06 k10 00 s1 'p' 08 16 s1 'p' 16 s1 'p' s1 'p' s1 'p'"}]}, { "name": "authentication-data (binary) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 16 s1 'p' s1 'p'"}]}, { "name": "authentication-data (binary) empty", "msgs":[{"type":"send", "payload":"10 r24 s4 'MQTT' 05 06 k10 00 s1 'p' 03 16 s0 s1 'p' s1 'p'"}]}, { "name": "subscription-identifier (variable byte integer)", "msgs":[{"type":"send", "payload":"10 r23 s4 'MQTT' 05 06 k10 00 s1 'p' 02 0B 01 s1 'p' s1 'p'"}]}, { "name": "subscription-identifier (variable byte integer) missing", "msgs":[{"type":"send", "payload":"10 r22 s4 'MQTT' 05 06 k10 00 s1 'p' 01 0B s1 'p' s1 'p'"}]} ] } ] ================================================ FILE: test/lib/data/DISCONNECT.json ================================================ [ { "group": "v3.1.1 DISCONNECT", "ver":4, "tests": [ { "name": "E0 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"E0 r0"}]}, { "name": "E0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"E0 r268435456"}]}, { "name": "E0 long", "msgs": [{"type":"send", "payload":"E0 r1 00"}]}, { "name": "E0 valid", "msgs": [{"type":"send", "payload":"E0 r0"}]}, { "name": "E1 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E1 r0"}]}, { "name": "E2 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E2 r0"}]}, { "name": "E4 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E4 r0"}]}, { "name": "E8 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E8 r0"}]} ] }, { "group": "v5.0 DISCONNECT", "ver":5, "tests": [ { "name": "E0 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"E0 r0"}]}, { "name": "E0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"E0 r268435456"}]}, { "name": "E0 long", "msgs": [{"type":"send", "payload":"E0 r1 00"}]}, { "name": "E0 valid", "msgs": [{"type":"send", "payload":"E0 r0"}]}, { "name": "E1 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E1 r0"}]}, { "name": "E2 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E2 r0"}]}, { "name": "E4 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E4 r0"}]}, { "name": "E8 [MQTT-3.14.1-1]", "msgs": [{"type":"send", "payload":"E8 r0"}]}, { "name": "E0 RC=0x00 (normal disconnection)", "msgs": [{"type":"send", "payload":"E0 r1 00"}]}, { "name": "E0 RC=0x01 (qos 1 - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 01"}]}, { "name": "E0 RC=0x04 (disconnect with will)", "msgs": [{"type":"send", "payload":"E0 r1 04"}]}, { "name": "E0 RC=0x05 (invalid)", "msgs": [{"type":"send", "payload":"E0 r1 05"}]}, { "name": "E0 RC=0x80 (unspecified error)", "msgs": [{"type":"send", "payload":"E0 r1 80"}]}, { "name": "E0 RC=0x81 (malformed packet)", "msgs": [{"type":"send", "payload":"E0 r1 81"}]}, { "name": "E0 RC=0x82 (protocol error)", "msgs": [{"type":"send", "payload":"E0 r1 82"}]}, { "name": "E0 RC=0x83 (implementation specific error)", "msgs": [{"type":"send", "payload":"E0 r1 83"}]}, { "name": "E0 RC=0x87 (not authorised - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 87"}]}, { "name": "E0 RC=0x89 (server busy - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 89"}]}, { "name": "E0 RC=0x8B (server shutting down - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 8B"}]}, { "name": "E0 RC=0x8D (keep alive timeout - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 8D"}]}, { "name": "E0 RC=0x8E (session taken over - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 8E"}]}, { "name": "E0 RC=0x8F (topic filter invalid - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 8F"}]}, { "name": "E0 RC=0x90 (topic name invalid)", "msgs": [{"type":"send", "payload":"E0 r1 90"}]}, { "name": "E0 RC=0x93 (receive maximum exceeded)", "msgs": [{"type":"send", "payload":"E0 r1 93"}]}, { "name": "E0 RC=0x94 (topic alias invalid)", "msgs": [{"type":"send", "payload":"E0 r1 94"}]}, { "name": "E0 RC=0x95 (packet too large)", "msgs": [{"type":"send", "payload":"E0 r1 95"}]}, { "name": "E0 RC=0x96 (message rate too high)", "msgs": [{"type":"send", "payload":"E0 r1 96"}]}, { "name": "E0 RC=0x97 (quota exceeded)", "msgs": [{"type":"send", "payload":"E0 r1 97"}]}, { "name": "E0 RC=0x98 (administrative action)", "msgs": [{"type":"send", "payload":"E0 r1 98"}]}, { "name": "E0 RC=0x99 (payload format invalid)", "msgs": [{"type":"send", "payload":"E0 r1 99"}]}, { "name": "E0 RC=0x9A (retain not supported - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9A"}]}, { "name": "E0 RC=0x9B (qos not supported - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9B"}]}, { "name": "E0 RC=0x9C (use another server - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9C"}]}, { "name": "E0 RC=0x9D (server moved - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9D"}]}, { "name": "E0 RC=0x9E (shared subs not supported - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9E"}]}, { "name": "E0 RC=0x9F (connection rate exceeded - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 9F"}]}, { "name": "E0 RC=0xA0 (maximum connect time - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 A0"}]}, { "name": "E0 RC=0xA1 (subscription ids not supported - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 A1"}]}, { "name": "E0 RC=0xA2 (wildcard subs not supported - invalid)", "msgs": [{"type":"send", "payload":"E0 r1 A2"}]}, { "name": "E0 RC=0x82 PL=0", "msgs": [{"type":"send", "payload":"E0 r2 82 00"}]}, { "name": "E0 RC=0x00 PL=1 P=0", "msgs": [{"type":"send", "payload":"E0 r3 00 01 00"}]}, { "name": "E0 RC=0x00 PL=1 P=0x11", "msgs": [{"type":"send", "payload":"E0 r3 00 01 11"}]}, { "name": "E0 RC=0x00 PL=2 P=0x11", "msgs": [{"type":"send", "payload":"E0 r4 00 02 1100"}]}, { "name": "E0 RC=0x00 PL=3 P=0x11", "msgs": [{"type":"send", "payload":"E0 r5 00 03 110000"}]}, { "name": "E0 RC=0x00 PL=4 P=0x11", "msgs": [{"type":"send", "payload":"E0 r6 00 04 11000000"}]}, { "name": "E0 RC=0x00 PL=5 P=0x11", "msgs": [{"type":"send", "payload":"E0 r7 00 05 1100000000"}]} ] }, { "group": "v5.0 DISCONNECT ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "E0 with reason-string property", "msgs": [{"type":"send", "payload":"E0 r6 00 04 1F s1 'p'"}]}, { "name": "E0 with 2*reason-string property (invalid)", "msgs": [{"type":"send", "payload":"E0 r10 00 v8 1F s1 'p' 1F s1 'q'"}]}, { "name": "E0 with reason-string property missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 1F"}]}, { "name": "E0 with reason-string property empty", "msgs": [{"type":"send", "payload":"E0 r5 00 v3 1F s0"}]}, { "name": "E0 with user-property", "msgs": [{"type":"send", "payload":"E0 r9 00 v7 26 s1 'p' s1 'q'"}]}, { "name": "E0 with user-property missing value", "msgs": [{"type":"send", "payload":"E0 r6 00 v4 26 s1 'p'"}]}, { "name": "E0 with user-property missing key,value", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 26"}]}, { "name": "E0 with user-property empty key", "msgs": [{"type":"send", "payload":"E0 r8 00 v6 26 s0 s1 'p'"}]}, { "name": "E0 with user-property empty key,value", "msgs": [{"type":"send", "payload":"E0 r8 00 v6 26 s1 'p' s0"}]}, { "name": "E0 with user-property empty key,value", "msgs": [{"type":"send", "payload":"E0 r7 00 v5 26 s0 s0"}]}, { "name": "E0 with session-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"E0 r7 00 v5 11 L0"}]}, { "name": "E0 with 2*session-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"E0 r12 00 v10 11 L0 11 L0"}]}, { "name": "E0 with session-expiry-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 11"}]}, { "name": "E0 with server-reference (UTF-8 string)", "msgs": [{"type":"send", "payload":"E0 r6 00 v4 1C s1 'p'"}]}, { "name": "E0 with 2*server-reference (UTF-8 string)", "msgs": [{"type":"send", "payload":"E0 r10 00 v8 1C s1 'p' 1C s1 'q'"}]}, { "name": "E0 with server-reference (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 1C"}]}, { "name": "E0 with server-reference (UTF-8 string) empty", "msgs": [{"type":"send", "payload":"E0 r5 00 v3 1C s0"}]} ] }, { "group": "v5.0 DISCONNECT DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "E0 with payload-format-indicator (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 01 i0"}]}, { "name": "E0 with request-problem-information (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 17 i0"}]}, { "name": "E0 with maximum-qos (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 24 i0"}]}, { "name": "E0 with retain-available (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 25 i0"}]}, { "name": "E0 with wildcard-subscription-available (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 28 i0"}]}, { "name": "E0 with subscription-identifier-available (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 29 i0"}]}, { "name": "E0 with shared-subscription-available (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 2A i0"}]}, { "name": "E0 with payload-format-indicator (byte) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 01"}]}, { "name": "E0 with request-problem-information (byte) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 17"}]}, { "name": "E0 with maximum-qos (byte) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 24"}]}, { "name": "E0 with retain-available (byte) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 25"}]}, { "name": "E0 with wildcard-subscription-available (byte) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 28"}]}, { "name": "E0 with subscription-identifier-available (byte) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 29"}]}, { "name": "E0 with shared-subscription-available (byte) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 2A"}]}, { "name": "E0 with message-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"E0 r7 00 v5 02 L1"}]}, { "name": "E0 with will-delay-interval (four byte integer)", "msgs": [{"type":"send", "payload":"E0 r7 00 v5 18 L1"}]}, { "name": "E0 with maximum-packet-size (four byte integer)", "msgs": [{"type":"send", "payload":"E0 r7 00 v5 27 L1"}]}, { "name": "E0 with message-expiry-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 02"}]}, { "name": "E0 with will-delay-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 18"}]}, { "name": "E0 with maximum-packet-size (four byte integer) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 27"}]}, { "name": "E0 with content-type (UTF-8 string)", "msgs": [{"type":"send", "payload":"E0 r6 00 v4 03 s1 'p'"}]}, { "name": "E0 with response-topic (UTF-8 string)", "msgs": [{"type":"send", "payload":"E0 r6 00 v4 08 s1 'p'"}]}, { "name": "E0 with assigned-client-identifier (UTF-8 string)", "msgs": [{"type":"send", "payload":"E0 r6 00 v4 12 s1 'p'"}]}, { "name": "E0 with authentication-method (UTF-8 string)", "msgs": [{"type":"send", "payload":"E0 r6 00 v4 15 s1 'p'"}]}, { "name": "E0 with response-information (UTF-8 string)", "msgs": [{"type":"send", "payload":"E0 r6 00 v4 1A s1 'p'"}]}, { "name": "E0 with content-type (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 03"}]}, { "name": "E0 with response-topic (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 08"}]}, { "name": "E0 with assigned-client-identifier (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 12"}]}, { "name": "E0 with authentication-method (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 15"}]}, { "name": "E0 with response-information (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 1A"}]}, { "name": "E0 with correlation-data (binary data)", "msgs": [{"type":"send", "payload":"E0 r6 00 v4 09 s1 'p'"}]}, { "name": "E0 with authentication-data (binary data)", "msgs": [{"type":"send", "payload":"E0 r6 00 v4 16 s1 'p'"}]}, { "name": "E0 with correlation-data (binary data) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 09"}]}, { "name": "E0 with authentication-data (binary data) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 16"}]}, { "name": "E0 with subscription-identifier (variable byte integer)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 0B v1"}]}, { "name": "E0 with subscription-identifier (variable byte integer) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 0B"}]}, { "name": "E0 with server-keep-alive (two byte integer)", "msgs": [{"type":"send", "payload":"E0 r5 00 03 13 H5"}]}, { "name": "E0 with receive-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"E0 r5 00 v3 21 H5"}]}, { "name": "E0 with topic-alias-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"E0 r5 00 v3 22 H5"}]}, { "name": "E0 with topic-alias (two byte integer)", "msgs": [{"type":"send", "payload":"E0 r5 00 v3 23 H5"}]}, { "name": "E0 with server-keep-alive (two byte integer) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 13"}]}, { "name": "E0 with receive-maximum (two byte integer) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 21"}]}, { "name": "E0 with topic-alias-maximum (two byte integer) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 22"}]}, { "name": "E0 with topic-alias (two byte integer) missing", "msgs": [{"type":"send", "payload":"E0 r3 00 v1 23"}]}, { "name": "E0 with invalid-property 0x00 (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 00 i1"}]}, { "name": "E0 with unknown-property 0x04 (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 04 i1"}]}, { "name": "E0 with unknown-property 0x05 (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 05 i1"}]}, { "name": "E0 with unknown-property 0x06 (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 06 i1"}]}, { "name": "E0 with unknown-property 0x07 (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 07 i1"}]}, { "name": "E0 with unknown-property 0x0A (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 0A i1"}]}, { "name": "E0 with unknown-property 0x0C (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 0C i1"}]}, { "name": "E0 with unknown-property 0x0D (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 0D i1"}]}, { "name": "E0 with unknown-property 0x0E (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 0E i1"}]}, { "name": "E0 with unknown-property 0x0F (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 0F i1"}]}, { "name": "E0 with unknown-property 0x10 (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 10 i1"}]}, { "name": "E0 with unknown-property 0x14 (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 14 i1"}]}, { "name": "E0 with unknown-property 0x1B (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 1B i1"}]}, { "name": "E0 with unknown-property 0x1D (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 1D i1"}]}, { "name": "E0 with unknown-property 0x1E (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 1E i1"}]}, { "name": "E0 with unknown-property 0x20 (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 20 i1"}]}, { "name": "E0 with unknown-property 0x7F (byte)", "msgs": [{"type":"send", "payload":"E0 r4 00 v2 7F i1"}]}, { "name": "E0 with invalid-property 0x8000 (byte)", "msgs": [{"type":"send", "payload":"E0 r5 00 v3 8000 i1"}]}, { "name": "E0 with unknown-property 0x8001 (byte)", "msgs": [{"type":"send", "payload":"E0 r5 00 v3 8001 i1"}]}, { "name": "E0 with unknown-property 0xFF7F (byte)", "msgs": [{"type":"send", "payload":"E0 r5 00 v3 FF7F i1"}]}, { "name": "E0 with unknown-property 0x808001 (byte)", "msgs": [{"type":"send", "payload":"E0 r6 00 v4 808001 i1"}]}, { "name": "E0 with unknown-property 0xFFFF7F (byte)", "msgs": [{"type":"send", "payload":"E0 r6 00 v4 FFFF7F i1"}]}, { "name": "E0 with unknown-property 0x80808001 (byte)", "msgs": [{"type":"send", "payload":"E0 r7 00 v5 80808001 i1"}]}, { "name": "E0 with unknown-property 0xFFFFFF7F (byte)", "msgs": [{"type":"send", "payload":"E0 r7 00 v5 FFFFFF7F i1"}]} ] } ] ================================================ FILE: test/lib/data/FORBIDDEN.json ================================================ [ { "group": "v3.1.1 FORBIDDEN", "ver":4, "tests": [ { "name": "00 first packet", "connack": false, "msgs": [{"type":"send", "payload":"00 r0"}]}, { "name": "00 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"00 r268435456"}]}, { "name": "01 first packet", "connack": false, "msgs": [{"type":"send", "payload":"01 r0"}]}, { "name": "02 first packet", "connack": false, "msgs": [{"type":"send", "payload":"02 r0"}]}, { "name": "04 first packet", "connack": false, "msgs": [{"type":"send", "payload":"04 r0"}]}, { "name": "08 first packet", "connack": false, "msgs": [{"type":"send", "payload":"08 r0"}]}, { "name": "00 long", "msgs": [{"type":"send", "payload":"00 r1 00"}]}, { "name": "00", "msgs": [{"type":"send", "payload":"00 r0"}]}, { "name": "01", "msgs": [{"type":"send", "payload":"01 r0"}]}, { "name": "02", "msgs": [{"type":"send", "payload":"02 r0"}]}, { "name": "04", "msgs": [{"type":"send", "payload":"04 r0"}]}, { "name": "08", "msgs": [{"type":"send", "payload":"08 r0"}]} ] }, { "group": "v5.0 FORBIDDEN", "ver":5, "tests": [ { "name": "00 first packet", "connack": false, "msgs": [{"type":"send", "payload":"00 r0"}]}, { "name": "00 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"00 r268435456"}]}, { "name": "01 first packet", "connack": false, "msgs": [{"type":"send", "payload":"01 r0"}]}, { "name": "02 first packet", "connack": false, "msgs": [{"type":"send", "payload":"02 r0"}]}, { "name": "04 first packet", "connack": false, "msgs": [{"type":"send", "payload":"04 r0"}]}, { "name": "08 first packet", "connack": false, "msgs": [{"type":"send", "payload":"08 r0"}]}, { "name": "00 long", "msgs": [{"type":"send", "payload":"00 r1 00"}]}, { "name": "00", "msgs": [{"type":"send", "payload":"00 r0"}]}, { "name": "01", "msgs": [{"type":"send", "payload":"01 r0"}]}, { "name": "02", "msgs": [{"type":"send", "payload":"02 r0"}]}, { "name": "04", "msgs": [{"type":"send", "payload":"04 r0"}]}, { "name": "08", "msgs": [{"type":"send", "payload":"08 r0"}]} ] } ] ================================================ FILE: test/lib/data/PINGREQ.json ================================================ [ { "group": "v3.1.1 PINGREQ", "ver":4, "tests": [ { "name": "C0 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"C0 r0"}]}, { "name": "C0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"C0 r268435456"}]}, { "name": "C0 long", "msgs": [{"type":"send", "payload":"C0 r1 00"}]}, { "name": "C0 valid", "msgs": [{"type":"send", "payload":"C0 00"}]}, { "name": "C1", "msgs": [{"type":"send", "payload":"C1 r0"}]}, { "name": "C2", "msgs": [{"type":"send", "payload":"C2 r0"}]}, { "name": "C4", "msgs": [{"type":"send", "payload":"C4 r0"}]}, { "name": "C8", "msgs": [{"type":"send", "payload":"C8 r0"}]} ] }, { "group": "v5.0 PINGREQ", "ver":5, "tests": [ { "name": "C0 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"C0 r0"}]}, { "name": "C0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"C0 r268435456"}]}, { "name": "C0 long", "msgs": [{"type":"send", "payload":"C0 r1 00"}]}, { "name": "C0 valid", "msgs": [{"type":"send", "payload":"C0 r0"}]}, { "name": "C1", "msgs": [{"type":"send", "payload":"C1 r0"}]}, { "name": "C2", "msgs": [{"type":"send", "payload":"C2 r0"}]}, { "name": "C4", "msgs": [{"type":"send", "payload":"C4 r0"}]}, { "name": "C8", "msgs": [{"type":"send", "payload":"C8 r0"}]} ] } ] ================================================ FILE: test/lib/data/PINGRESP.json ================================================ [ { "group": "v3.1.1 PINGRESP", "ver":4, "tests": [ { "name": "D0 [MQTT-3.1.0-1]", "connack": false, "msgs": [{"type":"send", "payload":"D0 r0"}]}, { "name": "D0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"D0 r268435456"}]}, { "name": "D0 long", "msgs": [{"type":"send", "payload":"D0 r1 00"}]}, { "name": "D0", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"D0 r0"}]}, { "name": "D1", "msgs": [{"type":"send", "payload":"D1 r0"}]}, { "name": "D2", "msgs": [{"type":"send", "payload":"D2 r0"}]}, { "name": "D4", "msgs": [{"type":"send", "payload":"D4 r0"}]}, { "name": "D8", "msgs": [{"type":"send", "payload":"D8 r0"}]} ] }, { "group": "v5.0 PINGRESP", "ver":5, "tests": [ { "name": "D0 [MQTT-3.1.0-1]", "connack": false, "msgs": [{"type":"send", "payload":"D0 r0"}]}, { "name": "D0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"D0 r268435456"}]}, { "name": "D0 long", "msgs": [{"type":"send", "payload":"D0 r1 00"}]}, { "name": "D0", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"D0 r0"}]}, { "name": "D1", "msgs": [{"type":"send", "payload":"D1 r0"}]}, { "name": "D2", "msgs": [{"type":"send", "payload":"D2 r0"}]}, { "name": "D4", "msgs": [{"type":"send", "payload":"D4 r0"}]}, { "name": "D8", "msgs": [{"type":"send", "payload":"D8 r0"}]} ] } ] ================================================ FILE: test/lib/data/PUBACK.json ================================================ [ { "group": "v3.1.1 PUBACK unsolicited", "ver":4, "tests": [ { "name": "40 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"40 r2 m1"}]}, { "name": "40 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"40 r268435456"}]}, { "name": "40 long", "msgs": [{"type":"send", "payload":"40 r3 m1 00"}]}, { "name": "40 mid 0", "msgs": [{"type":"send", "payload":"40 r2 m0"}]}, { "name": "40 short 0", "msgs": [{"type":"send", "payload":"40 r0"}]}, { "name": "40 short 1", "msgs": [{"type":"send", "payload":"40 r1 01"}]}, { "name": "40", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r2 m1"}]}, { "name": "41", "msgs": [{"type":"send", "payload":"41 r2 m1"}]}, { "name": "42", "msgs": [{"type":"send", "payload":"42 r2 m1"}]}, { "name": "44", "msgs": [{"type":"send", "payload":"44 r2 m1"}]}, { "name": "48", "msgs": [{"type":"send", "payload":"48 r2 m1"}]} ] }, { "group": "v3.1.1 PUBACK", "ver":4, "command":"publish-1", "group_msgs": [ {"type":"recv", "payload":"32 r23 s12 'test/publish' m1 'message'"} ], "tests": [ { "name": "40 long", "msgs": [{"type":"send", "payload":"40 r3 m1 00"}]}, { "name": "40 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"40 r268435456"}]}, { "name": "40 mid 0", "msgs": [{"type":"send", "payload":"40 r2 m0"}]}, { "name": "40 short 0", "msgs": [{"type":"send", "payload":"40 r0"}]}, { "name": "40 short 1", "msgs": [{"type":"send", "payload":"40 r1 01"}]}, { "name": "41", "msgs": [{"type":"send", "payload":"41 r2 m1"}]}, { "name": "42", "msgs": [{"type":"send", "payload":"42 r2 m1"}]}, { "name": "44", "msgs": [{"type":"send", "payload":"44 r2 m1"}]}, { "name": "48", "msgs": [{"type":"send", "payload":"48 r2 m1"}]} ] }, { "group": "v5.0 PUBACK unsolicited", "ver":5, "tests": [ { "name": "40 [MQTT-3.1.0-1] (no reason code)", "connack":false, "msgs": [{"type":"send", "payload":"40 r2 m1"}]}, { "name": "40 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"40 r3 m1 00"}]}, { "name": "40 long", "msgs": [{"type":"send", "payload":"40 r5 m1 00 00 00"}]}, { "name": "40 mid 0", "msgs": [{"type":"send", "payload":"40 r3 m0 00"}]}, { "name": "40 short 0", "msgs": [{"type":"send", "payload":"40 r0"}]}, { "name": "40 short 1", "msgs": [{"type":"send", "payload":"40 r1 01"}]}, { "name": "40 len=2", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r2 m1"}]}, { "name": "40 len=3", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r3 m1 00"}]}, { "name": "40 len=3 fail", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r3 m1 80"}]}, { "name": "40 len=4 ok", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r4 m1 00 00"}]}, { "name": "40 len=4 rc=fail", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"40 r4 m1 80 00"}]}, { "name": "40 len=4 rc=unknown", "msgs": [{"type":"send", "payload":"40 r4 m1 FF 00"}]}, { "name": "40 len=4 short", "msgs": [{"type":"send", "payload":"40 r4 m1 00 01"}]}, { "name": "41 ", "msgs": [{"type":"send", "payload":"41 r3 m1 00"}]}, { "name": "42", "msgs": [{"type":"send", "payload":"42 r3 m1 00"}]}, { "name": "44", "msgs": [{"type":"send", "payload":"44 r3 m1 00"}]}, { "name": "48", "msgs": [{"type":"send", "payload":"48 r3 m1 00"}]} ] }, { "group": "v5.0 PUBACK", "ver":5, "command": "publish-1", "group_msgs": [ {"type":"recv", "payload":"32 r116 s12 'test/publish' m1 v92 01 i1 02 ffffffff 23 ffff 08 s14 'response/topic' 09 H36 '7deac5c5-8802-44ff-86ce-11479f337419' 03 s10 'text/plain' 26 s3 'key' s5 'value' 'message'"} ], "tests": [ { "name": "40 long", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 00 00"} ]}, { "name": "40 mid 0", "msgs": [ {"type":"send", "payload":"40 r3 m0 00"} ]}, { "name": "40 short 0", "msgs": [ {"type":"send", "payload":"40 r0"} ]}, { "name": "40 short 1", "msgs": [ {"type":"send", "payload":"40 r1 01"} ]}, { "name": "40 len=2", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"40 r2 m1"} ]}, { "name": "40 len=3", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"40 r3 m1 00"} ]}, { "name": "40 len=3 fail", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"40 r3 m1 80"} ]}, { "name": "40 len=4 ok", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"40 r4 m1 00 00"} ]}, { "name": "40 len=4 rc=fail", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"40 r4 m1 80 00"} ]}, { "name": "40 len=4 rc=unknown", "msgs": [ {"type":"send", "payload":"40 r4 m1 FF 00"} ]}, { "name": "40 len=4 short", "msgs": [ {"type":"send", "payload":"40 r4 m1 00 01"} ]}, { "name": "41", "msgs": [ {"type":"send", "payload":"41 r3 m1 00"} ]}, { "name": "42", "msgs": [ {"type":"send", "payload":"42 r3 m1 00"} ]}, { "name": "44", "msgs": [ {"type":"send", "payload":"44 r3 m1 00"} ]}, { "name": "48", "msgs": [ {"type":"send", "payload":"48 r3 m1 00"} ]} ] }, { "group": "v5.0 PUBACK ALLOWED PROPERTIES", "ver":5, "expect_disconnect":false, "command":"publish-1", "group_msgs": [ {"type":"recv", "payload":"32 r116 s12 'test/publish' m1 v92 01 i1 02 ffffffff 23 ffff 08 s14 'response/topic' 09 H36 '7deac5c5-8802-44ff-86ce-11479f337419' 03 s10 'text/plain' 26 s3 'key' s5 'value' 'message'"} ], "tests": [ { "name": "40 with reason-string property", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 1F s1 'p'"} ]}, { "name": "40 with 2*reason-string property", "expect_disconnect":true, "msgs": [ {"type":"send", "payload":"40 r12 m1 00 v8 1F s1 'p' 1F s1 'q'"} ]}, { "name": "40 with reason-string property missing", "expect_disconnect":true, "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 1F"} ]}, { "name": "40 with reason-string property incomplete string", "expect_disconnect":true, "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 1F 00"} ]}, { "name": "40 with reason-string property empty string", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 1F s0"} ]}, { "name": "40 with user-property", "msgs": [ {"type":"send", "payload":"40 r11 m1 00 v7 26 s1 'p' s1 'q'"} ]}, { "name": "40 with 2*user-property", "msgs": [ {"type":"send", "payload":"40 r18 m1 00 v14 26 s1 'p' s1 'q' 26 s1 'p' s1 'q'"} ]}, { "name": "40 with user-property missing value", "expect_disconnect":true, "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 26 s1 'p'"} ]}, { "name": "40 with user-property missing key,value", "expect_disconnect":true, "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 26"} ]}, { "name": "40 with user-property empty key", "msgs": [ {"type":"send", "payload":"40 r10 m1 00 v6 26 s0 s1 'p'"} ]}, { "name": "40 with user-property empty value", "msgs": [ {"type":"send", "payload":"40 r10 m1 00 v6 26 s1 'p' s0"} ]}, { "name": "40 with user-property empty key,value", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 26 s0 s0"}]} ] }, { "group": "v5.0 PUBACK DISALLOWED PROPERTIES", "ver":5, "command":"publish-1", "group_msgs": [ {"type":"recv", "payload":"32 r116 s12 'test/publish' m1 v92 01 i1 02 ffffffff 23 ffff 08 s14 'response/topic' 09 H36 '7deac5c5-8802-44ff-86ce-11479f337419' 03 s10 'text/plain' 26 s3 'key' s5 'value' 'message'"} ], "tests": [ { "name": "40 with payload-format-indicator (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 01 i0"} ]}, { "name": "40 with request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 17 i0"} ]}, { "name": "40 with maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 24 i0"} ]}, { "name": "40 with retain-available (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 25 i0"} ]}, { "name": "40 with wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 28 i0"} ]}, { "name": "40 with subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 29 i0"} ]}, { "name": "40 with shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 2A i0"} ]}, { "name": "40 with payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 01"} ]}, { "name": "40 with request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 17"} ]}, { "name": "40 with maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 24"} ]}, { "name": "40 with retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 25"} ]}, { "name": "40 with wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 28"} ]}, { "name": "40 with subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 29"} ]}, { "name": "40 with shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 2A"} ]}, { "name": "40 with message-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 02 L1"} ]}, { "name": "40 with session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 11 L1"} ]}, { "name": "40 with will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 18 L1"} ]}, { "name": "40 with maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 27 L1"} ]}, { "name": "40 with message-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 02"} ]}, { "name": "40 with session-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 11"} ]}, { "name": "40 with will-delay-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 18"} ]}, { "name": "40 with maximum-packet-size (four byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 27"} ]}, { "name": "40 with content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 03 s1 'p'"} ]}, { "name": "40 with response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 08 s1 'p'"} ]}, { "name": "40 with assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 12 s1 'p'"} ]}, { "name": "40 with authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 15 s1 'p'"} ]}, { "name": "40 with response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 1A s1 'p'"} ]}, { "name": "40 with server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 1C s1 'p'"} ]}, { "name": "40 with content-type (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 03"} ]}, { "name": "40 with response-topic (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 08"} ]}, { "name": "40 with assigned-client-identifier (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 12"} ]}, { "name": "40 with authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 15"} ]}, { "name": "40 with response-information (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 1A"} ]}, { "name": "40 with server-reference (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 1C"} ]}, { "name": "40 with correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 09 s1 'p'"} ]}, { "name": "40 with authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 16 s1 'p'"} ]}, { "name": "40 with correlation-data (binary data) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 09"} ]}, { "name": "40 with authentication-data (binary data) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 16"} ]}, { "name": "40 with subscription-identifier (variable byte integer)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0B v1"} ]}, { "name": "40 with subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 0B"} ]}, { "name": "40 with server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 13 H5"} ]}, { "name": "40 with receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 21 H5"} ]}, { "name": "40 with topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 22 H5"} ]}, { "name": "40 with topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 23 H5"} ]}, { "name": "40 with server-keep-alive (two byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 13"} ]}, { "name": "40 with receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 21"} ]}, { "name": "40 with topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 22"} ]}, { "name": "40 with topic-alias (two byte integer) missing", "msgs": [ {"type":"send", "payload":"40 r5 m1 00 v1 23"} ]}, { "name": "40 with invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 00 i1"} ]}, { "name": "40 with unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 04 i1"} ]}, { "name": "40 with unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 05 i1"} ]}, { "name": "40 with unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 06 i1"} ]}, { "name": "40 with unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 07 i1"} ]}, { "name": "40 with unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0A i1"} ]}, { "name": "40 with unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0C i1"} ]}, { "name": "40 with unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0D i1"} ]}, { "name": "40 with unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0E i1"} ]}, { "name": "40 with unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 0F i1"} ]}, { "name": "40 with unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 10 i1"} ]}, { "name": "40 with unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 14 i1"} ]}, { "name": "40 with unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 1B i1"} ]}, { "name": "40 with unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 1D i1"} ]}, { "name": "40 with unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 1E i1"} ]}, { "name": "40 with unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 20 i1"} ]}, { "name": "40 with unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"40 r6 m1 00 v2 7F i1"} ]}, { "name": "40 with invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 8000 i1"} ]}, { "name": "40 with unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 8001 i1"} ]}, { "name": "40 with unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"40 r7 m1 00 v3 FF7F i1"} ]}, { "name": "40 with unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 808001 i1"} ]}, { "name": "40 with unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"40 r8 m1 00 v4 FFFF7F i1"} ]}, { "name": "40 with unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 80808001 i1"} ]}, { "name": "40 with unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"40 r9 m1 00 v5 FFFFFF7F i1"} ]} ] } ] ================================================ FILE: test/lib/data/PUBLISH.json ================================================ [ { "group": "v3.1.1 PUBLISH", "ver":4, "tests": [ { "name": "30 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"30 r14 s5 'topic' 'payload'"}]}, { "name": "30 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"30 r268435456"}]}, { "name": "30", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"30 r14 s5 'topic' 'payload'"}]}, { "name": "31 retain 1", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"31 r14 s5 'topic' 'payload'"}]}, { "name": "31 retain 1 zero length", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"31 r7 s5 'topic'"}]}, { "name": "30 topic 0", "msgs": [{"type":"send", "payload":"30 r9 s0 'payload'"}]}, { "name": "38 QoS 0 Dup 1", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"38 r14 s5 'topic' 'payload'"}]}, { "name": "36 QoS 3 (no mid) [MQTT-3.3.1-4]", "msgs": [{"type":"send", "payload":"36 r14 s5 'topic' 'payload'"}]}, { "name": "36 QoS 3 (with mid) [MQTT-3.3.1-4]", "msgs": [{"type":"send", "payload":"36 r16 s5 'topic' m1234 'payload'"}]}, { "name": "32 QoS 1 Mid 0", "msgs": [{"type":"send", "payload":"32 r16 s5 'topic' m0 'payload'"}]}, { "name": "34 QoS 2 Mid 0", "msgs": [{"type":"send", "payload":"34 r16 s5 'topic' m0 'payload'"}]}, { "name": "32 QoS 1 Dup 0", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r16 s5 'topic' m1234 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "3A QoS 1 Dup 1", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"3A r16 s5 'topic' m1234 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "34 QoS 2 Dup 0", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"34 r16 s5 'topic' m1234 'payload'"}, {"type":"recv", "payload":"50 r2 m1234"}, {"type":"send", "payload":"62 r2 m1234"}, {"type":"recv", "payload":"70 r2 m1234"} ]}, { "name": "3C QoS 2 Dup 1", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"3C r16 s5 'topic' m1234 'payload'"}, {"type":"recv", "payload":"50 r2 m1234"}, {"type":"send", "payload":"62 r2 m1234"}, {"type":"recv", "payload":"70 r2 m1234"} ]}, { "name": "30 topic with 0x0000", "msgs": [{"type":"send", "payload":"30 r14 m5 746F700000 'payload'"}]}, { "name": "30 topic with U+D800", "msgs": [{"type":"send", "payload":"30 r14 m5 746FEDA080 'payload'"}]}, { "name": "30 topic with U+0001", "msgs": [{"type":"send", "payload":"30 r14 m5 746F700170 'payload'"}]}, { "name": "30 topic with U+001F", "msgs": [{"type":"send", "payload":"30 r14 m5 746F701F70 'payload'"}]}, { "name": "30 topic with U+007F", "msgs": [{"type":"send", "payload":"30 r14 m5 746F707F70 'payload'"}]}, { "name": "30 topic with U+009F", "msgs": [{"type":"send", "payload":"30 r14 m5 746FC29F70 'payload'"}]}, { "name": "30 topic with U+FFFF", "msgs": [{"type":"send", "payload":"30 r14 m5 746FEDBFBF 'payload'"}]}, { "name": "30 topic with U+2A6D4 (section 1.5.3.1)", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"30 r14 m5 41F0AA9B94 'payload'"}]}, { "name": "30 topic with + [MQTT-3.3.2-2]", "msgs": [{"type":"send", "payload":"30 r14 m5 2B6F706963 'payload'"}]}, { "name": "30 topic with # [MQTT-3.3.2-2]", "msgs": [{"type":"send", "payload":"30 r14 m5 236F706963 'payload'"}]} ] }, { "group": "v5.0 PUBLISH", "ver":5, "tests": [ { "name": "30 [MQTT-3.1.0-1]", "connect":false, "msgs": [{"type":"send", "payload":"30 r15 s5 'topic' 00 'payload'"}]}, { "name": "30 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"30 r268435456"}]}, { "name": "30", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"30 r15 s5 'topic' 00 'payload'"}]}, { "name": "31 retain 1", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"31 r15 s5 'topic' 00 'payload'"}]}, { "name": "31 retain 1 zero length", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"31 r8 s5 'topic' 00"}]}, { "name": "30 topic 0", "msgs": [ {"type":"send", "payload":"30 r10 m0 00 'payload'"} ]}, { "name": "36 QoS 3 (no mid) [MQTT-3.3.1-4]", "msgs": [ {"type":"send", "payload":"36 r15 s5 'topic' 00 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "36 QoS 3 (with mid) [MQTT-3.3.1-4]", "msgs": [ {"type":"send", "payload":"36 r17 s5 'topic' m1234 00 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "32 QoS 1 Mid 0", "msgs": [ {"type":"send", "payload":"32 r17 s5 'topic' m0 00 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "34 QoS 2 Mid 0", "msgs": [ {"type":"send", "payload":"34 r17 s5 'topic' m0 00 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "32 QoS 1 Dup 0", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r17 s5 'topic' m1234 00 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "3A QoS 1 Dup 1", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"3A r17 s5 'topic' m1234 00 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "34 QoS 2 Dup 0", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"34 r17 s5 'topic' m1234 00 'payload'"}, {"type":"recv", "payload":"50 r2 m1234"}, {"type":"send", "payload":"62 r2 m1234"}, {"type":"recv", "payload":"70 r2 m1234"} ]}, { "name": "3C QoS 2 Dup 1", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"3C r17 s5 'topic' m1234 00 'payload'"}, {"type":"recv", "payload":"50 r2 m1234"}, {"type":"send", "payload":"62 r2 m1234"}, {"type":"recv", "payload":"70 r2 m1234"} ]}, { "name": "30 topic with 0x0000", "msgs": [ {"type":"send", "payload":"30 r15 s5 746F700000 00 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+D800", "msgs": [ {"type":"send", "payload":"30 r15 s5 746FEDA080 00 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+0001", "msgs": [ {"type":"send", "payload":"30 r15 s5 746F700170 00 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+001F", "msgs": [ {"type":"send", "payload":"30 r15 s5 746F701F70 00 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+007F", "msgs": [ {"type":"send", "payload":"30 r15 s5 746F707F70 00 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+009F", "msgs": [ {"type":"send", "payload":"30 r15 s5 746FC29F70 00 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+FFFF", "msgs": [ {"type":"send", "payload":"30 r15 s5 746FEDBFBF 00 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with U+2A6D4 (section 1.5.3.1)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"30 r15 s5 41F0AA9B94 00 'payload'"} ]}, { "name": "30 topic with + [MQTT-3.3.2-2]", "msgs": [ {"type":"send", "payload":"30 r15 s5 '+opic' 00 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "30 topic with # [MQTT-3.3.2-2]", "msgs": [ {"type":"send", "payload":"30 r15 s5 '#opic' 00 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] }, { "group": "v5.0 PUBLISH ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "payload-format-indicator=0 (byte)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 01 i0 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "payload-format-indicator=1 (byte)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 01 i1 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "payload-format-indicator=2 (byte, invalid)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 01 i2 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "2*payload-format-indicator=1 (byte)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 01 i1 01 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "payload-format-indicator (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 01 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "message-expiry-interval=0 (four byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 02 L0 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "message-expiry-interval=1 (four byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 02 L1 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "2*message-expiry-interval=1 (four byte integer)", "msgs": [ {"type":"send", "payload":"32 r27 s5 'topic' m1234 v10 02 L1 02 L1 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "message-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 02 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "topic alias > max topic alias", "msgs": [ {"type":"send", "payload":"30 r18 s5 'topic' v3 23 H11 'payload'", "comment":"PUBLISH with topic alias 11 (server has set max topic alias=10)"}, {"type":"recv", "payload":"E0 r1 94"} ]}, { "name": "topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 23 H1 'payload'"}, {"type":"recv", "payload":"E0 r1 94"} ]}, { "name": "2*topic-alias (two byte integer)", "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 23 H1 23 H1 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "2*topic-alias different (two byte integer)", "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 23 H1 23 H2 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "topic-alias (two byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 23 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "response-topic (UTF-8 string)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 08 s1 'p' 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "response-topic (UTF-8 string, with wildcard)", "ver":5, "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 08 s1 '#' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "2*response-topic (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r25 s5 'topic' m1234 v8 08 s1 'p' 08 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "response-topic (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 08 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "response-topic (UTF-8 string) empty", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 08 s0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "correlation-data (binary data)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 09 s1 'p' 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "2*correlation-data (binary data)", "msgs": [ {"type":"send", "payload":"32 r25 s5 'topic' m1234 v8 09 s1 'p' 09 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "correlation-data (binary data) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 09 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "correlation-data (binary data) empty", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 09 H0 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r24 s5 'topic' m1234 v7 26 s1 'p' s1 'q' 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "2*user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r31 s5 'topic' m1234 v14 26 s1 'p' s1 'q' 26 s1 'p' s1 'q' 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "user-property missing value", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 26 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "user-property missing key,value", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 26 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "user-property empty key", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 26 s0 s1 'p' 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "user-property empty value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 26 s1 'p' s0 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "user-property empty key,value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 26 s0 s0 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "subscription-identifier=0 (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0B v0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier=0x7F (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0B 7F 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "subscription-identifier=0x8000 (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 0B 8000 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "subscription-identifier=0x8001 (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 0B 8001 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "subscription-identifier=0xFF7F (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 0B FF7F 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "subscription-identifier=0x808001 (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 0B 808001 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "subscription-identifier=0xFFFF7F (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 0B FFFF7F 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "subscription-identifier=0x80808001 (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 0B 80808001 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "subscription-identifier=0xFFFFFF7F (variable byte integer)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 0B FFFFFF7F 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "subscription-identifier=0x8080808001 (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 0B 8080808001 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "2*subscription-identifier=1 (variable byte integer)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 0B v1 0B v1 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier (variable byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 0B 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "content-type (UTF-8 string)", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 03 s1 'p' 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]}, { "name": "2*content-type (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r25 s5 'topic' m1234 v8 03 s1 'p' 03 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "content-type (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 03 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "content-type (UTF-8 string) empty", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 03 s0 'payload'"}, {"type":"recv", "payload":"40 r2 m1234"} ]} ] }, { "group": "v5.0 PUBLISH DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "reason-string property", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 1F s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "request-problem-information (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 17 i0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "maximum-qos (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 24 i0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "retain-available (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 25 i0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "wildcard-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 28 i0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "subscription-identifier-available (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 29 i0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "shared-subscription-available (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 2A i0 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "request-problem-information (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 17 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "maximum-qos (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 24 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "retain-available (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 25 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "wildcard-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 28 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "subscription-identifier-available (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 29 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "shared-subscription-available (byte) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 2A 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "session-expiry-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 11 L1 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "will-delay-interval (four byte integer)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 18 L1 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "maximum-packet-size (four byte integer)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 27 L1 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "session-expiry-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v4 11 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "will-delay-interval (four byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v4 18 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "maximum-packet-size (four byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v4 27 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "assigned-client-identifier (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 12 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "authentication-method (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 15 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "response-information (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 1A s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "server-reference (UTF-8 string)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 1C s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "assigned-client-identifier (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 12 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "authentication-method (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 15 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "response-information (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 1A 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "server-reference (UTF-8 string) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 1C 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "authentication-data (binary data)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 16 s1 'p' 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "authentication-data (binary data) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 16 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "server-keep-alive (two byte integer)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 13 H5 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "receive-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 21 H5 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "topic-alias-maximum (two byte integer)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 22 H5 'payload'"}, {"type":"recv", "payload":"E0 r1 82"} ]}, { "name": "server-keep-alive (two byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 13 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "receive-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 21 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "topic-alias-maximum (two byte integer) missing", "msgs": [ {"type":"send", "payload":"32 r18 s5 'topic' m1234 v1 22 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "invalid-property 0x00 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 00 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x04 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 04 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x05 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 05 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x06 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 06 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x07 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 07 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x0A (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0A i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x0C (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0C i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x0D (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0D i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x0E (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0E i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x0F (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 0F i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x10 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 10 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x14 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 14 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x1B (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 1B i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x1D (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 1D i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x1E (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 1E i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x20 (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 20 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x7F (byte)", "msgs": [ {"type":"send", "payload":"32 r19 s5 'topic' m1234 v2 7F i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "invalid-property 0x8000 (byte)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 8000 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x8001 (byte)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 8001 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0xFF7F (byte)", "msgs": [ {"type":"send", "payload":"32 r20 s5 'topic' m1234 v3 FF7F i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x808001 (byte)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 808001 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0xFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"32 r21 s5 'topic' m1234 v4 FFFF7F i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x80808001 (byte)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 80808001 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0xFFFFFF7F (byte)", "msgs": [ {"type":"send", "payload":"32 r22 s5 'topic' m1234 v5 FFFFFF7F i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]}, { "name": "unknown-property 0x8080808001 (byte)", "msgs": [ {"type":"send", "payload":"32 r23 s5 'topic' m1234 v6 8080808001 i1 'payload'"}, {"type":"recv", "payload":"E0 r1 81"} ]} ] } ] ================================================ FILE: test/lib/data/PUBREC.json ================================================ [ { "group": "v3.1.1 PUBREC unsolicited", "ver":4, "tests": [ { "name": "50 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"50 r2 m1"}]}, { "name": "50 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"50 r268435456"}]}, { "name": "50", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r2 m1"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 long", "msgs": [{"type":"send", "payload":"50 r3 m1 00"}]}, { "name": "50 mid 0", "msgs": [{"type":"send", "payload":"50 r2 m0"}]}, { "name": "50 short 0", "msgs": [{"type":"send", "payload":"50 r0"}]}, { "name": "50 short 1", "msgs": [{"type":"send", "payload":"50 r1 01"}]}, { "name": "51", "msgs": [{"type":"send", "payload":"51 r2 m1"}]}, { "name": "52", "msgs": [{"type":"send", "payload":"52 r2 m1"}]}, { "name": "54", "msgs": [{"type":"send", "payload":"54 r2 m1"}]}, { "name": "58", "msgs": [{"type":"send", "payload":"58 r2 m1"}]} ] }, { "group": "v3.1.1 PUBREC", "ver":4, "command":"publish-2", "group_msgs":[ {"type":"recv", "payload":"34 r23 s12 'test/publish' m1 'message'"} ], "tests": [ { "name": "50", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r2 m1"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"50 r268435456"}]}, { "name": "50 long", "msgs": [{"type":"send", "payload":"50 r3 m1 00"}]}, { "name": "50 mid 0", "msgs": [{"type":"send", "payload":"50 r2 m0"}]}, { "name": "50 short 0", "msgs": [{"type":"send", "payload":"50 r0"}]}, { "name": "50 short 1", "msgs": [{"type":"send", "payload":"50 r1 01"}]}, { "name": "51", "msgs": [{"type":"send", "payload":"51 r2 m1"}]}, { "name": "52", "msgs": [{"type":"send", "payload":"52 r2 m1"}]}, { "name": "54", "msgs": [{"type":"send", "payload":"54 r2 m1"}]}, { "name": "58", "msgs": [{"type":"send", "payload":"58 r2 m1"}]} ] }, { "group": "v5.0 PUBREC unsolicited", "ver":5, "tests": [ { "name": "50 [MQTT-3.1.0-1] (no reason code)", "connack":false, "msgs": [{"type":"send", "payload":"50 r2 m1"}]}, { "name": "50 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"50 r3 m1 00"}]}, { "name": "50 long", "msgs": [{"type":"send", "payload":"50 r5 m1 00 00 00"}]}, { "name": "50 mid 0", "msgs": [{"type":"send", "payload":"50 r3 m0 00"}]}, { "name": "50 short 0", "msgs": [{"type":"send", "payload":"50 r0"}]}, { "name": "50 short 1", "msgs": [{"type":"send", "payload":"50 r1 01"}]}, { "name": "50 len=2", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r2 m1"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 len=3", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r3 m1 00"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 len=3 fail", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"50 r3 m1 80"}]}, { "name": "50 len=4 ok", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r4 m1 00 00"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 len=4 rc=fail", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"50 r4 m1 80 00"}]}, { "name": "50 len=4 rc=unknown", "msgs": [{"type":"send", "payload":"50 r4 m1 FF 00"}]}, { "name": "50 len=4 short", "msgs": [{"type":"send", "payload":"50 r4 m1 00 01"}]}, { "name": "51", "msgs": [{"type":"send", "payload":"51 r3 m1 00"}]}, { "name": "52", "msgs": [{"type":"send", "payload":"52 r3 m1 00"}]}, { "name": "54", "msgs": [{"type":"send", "payload":"54 r3 m1 00"}]}, { "name": "58", "msgs": [{"type":"send", "payload":"58 r3 m1 00"}]} ] }, { "group": "v5.0 PUBREC valid", "ver":5, "expect_disconnect":false, "command":"publish-2", "group_msgs":[ {"type":"recv", "payload":"34 r116 s12 'test/publish' m1 v92 01 i1 02 ffffffff 23 ffff 08 s14 'response/topic' 09 H36 '7deac5c5-8802-44ff-86ce-11479f337419' 03 s10 'text/plain' 26 s3 'key' s5 'value' 'message'"} ], "tests": [ { "name": "50 len=2", "msgs": [ {"type":"send", "payload":"50 r2 m1"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 len=3", "msgs": [ {"type":"send", "payload":"50 r3 m1 00"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 len=3 fail", "msgs": [{"type":"send", "payload":"50 r3 m1 80"}]}, { "name": "50 len=4 ok", "msgs": [ {"type":"send", "payload":"50 r4 m1 00 00"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 len=4 rc=fail", "msgs": [{"type":"send", "payload":"50 r4 m1 80 00"}]} ] }, { "group": "v5.0 PUBREC invalid", "ver":5, "command":"publish-2", "expect_disconnect":true, "group_msgs":[ {"type":"recv", "payload":"34 r116 s12 'test/publish' m1 v92 01 i1 02 ffffffff 23 ffff 08 s14 'response/topic' 09 H36 '7deac5c5-8802-44ff-86ce-11479f337419' 03 s10 'text/plain' 26 s3 'key' s5 'value' 'message'"} ], "tests": [ { "name": "50 long", "msgs": [{"type":"send", "payload":"50 r5 m1 00 00 00"}]}, { "name": "50 mid 0", "msgs": [{"type":"send", "payload":"50 r3 m0 00"}]}, { "name": "50 short 0", "msgs": [{"type":"send", "payload":"50 r0"}]}, { "name": "50 short 1", "msgs": [{"type":"send", "payload":"50 r1 01"}]}, { "name": "50 len=4 rc=unknown", "msgs": [{"type":"send", "payload":"50 r4 m1 FF 00"}]}, { "name": "50 len=4 short", "msgs": [{"type":"send", "payload":"50 r4 m1 00 01"}]}, { "name": "51 ", "msgs": [{"type":"send", "payload":"51 r3 m1 00"}]}, { "name": "52", "msgs": [{"type":"send", "payload":"52 r3 m1 00"}]}, { "name": "54", "msgs": [{"type":"send", "payload":"54 r3 m1 00"}]}, { "name": "58", "msgs": [{"type":"send", "payload":"58 r3 m1 00"}]} ] }, { "group": "v5.0 PUBREC ALLOWED PROPERTIES", "ver":5, "command":"publish-2", "group_msgs":[ {"type":"recv", "payload":"34 r116 s12 'test/publish' m1 v92 01 i1 02 ffffffff 23 ffff 08 s14 'response/topic' 09 H36 '7deac5c5-8802-44ff-86ce-11479f337419' 03 s10 'text/plain' 26 s3 'key' s5 'value' 'message'"} ], "tests": [ { "name": "50 with reason-string property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r8 m1 00 v4 1F s1 'p'"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 with 2*reason-string property", "msgs": [{"type":"send", "payload":"50 r12 m1 00 v8 1F s1 'p' 1F s1 'q'"}]}, { "name": "50 with reason-string property missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 1F"}]}, { "name": "50 with reason-string property empty", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r7 m1 00 v3 1F s0"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 with user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r11 m1 00 v7 26 s1 'p' s1 'q'"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 with 2*user-property", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 12 m1 00 v14 26 s1 'p' s1 'q' 26 s1 'p' s1 'q'"}, {"type":"recv", "payload":"62 02 m1"} ]}, { "name": "50 with user-property missing value", "msgs": [{"type":"send", "payload":"50 r8 m1 00 v4 26 s1 'p'"}]}, { "name": "50 with user-property missing key,value", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 26"}]}, { "name": "50 with user-property empty key", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r10 m1 00 v6 26 s0 s1 'p'"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 with user-property empty value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r10 m1 00 v6 26 s1 'p' s0"}, {"type":"recv", "payload":"62 r2 m1"} ]}, { "name": "50 with user-property empty key,value", "expect_disconnect":false, "msgs": [ {"type":"send", "payload":"50 r9 m1 00 v5 26 s0 s0"}, {"type":"recv", "payload":"62 r2 m1"} ]} ] }, { "group": "v5.0 PUBREC DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "50 with payload-format-indicator (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 01 i0"}]}, { "name": "50 with request-problem-information (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 17 i0"}]}, { "name": "50 with maximum-qos (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 24 i0"}]}, { "name": "50 with retain-available (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 25 i0"}]}, { "name": "50 with wildcard-subscription-available (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 28 i0"}]}, { "name": "50 with subscription-identifier-available (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 29 i0"}]}, { "name": "50 with shared-subscription-available (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 2A i0"}]}, { "name": "50 with payload-format-indicator (byte) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 01"}]}, { "name": "50 with request-problem-information (byte) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 17"}]}, { "name": "50 with maximum-qos (byte) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 24"}]}, { "name": "50 with retain-available (byte) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 25"}]}, { "name": "50 with wildcard-subscription-available (byte) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 28"}]}, { "name": "50 with subscription-identifier-available (byte) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 29"}]}, { "name": "50 with shared-subscription-available (byte) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 2A"}]}, { "name": "50 with message-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"50 r9 m1 00 05 02 L1"}]}, { "name": "50 with session-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"50 r9 m1 00 05 11 L1"}]}, { "name": "50 with will-delay-interval (four byte integer)", "msgs": [{"type":"send", "payload":"50 r9 m1 00 v5 18 L1"}]}, { "name": "50 with maximum-packet-size (four byte integer)", "msgs": [{"type":"send", "payload":"50 r9 m1 00 v5 27 L1"}]}, { "name": "50 with message-expiry-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 02"}]}, { "name": "50 with session-expiry-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 11"}]}, { "name": "50 with will-delay-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 18"}]}, { "name": "50 with maximum-packet-size (four byte integer) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 27"}]}, { "name": "50 with content-type (UTF-8 string)", "msgs": [{"type":"send", "payload":"50 r8 m1 00 v4 03 s1 'p'"}]}, { "name": "50 with response-topic (UTF-8 string)", "msgs": [{"type":"send", "payload":"50 r8 m1 00 v4 08 s1 'p'"}]}, { "name": "50 with assigned-client-identifier (UTF-8 string)", "msgs": [{"type":"send", "payload":"50 r8 m1 00 v4 12 s1 'p'"}]}, { "name": "50 with authentication-method (UTF-8 string)", "msgs": [{"type":"send", "payload":"50 r8 m1 00 v4 15 s1 'p'"}]}, { "name": "50 with response-information (UTF-8 string)", "msgs": [{"type":"send", "payload":"50 r8 m1 00 v4 1A s1 'p'"}]}, { "name": "50 with server-reference (UTF-8 string)", "msgs": [{"type":"send", "payload":"50 r8 m1 00 v4 1C s1 'p'"}]}, { "name": "50 with content-type (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 03"}]}, { "name": "50 with response-topic (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 08"}]}, { "name": "50 with assigned-client-identifier (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 12"}]}, { "name": "50 with authentication-method (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 15"}]}, { "name": "50 with response-information (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 1A"}]}, { "name": "50 with server-reference (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 1C"}]}, { "name": "50 with correlation-data (binary data)", "msgs": [{"type":"send", "payload":"50 r8 m1 00 v4 09 s1 'p'"}]}, { "name": "50 with authentication-data (binary data)", "msgs": [{"type":"send", "payload":"50 r8 m1 00 v4 16 s1 'p'"}]}, { "name": "50 with correlation-data (binary data) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 09"}]}, { "name": "50 with authentication-data (binary data) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 16"}]}, { "name": "50 with subscription-identifier (variable byte integer)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 0B v1"}]}, { "name": "50 with subscription-identifier (variable byte integer) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 0B"}]}, { "name": "50 with server-keep-alive (two byte integer)", "msgs": [{"type":"send", "payload":"50 r7 m1 00 v3 13 H5"}]}, { "name": "50 with receive-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"50 r7 m1 00 v3 21 H5"}]}, { "name": "50 with topic-alias-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"50 r7 m1 00 v3 22 H5"}]}, { "name": "50 with topic-alias (two byte integer)", "msgs": [{"type":"send", "payload":"50 r7 m1 00 v3 23 H5"}]}, { "name": "50 with server-keep-alive (two byte integer) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 13"}]}, { "name": "50 with receive-maximum (two byte integer) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 21"}]}, { "name": "50 with topic-alias-maximum (two byte integer) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 22"}]}, { "name": "50 with topic-alias (two byte integer) missing", "msgs": [{"type":"send", "payload":"50 r5 m1 00 v1 23"}]}, { "name": "50 with invalid-property 0x00 (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 00 i1"}]}, { "name": "50 with unknown-property 0x04 (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 04 i1"}]}, { "name": "50 with unknown-property 0x05 (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 05 i1"}]}, { "name": "50 with unknown-property 0x06 (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 06 i1"}]}, { "name": "50 with unknown-property 0x07 (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 07 i1"}]}, { "name": "50 with unknown-property 0x0A (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 0A i1"}]}, { "name": "50 with unknown-property 0x0C (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 0C i1"}]}, { "name": "50 with unknown-property 0x0D (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 0D i1"}]}, { "name": "50 with unknown-property 0x0E (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 0E i1"}]}, { "name": "50 with unknown-property 0x0F (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 0F i1"}]}, { "name": "50 with unknown-property 0x10 (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 10 i1"}]}, { "name": "50 with unknown-property 0x14 (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 14 i1"}]}, { "name": "50 with unknown-property 0x1B (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 1B i1"}]}, { "name": "50 with unknown-property 0x1D (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 1D i1"}]}, { "name": "50 with unknown-property 0x1E (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 1E i1"}]}, { "name": "50 with unknown-property 0x20 (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 20 i1"}]}, { "name": "50 with unknown-property 0x7F (byte)", "msgs": [{"type":"send", "payload":"50 r6 m1 00 v2 7F i1"}]}, { "name": "50 with invalid-property 0x8000 (byte)", "msgs": [{"type":"send", "payload":"50 r7 m1 00 v3 8000 i1"}]}, { "name": "50 with unknown-property 0x8001 (byte)", "msgs": [{"type":"send", "payload":"50 r7 m1 00 v3 8001 i1"}]}, { "name": "50 with unknown-property 0xFF7F (byte)", "msgs": [{"type":"send", "payload":"50 r7 m1 00 v3 FF7F i1"}]}, { "name": "50 with unknown-property 0x808001 (byte)", "msgs": [{"type":"send", "payload":"50 r8 m1 00 v4 808001 i1"}]}, { "name": "50 with unknown-property 0xFFFF7F (byte)", "msgs": [{"type":"send", "payload":"50 r8 m1 00 v4 FFFF7F i1"}]}, { "name": "50 with unknown-property 0x80808001 (byte)", "msgs": [{"type":"send", "payload":"50 r9 m1 00 v5 80808001 i1"}]}, { "name": "50 with unknown-property 0xFFFFFF7F (byte)", "msgs": [{"type":"send", "payload":"50 r9 m1 00 v5 FFFFFF7F i1"}]} ] } ] ================================================ FILE: test/lib/data/SUBSCRIBE.json ================================================ [ { "group": "v3.1.1 SUBSCRIBE", "ver":4, "tests": [ { "name": "82 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 00"}]}, { "name": "82 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"82 r268435456"}]}, { "name": "80", "msgs": [{"type":"send", "payload":"80 r6 m1234 s1 'p' 00"}]}, { "name": "83 [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"83 r6 m1234 s1 'p' 00"}]}, { "name": "84 [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"84 r6 m1234 s1 'p' 00"}]}, { "name": "86 [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"86 r6 m1234 s1 'p' 00"}]}, { "name": "8A [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"8A r6 m1234 s1 'p' 00"}]}, { "name": "82 QoS 3 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 03"}]}, { "name": "82 QoS 0x04 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 04"}]}, { "name": "82 QoS 0x08 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 08"}]}, { "name": "82 QoS 0x10 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 10"}]}, { "name": "82 QoS 0x20 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 20"}]}, { "name": "82 QoS 0x40 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 40"}]}, { "name": "82 QoS 0x80 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 80"}]}, { "name": "82 topic with 0x0000", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746F700000 00"} ] }, { "name": "82 topic with U+D800", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746FEDA080 00"} ] }, { "name": "82 topic with U+0001", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746F700170 00"} ] }, { "name": "82 topic with U+001F", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746F701F70 00"} ] }, { "name": "82 topic with U+007F", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746F707F70 00"} ] }, { "name": "82 topic with U+009F", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746FC29F70 00"} ] }, { "name": "82 topic with U+FFFF", "msgs": [{"type":"send", "payload":"82 r10 m1234 s5 746FEDBFBF 00"} ] }, { "name": "82 long", "msgs": [{"type":"send", "payload":"82 r7 m1234 s1 'p' 00 00"}]}, { "name": "82 short 5 [MQTT-3.8.3-3]", "msgs": [{"type":"send", "payload":"82 05 m1234 s1 'p'"}]}, { "name": "82 short 4", "msgs": [{"type":"send", "payload":"82 r4 m1234 0000"}]}, { "name": "82 short 3", "msgs": [{"type":"send", "payload":"82 r3 m1234 00"}]}, { "name": "82 short 2", "msgs": [{"type":"send", "payload":"82 r2 1234"}]}, { "name": "82 short 1", "msgs": [{"type":"send", "payload":"82 r1 12"}]}, { "name": "82 short 0", "msgs": [{"type":"send", "payload":"82 r0"}]}, { "name": "82 single topic len 0", "msgs": [{"type":"send", "payload":"82 r5 m1234 s0 00"}]}, { "name": "82 multiple topic 1 len 0", "msgs": [{"type":"send", "payload":"82 r9 m1234 s0 00 s1 'q' 00"}]}, { "name": "82 multiple topic 2 len 0", "msgs": [{"type":"send", "payload":"82 r9 m1234 s1 'q' 00 s0 00"}]}, { "name": "82 multiple topic 1,2 len 0", "msgs": [{"type":"send", "payload":"82 r8 m1234 s0 00 s0 00"}]}, { "name": "82 mid 0", "msgs": [{"type":"send", "payload":"82 r6 m0 s1 'p' 00"}]}, { "name": "82 single ok QoS 0 [MQTT-3.8.4-1]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 00"}]}, { "name": "82 single ok QoS 1 [MQTT-3.8.4-1]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 01"}]}, { "name": "82 single ok QoS 2 [MQTT-3.8.4-1]", "msgs": [{"type":"send", "payload":"82 r6 m1234 s1 'p' 02"}]}, { "name": "82 multiple ok [MQTT-3.8.4-4]", "msgs": [{"type":"send", "payload":"82 r10 m1234 s1 'p' 00 s1 'q' 00"}]} ] }, { "group": "v5.0 SUBSCRIBE", "ver":5, "tests": [ { "name": "82 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"82 07 m1234 v0 s1 'p' 00"}]}, { "name": "82 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"82 r268435456"}]}, { "name": "82 single ok QoS 0 [MQTT-3.8.4-1]", "msgs": [{"type":"send", "payload":"82 07 m1234 v0 s1 'p' 00"}]}, { "name": "82 single ok QoS 1 [MQTT-3.8.4-1]", "msgs": [{"type":"send", "payload":"82 07 m1234 v0 s1 'p' 01"}]}, { "name": "82 single ok QoS 2 [MQTT-3.8.4-1]", "msgs": [{"type":"send", "payload":"82 07 m1234 v0 s1 'p' 02"}]}, { "name": "80", "msgs": [{"type":"send", "payload":"80 r7 m1234 v0 s1 'p' 00"}]}, { "name": "83 [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"83 r7 m1234 v0 s1 'p' 00"}]}, { "name": "84 [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"84 r7 m1234 v0 s1 'p' 00"}]}, { "name": "86 [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"86 r7 m1234 v0 s1 'p' 00"}]}, { "name": "8A [MQTT-3.8.1-1]", "msgs": [{"type":"send", "payload":"8A r7 m1234 v0 s1 'p' 00"}]}, { "name": "82 QoS 3 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 03"}]}, { "name": "82 QoS 0 no local 0x04", "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 04"}]}, { "name": "82 QoS 0 retain as published 0x08", "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 08"}]}, { "name": "82 QoS 0 retain handling=1 0x10", "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 10"}]}, { "name": "82 QoS 0 retain handling=2 0x20", "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 20"}]}, { "name": "82 QoS 0 retain handling=3 0x30 [MQTT-3-8.3-4]", "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 30"}]}, { "name": "82 QoS 0x40 [MQTT-3-8.3-5]", "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 40"}]}, { "name": "82 QoS 0x80 [MQTT-3-8.3-5]", "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 80"}]}, { "name": "82 topic with 0x0000", "msgs": [{"type":"send", "payload":"82 r18 m1234 v0 s5 746F700000 'payload' 00"}]}, { "name": "82 topic with U+D800", "msgs": [{"type":"send", "payload":"82 r18 m1234 v0 s5 746FEDA080 'payload' 00"}]}, { "name": "82 topic with U+0001", "msgs": [{"type":"send", "payload":"82 r18 m1234 v0 s5 746F700170 'payload' 00"}]}, { "name": "82 topic with U+001F", "msgs": [{"type":"send", "payload":"82 r18 m1234 v0 s5 746F701F70 'payload' 00"}]}, { "name": "82 topic with U+007F", "msgs": [{"type":"send", "payload":"82 r18 m1234 v0 s5 746F707F70 'payload' 00"}]}, { "name": "82 topic with U+009F", "msgs": [{"type":"send", "payload":"82 r18 m1234 v0 s5 746FC29F70 'payload' 00"}]}, { "name": "82 topic with U+FFFF", "msgs": [{"type":"send", "payload":"82 r18 m1234 v0 s5 746FEDBFBF 'payload' 00"}]}, { "name": "82 long", "msgs": [{"type":"send", "payload":"82 r8 m1234 v0 s1 'p' 00 00"}]}, { "name": "82 short 5 [MQTT-3.8.3-3]", "msgs": [{"type":"send", "payload":"82 06 m1234 v0 0001 70"}]}, { "name": "82 short 5", "msgs": [{"type":"send", "payload":"82 r5 m1234 v0 0000"}]}, { "name": "82 short 4", "msgs": [{"type":"send", "payload":"82 r4 m1234 v0 00"}]}, { "name": "82 short 3", "msgs": [{"type":"send", "payload":"82 r3 m1234 v0"}]}, { "name": "82 short 2", "msgs": [{"type":"send", "payload":"82 r2 m1234"}]}, { "name": "82 short 1", "msgs": [{"type":"send", "payload":"82 r1 12"}]}, { "name": "82 short 0", "msgs": [{"type":"send", "payload":"82 r0"}]}, { "name": "82 single topic len 0", "msgs": [{"type":"send", "payload":"82 r6 m1234 v0 0000 00"}]}, { "name": "82 multiple topic 1 len 0", "msgs": [{"type":"send", "payload":"82 r10 m1234 v0 0000 00 s1 'q' 00"}]}, { "name": "82 multiple topic 2 len 0", "msgs": [{"type":"send", "payload":"82 r10 m1234 v0 s1 'q' 00 0000 00"}]}, { "name": "82 multiple topic 1,2 len 0", "msgs": [{"type":"send", "payload":"82 r9 m1234 v0 0000 00 0000 00"}]}, { "name": "82 single ok QoS 0 [MQTT-3.8.4-1]", "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 00"}]}, { "name": "82 single ok QoS 1 [MQTT-3.8.4-1]", "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 01"}]}, { "name": "82 single ok QoS 2 [MQTT-3.8.4-1]", "msgs": [{"type":"send", "payload":"82 r7 m1234 v0 s1 'p' 02"}]}, { "name": "82 multiple ok [MQTT-3.8.4-4]", "msgs": [{"type":"send", "payload":"82 r11 m1234 v0 s1 'p' 00 s1 'q' 00"}]}, { "name": "82 mid 0", "msgs": [{"type":"send", "payload":"82 r7 m0 v0 s1 'p' 00"}]} ] }, { "group": "v5.0 SUBSCRIBE ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "82 with user-property", "msgs": [{"type":"send", "payload":"82 r14 m1 v7 26 s1 'p' s1 'q' s1 'p' 00"}]}, { "name": "82 with 2*user-property", "msgs": [{"type":"send", "payload":"82 r21 m1 v14 26 s1 'p' s1 'q' 26 s1 'p' s1 'q' s1 'p' 00"}]}, { "name": "82 with user-property missing value", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 26 s1 'p' s1 'p' 00"}]}, { "name": "82 with user-property missing key,value", "msgs": [{"type":"send", "payload":"82 r8 m1 v1 26 s1 'p' 00"}]}, { "name": "82 with user-property empty key", "msgs": [{"type":"send", "payload":"82 r13 m1 v6 26 0000 s1 'p' s1 'p' 00"}]}, { "name": "82 with user-property empty value", "msgs": [{"type":"send", "payload":"82 r13 m1 v6 26 s1 'p' s0 s1 'p' 00"}]}, { "name": "82 with user-property empty key,value", "msgs": [{"type":"send", "payload":"82 r12 m1 v5 26 s0 s0 s1 'p' 00"}]}, { "name": "82 with subscription-identifier missing (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r8 m1 v1 0B s1 'p' 00"}]}, { "name": "82 with subscription-identifier=0 (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 0B v0 s1 'p' 00"}]}, { "name": "82 with subscription-identifier=1 (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 0B v8 s1 'p' 00"}]}, { "name": "82 with 2*subscription-identifier=1 (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 0B v1 0B i1 s1 'p' 00"}]}, { "name": "82 with subscription-identifier=0x7F (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 0B 7F s1 'p' 00"}]}, { "name": "82 with subscription-identifier=0x8000 (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r10 m1 v3 0B 8000 s1 'p' 00"}]}, { "name": "82 with subscription-identifier=0x8001 (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r10 m1 v3 0B 8001 s1 'p' 00"}]}, { "name": "82 with subscription-identifier=0xFF7F (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r10 m1 v3 0B FF7F s1 'p' 00"}]}, { "name": "82 with subscription-identifier=0x808001 (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 0B 808001 s1 'p' 00"}]}, { "name": "82 with subscription-identifier=0xFFFF7F (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 0B FFFF7F s1 'p' 00"}]}, { "name": "82 with subscription-identifier=0x80808001 (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r12 m1 v5 0B 80808001 s1 'p' 00"}]}, { "name": "82 with subscription-identifier=0xFFFFFF7F (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r12 m1 v5 0B FFFFFF7F s1 'p' 00"}]}, { "name": "82 with subscription-identifier=0x8080808001 (variable byte integer)", "msgs": [{"type":"send", "payload":"82 r13 m1 v6 0B 8080808001 s1 'p' 00"}]} ] }, { "group": "v5.0 SUBSCRIBE DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "82 with payload-format-indicator (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 01 i0 s1 'p' 00"}]}, { "name": "82 with request-problem-information (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 17 i0 s1 'p' 00"}]}, { "name": "82 with maximum-qos (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 24 i0 s1 'p' 00"}]}, { "name": "82 with retain-available (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 25 i0 s1 'p' 00"}]}, { "name": "82 with wildcard-subscription-available (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 28 i0 s1 'p' 00"}]}, { "name": "82 with subscription-identifier-available (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 29 i0 s1 'p' 00"}]}, { "name": "82 with shared-subscription-available (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 02 2A i0 s1 'p' 00"}]}, { "name": "82 with message-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"82 r12 m1 v5 02 L1 s1 'p' 00"}]}, { "name": "82 with session-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"82 r12 m1 v5 11 L1 s1 'p' 00"}]}, { "name": "82 with will-delay-interval (four byte integer)", "msgs": [{"type":"send", "payload":"82 r12 m1 v5 18 L1 s1 'p' 00"}]}, { "name": "82 with maximum-packet-size (four byte integer)", "msgs": [{"type":"send", "payload":"82 r12 m1 v5 27 L1 s1 'p' 00"}]}, { "name": "82 with content-type (UTF-8 string)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 03 s1 'p' s1 'p' 00"}]}, { "name": "82 with response-topic (UTF-8 string)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 08 s1 'p' s1 'p' 00"}]}, { "name": "82 with assigned-client-identifier (UTF-8 string)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 12 s1 'p' s1 'p' 00"}]}, { "name": "82 with authentication-method (UTF-8 string)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 15 s1 'p' s1 'p' 00"}]}, { "name": "82 with response-information (UTF-8 string)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 1A s1 'p' s1 'p' 00"}]}, { "name": "82 with server-reference (UTF-8 string)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 1C s1 'p' s1 'p' 00"}]}, { "name": "82 with correlation-data (binary data)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 09 s1 'p' s1 'p' 00"}]}, { "name": "82 with authentication-data (binary data)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 16 s1 'p' s1 'p' 00"}]}, { "name": "82 with server-keep-alive (two byte integer)", "msgs": [{"type":"send", "payload":"82 r10 m1 v3 13 H5 s1 'p' 00"}]}, { "name": "82 with receive-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"82 r10 m1 v3 21 H5 s1 'p' 00"}]}, { "name": "82 with topic-alias-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"82 r10 m1 v3 22 H5 s1 'p' 00"}]}, { "name": "82 with topic-alias (two byte integer)", "msgs": [{"type":"send", "payload":"82 r10 m1 v3 23 H5 s1 'p' 00"}]}, { "name": "82 with invalid-property 0x00 (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 m1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x04 (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 04 i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x05 (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 05 i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x06 (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 06 i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x07 (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 07 i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x0A (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 0A i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x0C (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 0C i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x0D (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 0D i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x0E (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 0E i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x0F (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 0F i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x10 (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 10 i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x14 (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 14 i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x1B (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 1B i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x1D (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 1D i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x1E (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 1E i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x20 (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 20 i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x7F (byte)", "msgs": [{"type":"send", "payload":"82 r9 m1 v2 7F i1 s1 'p' 00"}]}, { "name": "82 with invalid-property 0x8000 (byte)", "msgs": [{"type":"send", "payload":"82 r10 m1 v3 8000 i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x8001 (byte)", "msgs": [{"type":"send", "payload":"82 r10 m1 v3 8001 i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0xFF7F (byte)", "msgs": [{"type":"send", "payload":"82 r10 m1 v3 FF7F i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x808001 (byte)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 808001 i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0xFFFF7F (byte)", "msgs": [{"type":"send", "payload":"82 r11 m1 v4 FFFF7F i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0x80808001 (byte)", "msgs": [{"type":"send", "payload":"82 r12 m1 v5 80808001 i1 s1 'p' 00"}]}, { "name": "82 with unknown-property 0xFFFFFF7F (byte)", "msgs": [{"type":"send", "payload":"82 r12 m1 v5 FFFFFF7F i1 s1 'p' 00"}]} ] } ] ================================================ FILE: test/lib/data/UNSUBACK.json ================================================ [ { "group": "v3.1.1 UNSUBACK unsolicited", "ver":4, "tests": [ { "name": "B0 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"B0 r2 m1"}]}, { "name": "B0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"B0 r268435456"}]}, { "name": "B0 short 0", "msgs": [{"type":"send", "payload":"B0 r0"}]}, { "name": "B0 short 1", "msgs": [{"type":"send", "payload":"B0 r1 01"}]}, { "name": "B0", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r2 m1"}]}, { "name": "B1", "msgs": [{"type":"send", "payload":"B1 r2 m1"}]}, { "name": "B2", "msgs": [{"type":"send", "payload":"B2 r2 m1"}]}, { "name": "B4", "msgs": [{"type":"send", "payload":"B4 r2 m1"}]}, { "name": "B8", "msgs": [{"type":"send", "payload":"B8 r2 m1"}]} ] }, { "group": "v3.1.1 UNSUBACK", "ver":4, "command":"unsubscribe", "group_msgs":[ {"type":"recv", "payload":"A2 r18 m1 s14 'test/subscribe'"} ], "tests": [ { "name": "B0 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"B0 r268435456"}]}, { "name": "B0 short 0", "msgs": [{"type":"send", "payload":"B0 r0"}]}, { "name": "B0 short 1", "msgs": [{"type":"send", "payload":"B0 r1 01"}]}, { "name": "B0", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r2 m1"}]}, { "name": "B1", "msgs": [{"type":"send", "payload":"B1 r2 m1"}]}, { "name": "B2", "msgs": [{"type":"send", "payload":"B2 r2 m1"}]}, { "name": "B4", "msgs": [{"type":"send", "payload":"B4 r2 m1"}]}, { "name": "B8", "msgs": [{"type":"send", "payload":"B8 r2 m1"}]} ] }, { "group": "v5.0 UNSUBACK unsolicited", "ver":5, "tests": [ { "name": "B0 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"B0 r3 m1 00"}]}, { "name": "B0 short 0", "msgs": [{"type":"send", "payload":"B0 r0"}]}, { "name": "B0 short 1", "msgs": [{"type":"send", "payload":"B0 r1 01"}]}, { "name": "B0 short 2", "msgs": [{"type":"send", "payload":"B0 r2 m1"}]}, { "name": "B0", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r3 m1 00"}]}, { "name": "B1", "msgs": [{"type":"send", "payload":"B1 r3 m1 00"}]}, { "name": "B2", "msgs": [{"type":"send", "payload":"B2 r3 m1 00"}]}, { "name": "B4", "msgs": [{"type":"send", "payload":"B4 r3 m1 00"}]}, { "name": "B8", "msgs": [{"type":"send", "payload":"B8 r3 m1 00"}]}, { "name": "B0 with property", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r7 m1 04 1F s1 'p'"}]}, { "name": "B0 reason code 0x11 no sub", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r4 m1 00 11"}]}, { "name": "B0 reason code 0x80 unspecified error", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r4 m1 00 80"}]}, { "name": "B0 reason code 0x83 implementation specific error", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r4 m1 00 83"}]}, { "name": "B0 reason code 0x87 not authorised", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r4 m1 00 87"}]}, { "name": "B0 reason code 0x8F topic filter invalid", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r4 m1 00 8F"}]}, { "name": "B0 reason code 0x91 packet identifier in use", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r4 m1 00 91"}]}, { "name": "B0 reason code 0xFF unknown", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r4 m1 00 FF"}]} ] }, { "group": "v5.0 UNSUBACK", "ver":5, "command":"unsubscribe", "group_msgs":[ {"type":"recv", "payload":"A2 r32 m1 v13 26 s3 'key' s5 'value' s14 'test/subscribe'"} ], "tests": [ { "name": "B0 short 0", "msgs": [{"type":"send", "payload":"B0 r0"}]}, { "name": "B0 short 1", "msgs": [{"type":"send", "payload":"B0 r1 01"}]}, { "name": "B0 short 2", "msgs": [{"type":"send", "payload":"B0 r2 m1"}]}, { "name": "B0", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r3 m1 00"}]}, { "name": "B1", "msgs": [{"type":"send", "payload":"B1 r3 m1 00"}]}, { "name": "B2", "msgs": [{"type":"send", "payload":"B2 r3 m1 00"}]}, { "name": "B4", "msgs": [{"type":"send", "payload":"B4 r3 m1 00"}]}, { "name": "B8", "msgs": [{"type":"send", "payload":"B8 r3 m1 00"}]}, { "name": "B0 with property", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 v7 m1 v4 1F s1 'p'"}]}, { "name": "B0 reason code 0x11 no sub", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 v4 m1 v0 11"}]}, { "name": "B0 reason code 0x80 unspecified error", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 v4 m1 v0 80"}]}, { "name": "B0 reason code 0x83 implementation specific error", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 v4 m1 v0 83"}]}, { "name": "B0 reason code 0x87 not authorised", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 v4 m1 v0 87"}]}, { "name": "B0 reason code 0x8F topic filter invalid", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 v4 m1 v0 8F"}]}, { "name": "B0 reason code 0x91 packet identifier in use", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 v4 m1 v0 91"}]}, { "name": "B0 reason code 0xFF unknown", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 v4 m1 v0 FF"}]} ] }, { "group": "v5.0 UNSUBACK ALLOWED PROPERTIES", "ver":5, "command":"unsubscribe", "group_msgs":[ {"type":"recv", "payload":"A2 r32 m1 v13 26 s3 'key' s5 'value' s14 'test/subscribe'"} ], "tests": [ { "name": "B0 with reason-string property", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 1F s1 'p' 00"}]}, { "name": "B0 with reason-string property missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 1F 00"}]}, { "name": "B0 with user-property", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r11 m1 v7 26 s1 'p' s1 'q' 00"}]}, { "name": "B0 with user-property missing value", "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 26 s1 'p' 00"}]}, { "name": "B0 with user-property missing key,value", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 26 00"}]}, { "name": "B0 with user-property empty key", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r10 m1 v6 26 s0 s1 'p' 00"}]}, { "name": "B0 with user-property empty value", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r10 m1 v6 26 s1 'p' s0 00"}]}, { "name": "B0 with user-property empty key,value", "expect_disconnect":false, "msgs": [{"type":"send", "payload":"B0 r9 m1 v5 26 s0 s0 00"}]} ] }, { "group": "v5.0 UNSUBACK DISALLOWED PROPERTIES", "ver":5, "group_msgs":[ {"type":"recv", "payload":"A2 r32 m1 v13 26 s3 'key' s5 'value' s14 'test/subscribe'"} ], "command":"unsubscribe", "tests": [ { "name": "B0 with payload-format-indicator (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 01 i0 00"}]}, { "name": "B0 with request-problem-information (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 17 i0 00"}]}, { "name": "B0 with maximum-qos (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 24 i0 00"}]}, { "name": "B0 with retain-available (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 25 i0 00"}]}, { "name": "B0 with wildcard-subscription-available (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 28 i0 00"}]}, { "name": "B0 with subscription-identifier-available (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 29 i0 00"}]}, { "name": "B0 with shared-subscription-available (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 2A i0 00"}]}, { "name": "B0 with payload-format-indicator (byte) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 01 00"}]}, { "name": "B0 with request-problem-information (byte) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 17 00"}]}, { "name": "B0 with maximum-qos (byte) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 24 00"}]}, { "name": "B0 with retain-available (byte) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 25 00"}]}, { "name": "B0 with wildcard-subscription-available (byte) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 28 00"}]}, { "name": "B0 with subscription-identifier-available (byte) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 29 00"}]}, { "name": "B0 with shared-subscription-available (byte) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 2A 00"}]}, { "name": "B0 with message-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"B0 r9 m1 v5 02 L1 00"}]}, { "name": "B0 with session-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"B0 r9 m1 v5 11 L1 00"}]}, { "name": "B0 with will-delay-interval (four byte integer)", "msgs": [{"type":"send", "payload":"B0 r9 m1 v5 18 L1 00"}]}, { "name": "B0 with maximum-packet-size (four byte integer)", "msgs": [{"type":"send", "payload":"B0 r9 m1 v5 27 L1 00"}]}, { "name": "B0 with message-expiry-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 02 00"}]}, { "name": "B0 with session-expiry-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 11 00"}]}, { "name": "B0 with will-delay-interval (four byte integer) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 18 00"}]}, { "name": "B0 with maximum-packet-size (four byte integer) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 27 00"}]}, { "name": "B0 with content-type (UTF-8 string)", "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 03 s1 'p' 00"}]}, { "name": "B0 with response-topic (UTF-8 string)", "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 08 s1 'p' 00"}]}, { "name": "B0 with assigned-client-identifier (UTF-8 string)", "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 12 s1 'p' 00"}]}, { "name": "B0 with authentication-method (UTF-8 string)", "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 15 s1 'p' 00"}]}, { "name": "B0 with response-information (UTF-8 string)", "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 1A s1 'p' 00"}]}, { "name": "B0 with server-reference (UTF-8 string)", "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 1C s1 'p' 00"}]}, { "name": "B0 with content-type (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 03 00"}]}, { "name": "B0 with response-topic (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 08 00"}]}, { "name": "B0 with assigned-client-identifier (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 12 00"}]}, { "name": "B0 with authentication-method (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 15 00"}]}, { "name": "B0 with response-information (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 1A 00"}]}, { "name": "B0 with server-reference (UTF-8 string) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 1C 00"}]}, { "name": "B0 with correlation-data (binary data)", "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 09 s1 'p' 00"}]}, { "name": "B0 with authentication-data (binary data)", "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 16 s1 'p' 00"}]}, { "name": "B0 with correlation-data (binary data) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 09 00"}]}, { "name": "B0 with authentication-data (binary data) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 16 00"}]}, { "name": "B0 with subscription-identifier (variable byte integer)", "msgs": [{"type":"send", "payload":"B0 r5 m1 v2 0B01"}]}, { "name": "B0 with subscription-identifier (variable byte integer) missing", "msgs": [{"type":"send", "payload":"B0 r4 m1 v1 0B"}]}, { "name": "B0 with server-keep-alive (two byte integer)", "msgs": [{"type":"send", "payload":"B0 r7 m1 v3 13 H5 00"}]}, { "name": "B0 with receive-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"B0 r7 m1 v3 21 H5 00"}]}, { "name": "B0 with topic-alias-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"B0 r7 m1 v3 22 H5 00"}]}, { "name": "B0 with topic-alias (two byte integer)", "msgs": [{"type":"send", "payload":"B0 r7 m1 v3 23 H5 00"}]}, { "name": "B0 with server-keep-alive (two byte integer) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 13 00"}]}, { "name": "B0 with receive-maximum (two byte integer) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 21 00"}]}, { "name": "B0 with topic-alias-maximum (two byte integer) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 22 00"}]}, { "name": "B0 with topic-alias (two byte integer) missing", "msgs": [{"type":"send", "payload":"B0 r5 m1 v1 23 00"}]}, { "name": "B0 with invalid-property 0x00 (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 00 i1 00"}]}, { "name": "B0 with unknown-property 0x04 (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 04 i1 00"}]}, { "name": "B0 with unknown-property 0x05 (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 05 i1 00"}]}, { "name": "B0 with unknown-property 0x06 (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 06 i1 00"}]}, { "name": "B0 with unknown-property 0x07 (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 07 i1 00"}]}, { "name": "B0 with unknown-property 0x0A (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 0A i1 00"}]}, { "name": "B0 with unknown-property 0x0C (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 0C i1 00"}]}, { "name": "B0 with unknown-property 0x0D (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 0D i1 00"}]}, { "name": "B0 with unknown-property 0x0E (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 0E i1 00"}]}, { "name": "B0 with unknown-property 0x0F (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 0F i1 00"}]}, { "name": "B0 with unknown-property 0x10 (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 10 i1 00"}]}, { "name": "B0 with unknown-property 0x14 (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 14 i1 00"}]}, { "name": "B0 with unknown-property 0x1B (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 1B i1 00"}]}, { "name": "B0 with unknown-property 0x1D (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 1D i1 00"}]}, { "name": "B0 with unknown-property 0x1E (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 1E i1 00"}]}, { "name": "B0 with unknown-property 0x20 (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 20 i1 00"}]}, { "name": "B0 with unknown-property 0x7F (byte)", "msgs": [{"type":"send", "payload":"B0 r6 m1 v2 7F i1 00"}]}, { "name": "B0 with invalid-property 0x8000 (byte)", "msgs": [{"type":"send", "payload":"B0 r7 m1 v3 8000 i1 00"}]}, { "name": "B0 with unknown-property 0x8001 (byte)", "msgs": [{"type":"send", "payload":"B0 r7 m1 v3 8001 i1 00"}]}, { "name": "B0 with unknown-property 0xFF7F (byte)", "msgs": [{"type":"send", "payload":"B0 r7 m1 v3 FF7F i1 00"}]}, { "name": "B0 with unknown-property 0x808001 (byte)", "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 808001 i1 00"}]}, { "name": "B0 with unknown-property 0xFFFF7F (byte)", "msgs": [{"type":"send", "payload":"B0 r8 m1 v4 FFFF7F i1 00"}]}, { "name": "B0 with unknown-property 0x80808001 (byte)", "msgs": [{"type":"send", "payload":"B0 r9 m1 v5 80808001 i1 00"}]}, { "name": "B0 with unknown-property 0xFFFFFF7F (byte)", "msgs": [{"type":"send", "payload":"B0 r9 m1 v5 FFFFFF7F i1 00"}]} ] } ] ================================================ FILE: test/lib/data/UNSUBSCRIBE.json ================================================ [ { "group": "v3.1.1 UNSUBSCRIBE", "ver":4, "tests": [ { "name": "A2 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"A2 r5 m1234 s1 'p'"}]}, { "name": "A2 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"A2 r268435456"}]}, { "name": "A2 (no subscribe) [MQTT-3.10.4-5]", "msgs": [{"type":"send", "payload":"A2 r5 m1234 s1 'p'"}]}, { "name": "A2 multiple [MQTT-3.10.4-6]", "msgs": [{"type":"send", "payload":"A2 r8 m1234 s1 'p' s1 'q'"}]}, { "name": "A2 multiple zero 1st", "msgs": [{"type":"send", "payload":"A2 r7 m1234 s0 s1 'q'"}]}, { "name": "A2 multiple zero 2nd", "msgs": [{"type":"send", "payload":"A2 r7 m1234 s1 'q' s0"}]}, { "name": "A2 short 4", "msgs": [{"type":"send", "payload":"A2 r4 m1234 0001"}]}, { "name": "A2 short 3", "msgs": [{"type":"send", "payload":"A2 r3 m1234 01"}]}, { "name": "A2 short 2 [MQTT-3.10.3-2]", "msgs": [{"type":"send", "payload":"A2 r2 m1234"}]}, { "name": "A2 short 1", "msgs": [{"type":"send", "payload":"A2 r1 12"}]}, { "name": "A2 short 0", "msgs": [{"type":"send", "payload":"A2 r0"}]}, { "name": "A0 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A0 r5 m1234 s1 'p'"}]}, { "name": "A3 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A3 r5 m1234 s1 'p'"}]}, { "name": "A4 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A4 r5 m1234 s1 'p'"}]}, { "name": "A6 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A6 r5 m1234 s1 'p'"}]}, { "name": "AA [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"AA r5 m1234 s1 'p'"}]}, { "name": "A2 topic with 0x0000", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746F700000"}]}, { "name": "A2 topic with U+D800", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746FEDA080"}]}, { "name": "A2 topic with U+0001", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746F700170"}]}, { "name": "A2 topic with U+001F", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746F701F70"}]}, { "name": "A2 topic with U+007F", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746F707F70"}]}, { "name": "A2 topic with U+009F", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746FC29F70"}]}, { "name": "A2 topic with U+FFFF", "msgs": [{"type":"send", "payload":"A2 r9 m1234 s5 746FEDBFBF"}]}, { "name": "A2 zero mid", "msgs": [ {"type":"send", "payload":"A2 r8 m0 s1 'p' s1 'q'"}]} ] }, { "group": "v5.0 UNSUBSCRIBE", "ver":5, "tests": [ { "name": "A2 [MQTT-3.1.0-1]", "connack":false, "msgs": [{"type":"send", "payload":"A2 r6 m1234 00 s1 'p'"}]}, { "name": "A2 remaining length 5 bytes", "msgs":[{"type":"send", "payload":"A2 r268435456"}]}, { "name": "A2 [MQTT-3.10.4-5]", "msgs": [{"type":"send", "payload":"A2 r6 m1234 00 s1 'p'"}]}, { "name": "A2 multiple zero 1st", "msgs": [{"type":"send", "payload":"A2 r8 m1234 00 s0 s1 'q'"}]}, { "name": "A2 multiple zero 2nd", "msgs": [{"type":"send", "payload":"A2 r8 m1234 00 s1 'q' s0"}]}, { "name": "A2 short 5", "msgs": [{"type":"send", "payload":"A2 r5 m1234 00 0001"}]}, { "name": "A2 short 4", "msgs": [{"type":"send", "payload":"A2 r4 m1234 00 01"}]}, { "name": "A2 short 3 [MQTT-3.10.3-2]", "msgs": [{"type":"send", "payload":"A2 r3 m1234 00"}]}, { "name": "A2 short 2", "msgs": [{"type":"send", "payload":"A2 r1 m1234"}]}, { "name": "A2 short 1", "msgs": [{"type":"send", "payload":"A2 r1 12"}]}, { "name": "A2 short 0", "msgs": [{"type":"send", "payload":"A2 r0"}]}, { "name": "A0 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A0 r6 m1234 00 s1 'p'"}]}, { "name": "A3 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A3 r6 m1234 00 s1 'p'"}]}, { "name": "A4 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A4 r6 m1234 00 s1 'p'"}]}, { "name": "A6 [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"A6 r6 m1234 00 s1 'p'"}]}, { "name": "AA [MQTT-3.10.1-1]", "msgs": [{"type":"send", "payload":"AA r6 m1234 00 s1 'p'"}]}, { "name": "A2 topic with 0x0000", "msgs": [{"type":"send", "payload":"A2 r10 m1234 00 s5 746F700000"}]}, { "name": "A2 topic with U+D800", "msgs": [{"type":"send", "payload":"A2 r10 m1234 00 s5 746FEDA080"}]}, { "name": "A2 topic with U+0001", "msgs": [{"type":"send", "payload":"A2 r10 m1234 00 s5 746F700170"}]}, { "name": "A2 topic with U+001F", "msgs": [{"type":"send", "payload":"A2 r10 m1234 00 s5 746F701F70"}]}, { "name": "A2 topic with U+007F", "msgs": [{"type":"send", "payload":"A2 r10 m1234 00 s5 746F707F70"}]}, { "name": "A2 topic with U+009F", "msgs": [{"type":"send", "payload":"A2 r10 m1234 00 s5 746FC29F70"}]}, { "name": "A2 topic with U+FFFF", "msgs": [{"type":"send", "payload":"A2 r10 m1234 00 s5 746FEDBFBF"}]}, { "name": "A2 multiple [MQTT-3.10.4-6]", "msgs": [{"type":"send", "payload":"A2 r9 m1234 00 s1 'p' s1 'q'"}]}, { "name": "A2 zero mid", "msgs": [{"type":"send", "payload":"A2 r6 m0 00 s1 'p'"}]} ] }, { "group": "v5.0 UNSUBSCRIBE ALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "A2 with user-property", "msgs": [{"type":"send", "payload":"A2 r13 m1 v7 26 s1 'p' s1 'q' s1 'p'"}]}, { "name": "A2 with 2*user-property", "msgs": [{"type":"send", "payload":"A2 r20 m1 v14 26 s1 'p' s1 'q' 26 s1 'p' s1 'q' s1 'p'"}]}, { "name": "A2 with user-property missing value", "msgs": [{"type":"send", "payload":"A2 r10 m1 v4 26 s1 'p' s1 'p'"}]}, { "name": "A2 with user-property missing key,value", "msgs": [{"type":"send", "payload":"A2 r7 m1 v1 26 s1 'p'"}]}, { "name": "A2 with user-property empty key", "msgs": [{"type":"send", "payload":"A2 r12 m1 v6 26 s0 s1 'p' s1 'p'"}]}, { "name": "A2 with user-property empty value", "msgs": [{"type":"send", "payload":"A2 r12 m1 v6 26 s1 'p' s0 s1 'p'"}]}, { "name": "A2 with user-property empty key,value", "msgs": [{"type":"send", "payload":"A2 r11 m1 v5 26 s0 s0 s1 'p'"}]} ] }, { "group": "v5.0 UNSUBSCRIBE DISALLOWED PROPERTIES", "ver":5, "tests": [ { "name": "A2 with payload-format-indicator (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 01 i0 s1 'p'"}]}, { "name": "A2 with request-problem-information (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 17 i0 s1 'p'"}]}, { "name": "A2 with maximum-qos (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 24 i0 s1 'p'"}]}, { "name": "A2 with retain-available (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 25 i0 s1 'p'"}]}, { "name": "A2 with wildcard-subscription-available (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 28 i0 s1 'p'"}]}, { "name": "A2 with subscription-identifier-available (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 29 i0 s1 'p'"}]}, { "name": "A2 with shared-subscription-available (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 2A i0 s1 'p'"}]}, { "name": "A2 with message-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"A2 r11 m1 v5 02 L1 s1 'p'"}]}, { "name": "A2 with session-expiry-interval (four byte integer)", "msgs": [{"type":"send", "payload":"A2 r11 m1 v5 11 L1 s1 'p'"}]}, { "name": "A2 with will-delay-interval (four byte integer)", "msgs": [{"type":"send", "payload":"A2 r11 m1 v5 18 L1 s1 'p'"}]}, { "name": "A2 with maximum-packet-size (four byte integer)", "msgs": [{"type":"send", "payload":"A2 r11 m1 v5 27 L1 s1 'p'"}]}, { "name": "A2 with content-type (UTF-8 string)", "msgs": [{"type":"send", "payload":"A2 r10 m1 v4 03 s1 'p' s1 'p'"}]}, { "name": "A2 with response-topic (UTF-8 string)", "msgs": [{"type":"send", "payload":"A2 r10 m1 v4 08 s1 'p' s1 'p'"}]}, { "name": "A2 with assigned-client-identifier (UTF-8 string)", "msgs": [{"type":"send", "payload":"A2 r10 m1 v4 12 s1 'p' s1 'p'"}]}, { "name": "A2 with authentication-method (UTF-8 string)", "msgs": [{"type":"send", "payload":"A2 r10 m1 v4 15 s1 'p' s1 'p'"}]}, { "name": "A2 with response-information (UTF-8 string)", "msgs": [{"type":"send", "payload":"A2 r10 m1 v4 1A s1 'p' s1 'p'"}]}, { "name": "A2 with server-reference (UTF-8 string)", "msgs": [{"type":"send", "payload":"A2 r10 m1 v4 1C s1 'p' s1 'p'"}]}, { "name": "A2 with correlation-data (binary data)", "msgs": [{"type":"send", "payload":"A2 r10 m1 v4 09 s1 'p' s1 'p'"}]}, { "name": "A2 with authentication-data (binary data)", "msgs": [{"type":"send", "payload":"A2 r10 m1 v4 16 s1 'p' s1 'p'"}]}, { "name": "A2 with subscription-identifier (variable byte integer)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 0B v1 s1 'p'"}]}, { "name": "A2 with server-keep-alive (two byte integer)", "msgs": [{"type":"send", "payload":"A2 r9 m1 v3 13 H5 s1 'p'"}]}, { "name": "A2 with receive-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"A2 r9 m1 v3 21 H5 s1 'p'"}]}, { "name": "A2 with topic-alias-maximum (two byte integer)", "msgs": [{"type":"send", "payload":"A2 r9 m1 v3 22 H5 s1 'p'"}]}, { "name": "A2 with topic-alias (two byte integer)", "msgs": [{"type":"send", "payload":"A2 r9 m1 v3 23 H5 s1 'p'"}]}, { "name": "A2 with invalid-property 0x00 (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 00 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x04 (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 04 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x05 (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 05 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x06 (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 06 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x07 (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 07 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x0A (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 0A i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x0C (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 0C i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x0D (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 0D i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x0E (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 0E i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x0F (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 0F i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x10 (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 10 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x14 (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 14 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x1B (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 1B i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x1D (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 1D i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x1E (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 1E i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x20 (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 20 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x7F (byte)", "msgs": [{"type":"send", "payload":"A2 r8 m1 v2 7F i1 s1 'p'"}]}, { "name": "A2 with invalid-property 0x8000 (byte)", "msgs": [{"type":"send", "payload":"A2 r9 m1 v3 8000 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x8001 (byte)", "msgs": [{"type":"send", "payload":"A2 r9 m1 v3 8001 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0xFF7F (byte)", "msgs": [{"type":"send", "payload":"A2 r9 m1 v3 FF7F i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x808001 (byte)", "msgs": [{"type":"send", "payload":"r2 r10 m1 v4 808001 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0xFFFF7F (byte)", "msgs": [{"type":"send", "payload":"A2 r10 m1 v4 FFFF7F i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0x80808001 (byte)", "msgs": [{"type":"send", "payload":"A2 r11 m1 v5 80808001 i1 s1 'p'"}]}, { "name": "A2 with unknown-property 0xFFFFFF7F (byte)", "msgs": [{"type":"send", "payload":"A2 r11 m1 v5 FFFFFF7F i1 s1 'p'"}]} ] } ] ================================================ FILE: test/lib/mosq_test_helper.py ================================================ import 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 from pathlib import Path source_dir = Path(__file__).resolve().parent ssl_dir = source_dir.parent / "ssl" ================================================ FILE: test/lib/msg_sequence_test.py ================================================ #!/usr/bin/env python3 # Test whether a valid CONNECT results in the correct CONNACK packet. import atexit from mosq_test_helper import * import importlib from os import walk import socket import json from collections import deque import mosq_test send = 1 recv = 2 disconnected_check = 3 connected_check = 4 publish = 5 vg_index = 1 vg_logfiles = [] @atexit.register def test_cleanup(): global vg_logfiles for f in vg_logfiles: try: if os.stat(f).st_size == 0: os.remove(f) except OSError: pass class SingleMsg(object): __slots__ = 'action', 'message', 'comment' def __init__(self, action, message, comment=''): self.action = action self.message = message self.comment = comment class MsgSequence(object): __slots__ = 'name', 'port', 'proto_ver', 'msgs', 'expect_disconnect', 'sock', 'client', 'clean_start', 'command' def __init__(self, name, port, default_connect=True, default_connack=True, proto_ver=4, clean_start=True, expect_disconnect=True, command=None): self.name = name self.msgs = deque() self.expect_disconnect = expect_disconnect self.port = port self.proto_ver = proto_ver self.clean_start = clean_start self.command = command self.sock = -1 self.client = None if default_connect: self.add_recv(mosq_test.gen_connect("fuzzish", proto_ver=proto_ver), "default connect") if default_connack: properties = mqtt5_props.gen_uint16_prop(mqtt5_props.RECEIVE_MAXIMUM, 20) self.add_send(mosq_test.gen_connack(rc=0, proto_ver=proto_ver, properties=properties, property_helper=False), "default connack") def add_msg(self, message): try: c = message["comment"] except KeyError: c = "" if message["type"] == "send": self.add_send(parse_message(message["payload"]), c) elif message["type"] == "recv": self.add_recv(parse_message(message["payload"]), c) elif message["type"] == "publish": self.add_publish(message, c) def add_send(self, message, comment=""): self._add(send, message, comment) def add_recv(self, message, comment): self._add(recv, message, comment) def add_publish(self, message, comment): self._add(publish, message, comment) def add_connected_check(self): self._add(connected_check, b"") def add_disconnected_check(self): self._add(disconnected_check, b"") def run_client(self, server_sock, port): global vg_index global vg_logfiles env = mosq_test.env_add_ld_library_path() cmd = [ mosq_test.get_build_root() + '/test/lib/c/fuzzish.test', str(port), str(self.proto_ver), str(self.clean_start) ] if os.environ.get('MOSQ_USE_VALGRIND') is not None: logfile = 'seq.'+str(vg_index)+'.vglog' cmd = ['/snap/bin/valgrind', '-q', '--trace-children=yes', '--leak-check=full', '--show-leak-kinds=all', '--log-file='+logfile] + cmd vg_logfiles.append(logfile) vg_index += 1 if self.command is not None: cmd.append(self.command) self.client = subprocess.Popen(cmd, stderr=subprocess.PIPE, env=env) (self.sock, _) = server_sock.accept() def kill_client(self): self.sock.close() self.client.terminate() self.client.wait() if self.client.returncode != 0: raise RuntimeError def _add(self, action, message, comment=""): msg = SingleMsg(action, message, comment) self.msgs.append(msg) def _connected_check(self): if not self._puback_check(): raise ValueError("connection failed") def _send_message(self, msg): self.sock.send(msg.message) def _publish_message(self, msg): sock = mosq_test.client_connect_only(hostname="localhost", port=1888, timeout=2) sock.send(mosq_test.gen_connect("helper")) mosq_test.expect_packet(sock, "connack", mosq_test.gen_connack(rc=0)) m = msg.message if m['qos'] == 0: sock.send(mosq_test.gen_publish(topic=m['topic'], payload=m['payload'])) elif m['qos'] == 1: sock.send(mosq_test.gen_publish(mid=1, qos=1, topic=m['topic'], payload=m['payload'])) mosq_test.expect_packet(sock, "helper puback", mosq_test.gen_puback(mid=1)) elif m['qos'] == 2: sock.send(mosq_test.gen_publish(mid=1, qos=2, topic=m['topic'], payload=m['payload'])) mosq_test.expect_packet(sock, "helper pubrec", mosq_test.gen_pubrec(mid=1)) sock.send(mosq_test.gen_pubrel(mid=1)) mosq_test.expect_packet(sock, "helper pubcomp", mosq_test.gen_pubcomp(mid=1)) sock.close() def _recv_message(self, msg): data = self.sock.recv(len(msg.message)) if data != msg.message: raise ValueError("Receive message %s | %s | %s" % (msg.comment, data, msg.message)) def _puback_check(self): publish_packet = mosq_test.gen_publish(mid=65535, qos=1, topic="alive check", payload="payload", proto_ver=self.proto_ver) puback_packet = mosq_test.gen_puback(mid=65535, proto_ver=self.proto_ver) self.sock.send(publish_packet) packet = self.sock.recv(len(puback_packet)) return packet == puback_packet def _disconnected_check(self): try: if self._puback_check() and self.expect_disconnect: raise ValueError("Still connected") except ConnectionResetError: if self.expect_disconnect: pass else: raise def _process_message(self, msg): if msg.action == send: self._send_message(msg) elif msg.action == recv: self._recv_message(msg) elif msg.action == publish: self._publish_message(msg) elif msg.action == disconnected_check: self._disconnected_check() elif msg.action == connected_check: self._connected_check() def process_next(self): msg = self.msgs.popleft() self._process_message(msg) def process_all(self): while len(self.msgs): self.process_next() if self.expect_disconnect: self._disconnected_check() else: self._connected_check() def parse_message(message): b = bytes() parts = message.split(" ") for i in range(0, len(parts)): if len(parts[i]) == 0: continue elif parts[i][0] in ['i']: # General 8-bit unsigned decimal b += int(parts[i][1:]).to_bytes(length=1, byteorder='big', signed=False) elif parts[i][0] in ['H', 'k', 'm', 's']: # General 16-bit unsigned decimal # Or 'k' keepalive specific # Or 'm' mid specific # Or 's' string specific b += int(parts[i][1:]).to_bytes(length=2, byteorder='big', signed=False) elif parts[i][0] == "L": # 32-bit unsigned decimal b += int(parts[i][1:]).to_bytes(length=4, byteorder='big', signed=False) elif parts[i][0] == "'": s = parts[i][1:] while s[-1] != "'" and i < len(parts)-1: i += 1 s += " " + parts[i] if s[-1] != "'": raise ValueError(f"message {message} has incomplete string type") b += bytes(s[0:-1].encode('utf-8')) elif parts[i][0] in ['v', 'r']: # General variable length integer # Or 'r' remaining length v = int(parts[i][1:]) # This allows non-compliant values >=2^28 while True: byte = v % 128 v = v // 128 if v > 0: byte = byte | 0x80 b += byte.to_bytes(length=1, byteorder='big', signed=False) if v == 0: break else: # hex try: b += bytes.fromhex(parts[i]) except ValueError: raise ValueError(f"message {message} has invalid hex bytes") return b def do_test(hostname, port): data_path=Path(__file__).resolve().parent/"data" rc = 0 sequences = [] for (_, _, filenames) in walk(data_path): sequences.extend(filenames) break total = 0 succeeded = 0 test = None server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_sock.settimeout(10) server_sock.bind(('', port)) server_sock.listen(5) for seq in sorted(sequences): if seq[-5:] != ".json": continue with open(data_path/seq, "r") as f: test_file = json.load(f) for g in test_file: group_name = g["group"] try: disabled = g["disable"] if disabled: continue except KeyError: pass try: g_command = g["command"] except KeyError: g_command = None try: g_proto_ver = g["ver"] except KeyError: g_proto_ver = 4 try: g_clean_start = g["clean_start"] except KeyError: g_clean_start = True try: g_connect = g["connect"] except KeyError: g_connect = True try: g_connack = g["connack"] except KeyError: g_connack = True try: g_expect_disconnect = g["expect_disconnect"] except KeyError: g_expect_disconnect = True try: group_msgs = g["group_msgs"] except KeyError: group_msgs = None tests = g["tests"] for t in tests: tname = group_name + " " + t["name"] try: command = t["command"] except KeyError: command = g_command try: proto_ver = t["ver"] except KeyError: proto_ver = g_proto_ver try: clean_start = t["clean_start"] except KeyError: clean_start = g_clean_start try: connect = t["connect"] except KeyError: connect = g_connect try: connack = t["connack"] except KeyError: connack = g_connack try: expect_disconnect = t["expect_disconnect"] except KeyError: expect_disconnect = g_expect_disconnect this_test = MsgSequence(tname, port, proto_ver=proto_ver, clean_start=clean_start, expect_disconnect=expect_disconnect, default_connect=connect, default_connack=connack, command=command) if group_msgs is not None: for m in group_msgs: this_test.add_msg(m) for m in t["msgs"]: this_test.add_msg(m) this_test.run_client(server_sock, port) total += 1 try: this_test.process_all() this_test.kill_client() this_test = None #print("\033[32m" + tname + "\033[0m") succeeded += 1 except (ValueError, ConnectionResetError, socket.timeout, mosq_test.TestError, RuntimeError) as e: print("\033[31m" + tname + " failed: " + str(e) + "\033[0m") rc = 1 finally: if this_test is not None: try: this_test.kill_client() except RuntimeError: pass print("%d tests total\n%d tests succeeded" % (total, succeeded)) return rc hostname = "localhost" port = mosq_test.get_port() rc = do_test(hostname=hostname, port=port) exit(rc) ================================================ FILE: test/lib/test.py ================================================ #!/usr/bin/env python3 import sys sys.path.insert(0, "..") import ptest tests = [ (1, './msg_sequence_test.py'), (1, './01-con-discon-success-v5.py'), (1, './01-con-discon-success.py'), (1, './01-con-discon-will-clear.py'), (1, './01-con-discon-will-v5.py'), (1, './01-con-discon-will.py'), (1, './01-extended-auth-continue.py'), (1, './01-extended-auth-failure.py'), (1, './01-keepalive-pingreq.py'), (1, './01-no-clean-session.py'), (1, './01-server-keepalive-pingreq.py'), (1, './01-unpwd-set.py'), (1, './01-will-set.py'), (1, './01-will-unpwd-set.py'), (1, './02-subscribe-qos0.py'), (1, './02-subscribe-qos1.py'), (1, './02-subscribe-qos2.py'), (1, './02-unsubscribe-multiple-v5.py'), (1, './02-unsubscribe-v5.py'), (1, './02-unsubscribe.py'), (1, './03-publish-b2c-qos1-unexpected-puback.py'), (1, './03-publish-b2c-qos1.py'), (1, './03-publish-b2c-qos2-len.py'), (1, './03-publish-b2c-qos2-unexpected-pubcomp.py'), (1, './03-publish-b2c-qos2-unexpected-pubrel.py'), (1, './03-publish-b2c-qos2.py'), (1, './03-publish-c2b-qos1-disconnect.py'), (1, './03-publish-c2b-qos1-len.py'), (1, './03-publish-c2b-qos1-receive-maximum.py'), (1, './03-publish-c2b-qos2-disconnect.py'), (1, './03-publish-c2b-qos2-len.py'), (1, './03-publish-c2b-qos2-maximum-qos-0.py'), (1, './03-publish-c2b-qos2-maximum-qos-1.py'), (1, './03-publish-c2b-qos2-pubrec-error.py'), (1, './03-publish-c2b-qos2-receive-maximum-1.py'), (1, './03-publish-c2b-qos2-receive-maximum-2.py'), (1, './03-publish-c2b-qos2.py'), (1, './03-publish-qos0-no-payload.py'), (1, './03-publish-qos0.py'), (1, './03-request-response-correlation.py'), (1, './03-request-response.py'), (1, './04-retain-qos0.py'), (1, './08-ssl-bad-cacert.py'), (1, './08-ssl-connect-cert-auth-enc.py'), (1, './08-ssl-connect-cert-auth.py'), (1, './08-ssl-connect-no-auth.py'), (1, './08-ssl-connect-san.py'), (1, './09-util-topic-tokenise.py'), (1, './11-prop-oversize-packet.py'), (1, './11-prop-send-content-type.py'), (1, './11-prop-send-payload-format.py'), ] if __name__ == "__main__": test = ptest.PTest() if len(sys.argv) == 2 and sys.argv[1] == "--rerun-failed": test.run_failed_tests() else: test.run_tests(tests) ================================================ FILE: test/mock/CMakeLists.txt ================================================ add_subdirectory(libcommon) add_subdirectory(lib) add_subdirectory(apps) if(EDITLINE_FOUND) add_library(editline_mock OBJECT editline_mock.cpp) target_include_directories(editline_mock PUBLIC ${mosquitto_SOURCE_DIR}/test/mock ${LINEEDITING_INCLUDE_DIRS} ) target_link_libraries(editline_mock PRIVATE GTest::gmock) endif() add_library(pthread_mock OBJECT pthread_mock.cpp) target_include_directories(pthread_mock PUBLIC ${mosquitto_SOURCE_DIR}/test/mock ) target_link_libraries(pthread_mock PRIVATE GTest::gmock) ================================================ FILE: test/mock/Makefile ================================================ R=../.. include ${R}/config.mk .PHONY: all check test-compile test clean LOCAL_CPPFLAGS+= \ -DWITH_THREADING \ -DWITH_TLS \ -I../ \ -I${R}/include \ -I${R} \ -I${R}/lib \ -I${R}/test/mock LOCAL_CXXFLAGS+=-std=c++20 -Wall -ggdb -D TEST_SOURCE_DIR='"$(realpath .)"' MOCKS = \ pthread_mock.o ifeq ($(WITH_EDITLINE),yes) MOCKS+=editline_mock.o endif all : test-compile test-compile : ${MOCKS} $(MAKE) -C apps/mosquitto_ctrl test-compile $(MAKE) -C lib test-compile check : test test : ${MOCKS} : %.o: %.cpp $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_CXXFLAGS) -c $< -o $@ clean : -rm -rf *.o *.gcda *.gcno coverage.info out/ coverage : lcov --capture --directory . --output-file coverage.info genhtml coverage.info --output-directory out install: uninstall: ================================================ FILE: test/mock/apps/CMakeLists.txt ================================================ add_subdirectory(mosquitto_ctrl) ================================================ FILE: test/mock/apps/mosquitto_ctrl/CMakeLists.txt ================================================ if(WITH_CTRL_SHELL AND EDITLINE_FOUND) add_library(ctrl_shell_mock OBJECT ctrl_shell_mock.cpp ctrl_shell_mock.hpp ) target_compile_definitions(ctrl_shell_mock PRIVATE WITH_CTRL_SHELL WITH_EDITLINE ) target_include_directories(ctrl_shell_mock PUBLIC ${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/include ${mosquitto_SOURCE_DIR}/apps/mosquitto_ctrl ${mosquitto_SOURCE_DIR}/test/mock ${mosquitto_SOURCE_DIR}/test/mock/apps/mosquitto_ctrl ) target_link_libraries(ctrl_shell_mock PRIVATE cJSON GTest::gmock) endif() ================================================ FILE: test/mock/apps/mosquitto_ctrl/Makefile ================================================ R=../../../.. include ${R}/config.mk .PHONY: all check test-compile test clean LOCAL_CPPFLAGS+= \ -DWITH_CTRL_SHELL \ -DWITH_EDITLINE \ -I../ \ -I${R} \ -I${R}/apps/mosquitto_ctrl \ -I${R}/include \ -I${R}/lib \ -I${R}/test/mock LOCAL_CXXFLAGS+=-std=c++20 -Wall -ggdb -D TEST_SOURCE_DIR='"$(realpath .)"' MOCK_OBJS = \ ctrl_shell_mock.o ifeq ($(WITH_EDITLINE),yes) all : test-compile test-compile: ${MOCK_OBJS} check : test else all : test-compile: check : endif # MOCKS ${MOCK_OBJS} : %.o: %.cpp ctrl_shell_mock.hpp $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_CXXFLAGS) -c $< -o $@ clean : -rm -rf *.o *.gcda *.gcno install: uninstall: ================================================ FILE: test/mock/apps/mosquitto_ctrl/ctrl_shell_mock.cpp ================================================ #include "ctrl_shell_mock.hpp" CtrlShellMock::CtrlShellMock() { } CtrlShellMock::~CtrlShellMock() { } void ctrl_shell__output(const char *s) { return CtrlShellMock::get_mock().ctrl_shell__output(s); } char *ctrl_shell_fgets(char *s, int size, FILE *stream) { return CtrlShellMock::get_mock().ctrl_shell_fgets(s, size, stream); } ================================================ FILE: test/mock/apps/mosquitto_ctrl/ctrl_shell_mock.hpp ================================================ #pragma once #include #include #include "mosquitto_ctrl.h" #include "ctrl_shell_internal.h" #include "c_function_mock.hpp" class CtrlShellMock : public CFunctionMock { public: CtrlShellMock(); virtual ~CtrlShellMock(); MOCK_METHOD(void, ctrl_shell__output, (const char *s)); MOCK_METHOD(char *, ctrl_shell_fgets, (char *s, int size, FILE *stream)); }; ================================================ FILE: test/mock/c_function_mock.hpp ================================================ #pragma once #include #include #include template class CFunctionMock { static CFunctionMock*& get_obj() { static CFunctionMock* mock_obj = nullptr; return mock_obj; } public: CFunctionMock() { if (get_obj() != nullptr) { throw std::logic_error("only one instance of MockClass allowed"); } get_obj() = this; } CFunctionMock(const CFunctionMock&) = delete; CFunctionMock(CFunctionMock&&) = delete; CFunctionMock& operator=(const CFunctionMock&) = delete; CFunctionMock& operator=(CFunctionMock&&) = delete; virtual ~CFunctionMock() { get_obj() = nullptr; } static bool mock_exists() { return get_obj() != nullptr; } static MockClass& get_mock() { auto* instance = dynamic_cast(get_obj()); if (instance == nullptr) { throw std::logic_error(std::string("mock ") + typeid(MockClass).name() + " is not initialized"); } return *instance; } template ::value, typename... Args> static std::function optional_mocked_fn( ReturnType (MockClass::*mock_fn)(Args...), const std::string& function_name) { return std::function{ OptionalMockFnWrapper::value, Args...>(mock_fn, function_name)}; } template ::value, typename... Args> static std::function original_fn(ReturnType (MockClass::*mock_fn)(Args...), const std::string& function_name) { return std::function{ OriginalFnWrapper::value, Args...>(mock_fn, function_name)}; } private: template ::value, typename... Args> class OriginalFnWrapper { public: OriginalFnWrapper(ReturnType (MockClass::* /* mock_fn */)(Args...), const std::string& function_name) : orginial_fn{ reinterpret_cast(dlsym(RTLD_NEXT, function_name.c_str()))} {} ReturnType operator()(Args... args) { return (*orginial_fn)(args...); } private: ReturnType (*orginial_fn)(Args...); }; template ::value, typename... Args> class OptionalMockFnWrapper : public OriginalFnWrapper { public: using base_class = OriginalFnWrapper; OptionalMockFnWrapper(ReturnType (MockClass::*mock_fn)(Args...), const std::string& function_name) : base_class{mock_fn, function_name}, mock_fn_(mock_fn) {} ReturnType operator()(Args... args) { if (get_obj() != nullptr) { return (get_mock().*mock_fn_)(args...); } return base_class::operator()(args...); } private: ReturnType (MockClass::*mock_fn_)(Args...); }; template class OriginalFnWrapper { public: OriginalFnWrapper(void (MockClass::* /* mock_fn */)(Args...), const std::string& function_name) : orginial_fn{ reinterpret_cast(dlsym(RTLD_NEXT, function_name.c_str()))} {} void operator()(Args... args) { (*orginial_fn)(args...); } private: void (*orginial_fn)(Args...); }; template class OptionalMockFnWrapper : public OriginalFnWrapper { public: using base_class = OriginalFnWrapper; OptionalMockFnWrapper(void (MockClass::*mock_fn)(Args...), const std::string& function_name) : base_class(mock_fn, function_name), mock_fn_(mock_fn) {} void operator()(Args... args) { if (get_obj() != nullptr) { (get_mock().*mock_fn_)(args...); } else { base_class::operator()(args...); } } private: void (MockClass::*mock_fn_)(Args...); }; }; ================================================ FILE: test/mock/editline_mock.cpp ================================================ #include "editline_mock.hpp" char *rl_line_buffer = nullptr; const char *rl_readline_name = nullptr; rl_compentry_func_t *rl_completion_entry_function = nullptr; int rl_attempted_completion_over = 0; rl_completion_func_t *rl_attempted_completion_function = nullptr; EditLineMock::EditLineMock() { } EditLineMock::~EditLineMock() { } void EditLineMock::reset() { free(rl_line_buffer); rl_line_buffer = nullptr; rl_readline_name = nullptr; rl_completion_entry_function = nullptr; rl_attempted_completion_over = 9; rl_attempted_completion_function = nullptr; } int add_history(const char *s) { return EditLineMock::get_mock().add_history(s); } void clear_history(void) { EditLineMock::get_mock().clear_history(); } void rl_resize_terminal(void) { EditLineMock::get_mock().rl_resize_terminal(); } char *readline(const char *s) { return EditLineMock::get_mock().readline(s); } char **rl_completion_matches(const char *s, rl_compentry_func_t *f) { return EditLineMock::get_mock().rl_completion_matches(s, f); } int rl_complete(int a, int b) { return EditLineMock::get_mock().rl_complete(a, b); } int rl_bind_key(int a, rl_command_func_t *f) { return EditLineMock::get_mock().rl_bind_key(a, f); } ================================================ FILE: test/mock/editline_mock.hpp ================================================ #pragma once #include #include #include "c_function_mock.hpp" class EditLineMock : public CFunctionMock { public: EditLineMock(); virtual ~EditLineMock(); void reset(); MOCK_METHOD(int, add_history, (const char *s)); MOCK_METHOD(void, clear_history, ()); MOCK_METHOD(void, rl_resize_terminal, ()); MOCK_METHOD(char *, readline, (const char *s)); MOCK_METHOD(char **, rl_completion_matches, (const char *s, rl_compentry_func_t *f)); MOCK_METHOD(int, rl_complete, (int a, int b)); MOCK_METHOD(int, rl_bind_key, (int a, rl_command_func_t *f)); }; ================================================ FILE: test/mock/lib/CMakeLists.txt ================================================ add_library(libmosquitto_mock OBJECT actions_publish_mock.cpp actions_subscribe_mock.cpp actions_unsubscribe_mock.cpp callbacks_mock.cpp connect_mock.cpp extended_auth_mock.cpp helpers_mock.cpp libmosquitto_mock.cpp libmosquitto_mock.hpp loop_mock.cpp messages_mosq_mock.cpp net_mosq_mock.cpp options_mock.cpp socks_mosq_mock.cpp srv_mosq_mock.cpp thread_mosq_mock.cpp ) target_include_directories(libmosquitto_mock PUBLIC ${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/include ${mosquitto_SOURCE_DIR}/lib ${mosquitto_SOURCE_DIR}/test/mock ${mosquitto_SOURCE_DIR}/test/mock/lib ) target_link_libraries(libmosquitto_mock PRIVATE cJSON GTest::gmock) ================================================ FILE: test/mock/lib/Makefile ================================================ R=../../.. include ${R}/config.mk .PHONY: all check test-compile test clean LOCAL_CPPFLAGS+= \ -I../ \ -I${R}/include \ -I${R} \ -I${R}/lib \ -I${R}/test/mock LOCAL_CXXFLAGS+=-std=c++20 -Wall -ggdb -D TEST_SOURCE_DIR='"$(realpath .)"' MOCK_OBJS = \ actions_publish_mock.o \ actions_subscribe_mock.o \ actions_unsubscribe_mock.o \ callbacks_mock.o \ connect_mock.o \ extended_auth_mock.o \ helpers_mock.o \ libmosquitto_mock.o \ loop_mock.o \ messages_mosq_mock.o \ net_mosq_mock.o \ options_mock.o \ socks_mosq_mock.o \ srv_mosq_mock.o \ thread_mosq_mock.o all : test-compile test-compile: ${MOCK_OBJS} check : test # MOCKS ${MOCK_OBJS} : %.o: %.cpp libmosquitto_mock.hpp $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_CXXFLAGS) -c $< -o $@ clean : -rm -rf *.o *.gcda *.gcno install: uninstall: ================================================ FILE: test/mock/lib/actions_publish_mock.cpp ================================================ #include "libmosquitto_mock.hpp" int mosquitto_publish(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain) { return LibMosquittoMock::get_mock().mosquitto_publish(mosq, mid, topic, payloadlen, static_cast(payload), qos, retain); } 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) { return LibMosquittoMock::get_mock().mosquitto_publish_v5(mosq, mid, topic, payloadlen, static_cast(payload), qos, retain, properties); } ================================================ FILE: test/mock/lib/actions_subscribe_mock.cpp ================================================ #include "libmosquitto_mock.hpp" int mosquitto_subscribe(struct mosquitto *mosq, int *mid, const char *sub, int qos) { return LibMosquittoMock::get_mock().mosquitto_subscribe(mosq, mid, sub, qos); } int mosquitto_subscribe_v5(struct mosquitto *mosq, int *mid, const char *sub, int qos, int options, const mosquitto_property *properties) { return LibMosquittoMock::get_mock().mosquitto_subscribe_v5(mosq, mid, 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) { return LibMosquittoMock::get_mock().mosquitto_subscribe_multiple(mosq, mid, sub_count, sub, qos, options, properties); } ================================================ FILE: test/mock/lib/actions_unsubscribe_mock.cpp ================================================ #include "libmosquitto_mock.hpp" int mosquitto_unsubscribe(struct mosquitto *mosq, int *mid, const char *sub) { return LibMosquittoMock::get_mock().mosquitto_unsubscribe(mosq, mid, sub); } int mosquitto_unsubscribe_v5(struct mosquitto *mosq, int *mid, const char *sub, const mosquitto_property *properties) { return LibMosquittoMock::get_mock().mosquitto_unsubscribe_v5(mosq, mid, sub, properties); } int mosquitto_unsubscribe_multiple(struct mosquitto *mosq, int *mid, int sub_count, char *const *const sub, const mosquitto_property *properties) { return LibMosquittoMock::get_mock().mosquitto_unsubscribe_multiple(mosq, mid, sub_count, sub, properties); } ================================================ FILE: test/mock/lib/callbacks_mock.cpp ================================================ #include "libmosquitto_mock.hpp" void mosquitto_connect_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_connect on_connect) { return LibMosquittoMock::get_mock().mosquitto_connect_callback_set(mosq, on_connect); } void mosquitto_connect_with_flags_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_connect_with_flags on_connect) { return LibMosquittoMock::get_mock().mosquitto_connect_with_flags_callback_set(mosq, on_connect); } void mosquitto_connect_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_connect_v5 on_connect) { return LibMosquittoMock::get_mock().mosquitto_connect_v5_callback_set(mosq, on_connect); } void mosquitto_pre_connect_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_pre_connect on_pre_connect) { return LibMosquittoMock::get_mock().mosquitto_pre_connect_callback_set(mosq, on_pre_connect); } void mosquitto_disconnect_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_disconnect on_disconnect) { return LibMosquittoMock::get_mock().mosquitto_disconnect_callback_set(mosq, on_disconnect); } void mosquitto_disconnect_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_disconnect_v5 on_disconnect) { return LibMosquittoMock::get_mock().mosquitto_disconnect_v5_callback_set(mosq, on_disconnect); } void mosquitto_publish_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_publish on_publish) { return LibMosquittoMock::get_mock().mosquitto_publish_callback_set(mosq, on_publish); } void mosquitto_publish_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_publish_v5 on_publish) { return LibMosquittoMock::get_mock().mosquitto_publish_v5_callback_set(mosq, on_publish); } void mosquitto_message_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_message on_message) { return LibMosquittoMock::get_mock().mosquitto_message_callback_set(mosq, on_message); } void mosquitto_message_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_message_v5 on_message) { return LibMosquittoMock::get_mock().mosquitto_message_v5_callback_set(mosq, on_message); } void mosquitto_subscribe_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_subscribe on_subscribe) { return LibMosquittoMock::get_mock().mosquitto_subscribe_callback_set(mosq, on_subscribe); } void mosquitto_subscribe_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_subscribe_v5 on_subscribe) { return LibMosquittoMock::get_mock().mosquitto_subscribe_v5_callback_set(mosq, on_subscribe); } void mosquitto_unsubscribe_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe on_unsubscribe) { return LibMosquittoMock::get_mock().mosquitto_unsubscribe_callback_set(mosq, on_unsubscribe); } void mosquitto_unsubscribe_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe_v5 on_unsubscribe) { return LibMosquittoMock::get_mock().mosquitto_unsubscribe_v5_callback_set(mosq, on_unsubscribe); } void mosquitto_unsubscribe2_v5_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe2_v5 on_unsubscribe) { return LibMosquittoMock::get_mock().mosquitto_unsubscribe2_v5_callback_set(mosq, on_unsubscribe); } void mosquitto_log_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_log on_log) { return LibMosquittoMock::get_mock().mosquitto_log_callback_set(mosq, on_log); } void mosquitto_ext_auth_callback_set(struct mosquitto *mosq, LIBMOSQ_CB_ext_auth on_ext_auth) { return LibMosquittoMock::get_mock().mosquitto_ext_auth_callback_set(mosq, on_ext_auth); } ================================================ FILE: test/mock/lib/connect_mock.cpp ================================================ #include "libmosquitto_mock.hpp" int mosquitto_connect(struct mosquitto *mosq, const char *host, int port, int keepalive) { return LibMosquittoMock::get_mock().mosquitto_connect(mosq, host, port, keepalive); } int mosquitto_connect_bind(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address) { return LibMosquittoMock::get_mock().mosquitto_connect_bind(mosq, host, port, keepalive, bind_address); } int mosquitto_connect_bind_v5(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address, const mosquitto_property *properties) { return LibMosquittoMock::get_mock().mosquitto_connect_bind_v5(mosq, host, port, keepalive, bind_address, properties); } int mosquitto_connect_async(struct mosquitto *mosq, const char *host, int port, int keepalive) { return LibMosquittoMock::get_mock().mosquitto_connect_async(mosq, host, port, keepalive); } int mosquitto_connect_bind_async(struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address) { return LibMosquittoMock::get_mock().mosquitto_connect_bind_async(mosq, host, port, keepalive, bind_address); } int mosquitto_reconnect_async(struct mosquitto *mosq) { return LibMosquittoMock::get_mock().mosquitto_reconnect_async(mosq); } int mosquitto_reconnect(struct mosquitto *mosq) { return LibMosquittoMock::get_mock().mosquitto_reconnect(mosq); } int mosquitto_disconnect(struct mosquitto *mosq) { return LibMosquittoMock::get_mock().mosquitto_disconnect(mosq); } int mosquitto_disconnect_v5(struct mosquitto *mosq, int reason_code, const mosquitto_property *properties) { return LibMosquittoMock::get_mock().mosquitto_disconnect_v5(mosq, reason_code, properties); } ================================================ FILE: test/mock/lib/extended_auth_mock.cpp ================================================ #include "libmosquitto_mock.hpp" int mosquitto_ext_auth_continue(struct mosquitto *context, const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *input_props) { return LibMosquittoMock::get_mock().mosquitto_ext_auth_continue(context, auth_method, auth_data_len, auth_data, input_props); } ================================================ FILE: test/mock/lib/helpers_mock.cpp ================================================ #include "libmosquitto_mock.hpp" 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 *clientid, int keepalive, bool clean_session, const char *username, const char *password, const struct libmosquitto_will *will, const struct libmosquitto_tls *tls) { return LibMosquittoMock::get_mock().mosquitto_subscribe_simple(messages, msg_count, want_retained, topic, qos, host, port, clientid, keepalive, clean_session, username, password, will, tls); } 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 *clientid, int keepalive, bool clean_session, const char *username, const char *password, const struct libmosquitto_will *will, const struct libmosquitto_tls *tls) { return LibMosquittoMock::get_mock().mosquitto_subscribe_callback( callback, userdata, topic, qos, host, port, clientid, keepalive, clean_session, username, password, will, tls); } ================================================ FILE: test/mock/lib/libmosquitto_mock.cpp ================================================ #include "libmosquitto_mock.hpp" LibMosquittoMock::LibMosquittoMock() { }; LibMosquittoMock::~LibMosquittoMock() { }; int mosquitto_lib_version(int *major, int *minor, int *revision) { return LibMosquittoMock::get_mock().mosquitto_lib_version( major, minor, revision); } int mosquitto_lib_init() { return LibMosquittoMock::get_mock().mosquitto_lib_init(); } int mosquitto_lib_cleanup() { return LibMosquittoMock::get_mock().mosquitto_lib_cleanup(); } struct mosquitto *mosquitto_new(const char *id, bool clean_start, void *userdata) { return LibMosquittoMock::get_mock().mosquitto_new(id, clean_start, userdata); } int mosquitto_reinitialise(struct mosquitto *mosq, const char *id, bool clean_start, void *userdata) { return LibMosquittoMock::get_mock().mosquitto_reinitialise(mosq, id, clean_start, userdata); } void mosquitto_destroy(struct mosquitto *mosq) { return LibMosquittoMock::get_mock().mosquitto_destroy(mosq); } int mosquitto_socket(struct mosquitto *mosq) { return LibMosquittoMock::get_mock().mosquitto_socket(mosq); } bool mosquitto_want_write(struct mosquitto *mosq) { return LibMosquittoMock::get_mock().mosquitto_want_write(mosq); } ================================================ FILE: test/mock/lib/libmosquitto_mock.hpp ================================================ #pragma once #include #include #include "c_function_mock.hpp" class LibMosquittoMock : public CFunctionMock { public: LibMosquittoMock(); virtual ~LibMosquittoMock(); /* libmosquitto.c */ MOCK_METHOD(int, mosquitto_lib_version, (int *major, int *minor, int *revision)); MOCK_METHOD(int, mosquitto_lib_init, ()); MOCK_METHOD(int, mosquitto_lib_cleanup, ()); MOCK_METHOD(struct mosquitto *, mosquitto_new, (const char *id, bool clean_start, void *userdata)); MOCK_METHOD(int, mosquitto_reinitialise, (struct mosquitto *mosq, const char *id, bool clean_start, void *userdata)); MOCK_METHOD(void, mosquitto_destroy, (struct mosquitto *mosq)); MOCK_METHOD(int, mosquitto_socket, (struct mosquitto *mosq)); MOCK_METHOD(bool, mosquitto_want_write, (struct mosquitto *mosq)); /* actions_publish.c */ MOCK_METHOD(int, mosquitto_publish, (struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, const /*void*/char *payload, int qos, bool retain)); MOCK_METHOD(int, mosquitto_publish_v5, (struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, const /*void*/char *payload, int qos, bool retain, const mosquitto_property *properties)); /* actions_subscribe.c */ MOCK_METHOD(int, mosquitto_subscribe, (struct mosquitto *mosq, int *mid, const char *sub, int qos)); MOCK_METHOD(int, mosquitto_subscribe_v5, (struct mosquitto *mosq, int *mid, const char *sub, int qos, int options, const mosquitto_property *properties)); MOCK_METHOD(int, mosquitto_subscribe_multiple, (struct mosquitto *mosq, int *mid, int sub_count, char *const *const sub, int qos, int options, const mosquitto_property *properties)); /* actions_unsubscribe.c */ MOCK_METHOD(int, mosquitto_unsubscribe, (struct mosquitto *mosq, int *mid, const char *sub)); MOCK_METHOD(int, mosquitto_unsubscribe_v5, (struct mosquitto *mosq, int *mid, const char *sub, const mosquitto_property *properties)); MOCK_METHOD(int, mosquitto_unsubscribe_multiple, (struct mosquitto *mosq, int *mid, int sub_count, char *const *const sub, const mosquitto_property *properties)); /* callbacks.c */ MOCK_METHOD(void, mosquitto_connect_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_connect on_connect)); MOCK_METHOD(void, mosquitto_connect_with_flags_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_connect_with_flags on_connect)); MOCK_METHOD(void, mosquitto_connect_v5_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_connect_v5 on_connect)); MOCK_METHOD(void, mosquitto_pre_connect_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_pre_connect on_pre_connect)); MOCK_METHOD(void, mosquitto_disconnect_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_disconnect on_disconnect)); MOCK_METHOD(void, mosquitto_disconnect_v5_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_disconnect_v5 on_disconnect)); MOCK_METHOD(void, mosquitto_publish_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_publish on_publish)); MOCK_METHOD(void, mosquitto_publish_v5_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_publish_v5 on_publish)); MOCK_METHOD(void, mosquitto_message_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_message on_message)); MOCK_METHOD(void, mosquitto_message_v5_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_message_v5 on_message)); MOCK_METHOD(void, mosquitto_subscribe_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_subscribe on_subscribe)); MOCK_METHOD(void, mosquitto_subscribe_v5_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_subscribe_v5 on_subscribe)); MOCK_METHOD(void, mosquitto_unsubscribe_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe on_unsubscribe)); MOCK_METHOD(void, mosquitto_unsubscribe_v5_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe_v5 on_unsubscribe)); MOCK_METHOD(void, mosquitto_unsubscribe2_v5_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_unsubscribe2_v5 on_unsubscribe)); MOCK_METHOD(void, mosquitto_log_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_log on_log)); MOCK_METHOD(void, mosquitto_ext_auth_callback_set, (struct mosquitto *mosq, LIBMOSQ_CB_ext_auth on_ext_auth)); /* connect.c */ MOCK_METHOD(int, mosquitto_connect, (struct mosquitto *mosq, const char *host, int port, int keepalive)); MOCK_METHOD(int, mosquitto_connect_bind, (struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address)); MOCK_METHOD(int, mosquitto_connect_bind_v5, (struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address, const mosquitto_property *properties)); MOCK_METHOD(int, mosquitto_connect_async, (struct mosquitto *mosq, const char *host, int port, int keepalive)); MOCK_METHOD(int, mosquitto_connect_bind_async, (struct mosquitto *mosq, const char *host, int port, int keepalive, const char *bind_address)); MOCK_METHOD(int, mosquitto_reconnect_async, (struct mosquitto *mosq)); MOCK_METHOD(int, mosquitto_reconnect, (struct mosquitto *mosq)); MOCK_METHOD(int, mosquitto_disconnect, (struct mosquitto *mosq)); MOCK_METHOD(int, mosquitto_disconnect_v5, (struct mosquitto *mosq, int reason_code, const mosquitto_property *properties)); /* extended_auth.c */ MOCK_METHOD(int, mosquitto_ext_auth_continue, (struct mosquitto *context, const char *auth_method, uint16_t auth_data_len, const void *auth_data, const mosquitto_property *input_props)); /* helpers.c */ MOCK_METHOD(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 *clientid, int keepalive, bool clean_session, const char *username, const char *password, const struct libmosquitto_will *will, const struct libmosquitto_tls *tls)); MOCK_METHOD(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 *clientid, int keepalive, bool clean_session, const char *username, const char *password, const struct libmosquitto_will *will, const struct libmosquitto_tls *tls)); /* loop.c */ MOCK_METHOD(int, mosquitto_loop, (struct mosquitto *mosq, int timeout, int max_packets)); MOCK_METHOD(int, mosquitto_loop_forever, (struct mosquitto *mosq, int timeout, int max_packets)); MOCK_METHOD(int, mosquitto_loop_misc, (struct mosquitto *mosq)); MOCK_METHOD(int, mosquitto_loop_read, (struct mosquitto *mosq, int max_packets)); MOCK_METHOD(int, mosquitto_loop_write, (struct mosquitto *mosq, int max_packets)); /* messages_mosq.c */ MOCK_METHOD(int, mosquitto_message_copy, (struct mosquitto_message *dst, const struct mosquitto_message *src)); MOCK_METHOD(void, mosquitto_message_free, (struct mosquitto_message **message)); MOCK_METHOD(void, mosquitto_message_free_contents, (struct mosquitto_message *message)); MOCK_METHOD(void, mosquitto_message_retry_set, (struct mosquitto *mosq, unsigned int message_retry)); /* net_mosq.c */ MOCK_METHOD(void *, mosquitto_ssl_get, (struct mosquitto *mosq)); /* options.c */ MOCK_METHOD(int, mosquitto_will_set, (struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain)); MOCK_METHOD(int, mosquitto_will_set_v5, (struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties)); MOCK_METHOD(int, mosquitto_will_clear, (struct mosquitto *mosq)); MOCK_METHOD(int, mosquitto_username_pw_set, (struct mosquitto *mosq, const char *username, const char *password)); MOCK_METHOD(int, mosquitto_reconnect_delay_set, (struct mosquitto *mosq, unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff)); MOCK_METHOD(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))); MOCK_METHOD(int, mosquitto_tls_opts_set, (struct mosquitto *mosq, int cert_reqs, const char *tls_version, const char *ciphers)); MOCK_METHOD(int, mosquitto_tls_insecure_set, (struct mosquitto *mosq, bool value)); MOCK_METHOD(int, mosquitto_string_option, (struct mosquitto *mosq, enum mosq_opt_t option, const char *value)); MOCK_METHOD(int, mosquitto_tls_psk_set, (struct mosquitto *mosq, const char *psk, const char *identity, const char *ciphers)); MOCK_METHOD(int, mosquitto_opts_set, (struct mosquitto *mosq, enum mosq_opt_t option, void *value)); MOCK_METHOD(int, mosquitto_int_option, (struct mosquitto *mosq, enum mosq_opt_t option, int value)); MOCK_METHOD(int, mosquitto_void_option, (struct mosquitto *mosq, enum mosq_opt_t option, void *value)); MOCK_METHOD(void, mosquitto_user_data_set, (struct mosquitto *mosq, void *userdata)); MOCK_METHOD(void *, mosquitto_userdata, (struct mosquitto *mosq)); /* socks_mosq.c */ MOCK_METHOD(int, mosquitto_socks5_set, (struct mosquitto *mosq, const char *host, int port, const char *username, const char *password)); /* srv_mosq.c */ MOCK_METHOD(int, mosquitto_connect_srv, (struct mosquitto *mosq, const char *host, int keepalive, const char *bind_address)); /* thread_mosq.c */ MOCK_METHOD(int, mosquitto_loop_start, (struct mosquitto *mosq)); MOCK_METHOD(int, mosquitto_loop_stop, (struct mosquitto *mosq, bool force)); MOCK_METHOD(int, mosquitto_threaded_set, (struct mosquitto *mosq, bool threaded)); }; ================================================ FILE: test/mock/lib/loop_mock.cpp ================================================ #include "libmosquitto_mock.hpp" int mosquitto_loop(struct mosquitto *mosq, int timeout, int max_packets) { return LibMosquittoMock::get_mock().mosquitto_loop(mosq, timeout, max_packets); } int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets) { return LibMosquittoMock::get_mock().mosquitto_loop_forever(mosq, timeout, max_packets); } int mosquitto_loop_misc(struct mosquitto *mosq) { return LibMosquittoMock::get_mock().mosquitto_loop_misc(mosq); } int mosquitto_loop_read(struct mosquitto *mosq, int max_packets) { return LibMosquittoMock::get_mock().mosquitto_loop_read(mosq, max_packets); } int mosquitto_loop_write(struct mosquitto *mosq, int max_packets) { return LibMosquittoMock::get_mock().mosquitto_loop_write(mosq, max_packets); } ================================================ FILE: test/mock/lib/messages_mosq_mock.cpp ================================================ #include "libmosquitto_mock.hpp" int mosquitto_message_copy(struct mosquitto_message *dst, const struct mosquitto_message *src) { return LibMosquittoMock::get_mock().mosquitto_message_copy(dst, src); } void mosquitto_message_free(struct mosquitto_message **message) { LibMosquittoMock::get_mock().mosquitto_message_free(message); } void mosquitto_message_free_contents(struct mosquitto_message *message) { LibMosquittoMock::get_mock().mosquitto_message_free_contents(message); } ================================================ FILE: test/mock/lib/net_mosq_mock.cpp ================================================ #include "libmosquitto_mock.hpp" void *mosquitto_ssl_get(struct mosquitto *mosq) { return LibMosquittoMock::get_mock().mosquitto_ssl_get(mosq); } ================================================ FILE: test/mock/lib/options_mock.cpp ================================================ #include "libmosquitto_mock.hpp" int mosquitto_will_set(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain) { return LibMosquittoMock::get_mock().mosquitto_will_set(mosq, topic, payloadlen, payload, qos, retain); } int mosquitto_will_set_v5(struct mosquitto *mosq, const char *topic, int payloadlen, const void *payload, int qos, bool retain, mosquitto_property *properties) { return LibMosquittoMock::get_mock().mosquitto_will_set_v5(mosq, topic, payloadlen, payload, qos, retain, properties); } int mosquitto_will_clear(struct mosquitto *mosq) { return LibMosquittoMock::get_mock().mosquitto_will_clear(mosq); } int mosquitto_username_pw_set(struct mosquitto *mosq, const char *username, const char *password) { return LibMosquittoMock::get_mock().mosquitto_username_pw_set(mosq, username, password); } int mosquitto_reconnect_delay_set(struct mosquitto *mosq, unsigned int reconnect_delay, unsigned int reconnect_delay_max, bool reconnect_exponential_backoff) { return LibMosquittoMock::get_mock().mosquitto_reconnect_delay_set(mosq, reconnect_delay, reconnect_delay_max, reconnect_exponential_backoff); } 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)) { return LibMosquittoMock::get_mock().mosquitto_tls_set(mosq, cafile, capath, certfile, keyfile, pw_callback); } int mosquitto_tls_opts_set(struct mosquitto *mosq, int cert_reqs, const char *tls_version, const char *ciphers) { return LibMosquittoMock::get_mock().mosquitto_tls_opts_set(mosq, cert_reqs, tls_version, ciphers); } int mosquitto_tls_insecure_set(struct mosquitto *mosq, bool value) { return LibMosquittoMock::get_mock().mosquitto_tls_insecure_set(mosq, value); } int mosquitto_string_option(struct mosquitto *mosq, enum mosq_opt_t option, const char *value) { return LibMosquittoMock::get_mock().mosquitto_string_option(mosq, option, value); } int mosquitto_tls_psk_set(struct mosquitto *mosq, const char *psk, const char *identity, const char *ciphers) { return LibMosquittoMock::get_mock().mosquitto_tls_psk_set(mosq, psk, identity, ciphers); } int mosquitto_opts_set(struct mosquitto *mosq, enum mosq_opt_t option, void *value) { return LibMosquittoMock::get_mock().mosquitto_opts_set(mosq, option, value); } int mosquitto_int_option(struct mosquitto *mosq, enum mosq_opt_t option, int value) { return LibMosquittoMock::get_mock().mosquitto_int_option(mosq, option, value); } int mosquitto_void_option(struct mosquitto *mosq, enum mosq_opt_t option, void *value) { return LibMosquittoMock::get_mock().mosquitto_void_option(mosq, option, value); } void mosquitto_user_data_set(struct mosquitto *mosq, void *userdata) { LibMosquittoMock::get_mock().mosquitto_user_data_set(mosq, userdata); } void *mosquitto_userdata(struct mosquitto *mosq) { return LibMosquittoMock::get_mock().mosquitto_userdata(mosq); } ================================================ FILE: test/mock/lib/socks_mosq_mock.cpp ================================================ #include "libmosquitto_mock.hpp" int mosquitto_socks5_set(struct mosquitto *mosq, const char *host, int port, const char *username, const char *password) { return LibMosquittoMock::get_mock().mosquitto_socks5_set(mosq, host, port, username, password); } ================================================ FILE: test/mock/lib/srv_mosq_mock.cpp ================================================ #include "libmosquitto_mock.hpp" int mosquitto_connect_srv(struct mosquitto *mosq, const char *host, int keepalive, const char *bind_address) { return LibMosquittoMock::get_mock().mosquitto_connect_srv(mosq, host, keepalive, bind_address); } ================================================ FILE: test/mock/lib/thread_mosq_mock.cpp ================================================ #include "libmosquitto_mock.hpp" int mosquitto_loop_start(struct mosquitto *mosq) { return LibMosquittoMock::get_mock().mosquitto_loop_start(mosq); } int mosquitto_loop_stop(struct mosquitto *mosq, bool force) { return LibMosquittoMock::get_mock().mosquitto_loop_stop(mosq, force); } int mosquitto_threaded_set(struct mosquitto *mosq, bool threaded) { return LibMosquittoMock::get_mock().mosquitto_threaded_set(mosq, threaded); } ================================================ FILE: test/mock/libcommon/CMakeLists.txt ================================================ add_library(libmosquitto_common_mock OBJECT libmosquitto_common_mock.hpp libmosquitto_common_mock.cpp base64_common_mock.cpp file_common_mock.cpp memory_common_mock.cpp mqtt_common_mock.cpp password_common_mock.cpp property_common_mock.cpp random_common_mock.cpp strings_common_mock.cpp time_common_mock.cpp topic_common_mock.cpp utf8_common_mock.cpp ) target_include_directories(libmosquitto_common_mock PUBLIC ${mosquitto_SOURCE_DIR} ${mosquitto_SOURCE_DIR}/include ${mosquitto_SOURCE_DIR}/lib ${mosquitto_SOURCE_DIR}/test/mock ${mosquitto_SOURCE_DIR}/test/mock/lib ) target_link_libraries(libmosquitto_common_mock PRIVATE cJSON GTest::gmock) ================================================ FILE: test/mock/libcommon/Makefile ================================================ R=../../.. include ${R}/config.mk .PHONY: all check test-compile test clean LOCAL_CPPFLAGS+= \ -I../ \ -I${R}/include \ -I${R} \ -I${R}/lib \ -I${R}/test/mock LOCAL_CXXFLAGS+=-std=c++20 -Wall -ggdb -D TEST_SOURCE_DIR='"$(realpath .)"' MOCK_OBJS = \ base64_common_mock.o \ file_common_mock.o \ libmosquitto_common_mock.o \ memory_common_mock.o \ mqtt_common_mock.o \ password_common_mock.o \ property_common_mock.o \ random_common_mock.o \ strings_common_mock.o \ time_common_mock.o \ topic_common_mock.o \ utf8_common_mock.o all : test-compile test-compile: ${MOCK_OBJS} check : test # MOCKS ${MOCK_OBJS} : %.o: %.cpp libmosquitto_common_mock.hpp $(CROSS_COMPILE)$(CXX) $(LOCAL_CPPFLAGS) $(LOCAL_CXXFLAGS) -c $< -o $@ clean : -rm -rf *.o *.gcda *.gcno install: uninstall: ================================================ FILE: test/mock/libcommon/base64_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" int mosquitto_base64_encode(const unsigned char *in, size_t in_len, char **encoded) { return LibMosquittoCommonMock::get_mock().mosquitto_base64_encode( in, in_len, encoded); } int mosquitto_base64_decode(const char *in, unsigned char **decoded, unsigned int *decoded_len) { return LibMosquittoCommonMock::get_mock().mosquitto_base64_decode( in, decoded, decoded_len); } ================================================ FILE: test/mock/libcommon/cjson_common.cpp ================================================ #include "libmosquitto_common_mock.hpp" cJSON *mosquitto_properties_to_json(const mosquitto_property *properties) { return LibMosquittoCommonMock::get_mock().mosquitto_properties_to_json( properties); } ================================================ FILE: test/mock/libcommon/file_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" FILE *mosquitto_fopen(const char *path, const char *mode, bool restrict_read) { return LibMosquittoCommonMock::get_mock().mosquitto_fopen( path, mode, restrict_read); } char *mosquitto_trimblanks(char *str) { return LibMosquittoCommonMock::get_mock().mosquitto_trimblanks(str); } char *mosquitto_fgets(char **buf, int *buflen, FILE *stream) { return LibMosquittoCommonMock::get_mock().mosquitto_fgets(buf, buflen, stream); } int mosquitto_write_file(const char *target_path, bool restrict_read, int (*write_fn)(FILE *fptr, void *user_data), void *user_data, void (*log_fn)(const char *msg)) { return LibMosquittoCommonMock::get_mock().mosquitto_write_file( target_path, restrict_read, write_fn, user_data, log_fn); } int mosquitto_read_file(const char *file, char **buf, size_t *buflen) { return LibMosquittoCommonMock::get_mock().mosquitto_read_file( file, buf, buflen); } ================================================ FILE: test/mock/libcommon/libmosquitto_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" LibMosquittoCommonMock::LibMosquittoCommonMock() { }; LibMosquittoCommonMock::~LibMosquittoCommonMock() { }; ================================================ FILE: test/mock/libcommon/libmosquitto_common_mock.hpp ================================================ #pragma once #include #include #include "c_function_mock.hpp" class LibMosquittoCommonMock : public CFunctionMock { public: LibMosquittoCommonMock(); virtual ~LibMosquittoCommonMock(); /* base64_common.c */ MOCK_METHOD(int, mosquitto_base64_encode, (const unsigned char *in, size_t in_len, char **encoded)); MOCK_METHOD(int, mosquitto_base64_decode, (const char *in, unsigned char **decoded, unsigned int *decoded_len)); /* cjson_common.c */ MOCK_METHOD(cJSON *, mosquitto_properties_to_json, (const mosquitto_property *properties)); /* file_common.c */ MOCK_METHOD(FILE *, mosquitto_fopen, (const char *path, const char *mode, bool restrict_read)); MOCK_METHOD(char *, mosquitto_trimblanks, (char *str)); MOCK_METHOD(char *, mosquitto_fgets, (char **buf, int *buflen, FILE *stream)); MOCK_METHOD(int, mosquitto_write_file, (const char* target_path, bool restrict_read, int (*write_fn)(FILE* fptr, void* user_data), void* user_data, void (*log_fn)(const char* msg))); MOCK_METHOD(int, mosquitto_read_file, (const char *file, char **buf, size_t *buflen)); /* memory_common.c */ MOCK_METHOD(void, mosquitto_memory_set_limit, (size_t lim)); MOCK_METHOD(unsigned long, mosquitto_memory_used, ()); MOCK_METHOD(unsigned long, mosquitto_max_memory_used, ()); MOCK_METHOD(void *, mosquitto_malloc, (size_t size)); MOCK_METHOD(void *, mosquitto_realloc, (void *ptr, size_t size)); MOCK_METHOD(void, mosquitto_free, (void *mem)); MOCK_METHOD(void *, mosquitto_calloc, (size_t nmemb, size_t size)); MOCK_METHOD(char *, mosquitto_strdup, (const char *s)); MOCK_METHOD(char *, mosquitto_strndup, (const char *s, size_t n)); /* mqtt_common.c */ MOCK_METHOD(unsigned int, mosquitto_varint_bytes, (uint32_t word)); /* password_common.c */ MOCK_METHOD(int, mosquitto_pw_new, (struct mosquitto_pw **pw, enum mosquitto_pwhash_type hashtype)); MOCK_METHOD(int, mosquitto_pw_hash_encoded, (struct mosquitto_pw *pw, const char *password)); MOCK_METHOD(int, mosquitto_pw_verify, (struct mosquitto_pw *pw, const char *password)); MOCK_METHOD(void, mosquitto_pw_set_valid, (struct mosquitto_pw *pw, bool valid)); MOCK_METHOD(bool, mosquitto_pw_is_valid, (struct mosquitto_pw *pw)); MOCK_METHOD(int, mosquitto_pw_decode, (struct mosquitto_pw *pw, const char *password)); MOCK_METHOD(const char *, mosquitto_pw_get_encoded, (struct mosquitto_pw *pw)); MOCK_METHOD(int, mosquitto_pw_set_param, (struct mosquitto_pw *pw, int param, int value)); MOCK_METHOD(void, mosquitto_pw_cleanup, (struct mosquitto_pw *pw)); /* property_common.c */ MOCK_METHOD(void, mosquitto_property_free, (mosquitto_property **property)); MOCK_METHOD(void, mosquitto_property_free_all, (mosquitto_property **property)); MOCK_METHOD(unsigned int, mosquitto_property_get_length, (const mosquitto_property *property)); MOCK_METHOD(unsigned int, mosquitto_property_get_length_all, (const mosquitto_property *property)); MOCK_METHOD(int, mosquitto_property_check_command, (int command, int identifier)); MOCK_METHOD(const char *, mosquitto_property_identifier_to_string, (int identifier)); MOCK_METHOD(int, mosquitto_string_to_property_info, (const char *propname, int *identifier, int *type)); MOCK_METHOD(int, mosquitto_property_add_byte, (mosquitto_property **proplist, int identifier, uint8_t value)); MOCK_METHOD(int, mosquitto_property_add_int16, (mosquitto_property **proplist, int identifier, uint16_t value)); MOCK_METHOD(int, mosquitto_property_add_int32, (mosquitto_property **proplist, int identifier, uint32_t value)); MOCK_METHOD(int, mosquitto_property_add_varint, (mosquitto_property **proplist, int identifier, uint32_t value)); MOCK_METHOD(int, mosquitto_property_add_binary, (mosquitto_property **proplist, int identifier, const void *value, uint16_t len)); MOCK_METHOD(int, mosquitto_property_add_string, (mosquitto_property **proplist, int identifier, const char *value)); MOCK_METHOD(int, mosquitto_property_add_string_pair, (mosquitto_property **proplist, int identifier, const char *name, const char *value)); MOCK_METHOD(int, mosquitto_property_check_all, (int command, const mosquitto_property *properties)); MOCK_METHOD(int, mosquitto_property_identifier, (const mosquitto_property *property)); MOCK_METHOD(int, mosquitto_property_type, (const mosquitto_property *property)); MOCK_METHOD(mosquitto_property *, mosquitto_property_next, (const mosquitto_property *proplist)); MOCK_METHOD(const mosquitto_property *, mosquitto_property_read_byte, (const mosquitto_property *proplist, int identifier, uint8_t *value, bool skip_first)); MOCK_METHOD(const mosquitto_property *, mosquitto_property_read_int16, (const mosquitto_property *proplist, int identifier, uint16_t *value, bool skip_first)); MOCK_METHOD(const mosquitto_property *, mosquitto_property_read_int32, (const mosquitto_property *proplist, int identifier, uint32_t *value, bool skip_first)); MOCK_METHOD(const mosquitto_property *, mosquitto_property_read_varint, (const mosquitto_property *proplist, int identifier, uint32_t *value, bool skip_first)); MOCK_METHOD(const mosquitto_property *, mosquitto_property_read_binary, (const mosquitto_property *proplist, int identifier, void **value, uint16_t *len, bool skip_first)); MOCK_METHOD(const mosquitto_property *, mosquitto_property_read_string, (const mosquitto_property *proplist, int identifier, char **value, bool skip_first)); MOCK_METHOD(const mosquitto_property *, mosquitto_property_read_string_pair, (const mosquitto_property *proplist, int identifier, char **name, char **value, bool skip_first)); MOCK_METHOD(int, mosquitto_property_remove, (mosquitto_property **proplist, const mosquitto_property *property)); MOCK_METHOD(int, mosquitto_property_copy_all, (mosquitto_property **dest, const mosquitto_property *src)); MOCK_METHOD(uint8_t, mosquitto_property_byte_value, (const mosquitto_property *property)); MOCK_METHOD(uint16_t, mosquitto_property_int16_value, (const mosquitto_property *property)); MOCK_METHOD(uint32_t, mosquitto_property_int32_value, (const mosquitto_property *property)); MOCK_METHOD(uint32_t, mosquitto_property_varint_value, (const mosquitto_property *property)); MOCK_METHOD(const void *, mosquitto_property_binary_value, (const mosquitto_property *property)); MOCK_METHOD(uint16_t, mosquitto_property_binary_value_length, (const mosquitto_property *property)); MOCK_METHOD(const char *, mosquitto_property_string_value, (const mosquitto_property *property)); MOCK_METHOD(uint16_t, mosquitto_property_string_value_length, (const mosquitto_property *property)); MOCK_METHOD(const char *, mosquitto_property_string_name, (const mosquitto_property *property)); MOCK_METHOD(uint16_t, mosquitto_property_string_name_length, (const mosquitto_property *property)); MOCK_METHOD(unsigned int, mosquitto_property_get_remaining_length, (const mosquitto_property *props)); /* random_common.c */ MOCK_METHOD(int, mosquitto_getrandom, (void *bytes, int count)); /* strings_common.c */ MOCK_METHOD(const char *, mosquitto_strerror, (int mosq_errno)); MOCK_METHOD(const char *, mosquitto_connack_string, (int connack_code)); MOCK_METHOD(const char *, mosquitto_reason_string, (int reason_code)); MOCK_METHOD(int, mosquitto_string_to_command, (const char *str, int *cmd)); /* time_common.c */ MOCK_METHOD(void, mosquitto_time_init, ()); MOCK_METHOD(time_t, mosquitto_time, ()); MOCK_METHOD(void, mosquitto_time_ns, (time_t *s, long *ns)); MOCK_METHOD(long, mosquitto_time_cmp, (time_t t1_s, long t1_ns, time_t t2_s, long t2_ns)); /* topic_common.c */ MOCK_METHOD(int, mosquitto_pub_topic_check, (const char *str)); MOCK_METHOD(int, mosquitto_pub_topic_check2, (const char *str, size_t len)); MOCK_METHOD(int, mosquitto_sub_topic_check, (const char *str)); MOCK_METHOD(int, mosquitto_sub_topic_check2, (const char *str, size_t len)); MOCK_METHOD(int, mosquitto_sub_matches_acl, (const char *acl, const char *sub, bool *result)); MOCK_METHOD(int, mosquitto_sub_matches_acl_with_pattern, (const char *acl, const char *sub, const char *clientid, const char *username, bool *result)); MOCK_METHOD(int, mosquitto_topic_matches_sub, (const char *sub, const char *topic, bool *result)); MOCK_METHOD(int, mosquitto_topic_matches_sub_with_pattern, (const char *sub, const char *topic, const char *clientid, const char *username, bool *result)); MOCK_METHOD(int, mosquitto_topic_matches_sub2, (const char *sub, size_t sublen, const char *topic, size_t topiclen, bool *result)); MOCK_METHOD(int, mosquitto_sub_topic_tokenise, (const char *subtopic, char ***topics, int *count)); MOCK_METHOD(int, mosquitto_sub_topic_tokens_free, (char ***topics, int count)); /* utf8_common.c */ MOCK_METHOD(int, mosquitto_validate_utf8, (const char *str, int len)); }; ================================================ FILE: test/mock/libcommon/memory_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" void mosquitto_memory_set_limit(size_t lim) { LibMosquittoCommonMock::get_mock().mosquitto_memory_set_limit(lim); } unsigned long mosquitto_memory_used(void) { return LibMosquittoCommonMock::get_mock().mosquitto_memory_used(); } unsigned long mosquitto_max_memory_used(void) { return LibMosquittoCommonMock::get_mock().mosquitto_max_memory_used(); } void *mosquitto_malloc(size_t size) { return LibMosquittoCommonMock::get_mock().mosquitto_malloc(size); } void *mosquitto_realloc(void *ptr, size_t size) { return LibMosquittoCommonMock::get_mock().mosquitto_realloc(ptr, size); } void mosquitto_free(void *mem) { LibMosquittoCommonMock::get_mock().mosquitto_free(mem); } void *mosquitto_calloc(size_t nmemb, size_t size) { return LibMosquittoCommonMock::get_mock().mosquitto_calloc(nmemb, size); } char *mosquitto_strdup(const char *s) { return LibMosquittoCommonMock::get_mock().mosquitto_strdup(s); } char *mosquitto_strndup(const char *s, size_t n) { return LibMosquittoCommonMock::get_mock().mosquitto_strndup(s, n); } ================================================ FILE: test/mock/libcommon/mqtt_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" unsigned int mosquitto_varint_bytes(uint32_t word) { return LibMosquittoCommonMock::get_mock().mosquitto_varint_bytes(word); } ================================================ FILE: test/mock/libcommon/password_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" int mosquitto_pw_new(struct mosquitto_pw **pw, enum mosquitto_pwhash_type hashtype) { return LibMosquittoCommonMock::get_mock().mosquitto_pw_new( pw, hashtype); } int mosquitto_pw_hash_encoded(struct mosquitto_pw *pw, const char *password) { return LibMosquittoCommonMock::get_mock().mosquitto_pw_hash_encoded( pw, password); } int mosquitto_pw_verify(struct mosquitto_pw *pw, const char *password) { return LibMosquittoCommonMock::get_mock().mosquitto_pw_verify( pw, password); } void mosquitto_pw_set_valid(struct mosquitto_pw *pw, bool valid) { LibMosquittoCommonMock::get_mock().mosquitto_pw_set_valid( pw, valid); } bool mosquitto_pw_is_valid(struct mosquitto_pw *pw) { return LibMosquittoCommonMock::get_mock().mosquitto_pw_is_valid(pw); } int mosquitto_pw_decode(struct mosquitto_pw *pw, const char *password) { return LibMosquittoCommonMock::get_mock().mosquitto_pw_decode( pw, password); } const char *mosquitto_pw_get_encoded(struct mosquitto_pw *pw) { return LibMosquittoCommonMock::get_mock().mosquitto_pw_get_encoded(pw); } int mosquitto_pw_set_param(struct mosquitto_pw *pw, int param, int value) { return LibMosquittoCommonMock::get_mock().mosquitto_pw_set_param( pw, param, value); } void mosquitto_pw_cleanup(struct mosquitto_pw *pw) { LibMosquittoCommonMock::get_mock().mosquitto_pw_cleanup(pw); } ================================================ FILE: test/mock/libcommon/property_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" void mosquitto_property_free(mosquitto_property **property) { LibMosquittoCommonMock::get_mock().mosquitto_property_free( property); } void mosquitto_property_free_all(mosquitto_property **property) { LibMosquittoCommonMock::get_mock().mosquitto_property_free_all( property); } unsigned int mosquitto_property_get_length(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_get_length( property); } unsigned int mosquitto_property_get_length_all(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_get_length_all( property); } int mosquitto_property_check_command(int command, int identifier) { return LibMosquittoCommonMock::get_mock().mosquitto_property_check_command( command, identifier); } const char *mosquitto_property_identifier_to_string(int identifier) { return LibMosquittoCommonMock::get_mock().mosquitto_property_identifier_to_string( identifier); } int mosquitto_string_to_property_info(const char *propname, int *identifier, int *type) { return LibMosquittoCommonMock::get_mock().mosquitto_string_to_property_info( propname, identifier, type); } int mosquitto_property_add_byte(mosquitto_property **proplist, int identifier, uint8_t value) { return LibMosquittoCommonMock::get_mock().mosquitto_property_add_byte( proplist, identifier, value); } int mosquitto_property_add_int16(mosquitto_property **proplist, int identifier, uint16_t value) { return LibMosquittoCommonMock::get_mock().mosquitto_property_add_int16( proplist, identifier, value); } int mosquitto_property_add_int32(mosquitto_property **proplist, int identifier, uint32_t value) { return LibMosquittoCommonMock::get_mock().mosquitto_property_add_int32( proplist, identifier, value); } int mosquitto_property_add_varint(mosquitto_property **proplist, int identifier, uint32_t value) { return LibMosquittoCommonMock::get_mock().mosquitto_property_add_varint( proplist, identifier, value); } int mosquitto_property_add_binary(mosquitto_property **proplist, int identifier, const void *value, uint16_t len) { return LibMosquittoCommonMock::get_mock().mosquitto_property_add_binary( proplist, identifier, value, len); } int mosquitto_property_add_string(mosquitto_property **proplist, int identifier, const char *value) { return LibMosquittoCommonMock::get_mock().mosquitto_property_add_string( proplist, identifier, value); } int mosquitto_property_add_string_pair(mosquitto_property **proplist, int identifier, const char *name, const char *value) { return LibMosquittoCommonMock::get_mock().mosquitto_property_add_string_pair( proplist, identifier, name, value); } int mosquitto_property_check_all(int command, const mosquitto_property *properties) { return LibMosquittoCommonMock::get_mock().mosquitto_property_check_all( command, properties); } int mosquitto_property_identifier(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_identifier( property); } int mosquitto_property_type(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_type( property); } mosquitto_property *mosquitto_property_next(const mosquitto_property *proplist) { return LibMosquittoCommonMock::get_mock().mosquitto_property_next( proplist); } const mosquitto_property *mosquitto_property_read_byte(const mosquitto_property *proplist, int identifier, uint8_t *value, bool skip_first) { return LibMosquittoCommonMock::get_mock().mosquitto_property_read_byte( proplist, identifier, value, skip_first); } const mosquitto_property *mosquitto_property_read_int16(const mosquitto_property *proplist, int identifier, uint16_t *value, bool skip_first) { return LibMosquittoCommonMock::get_mock().mosquitto_property_read_int16( proplist, identifier, value, skip_first); } const mosquitto_property *mosquitto_property_read_int32(const mosquitto_property *proplist, int identifier, uint32_t *value, bool skip_first) { return LibMosquittoCommonMock::get_mock().mosquitto_property_read_int32( proplist, identifier, value, skip_first); } const mosquitto_property *mosquitto_property_read_varint(const mosquitto_property *proplist, int identifier, uint32_t *value, bool skip_first) { return LibMosquittoCommonMock::get_mock().mosquitto_property_read_varint( proplist, identifier, value, skip_first); } const mosquitto_property *mosquitto_property_read_binary(const mosquitto_property *proplist, int identifier, void **value, uint16_t *len, bool skip_first) { return LibMosquittoCommonMock::get_mock().mosquitto_property_read_binary( proplist, identifier, value, len, skip_first); } const mosquitto_property *mosquitto_property_read_string(const mosquitto_property *proplist, int identifier, char **value, bool skip_first) { return LibMosquittoCommonMock::get_mock().mosquitto_property_read_string( proplist, identifier, value, skip_first); } const mosquitto_property *mosquitto_property_read_string_pair(const mosquitto_property *proplist, int identifier, char **name, char **value, bool skip_first) { return LibMosquittoCommonMock::get_mock().mosquitto_property_read_string_pair( proplist, identifier, name, value, skip_first); } int mosquitto_property_remove(mosquitto_property **proplist, const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_remove( proplist, property); } int mosquitto_property_copy_all(mosquitto_property **dest, const mosquitto_property *src) { return LibMosquittoCommonMock::get_mock().mosquitto_property_copy_all( dest, src); } uint8_t mosquitto_property_byte_value(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_byte_value( property); } uint16_t mosquitto_property_int16_value(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_int16_value( property); } uint32_t mosquitto_property_int32_value(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_int32_value( property); } uint32_t mosquitto_property_varint_value(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_varint_value( property); } const void *mosquitto_property_binary_value(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_binary_value( property); } uint16_t mosquitto_property_binary_value_length(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_binary_value_length( property); } const char *mosquitto_property_string_value(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_string_value( property); } uint16_t mosquitto_property_string_value_length(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_string_value_length( property); } const char *mosquitto_property_string_name(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_string_name( property); } uint16_t mosquitto_property_string_name_length(const mosquitto_property *property) { return LibMosquittoCommonMock::get_mock().mosquitto_property_string_name_length( property); } unsigned int mosquitto_property_get_remaining_length(const mosquitto_property *props) { return LibMosquittoCommonMock::get_mock().mosquitto_property_get_remaining_length( props); } ================================================ FILE: test/mock/libcommon/random_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" int mosquitto_getrandom(void *bytes, int count) { return LibMosquittoCommonMock::get_mock().mosquitto_getrandom( bytes, count); } ================================================ FILE: test/mock/libcommon/strings_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" const char *mosquitto_strerror(int mosq_errno) { return LibMosquittoCommonMock::get_mock().mosquitto_strerror( mosq_errno); } const char *mosquitto_connack_string(int connack_code) { return LibMosquittoCommonMock::get_mock().mosquitto_connack_string( connack_code); } const char *mosquitto_reason_string(int reason_code) { return LibMosquittoCommonMock::get_mock().mosquitto_reason_string( reason_code); } int mosquitto_string_to_command(const char *str, int *cmd) { return LibMosquittoCommonMock::get_mock().mosquitto_string_to_command( str, cmd); } ================================================ FILE: test/mock/libcommon/time_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" void mosquitto_time_init(void) { LibMosquittoCommonMock::get_mock().mosquitto_time_init(); } time_t mosquitto_time(void) { return LibMosquittoCommonMock::get_mock().mosquitto_time(); } void mosquitto_time_ns(time_t *s, long *ns) { return LibMosquittoCommonMock::get_mock().mosquitto_time_ns( s, ns); } long mosquitto_time_cmp(time_t t1_s, long t1_ns, time_t t2_s, long t2_ns) { return LibMosquittoCommonMock::get_mock().mosquitto_time_cmp( t1_s, t1_ns, t2_s, t2_ns); } ================================================ FILE: test/mock/libcommon/topic_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" int mosquitto_pub_topic_check(const char *str) { return LibMosquittoCommonMock::get_mock().mosquitto_pub_topic_check( str); } int mosquitto_pub_topic_check2(const char *str, size_t len) { return LibMosquittoCommonMock::get_mock().mosquitto_pub_topic_check2( str, len); } int mosquitto_sub_topic_check(const char *str) { return LibMosquittoCommonMock::get_mock().mosquitto_sub_topic_check( str); } int mosquitto_sub_topic_check2(const char *str, size_t len) { return LibMosquittoCommonMock::get_mock().mosquitto_sub_topic_check2( str, len); } int mosquitto_sub_matches_acl(const char *acl, const char *sub, bool *result) { return LibMosquittoCommonMock::get_mock().mosquitto_sub_matches_acl( acl, sub, result); } int mosquitto_sub_matches_acl_with_pattern(const char *acl, const char *sub, const char *clientid, const char *username, bool *result) { return LibMosquittoCommonMock::get_mock().mosquitto_sub_matches_acl_with_pattern( acl, sub, clientid, username, result); } int mosquitto_topic_matches_sub(const char *sub, const char *topic, bool *result) { return LibMosquittoCommonMock::get_mock().mosquitto_topic_matches_sub( sub, topic, result); } int mosquitto_topic_matches_sub_with_pattern(const char *sub, const char *topic, const char *clientid, const char *username, bool *result) { return LibMosquittoCommonMock::get_mock().mosquitto_topic_matches_sub_with_pattern( sub, topic, clientid, username, result); } int mosquitto_topic_matches_sub2(const char *sub, size_t sublen, const char *topic, size_t topiclen, bool *result) { return LibMosquittoCommonMock::get_mock().mosquitto_topic_matches_sub2( sub, sublen, topic, topiclen, result); } int mosquitto_sub_topic_tokenise(const char *subtopic, char ***topics, int *count) { return LibMosquittoCommonMock::get_mock().mosquitto_sub_topic_tokenise( subtopic, topics, count); } int mosquitto_sub_topic_tokens_free(char ***topics, int count) { return LibMosquittoCommonMock::get_mock().mosquitto_sub_topic_tokens_free( topics, count); } ================================================ FILE: test/mock/libcommon/utf8_common_mock.cpp ================================================ #include "libmosquitto_common_mock.hpp" int mosquitto_validate_utf8(const char *str, int len) { return LibMosquittoCommonMock::get_mock().mosquitto_validate_utf8( str, len); } ================================================ FILE: test/mock/pthread_mock.cpp ================================================ #include "pthread_mock.hpp" PThreadMock::PThreadMock() { } PThreadMock::~PThreadMock() { } int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) { return PThreadMock::get_mock().pthread_cond_timedwait(cond, mutex, abstime); } ================================================ FILE: test/mock/pthread_mock.hpp ================================================ #pragma once #include #include #include "c_function_mock.hpp" class PThreadMock : public CFunctionMock { public: PThreadMock(); virtual ~PThreadMock(); MOCK_METHOD(int, pthread_cond_timedwait, (pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)); }; ================================================ FILE: test/mosq_test.py ================================================ import atexit import base64 import errno import hashlib import os import socket import subprocess import struct import sys import time import uuid import traceback import mqtt5_props import __main__ from pathlib import Path vg_index = 1 vg_logfiles = [] class TestError(Exception): def __init__(self, message="Mismatched packets"): self.message = message def get_build_root(): result = os.getenv("BUILD_ROOT") if result is None: result = str(Path(__file__).resolve().parents[1]) return result def env_add_ld_library_path(env=None): p = ":".join([ get_build_root() + '/libcommon', get_build_root() + '/lib', get_build_root() + '/lib/cpp', os.getenv("LD_LIBRARY_PATH", "") ]) if env is None: env = { 'LD_LIBRARY_PATH': p, 'DYLIB_LIBRARY_PATH': p, } else: for v in ['LD_LIBRARY_PATH', 'DYLIB_LIBRARY_PATH']: try: val = env[v] env[v] = ":".join([val, p]) except KeyError: env[v] = p return env def listen_sock(port): 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) return sock def start_broker(filename, cmd=None, port=0, use_conf=False, expect_fail=False, expect_fail_log=None, nolog=False, checkhost="localhost", env=None, check_port=True, cmd_args=None, timeout=0.1): global vg_index global vg_logfiles if use_conf == True: cmd = [get_build_root() + '/src/mosquitto', '-v', '-c', filename.replace('.py', '.conf')] if port == 0: port = 1888 else: cmd += ['-p', str(port)] else: if cmd is None and port != 0: cmd = [get_build_root() + '/src/mosquitto', '-v', '-p', str(port)] elif cmd is None and port == 0: cmd = [get_build_root() + '/src/mosquitto', '-v', '-c', filename.replace('.py', '.conf')] if os.environ.get('MOSQ_USE_VALGRIND') is not None: logfile = filename+'.'+str(vg_index)+'.vglog' if os.environ.get('MOSQ_USE_VALGRIND') == 'callgrind': cmd = ['valgrind', '-q', '--tool=callgrind', '--log-file='+logfile] + cmd elif os.environ.get('MOSQ_USE_VALGRIND') == 'massif': cmd = ['valgrind', '-q', '--tool=massif', '--log-file='+logfile] + cmd elif os.environ.get('MOSQ_USE_VALGRIND') == 'failgrind': cmd = ['fg-helper'] + cmd else: cmd = ['valgrind', '-q', '--gen-suppressions=all', '--suppressions=test.supp', '--track-fds=yes', '--trace-children=yes', '--leak-check=full', '--show-leak-kinds=all', '--log-file='+logfile] + cmd vg_logfiles.append(logfile) vg_index += 1 timeout = 1 if cmd_args: cmd.extend(cmd_args) #print(port) #print(cmd) if nolog: stderr = subprocess.DEVNULL else: stderr = subprocess.PIPE broker = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=stderr, env=env) if expect_fail: try: broker.wait(timeout*10) if expect_fail_log is not None: (_, stde) = broker.communicate() if expect_fail_log not in stde.decode('utf-8'): print(f"{expect_fail_log} not found in log.") print(stde.decode('utf-8')) raise ValueError() except subprocess.TimeoutExpired: _, errs = terminate_broker(broker) print(f"Broker did not fail to start:\n{errs.decode('utf-8')}") raise return broker if check_port == False: return broker assert port != 0 for i in range(0, 20): time.sleep(timeout) c = None try: c = socket.create_connection((checkhost, port)) except socket.error as err: if err.errno != errno.ECONNREFUSED: raise if c is not None: c.close() return broker if expect_fail == False: outs, errs = broker.communicate(timeout=timeout) print("FAIL: unable to start broker: %s" % errs) raise IOError else: return broker def start_client(filename, cmd, env=None): if cmd is None: raise ValueError env = env_add_ld_library_path(env) if os.environ.get('MOSQ_USE_VALGRIND') is not None: cmd = ['valgrind', '-q', '--log-file='+filename+'.vglog'] + cmd return subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) def wait_for_subprocess(client,timeout=10,terminate_timeout=2): rc=0 try: client.wait(timeout) except subprocess.TimeoutExpired: rc=1 client.terminate() try: client.wait(terminate_timeout) except subprocess.TimeoutExpired: rc=2 client.kill() try: client.wait(terminate_timeout) except subprocess.TimeoutExpired: rc=3 pass return rc def terminate_broker(broker): broker.terminate() (_, stde) = broker.communicate() if wait_for_subprocess(broker): print("broker not terminated") return (1, stde) else: return (0, stde) def pub_helper(port, proto_ver=4): connect_packet = gen_connect("pub-helper", proto_ver=proto_ver) connack_packet = gen_connack(rc=0, proto_ver=proto_ver) sock = do_client_connect(connect_packet, connack_packet, port=port, connack_error="pub helper connack") return sock def sub_helper(port, topic='#', qos=0, proto_ver=4): connect_packet = gen_connect("sub-helper", proto_ver=proto_ver) connack_packet = gen_connack(rc=0, proto_ver=proto_ver) mid = 1 subscribe_packet = gen_subscribe(mid=mid, topic=topic, qos=qos, proto_ver=proto_ver) suback_packet = gen_suback(mid=mid, qos=qos, proto_ver=proto_ver) sock = do_client_connect(connect_packet, connack_packet, port=port) do_send_receive(sock, subscribe_packet, suback_packet, "sub helper suback") return sock def expect_packet(sock, name, expected): if len(expected) > 0: rlen = len(expected) else: rlen = 1 packet_recvd = b"" try: while len(packet_recvd) < rlen: data = sock.recv(rlen-len(packet_recvd)) if len(data) == 0: try: s = f"when reading {name} from {sock.getpeername()}" except OSError: s = f"when reading {name} from {sock}" raise BrokenPipeError(s) packet_recvd += data except socket.timeout: pass 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)) traceback.print_stack(file=sys.stdout) 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(sock, send_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 def do_send_receive(sock, send_packet, receive_packet, error_string="send receive error"): do_send(sock, send_packet) 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): do_send(sock, send_packet) return sock else: sock.close() raise ValueError def client_connect_only(hostname="localhost", port=1888, timeout=10, protocol="mqtt"): if protocol == "websockets": addr = (hostname, port) sock = socket.create_connection(addr, timeout=timeout) sock.settimeout(timeout) sock = WebsocketWrapper(sock, hostname, port, False, "/mqtt", None) #sock.setblocking(0) else: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((hostname, port)) return sock def client_connect_only_unix(path, timeout=10): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect(path) return sock def do_client_connect(connect_packet, connack_packet, hostname="localhost", port=1888, timeout=10, connack_error="connack", protocol="mqtt"): sock = client_connect_only(hostname, port, timeout, protocol) return do_send_receive(sock, connect_packet, connack_packet, connack_error) def do_client_connect_unix(connect_packet, connack_packet, path, timeout=10, connack_error="connack"): sock = client_connect_only_unix(path, timeout) 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 if len(packet) >= 4: (cmd, rl, flags, reason_code) = struct.unpack('!BBBB', packet[0:4]) s=f"CONNACK, rl={rl}, res/flags={flags}, rc={reason_code}" if len(packet) > 4: s = s+ f", properties={mqtt5_props.print_properties(packet[4:])}" return s else: return "CONNACK, (not decoded)" 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_fixed_hdr(command, remaining_length): return struct.pack("B", command) + pack_remaining_length(remaining_length) def gen_variable_hdr(mid=None): if mid is not None: return struct.pack("!H", mid) else: return b"" 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.RECEIVE_MAXIMUM, 20) if session_expiry != -1: properties += mqtt5_props.gen_uint32_prop(mqtt5_props.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.TOPIC_ALIAS_MAXIMUM, 10) \ + properties \ + mqtt5_props.gen_uint32_prop(mqtt5_props.MAXIMUM_PACKET_SIZE, 2000000) \ + mqtt5_props.gen_uint16_prop(mqtt5_props.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: if isinstance(payload, bytes) == False: 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)+len(properties) packet += pack_remaining_length(l) pack_format = "!H"+str(len(properties))+"sH"+str(len(topic))+"s" packet += struct.pack(pack_format, mid, 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 do_ping(sock, error_string="pingresp"): do_send_receive(sock, gen_pingreq(), gen_pingresp(), error_string) def client_test(client_cmd, client_args, callback, cb_data): port = get_port() rc = 1 sock = listen_sock(port) args = [get_build_root() + "/test/lib/" + client_cmd, str(port)] if client_args is not None: args = args + client_args client = start_client(filename=client_cmd.replace('/', '-'), cmd=args) try: (conn, address) = sock.accept() conn.settimeout(10) callback(conn, cb_data) rc = 0 conn.close() except TestError as err: print(err) except Exception as err: print(err) raise finally: client_rc = wait_for_subprocess(client) if client_rc: print("test client not finished") rc=1 sock.close() if rc: (o, e) = client.communicate() print(o) print(e) print(f"Fail: {client_cmd} rc={rc}, client_rc={client_rc}") exit(rc) def get_non_loopback_ip(): # https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(0) try: # doesn't even have to be reachable s.connect(('10.254.254.254', 1)) IP = s.getsockname()[0] except Exception: # Explicitly not 127.0.0.1 - we want something that doesn't match a # certificate SAN IP = '127.0.0.2' finally: s.close() return IP # ============================================= # Websockets wrapper # ============================================= class WebsocketConnectionError(ValueError): pass class WebsocketWrapper(object): OPCODE_CONTINUATION = 0x0 OPCODE_TEXT = 0x1 OPCODE_BINARY = 0x2 OPCODE_CONNCLOSE = 0x8 OPCODE_PING = 0x9 OPCODE_PONG = 0xa def __init__(self, socket, host, port, is_ssl, path, extra_headers): self.connected = False self._ssl = is_ssl self._host = host self._port = port self._socket = socket self._path = path self._sendbuffer = bytearray() self._readbuffer = bytearray() self._requested_size = 0 self._payload_head = 0 self._readbuffer_head = 0 self._do_handshake(extra_headers) def __del__(self): self._sendbuffer = None self._readbuffer = None def _do_handshake(self, extra_headers): sec_websocket_key = uuid.uuid4().bytes sec_websocket_key = base64.b64encode(sec_websocket_key) websocket_headers = { "Host": "{self._host:s}:{self._port:d}".format(self=self), "Upgrade": "websocket", "Connection": "Upgrade", "Origin": "https://{self._host:s}:{self._port:d}".format(self=self), "Sec-WebSocket-Key": sec_websocket_key.decode("utf8"), "Sec-Websocket-Version": "13", "Sec-Websocket-Protocol": "mqtt", } # This is checked in ws_set_options so it will either be None, a # dictionary, or a callable if isinstance(extra_headers, dict): websocket_headers.update(extra_headers) elif callable(extra_headers): websocket_headers = extra_headers(websocket_headers) header = "\r\n".join([ "GET {self._path} HTTP/1.1".format(self=self), "\r\n".join("{}: {}".format(i, j) for i, j in websocket_headers.items()), "\r\n", ]).encode("utf8") self._socket.send(header) has_secret = False has_upgrade = False while True: # read HTTP response header as lines byte = self._socket.recv(1) self._readbuffer.extend(byte) # line end if byte == b"\n": if len(self._readbuffer) > 2: # check upgrade if b"connection" in str(self._readbuffer).lower().encode('utf-8'): if b"upgrade" not in str(self._readbuffer).lower().encode('utf-8'): raise WebsocketConnectionError( "WebSocket handshake error, connection not upgraded") else: has_upgrade = True # check key hash if b"sec-websocket-accept" in str(self._readbuffer).lower().encode('utf-8'): GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" server_hash = self._readbuffer.decode( 'utf-8').split(": ", 1)[1] server_hash = server_hash.strip().encode('utf-8') client_hash = sec_websocket_key.decode('utf-8') + GUID client_hash = hashlib.sha1(client_hash.encode('utf-8')) client_hash = base64.b64encode(client_hash.digest()) if server_hash != client_hash: raise WebsocketConnectionError( "WebSocket handshake error, invalid secret key") else: has_secret = True else: # ending linebreak break # reset linebuffer self._readbuffer = bytearray() # connection reset elif not byte: raise WebsocketConnectionError("WebSocket handshake error") if not has_upgrade or not has_secret: raise WebsocketConnectionError("WebSocket handshake error") self._readbuffer = bytearray() self.connected = True def _create_frame(self, opcode, data, do_masking=1): header = bytearray() length = len(data) mask_key = bytearray(os.urandom(4)) mask_flag = do_masking # 1 << 7 is the final flag, we don't send continuated data header.append(1 << 7 | opcode) if length < 126: header.append(mask_flag << 7 | length) elif length < 65536: header.append(mask_flag << 7 | 126) header += struct.pack("!H", length) elif length < 0x8000000000000001: header.append(mask_flag << 7 | 127) header += struct.pack("!Q", length) else: raise ValueError("Maximum payload size is 2^63") if mask_flag == 1: for index in range(length): data[index] ^= mask_key[index % 4] data = mask_key + data return header + data def _buffered_read(self, length): # try to recv and store needed bytes wanted_bytes = length - (len(self._readbuffer) - self._readbuffer_head) if wanted_bytes > 0: data = self._socket.recv(wanted_bytes) if not data: raise ConnectionAbortedError else: self._readbuffer.extend(data) if len(data) < wanted_bytes: print(f"{len(data)} {wanted_bytes}") raise BlockingIOError self._readbuffer_head += length return self._readbuffer[self._readbuffer_head - length:self._readbuffer_head] def _recv_impl(self, length): # try to decode websocket payload part from data try: self._readbuffer_head = 0 result = None chunk_startindex = self._payload_head chunk_endindex = self._payload_head + length header1 = self._buffered_read(1) header2 = self._buffered_read(1) opcode = (header1[0] & 0x0f) maskbit = (header2[0] & 0x80) == 0x80 lengthbits = (header2[0] & 0x7f) payload_length = lengthbits mask_key = None # read length if lengthbits == 0x7e: value = self._buffered_read(2) payload_length, = struct.unpack("!H", value) elif lengthbits == 0x7f: value = self._buffered_read(8) payload_length, = struct.unpack("!Q", value) # read mask if maskbit: mask_key = self._buffered_read(4) # if frame payload is shorter than the requested data, read only the possible part readindex = chunk_endindex if payload_length < readindex: readindex = payload_length if readindex > 0: # get payload chunk payload = self._buffered_read(readindex) # unmask only the needed part if maskbit: for index in range(chunk_startindex, readindex): payload[index] ^= mask_key[index % 4] result = payload[chunk_startindex:readindex] self._payload_head = readindex else: payload = bytearray() # check if full frame arrived and reset readbuffer and payloadhead if needed if readindex == payload_length: self._readbuffer = bytearray() self._payload_head = 0 # respond to non-binary opcodes, their arrival is not guaranteed beacause of non-blocking sockets if opcode == WebsocketWrapper.OPCODE_CONNCLOSE: frame = self._create_frame( WebsocketWrapper.OPCODE_CONNCLOSE, payload, 0) self._socket.send(frame) if opcode == WebsocketWrapper.OPCODE_PING: frame = self._create_frame( WebsocketWrapper.OPCODE_PONG, payload, 0) self._socket.send(frame) # This isn't *proper* handling of continuation frames, but given # that we only support binary frames, it is *probably* good enough. if (opcode == WebsocketWrapper.OPCODE_BINARY or opcode == WebsocketWrapper.OPCODE_CONTINUATION) \ and payload_length > 0: return result else: #raise BlockingIOError return b"" except ConnectionError: self.connected = False return b'' def _send_impl(self, data): # if previous frame was sent successfully if len(self._sendbuffer) == 0: # create websocket frame frame = self._create_frame( WebsocketWrapper.OPCODE_BINARY, bytearray(data)) self._sendbuffer.extend(frame) self._requested_size = len(data) # try to write out as much as possible length = self._socket.send(self._sendbuffer) self._sendbuffer = self._sendbuffer[length:] if len(self._sendbuffer) == 0: # buffer sent out completely, return with payload's size return self._requested_size else: # couldn't send whole data, request the same data again with 0 as sent length return 0 def recv(self, length): return self._recv_impl(length) def read(self, length): return self._recv_impl(length) def send(self, data): return self._send_impl(data) def write(self, data): return self._send_impl(data) def close(self): self._socket.close() def fileno(self): return self._socket.fileno() def pending(self): # Fix for bug #131: a SSL socket may still have data available # for reading without select() being aware of it. if self._ssl: return self._socket.pending() else: # normal socket rely only on select() return 0 def setblocking(self, flag): self._socket.setblocking(flag) @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 ================================================ FILE: test/mqtt5_opts.py ================================================ 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 ================================================ FILE: test/mqtt5_props.py ================================================ import struct PAYLOAD_FORMAT_INDICATOR = 1 MESSAGE_EXPIRY_INTERVAL = 2 CONTENT_TYPE = 3 RESPONSE_TOPIC = 8 CORRELATION_DATA = 9 SUBSCRIPTION_IDENTIFIER = 11 SESSION_EXPIRY_INTERVAL = 17 ASSIGNED_CLIENT_IDENTIFIER = 18 SERVER_KEEP_ALIVE = 19 AUTHENTICATION_METHOD = 21 AUTHENTICATION_DATA = 22 REQUEST_PROBLEM_INFO = 23 WILL_DELAY_INTERVAL = 24 REQUEST_RESPONSE_INFO = 25 RESPONSE_INFO = 26 SERVER_REFERENCE = 28 REASON_STRING = 31 RECEIVE_MAXIMUM = 33 TOPIC_ALIAS_MAXIMUM = 34 TOPIC_ALIAS = 35 MAXIMUM_QOS = 36 RETAIN_AVAILABLE = 37 USER_PROPERTY = 38 MAXIMUM_PACKET_SIZE = 39 WILDCARD_SUB_AVAILABLE = 40 SUBSCRIPTION_ID_AVAILABLE = 41 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 def gen_properties(properties_dict: dict) -> bytes: props = b"" if properties_dict is None: return props for prop in properties_dict: id = prop.get("identifier") value = prop.get("value") if id in ( PAYLOAD_FORMAT_INDICATOR, REQUEST_PROBLEM_INFO, REQUEST_RESPONSE_INFO, MAXIMUM_QOS, RETAIN_AVAILABLE, WILDCARD_SUB_AVAILABLE, SUBSCRIPTION_ID_AVAILABLE, SHARED_SUB_AVAILABLE, ): props += gen_byte_prop(id, value) elif id in ( MESSAGE_EXPIRY_INTERVAL, SESSION_EXPIRY_INTERVAL, WILL_DELAY_INTERVAL, MAXIMUM_PACKET_SIZE, ): props += gen_uint32_prop(id, value) elif id in ( CONTENT_TYPE, RESPONSE_TOPIC, CORRELATION_DATA, ASSIGNED_CLIENT_IDENTIFIER, AUTHENTICATION_METHOD, AUTHENTICATION_DATA, RESPONSE_INFO, SERVER_REFERENCE, REASON_STRING, ): props += gen_string_prop(id, value) elif id == SUBSCRIPTION_IDENTIFIER: props += gen_varint_prop(id, value) elif id in ( SERVER_KEEP_ALIVE, RECEIVE_MAXIMUM, TOPIC_ALIAS_MAXIMUM, TOPIC_ALIAS, ): props += gen_uint16_prop(id, value) elif id == USER_PROPERTY: props += gen_string_pair_prop(id, prop["name"], value) return props def unpack_varint(b: bytes): def decode_len(b: bytes): for i in range(len(b)): if b[i] & 0x80 == 0: return i + 1 return 0 var_len = decode_len(b) variant = 0 for i in range(var_len - 1, -1, -1): variant = 0x80 * variant + (struct.unpack("!B", b[i : i + 1])[0] & 0x7F) return variant, var_len def unpack_string(b: bytes): str_len = struct.unpack("!B", b[0:1])[0] str_value = struct.unpack(f"!{str_len}s", b[1 : str_len + 1])[0] return str_value, str_len + 1 def unpack_property(b: bytes): id = struct.unpack("!B", b[0:1])[0] if id == PAYLOAD_FORMAT_INDICATOR: return "PAYLOAD_FORMAT_INDICATOR", struct.unpack("!B", b[1:2])[0], 2 elif id == PAYLOAD_FORMAT_INDICATOR: return "PAYLOAD_FORMAT_INDICATOR", struct.unpack("!B", b[1:2])[0], 2 elif id == REQUEST_PROBLEM_INFO: return "REQUEST_PROBLEM_INFO", struct.unpack("!B", b[1:2])[0], 2 elif id == REQUEST_RESPONSE_INFO: return "REQUEST_RESPONSE_INFO", struct.unpack("!B", b[1:2])[0], 2 elif id == MAXIMUM_QOS: return "MAXIMUM_QOS", struct.unpack("!B", b[1:2])[0], 2 elif id == RETAIN_AVAILABLE: return "RETAIN_AVAILABLE", struct.unpack("!B", b[1:2])[0], 2 elif id == WILDCARD_SUB_AVAILABLE: return "WILDCARD_SUB_AVAILABLE", struct.unpack("!B", b[1:2])[0], 2 elif id == SUBSCRIPTION_ID_AVAILABLE: return "SUBSCRIPTION_ID_AVAILABLE", struct.unpack("!B", b[1:2])[0], 2 elif id == SHARED_SUB_AVAILABLE: return "SHARED_SUB_AVAILABLE", struct.unpack("!B", b[1:2])[0], 2 elif id == SERVER_KEEP_ALIVE: return "SERVER_KEEP_ALIVE", struct.unpack("!H", b[1:3])[0], 3 elif id == RECEIVE_MAXIMUM: return "RECEIVE_MAXIMUM", struct.unpack("!H", b[1:3])[0], 3 elif id == TOPIC_ALIAS_MAXIMUM: return "TOPIC_ALIAS_MAXIMUM", struct.unpack("!H", b[1:3])[0], 3 elif id == TOPIC_ALIAS: return "TOPIC_ALIAS", struct.unpack("!H", b[1:3])[0], 3 elif id == MESSAGE_EXPIRY_INTERVAL: return "MESSAGE_EXPIRY_INTERVAL", struct.unpack("!B", b[1:5])[0], 5 elif id == SESSION_EXPIRY_INTERVAL: return "SESSION_EXPIRY_INTERVAL", struct.unpack("!B", b[1:5])[0], 5 elif id == WILL_DELAY_INTERVAL: return "WILL_DELAY_INTERVAL", struct.unpack("!B", b[1:5])[0], 5 elif id == MAXIMUM_PACKET_SIZE: return "MAXIMUM_PACKET_SIZE", struct.unpack("!B", b[1:5])[0], 5 elif id == CONTENT_TYPE: value, pack_len = unpack_string(b[1:]) return "CONTENT_TYPE", value, pack_len + 1 elif id == RESPONSE_TOPIC: value, pack_len = unpack_string(b[1:]) return "RESPONSE_TOPIC", value, pack_len + 1 elif id == CORRELATION_DATA: value, pack_len = unpack_string(b[1:]) return "CORRELATION_DATA", value, pack_len + 1 elif id == ASSIGNED_CLIENT_IDENTIFIER: value, pack_len = unpack_string(b[1:]) return "ASSIGNED_CLIENT_IDENTIFIER", value, pack_len + 1 elif id == AUTHENTICATION_METHOD: value, pack_len = unpack_string(b[1:]) return "AUTHENTICATION_METHOD", value, pack_len + 1 elif id == AUTHENTICATION_DATA: value, pack_len = unpack_string(b[1:]) return "AUTHENTICATION_DATA", value, pack_len + 1 elif id == RESPONSE_INFO: value, pack_len = unpack_string(b[1:]) return "RESPONSE_INFO", value, pack_len + 1 elif id == SERVER_REFERENCE: value, pack_len = unpack_string(b[1:]) return "SERVER_REFERENCE", value, pack_len + 1 elif id == REASON_STRING: value, pack_len = unpack_string(b[1:]) return "REASON_STRING", value, pack_len + 1 elif id == SUBSCRIPTION_IDENTIFIER: value, pack_len = unpack_varint(b[1:]) return "SUBSCRIPTION_IDENTIFIER", value, pack_len + 1 elif id == USER_PROPERTY: name, pack_name_len = unpack_string(b[1:]) value, pack_value_len = unpack_varint(b[1 + pack_name_len :]) return ( f"USER_PROPERTY:{name}", value, 1 + pack_name_len + pack_value_len + pack_len, ) else: return f"", f"not decoded (len<={len(b)-1})", len(b) def print_properties(b: bytes): _, offset = unpack_varint(b) props = [] while offset < len(b): try: key, value, prop_len = unpack_property(b[offset:]) offset += prop_len props.append(f"{key}:{value}") except struct.error: props.append(f"decode error at offset {offset}: {b}") break return f"[{','.join(props)}]" ================================================ FILE: test/mqtt5_rc.py ================================================ SUCCESS = 0 NORMAL_DISCONNECTION = 0 GRANTED_QOS0 = 0 GRANTED_QOS1 = 1 GRANTED_QOS2 = 2 DISCONNECT_WITH_WILL_MSG = 4 NO_MATCHING_SUBSCRIBERS = 16 NO_SUBSCRIPTION_EXISTED = 17 CONTINUE_AUTHENTICATION = 24 REAUTHENTICATE = 25 UNSPECIFIED = 128 MALFORMED_PACKET = 129 PROTOCOL_ERROR = 130 IMPLEMENTATION_SPECIFIC = 131 UNSUPPORTED_PROTOCOL_VERSION = 132 CLIENTID_NOT_VALID = 133 BAD_USERNAME_OR_PASSWORD = 134 NOT_AUTHORIZED = 135 SERVER_UNAVAILABLE = 136 SERVER_BUSY = 137 BANNED = 138 SERVER_SHUTTING_DOWN = 139 BAD_AUTHENTICATION_METHOD = 140 KEEP_ALIVE_TIMEOUT = 141 SESSION_TAKEN_OVER = 142 TOPIC_FILTER_INVALID = 143 TOPIC_NAME_INVALID = 144 PACKET_ID_IN_USE = 145 PACKET_ID_NOT_FOUND = 146 RECEIVE_MAXIMUM_EXCEEDED = 147 TOPIC_ALIAS_INVALID = 148 PACKET_TOO_LARGE = 149 MESSAGE_RATE_TOO_HIGH = 150 QUOTA_EXCEEDED = 151 ADMINISTRATIVE_ACTION = 152 PAYLOAD_FORMAT_INVALID = 153 RETAIN_NOT_SUPPORTED = 154 QOS_NOT_SUPPORTED = 155 USE_ANOTHER_SERVER = 156 SERVER_MOVED = 157 SHARED_SUBS_NOT_SUPPORTED = 158 CONNECTION_RATE_EXCEEDED = 159 MAXIMUM_CONNECT_TIME = 160 SUBSCRIPTION_IDS_NOT_SUPPORTED = 161 WILDCARD_SUBS_NOT_SUPPORTED = 162 ================================================ FILE: test/old/Makefile ================================================ R=../.. include ${R}/config.mk CC=cc LOCAL_CFLAGS=-I${R}/src -I${R}/include -I. -I${R} -Wall -ggdb -DDEBUG -DWITH_CLIENT LOCAL_LDFLAGS= SOVERSION=1 .PHONY: all test clean all : msgsps_pub msgsps_sub msgsps_pub : msgsps_pub.o ${CC} $^ -o $@ ${LIBMOSQ} msgsps_pub.o : msgsps_pub.c msgsps_common.h ${CC} $(LOCAL_CFLAGS) -c $< -o $@ msgsps_sub : msgsps_sub.o ${CC} $^ -o $@ ${LIBMOSQ} msgsps_sub.o : msgsps_sub.c msgsps_common.h ${CC} $(LOCAL_CFLAGS) -c $< -o $@ clean : -rm -f *.o msgsps_pub msgsps_sub ================================================ FILE: test/old/msgsps_common.h ================================================ #ifndef MSGSPS_COMMON_H #define MSGSPS_COMMON_H #define HOST "127.0.0.1" #define PORT 1883 #define PUB_QOS 1 #define SUB_QOS 1 #define MESSAGE_SIZE 1024L #endif ================================================ FILE: test/old/msgsps_pub.c ================================================ /* 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; } ================================================ FILE: test/old/msgsps_sub.c ================================================ /* 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; } ================================================ FILE: test/path_helper.h ================================================ #ifndef PATH_HELPER_H #define PATH_HELPER_H #include #include #include #include #include /* returns / written to */ void cat_sourcedir_with_relpath(char *dest, const char *relpath) { strcpy(dest, TEST_SOURCE_DIR); strcat(dest, relpath); } #endif ================================================ FILE: test/ptest.py ================================================ #!/usr/bin/env python3 import json import os from pathlib import Path import subprocess import time import sys COLOUR_PASS = 34 COLOUR_FAIL = 124 class PTestCase(): def __init__(self, path, ports, cmd, args=None): self.path = path self.ports = ports self.cmd = str(cmd) self.attempts = 0 if args is not None: self.args = [self.cmd] + args else: self.args = [self.cmd] self.start_time = 0 self.proc = None self.mosq_port = None self.runtime = 0 def start(self): self.run_args = self.args.copy() for p in self.mosq_port: self.run_args.append(str(p)) self.proc = subprocess.Popen(self.run_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.path) self.start_time = time.time() def print_result(self, attempt, col): cmd = " ".join(self.run_args) if col == COLOUR_PASS: stat = "✓" elif col == COLOUR_FAIL: stat = "✗" else: stat = attempt if sys.stdout.isatty(): ansi_col = f"\033[38:5:{col}m" ansi_reset = "\033[0m" else: ansi_col = "" ansi_reset = "" print(f"{self.runtime:0.3f}s : {stat} : {ansi_col}{self.path}/{cmd}{ansi_reset}") def print_timed_out(self, col): cmd = " ".join(self.run_args) if sys.stdout.isatty(): ansi_col = f"\033[38:5:{col}m" ansi_reset = "\033[0m" else: ansi_col = "" ansi_reset = "" print(f"{self.runtime:0.3f}s : ⏳ : {ansi_col}{self.path}/{cmd}{ansi_reset}") def print_log(self): (stdo, stde) = self.proc.communicate() print(stdo.decode('utf-8')) print(stde.decode('utf-8')) class PTest(): def __init__(self, minport=1888, max_running=20): self.minport = minport self.max_running = 20 self.tests = [] def add_tests(self, test_list, path=".", label=""): for testdef in test_list: try: if isinstance(testdef[2], (list,)): args = testdef[2] else: args = [testdef[2]] except IndexError: args = None self.tests.append(PTestCase(path, testdef[0], testdef[1], args)) def _next_test(self, ports): if len(self.tests) == 0 or len(ports) == 0: return test = self.tests.pop() test.mosq_port = [] if len(ports) < test.ports: self.tests.insert(0, test) return None else: for i in range(0, test.ports): proc_port = ports.pop() test.mosq_port.append(proc_port) test.start() return test def run_tests(self, test_list): self.add_tests(test_list) self.run() def load_failed_tests(self): with open("failed-tests.json", "rt") as f: return json.loads(f.read()) def run_failed_tests(self): test_list = self.load_failed_tests() self.add_tests(test_list) self.run() def run(self): ports = list(range(self.minport, self.minport+self.max_running+1)) start_time = time.time() passed = 0 retried = 0 failed = 0 failed_tests = [] failed_tests_output = [] running_tests = [] retry_tests = [] while len(self.tests) > 0 or len(running_tests) > 0 or len(retry_tests) > 0: if len(running_tests) <= self.max_running: t = self._next_test(ports) if t is None: time.sleep(0.1) else: running_tests.append(t) if len(running_tests) == 0 and len(self.tests) == 0 and len(retry_tests) > 0: # Only retry tests after everything else has finished to reduce load self.tests = retry_tests retry_tests = [] for t in running_tests: t.proc.poll() t.runtime = time.time() - t.start_time if t.proc.returncode is not None: running_tests.remove(t) for portret in t.mosq_port: ports.append(portret) t.proc.terminate() t.proc.wait() if t.proc.returncode != 0 and t.attempts < 5: t.print_result(t.attempts+1, 226-6*t.attempts) retried += 1 t.attempts += 1 t.proc = None t.mosq_port = None retry_tests.append(t) continue if t.proc.returncode != 0: t.print_result(0, COLOUR_FAIL) failed = failed + 1 failed_tests.append(t.cmd) failed_tests_output.append([t.ports]+t.args) print(f"{t.cmd}:") t.print_log() else: passed = passed + 1 t.print_result(0, COLOUR_PASS) elif t.runtime > 180: # 3 minutes max t.print_timed_out(226-6*t.attempts) t.proc.terminate() t.proc.wait() t.print_log() print("Passed: %d\nRetried: %d\nFailed: %d\nTotal: %d\nTotal time: %0.2f" % (passed, retried, failed, passed+failed, time.time()-start_time)) if failed > 0: print("Failing tests:") failed_tests.sort() for f in failed_tests: print(f) with open("failed-tests.json", "wt") as out: out.write(json.dumps(failed_tests_output)) sys.exit(1) else: try: os.remove("failed-tests.json") except FileNotFoundError: pass ================================================ FILE: test/random/Makefile ================================================ R=../.. include ${R}/config.mk .PHONY: all test all : auth_plugin.so auth_plugin.so : auth_plugin.c $(CC) ${LOCAL_CFLAGS} -fPIC -shared $< -o $@ -I${R}/lib -I${R}/src ${R}/lib/libmosquitto.so.${SOVERSION} : $(MAKE) -C ${R}/lib ${R}/lib/libmosquitto.a : $(MAKE) -C ${R}/lib libmosquitto.a clean : -rm -f *.o random_client *.gcda *.gcno test : all ./test.py ================================================ FILE: test/random/auth_plugin.c ================================================ #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; } ================================================ FILE: test/random/pwfile ================================================ test:$6$cBP7e6sUriMSh8yf$+Z3E9P1g+Hui8zDJA+XJpTHl6+0eym0MtWokmOY4j1svAR5RtjZoXB4OQuHYzrGrdp1e8gXoqcKlcP+1lmepmg== ================================================ FILE: test/random/random.conf ================================================ per_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 ================================================ FILE: test/random/random_client.py ================================================ #!/usr/bin/env python3 from pathlib import Path 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: source_dir = Path(__file__).resolve().parent ssl_dir = source_dir.parent / "ssl" mqttc.tls_set(ca_certs=f"{ssl_dir}/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() ================================================ FILE: test/random/test.py ================================================ #!/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 = mosq_test.env_add_ld_library_path() #broker = subprocess.Popen([mosq_test.get_build_root()+"/src/mosquitto", "-c", "random.conf"], env=env) run_clients(1000) ================================================ FILE: test/ssl/all-ca.crt ================================================ Certificate: 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: Jul 7 22:27:28 2025 GMT Not After : Jul 6 22:27:28 2030 GMT Subject: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Signing CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: 00:b8:5b:81:cb:99:5e:85:66:42:fe:c4:f4:c6:ad: f9:9a:b4:c5:29:bb:05:5b:90:b2:a0:7d:ba:00:a3: f3:ec:8f:81:c4:45:98:79:6c:3e:04:77:26:dd:d9: 9f:57:6a:dc:56:25:ba:60:c9:7d:cc:fe:40:e1:e9: 75:02:a7:56:0e:bb:a8:a5:d1:b4:b1:57:62:d1:07: 67:23:77:ae:3e:41:ba:22:6f:b8:f3:3d:ac:5f:1f: 93:cb:62:33:93:61:0b:b1:33:be:ee:67:bb:b1:4b: 2a:3e:c3:99:e9:ea:51:ca:79:ac:91:ce:e6:ee:99: 86:85:f0:a4:11:91:2b:ef:9f:cf:6d:8c:8f:0a:f8: 69:5f:42:c5:ee:90:ca:fe:da:6f:c6:20:56:9d:ac: eb:b0:64:ab:a5:fc:9d:c2:db:ac:a9:a7:40:e1:60: 00:9f:87:f3:51:9f:64:7e:f8:4a:8e:7f:aa:95:f3: 4f:04:b0:ea:ee:77:0b:3e:27:bf:9a:b4:62:1f:76: 6d:a4:be:eb:e2:c3:c6:be:87:6d:f3:fb:ec:a0:09: 41:ef:8d:35:90:3f:fb:88:f8:fe:e2:25:cd:ff:c2: 72:13:d0:bd:fe:40:5e:9d:80:9f:7c:b0:ea:54:bd: 69:70:1f:cf:2f:c3:97:40:ee:ef:97:d6:c6:1d:16: 6b:01 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Subject Key Identifier: C8:63:DE:29:66:24:95:5D:B2:37:6D:F6:A2:01:85:AE:31:0F:8E:45 X509v3 Authority Key Identifier: 4F:56:ED:BA:57:12:46:13:CF:96:E3:2C:C1:91:64:69:5B:9A:E7:05 X509v3 Basic Constraints: critical CA:TRUE X509v3 Key Usage: Certificate Sign, CRL Sign Signature Algorithm: sha256WithRSAEncryption Signature Value: 07:ba:ab:2e:42:0c:ac:98:05:af:a0:49:44:db:36:4f:a1:15: 40:ec:4d:46:ca:ae:f0:ad:aa:1c:d0:99:11:6c:32:ce:62:b5: 3d:71:ab:1d:ed:cb:3e:3a:38:de:20:25:6f:02:fd:1f:b9:d7: 8d:5f:d1:d4:46:ea:a7:c5:fa:70:fc:aa:0f:63:a3:bb:dc:93: 6b:9d:1c:9c:64:f4:3f:ac:09:60:b7:d5:3d:b2:c5:df:58:44: 24:a4:bf:a9:d2:c3:0c:9d:f0:06:b1:20:f6:7d:1b:55:c4:f8: 96:84:1d:b1:b9:3d:06:16:ab:fd:cf:97:1d:ff:6d:e2:6d:fe: da:36:7e:4c:d6:f8:1c:df:b7:79:58:ce:ea:c4:50:3a:14:86: f8:55:21:77:90:ec:bf:af:82:29:c8:a7:5c:91:b9:33:e0:ee: 8a:6c:80:f1:e1:a5:55:26:a1:46:bb:d1:eb:59:d1:1c:90:a4: 19:54:e7:68:0c:b6:c7:9e:b0:d0:e3:12:24:a4:92:96:1c:bd: 82:cc:1f:3d:f4:a6:de:69:77:83:25:3a:02:ee:64:38:f7:ae: ef:06:09:06:3d:c2:19:0f:54:06:d3:e4:0c:e2:bd:be:e3:1c: ac:a7:e0:c2:50:37:b4:8b:4b:0f:58:71:24:00:6b:7a:71:1e: 7b:f5:a2:71 -----BEGIN CERTIFICATE----- MIIDsjCCApqgAwIBAgIBATANBgkqhkiG9w0BAQsFADByMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEOMAwGA1UEBwwFRGVyYnkxGjAYBgNVBAoMEU1v c3F1aXR0byBQcm9qZWN0MRAwDgYDVQQLDAdUZXN0aW5nMRAwDgYDVQQDDAdSb290 IENBMB4XDTI1MDcwNzIyMjcyOFoXDTMwMDcwNjIyMjcyOFowZTELMAkGA1UEBhMC R0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxGjAYBgNVBAoMEU1vc3F1aXR0byBQcm9q ZWN0MRAwDgYDVQQLDAdUZXN0aW5nMRMwEQYDVQQDDApTaWduaW5nIENBMIIBIjAN BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuFuBy5lehWZC/sT0xq35mrTFKbsF W5CyoH26AKPz7I+BxEWYeWw+BHcm3dmfV2rcViW6YMl9zP5A4el1AqdWDruopdG0 sVdi0QdnI3euPkG6Im+48z2sXx+Ty2Izk2ELsTO+7me7sUsqPsOZ6epRynmskc7m 7pmGhfCkEZEr75/PbYyPCvhpX0LF7pDK/tpvxiBWnazrsGSrpfydwtusqadA4WAA n4fzUZ9kfvhKjn+qlfNPBLDq7ncLPie/mrRiH3ZtpL7r4sPGvodt8/vsoAlB7401 kD/7iPj+4iXN/8JyE9C9/kBenYCffLDqVL1pcB/PL8OXQO7vl9bGHRZrAQIDAQAB o2AwXjAdBgNVHQ4EFgQUyGPeKWYklV2yN232ogGFrjEPjkUwHwYDVR0jBBgwFoAU T1btulcSRhPPluMswZFkaVua5wUwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMC AQYwDQYJKoZIhvcNAQELBQADggEBAAe6qy5CDKyYBa+gSUTbNk+hFUDsTUbKrvCt qhzQmRFsMs5itT1xqx3tyz46ON4gJW8C/R+5141f0dRG6qfF+nD8qg9jo7vck2ud HJxk9D+sCWC31T2yxd9YRCSkv6nSwwyd8AaxIPZ9G1XE+JaEHbG5PQYWq/3Plx3/ beJt/to2fkzW+Bzft3lYzurEUDoUhvhVIXeQ7L+vginIp1yRuTPg7opsgPHhpVUm oUa70etZ0RyQpBlU52gMtseesNDjEiSkkpYcvYLMHz30pt5pd4MlOgLuZDj3ru8G CQY9whkPVAbT5Azivb7jHKyn4MJQN7SLSw9YcSQAa3pxHnv1onE= -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIID0jCCArqgAwIBAgIUPWZteXB28AsU7emgSEDG3w7zqd8wDQYJKoZIhvcNAQEL BQAwcjELMAkGA1UEBhMCR0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxDjAMBgNVBAcM BURlcmJ5MRowGAYDVQQKDBFNb3NxdWl0dG8gUHJvamVjdDEQMA4GA1UECwwHVGVz dGluZzEQMA4GA1UEAwwHUm9vdCBDQTAeFw0yNTA3MDcyMjI3MjhaFw0zNTA3MDUy MjI3MjhaMHIxCzAJBgNVBAYTAkdCMRMwEQYDVQQIDApEZXJieXNoaXJlMQ4wDAYD VQQHDAVEZXJieTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3QxEDAOBgNVBAsM B1Rlc3RpbmcxEDAOBgNVBAMMB1Jvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IB DwAwggEKAoIBAQDyRXMUPa/pLzERcaE+/TkYmiH83MfGhJ2eSeEqY+vjuzePT/p3 GDLuM5IcprukEuif+4HbvLQC8zIdNjO+Xwb/Acg7njQfNTV9b8IzOn3r/k4ZcB2G rK7Kae338xAmkTYjACrTUnbUsdRmbRKZZCIk69fxlC4xhCp+7sZyKc4FOkGI4dOe TVkLN3DQflzR7mF78yCgbr2HBXoF2Eazv008YqTDS2gL3JbXIpt2H7Z8fNZHupbk B0gydAxmMSUnwBeXLkVkKFOJNDjjGtY4nDKOpuirEx8K0GYs6Mo0iFTwi4IDxjzM jP5uarn1hx5bAFpuN1r1jbzb0iopZAOhmG2TAgMBAAGjYDBeMB0GA1UdDgQWBBRP Vu26VxJGE8+W4yzBkWRpW5rnBTAfBgNVHSMEGDAWgBRPVu26VxJGE8+W4yzBkWRp W5rnBTAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsF AAOCAQEAjejhP+g9DbB/vgjUJbk5sRgBeq0sX8ghtq1B+LEgKV+l/h9dmsavChjF RWzEhfxK83iMJX8dAXbloYSgmXNSmh/7RfXQEBPbwzD9CyZXWa+HC4Rfv0YGvdua liyXVxHiND4wGiv/GyTOcGJ9P5zjB+svo7rnIHvC6vJyo0hp17AuBSZDWBWt096U QHwJ3DrLY09OpMwfLZaduEzH9Vpf+rkQrTAo0/jSmhCDPBtLx/c+PKptUiOjvsuc DlaKBh7s5OBjGDUUqWDmFhcQCEy4eg0KDaAfCUrjoXFK4yf+TAxVpNBCoUCaGOqk GvK7TZAfHoGSAxTuls/Y0N/StPSojw== -----END CERTIFICATE----- ================================================ FILE: test/ssl/client-encrypted.crt ================================================ Certificate: Data: Version: 3 (0x2) Serial Number: 7 (0x7) Signature Algorithm: sha256WithRSAEncryption Issuer: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Signing CA Validity Not Before: Jul 7 22:27:29 2025 GMT Not After : Jul 6 22:27:29 2030 GMT Subject: C=GB, ST=Nottinghamshire, L=Nottingham, O=Server, OU=Production, CN=test client encrypted Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: 00:a1:dd:b6:77:f9:03:1b:e1:7c:23:96:b5:a7:b6: c0:2a:2e:f8:14:e9:06:d6:97:64:06:e1:ad:a9:5e: a3:4d:e8:fd:1a:2e:72:6e:55:b3:6b:37:36:27:c5: e7:4a:71:a2:79:1c:c2:69:97:ff:2b:3c:7f:58:ec: 0d:c0:6e:65:93:44:a5:91:fa:75:f6:d9:a9:d8:2c: 7e:a2:2c:c7:58:55:97:c8:5d:cc:2a:ff:fe:7c:78: aa:49:12:6c:4c:7e:97:09:9f:bd:2c:83:c2:36:30: 35:ca:6d:43:a9:80:78:d2:56:14:a3:ce:92:6a:67: 51:52:ac:16:0c:b7:4b:2b:52:fe:79:62:4e:4a:65: 1f:e5:fa:b9:b3:6f:ae:d4:46:3d:d4:48:03:23:ab: 94:e6:ad:bc:38:85:f1:a9:df:43:3a:27:38:1e:fd: b0:5d:36:40:23:69:b2:fe:14:30:93:a1:d1:6b:36: 38:65:8a:e3:c7:0a:4b:b6:fc:c7:af:f3:5a:3a:22: ec:df:41:07:96:c0:14:4d:82:b8:25:40:49:4f:6d: ea:a8:44:1e:b9:c6:d0:6d:94:42:20:86:d1:62:05: 4f:7a:00:27:f0:27:23:8c:f9:26:6d:2e:f4:61:62: 79:26:ea:44:df:71:8e:b0:be:de:13:17:cb:77:14: a0:df Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: critical CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: BA:16:BE:F7:34:D2:63:6C:18:88:0A:92:5E:C3:3A:85:3A:09:38:56 X509v3 Authority Key Identifier: C8:63:DE:29:66:24:95:5D:B2:37:6D:F6:A2:01:85:AE:31:0F:8E:45 Signature Algorithm: sha256WithRSAEncryption Signature Value: 05:f8:d2:f3:95:b8:8e:b4:74:d8:2a:17:88:d8:aa:28:a9:72: 1b:a1:c1:67:1c:af:7d:fe:9a:bb:b5:e6:4b:01:19:27:a4:ab: fb:cd:aa:df:cb:52:61:22:43:be:d5:46:d7:64:bc:81:39:00: 98:27:db:e0:fe:b1:78:31:05:7c:bf:cc:9a:ad:5c:7b:d6:47: 7e:8f:c7:a8:31:b6:ac:21:d4:1a:85:b0:b4:84:84:b4:e7:fc: d3:a0:c5:97:f6:ed:6b:93:18:22:68:6a:8b:81:cd:c5:11:02: c6:9b:77:08:28:48:28:3b:77:bb:28:21:f7:9e:11:7a:d2:4f: 67:32:52:a7:aa:4a:59:ee:17:2d:20:f7:6b:61:3b:3f:7b:1b: 07:9b:82:cb:0e:d7:b1:9d:66:6d:fd:82:cd:5b:1b:66:e2:69: c6:33:1a:d4:18:26:49:52:f8:32:b5:6d:6b:22:e6:bc:79:ef: 85:64:db:e0:76:53:9a:ce:3b:3e:a0:81:6a:27:26:ac:1d:48: 07:79:6b:e3:bb:19:2c:63:7d:86:fd:ed:67:fa:6f:8e:26:94: 08:42:d3:55:6b:41:d7:1b:6c:18:c0:12:3c:12:80:61:de:95: 3b:fe:4a:7c:db:ac:09:5d:6f:ed:1a:1a:5a:fb:f0:fd:3a:17: 77:93:af:3f -----BEGIN CERTIFICATE----- MIID4TCCAsmgAwIBAgIBBzANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMjUwNzA3 MjIyNzI5WhcNMzAwNzA2MjIyNzI5WjCBgjELMAkGA1UEBhMCR0IxGDAWBgNVBAgM D05vdHRpbmdoYW1zaGlyZTETMBEGA1UEBwwKTm90dGluZ2hhbTEPMA0GA1UECgwG U2VydmVyMRMwEQYDVQQLDApQcm9kdWN0aW9uMR4wHAYDVQQDDBV0ZXN0IGNsaWVu dCBlbmNyeXB0ZWQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCh3bZ3 +QMb4XwjlrWntsAqLvgU6QbWl2QG4a2pXqNN6P0aLnJuVbNrNzYnxedKcaJ5HMJp l/8rPH9Y7A3AbmWTRKWR+nX22anYLH6iLMdYVZfIXcwq//58eKpJEmxMfpcJn70s g8I2MDXKbUOpgHjSVhSjzpJqZ1FSrBYMt0srUv55Yk5KZR/l+rmzb67URj3USAMj q5Tmrbw4hfGp30M6Jzge/bBdNkAjabL+FDCTodFrNjhliuPHCku2/Mev81o6Iuzf QQeWwBRNgrglQElPbeqoRB65xtBtlEIghtFiBU96ACfwJyOM+SZtLvRhYnkm6kTf cY6wvt4TF8t3FKDfAgMBAAGjfjB8MAwGA1UdEwEB/wQCMAAwLAYJYIZIAYb4QgEN BB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBS6Fr73 NNJjbBiICpJewzqFOgk4VjAfBgNVHSMEGDAWgBTIY94pZiSVXbI3bfaiAYWuMQ+O RTANBgkqhkiG9w0BAQsFAAOCAQEABfjS85W4jrR02CoXiNiqKKlyG6HBZxyvff6a u7XmSwEZJ6Sr+82q38tSYSJDvtVG12S8gTkAmCfb4P6xeDEFfL/Mmq1ce9ZHfo/H qDG2rCHUGoWwtISEtOf806DFl/bta5MYImhqi4HNxRECxpt3CChIKDt3uygh954R etJPZzJSp6pKWe4XLSD3a2E7P3sbB5uCyw7XsZ1mbf2CzVsbZuJpxjMa1BgmSVL4 MrVtayLmvHnvhWTb4HZTms47PqCBaicmrB1IB3lr47sZLGN9hv3tZ/pvjiaUCELT VWtB1xtsGMASPBKAYd6VO/5KfNusCV1v7RoaWvvw/ToXd5OvPw== -----END CERTIFICATE----- ================================================ FILE: test/ssl/client-encrypted.key ================================================ -----BEGIN ENCRYPTED PRIVATE KEY----- MIIFJDBWBgkqhkiG9w0BBQ0wSTAxBgkqhkiG9w0BBQwwJAQQCF9+wFpj0zV4f3eA 5SC2TAICCAAwDAYIKoZIhvcNAgkFADAUBggqhkiG9w0DBwQIPTGlf0N4mOMEggTI XC1qxxC/+Pw5sPv6DTFF463G7U+vAANLrLmE30XQ4JFDQcLJ8cStUIZUf4V5mNvP 3hLVo7zHSSyVp+7JbJvAAMeSSVpo3bXzp4oLHWIvbSxQV0bx6EJ3mS5FTbO5BVZR J/VtZ20teJZzWoBykENLU5rAsbGcs7N5ZqV1uvaKmnVf4AfHMEESKc6KoTEMC6gf BW9qDhcw5q6t49fnneaoK48G3xck9tl/N2Z2Bc0Bj+ruS4mH8B4WoCvPyYJ12C0l 5f449ZMGfxyQxXiSDl5H2gheGh5it3s1Lw+tLzlR+kfEIuliaZ7j/Y4rSupUa8pM ErcOeZVDicNwSsVS02HgerV5CEcX+ZI8WsiMtPS29eaYGJy8EtKmAiZ0UjWgmxTJ IkPTgrOVqL8/6kOgACTErMi3RIExAlCiAFPtLcyeXQRwE6BoGhUSsGR+j2Tvub9k yhnCc6dsEjoy3/LYDDL3gUxy5/VV0hAvO5mIFcA2d/HAWKn0Sxwx/7Xd76uDEZos 2/NmA3rISpbtNubOVkfiZ1zt3N3C5FBOa41uLRwZ/rs2gxBl/etCYJMXdicDMzmJ NTIp60AMIHQINlSYy/RecC5KaRLnL0UKVEr4jNtmdf/9fKzMBHz4QJLesivOWXgT ZerdB44MficbMiPoYkxJ+IdBYkRNP2Sifl82NO7pbxIhkhNUZFAJRBo/SWVOQ4B2 F0Cl7Vsa0pp0+71l76dF5Sxnhc+Vga1U3bURLDYFUlqOxhEImTINySY3QVkJpPmX GR/Jt15ttXGkpex1ZLngcrlD1QC2czuHwDBRbGeYIIjZJ6CmJPXOHm95iDlAWEQn bIcrokp4oZOXuDrUJT/vzSqmX0QpxkVw0HzPT3r7dddbb7AiXzXzCczaK5DVGbfG D9NimLgTyhVnQeRtPDTaI7JB0UpLRVI5dqT2TsFiulCiYfrufgEz2yKrpE8Njl8p Q3YBLCSTM3zzi7JxR/OfJkHlnK2sko9I5l5cA1D9uhu7QG4dShpXzxP0EA9lvXG7 Dl8DQuwzgUjSk2A/nA5bofbPtntyUihhdPZ8c2ni4Fj356fqU4FPUKmP978zKklR nLFuw1J9osv3UWn94glOHE4+nADhS8dCRicDRqpC0F72o6Jk0kUMyfaZYmj5OvQv xl5FpIa0QdSq+suP2JIkRC/CvbA+ugZJeL/Po8sFi6gd1eUdC6q5wJo/MgDUGdGA j953scDof+CvBFRCgMRUzbEgVVFoR84OImdlNuOOTLU0agodfJ3tRjI1prPu3WEh Y48UP5bfqOSxwebdWpxXTr+o24Xk7ryyiWXbPLgTFuxj1lL2erEWu604ls4TETD9 jBCwfQGF1Q+lYTYxGGBNGMPuyttUGr3oR0JFyCYtUZuSZB9oSJwKN7XHPAPVamf0 IcMoCNTbCHz+vhm6Mzca9m9lgHgsgHNvlSwHIFCTt6b9eWUxx6OKHxDoxBio2LE7 EvfN0yyefseTJC9vND0IN54qYBG0Gw4E94ayhn7AP5zKe7ebPzKBmwEE0VCBUSHg Cmv1PP12u7kCSyWuximn9kvxcBlwz3fhAoyN9BzRJc6NlVVURfgQEVu74VUckfaT t0hDukAZySz/9jtA7cn7BwyuINR3HLjL -----END ENCRYPTED PRIVATE KEY----- ================================================ FILE: test/ssl/client-expired.crt ================================================ Certificate: 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: 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 Public-Key: (2048 bit) Modulus: 00:aa:fd:ae:95:66:d0:c6:47:c8:d3:c3:61:66:cb: 4d:92:32:2a:6b:f1:66:9c:c1:22:a0:9e:1b:d7:e9: 90:e3:7e:e5:76:e7:34:fb:d7:74:24:5a:d2:4b:9e: 32:fd:c6:b4:7d:97:ff:e4:c8:b7:6f:e2:18:c4:c5: cd:58:88:21:e9:65:11:16:ba:72:dc:ef:3f:99:f3: d8:06:83:4d:42:2f:b7:a9:91:b4:31:45:77:23:18: 6f:2f:a3:38:74:01:c0:f9:cd:dc:61:2d:79:5d:fc: 2b:65:ad:01:77:a4:fe:84:12:4d:86:b7:7d:3b:41: 43:c2:91:b9:c7:08:64:7c:3c:c0:9f:0d:fc:9c:55: e7:51:10:00:b4:5c:67:55:e3:92:dc:c2:4e:09:0b: b8:9d:e3:c8:b5:a4:82:63:d3:e0:5c:bf:0e:c8:12: 76:d3:2f:2f:35:d8:4b:56:de:de:ba:21:5c:16:9f: b8:62:06:46:3e:d5:d3:6f:e6:7d:8a:98:b5:ed:96: a3:1e:3a:61:9e:27:f1:68:f1:63:2e:06:69:cf:49: 33:f9:4c:f1:79:b6:6d:75:3e:04:53:22:51:ed:20: 2f:60:e1:d4:ce:ac:25:ca:f0:a0:8e:85:8e:9d:06: a2:5b:7f:ea:9a:dc:a6:3f:9d:ff:89:28:a0:5b:17: 7a:95 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: critical CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 16:D7:08:AC:DC:6C:6E:31:9C:35:76:7D:43:26:67:FC:5D:42:67:3E X509v3 Authority Key Identifier: C8:63:DE:29:66:24:95:5D:B2:37:6D:F6:A2:01:85:AE:31:0F:8E:45 Signature Algorithm: sha256WithRSAEncryption Signature Value: 57:ab:0f:6a:2e:3e:c7:3a:02:71:5d:08:ec:9f:1d:f5:13:90: 6c:d2:b7:bf:63:28:b4:4d:7b:5e:b2:e0:06:98:a9:42:1f:13: 2a:78:7d:f5:4c:15:06:c8:79:ba:14:58:c7:97:8e:84:da:f5: 17:58:16:a9:ff:06:70:a7:40:49:cc:ad:22:33:87:d0:f9:cd: 6a:32:77:61:0f:71:cf:f5:c4:79:3d:44:1e:58:96:b0:fd:e5: d6:92:8b:88:f2:98:53:a9:b0:c8:24:9f:4a:d7:6c:a1:66:ea: 51:25:57:94:82:81:e7:bb:5d:51:a6:b7:48:bb:c0:ce:58:a6: 60:a6:a7:c6:d5:56:3f:a8:a8:cb:42:dc:f9:7b:e1:b8:c5:7f: f9:3f:0b:c4:88:18:f5:8c:0b:9a:0f:57:a1:dc:88:ad:56:e9: 65:b6:1e:3d:0a:8b:e5:bf:46:40:4f:51:15:cc:eb:18:30:f6: bc:66:e2:27:cb:5c:22:09:7d:d4:62:d4:77:7a:a6:66:f7:54: e3:07:10:dd:a0:28:ee:71:ff:61:ff:bd:a2:44:0d:a5:6d:74: 44:76:58:a3:09:d9:17:6e:5f:b8:64:02:7f:96:64:b7:2a:3e: 31:1b:01:ed:42:db:61:68:f8:a3:7b:02:7e:b9:7c:9c:28:c1: da:d3:ea:81 -----BEGIN CERTIFICATE----- MIID3zCCAsegAwIBAgIBBTANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMTIwODIw MDAwMDAwWhcNMTIwODIxMDAwMDAwWjCBgDELMAkGA1UEBhMCR0IxGDAWBgNVBAgM D05vdHRpbmdoYW1zaGlyZTETMBEGA1UEBwwKTm90dGluZ2hhbTEPMA0GA1UECgwG U2VydmVyMRMwEQYDVQQLDApQcm9kdWN0aW9uMRwwGgYDVQQDDBN0ZXN0IGNsaWVu dCBleHBpcmVkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqv2ulWbQ xkfI08NhZstNkjIqa/FmnMEioJ4b1+mQ437lduc0+9d0JFrSS54y/ca0fZf/5Mi3 b+IYxMXNWIgh6WURFrpy3O8/mfPYBoNNQi+3qZG0MUV3IxhvL6M4dAHA+c3cYS15 XfwrZa0Bd6T+hBJNhrd9O0FDwpG5xwhkfDzAnw38nFXnURAAtFxnVeOS3MJOCQu4 nePItaSCY9PgXL8OyBJ20y8vNdhLVt7euiFcFp+4YgZGPtXTb+Z9ipi17ZajHjph nifxaPFjLgZpz0kz+UzxebZtdT4EUyJR7SAvYOHUzqwlyvCgjoWOnQaiW3/qmtym P53/iSigWxd6lQIDAQABo34wfDAMBgNVHRMBAf8EAjAAMCwGCWCGSAGG+EIBDQQf Fh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUFtcIrNxs bjGcNXZ9QyZn/F1CZz4wHwYDVR0jBBgwFoAUyGPeKWYklV2yN232ogGFrjEPjkUw DQYJKoZIhvcNAQELBQADggEBAFerD2ouPsc6AnFdCOyfHfUTkGzSt79jKLRNe16y 4AaYqUIfEyp4ffVMFQbIeboUWMeXjoTa9RdYFqn/BnCnQEnMrSIzh9D5zWoyd2EP cc/1xHk9RB5YlrD95daSi4jymFOpsMgkn0rXbKFm6lElV5SCgee7XVGmt0i7wM5Y pmCmp8bVVj+oqMtC3Pl74bjFf/k/C8SIGPWMC5oPV6HciK1W6WW2Hj0Ki+W/RkBP URXM6xgw9rxm4ifLXCIJfdRi1Hd6pmb3VOMHEN2gKO5x/2H/vaJEDaVtdER2WKMJ 2RduX7hkAn+WZLcqPjEbAe1C22Fo+KN7An65fJwowdrT6oE= -----END CERTIFICATE----- ================================================ FILE: test/ssl/client-expired.key ================================================ -----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCq/a6VZtDGR8jT w2Fmy02SMipr8WacwSKgnhvX6ZDjfuV25zT713QkWtJLnjL9xrR9l//kyLdv4hjE xc1YiCHpZREWunLc7z+Z89gGg01CL7epkbQxRXcjGG8vozh0AcD5zdxhLXld/Ctl rQF3pP6EEk2Gt307QUPCkbnHCGR8PMCfDfycVedREAC0XGdV45Lcwk4JC7id48i1 pIJj0+Bcvw7IEnbTLy812EtW3t66IVwWn7hiBkY+1dNv5n2KmLXtlqMeOmGeJ/Fo 8WMuBmnPSTP5TPF5tm11PgRTIlHtIC9g4dTOrCXK8KCOhY6dBqJbf+qa3KY/nf+J KKBbF3qVAgMBAAECggEAPBREamQkyPZh/t3wdEDMsaiEtUatijhmJU9IczWy3ewx TfTw7egG+9sZds5QFlDiDBsDI2zO3zXvA/yIKSoz2CDVv0mloDFEBKDj723lEHNZ se/rA0DoGmG0d2V/KWuQVXVakJ58vWQkD2aZVGOZtegEa2g/TTmiSFQRlXhCblAL CEGKsp8H8QQePqirFcBOlHzZuLu4SVs49sQl6NYCX5U+PwMF7MQ5bqzmKqL/+Xq7 p+OMNL0tUp0xOSjC7hDoNM3La/bxu5HY92dV9jPY34QstuZzaRR8I/wO1dPc4tQZ ualJyNEm4PRdonLKv+MBy+YTnjI6JMNIFQ4rmozJZQKBgQDeGkcZd9PFhGce75mn 8McrKkqLmEFQvJD7gUq3YJqDgIkN4XxaTmBqEFewX2fCK4IybBxBBVTixy84sM2Z H7BkzjNgW5HkddudixJFPP6R/PXykeEkO+XE6EkeeDJRmnwUi7ZaVVeQ8sDsHbOE A7Eq7lTJ3rUdd9AolO7tCfU7QwKBgQDFFm40VL/qi6fbMIibR/IZiHkAmj4SIYVL DawQtSig9W3v3bYyZm7voIu/KK4aOm7bMVIXyGH8zPiTI2YAXl5vocW8boSJ5Gix dg3W2dpfQriwHC1DUwzpg/AvpH/AkWvKAw/vifDDBmBZFIISZVRWB+bRIahqEwqy rJq5xKOZRwKBgQCDgWOfvMdzJ9Y3Bv8f5PzInh3NUbU6rKvbfs5SjaxvOGfuBBix D78ejdad45935HMOj9ya0yFTtURMeMMDazPyO/VHlHBpqS8DtRh4Tokcv36Qxbdc 0OpXEIJavChvEN1u/NpX2jgi5tk79MoZ3GXGWZ9yd58dd5eUr7pYN5EwKQKBgFML u44jc+bByA4NKlK8AyCNJ+eAFs2PAFp6vVkg7Ki+If/jnWUpUm94Z8o5uvrkSlfk NWI+FkPunoNpdA6NtR82vFpE+2YbL54vT2+Lxn9DXw0eIlhvA07WQHvixc3/uLqb hbh6mE+lPS3r/U8BEYNauwC+PPfNZEGbh2rll8X7AoGAPr2LA4+11Ki1X0tdnF6+ P0Gye/m7Up/pPHHxszG64GLsQWEnvbG64CtYZCOZaNDIh70p2leDJbMRIOxjOF9U 58gd+A8Rogd5HacEiU+pd22+eDG6hP+8Gww7gcShRHNv1jrgpKl3BrFW/oihQuLJ vHcy85UX7q1bNoZW/ZjLErQ= -----END PRIVATE KEY----- ================================================ FILE: test/ssl/client-revoked.crt ================================================ Certificate: 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: Jul 7 22:27:29 2025 GMT Not After : Jul 6 22:27:29 2030 GMT Subject: C=GB, ST=Nottinghamshire, L=Nottingham, O=Server, OU=Production, CN=test client revoked Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: 00:ae:b6:68:e8:c4:ef:75:5c:6c:db:bb:a2:04:78: 49:8f:b5:81:9d:6f:e7:6d:60:09:fb:ad:cf:d3:60: 14:b2:de:5b:f2:18:fb:1d:8a:40:4e:b0:7c:37:7b: df:30:0f:c9:a6:56:5e:da:a6:ba:82:6f:7a:64:6b: fe:7d:c0:64:27:13:bb:1e:ba:40:3b:bf:15:2d:ce: ff:fe:1f:80:33:12:1f:a8:d2:59:cf:72:94:a4:03: 07:bc:0d:25:ca:53:76:6b:9c:76:7f:c7:1b:45:24: 39:33:04:6e:53:54:d3:f5:c4:f2:b6:52:d0:e2:aa: ac:6b:2b:52:d6:09:70:00:3d:ce:62:5c:e5:61:e7: a8:cb:1e:6a:93:f0:0e:17:6d:a6:ed:81:1b:38:34: 85:94:a0:36:7c:78:44:cd:7b:a4:91:00:94:5e:9b: 2b:c3:62:62:fe:ed:63:60:4d:05:73:b0:a7:dc:12: 7b:04:b1:18:88:f4:75:36:cd:60:6b:67:81:99:9a: 8d:17:6a:99:41:a8:2d:fe:07:64:65:f1:ad:6c:21: 79:d7:5b:35:00:de:94:6c:c3:9e:dd:6d:17:b5:e0: 26:e1:71:a0:78:b3:ec:96:13:d8:2f:6b:62:50:ba: ea:0b:70:04:17:6d:a4:79:03:88:e8:33:ce:9d:b2: 73:c5 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: critical CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 52:D2:DC:93:96:71:8E:C1:AD:9F:B4:D8:A7:6D:DB:08:C5:1C:C7:97 X509v3 Authority Key Identifier: C8:63:DE:29:66:24:95:5D:B2:37:6D:F6:A2:01:85:AE:31:0F:8E:45 Signature Algorithm: sha256WithRSAEncryption Signature Value: 9e:24:32:86:72:08:e7:79:8f:6c:21:15:52:b8:1f:01:75:a5: 7d:a8:60:1e:f8:da:39:3d:0c:f9:8a:e1:1e:97:81:4d:76:27: fa:97:a1:70:2c:79:26:ca:e6:f0:20:ec:1a:fd:2e:dc:73:58: d7:24:d1:ef:c8:f4:2c:e9:4f:29:d5:a5:67:a0:b0:c3:e9:ec: 8e:67:9d:b6:02:cb:1b:c8:8d:cf:7b:80:65:f8:65:b2:bd:f1: 96:b9:9d:34:ba:18:51:b4:0b:e7:95:99:80:b9:46:19:d7:d2: ab:a2:fb:67:1f:82:5d:73:66:40:0b:4b:b6:63:7a:08:6e:58: 9c:51:b8:c3:05:c3:84:52:cd:2b:20:3c:03:79:a8:bf:2e:fe: 2e:d6:50:9c:5e:1f:22:56:12:e8:f5:ab:01:18:41:be:56:21: f6:53:15:83:8a:de:3a:66:f2:f4:0f:25:91:f7:93:85:25:e5: 80:36:45:15:89:a8:46:bb:c3:ba:d4:71:3d:f6:ee:b0:29:9c: f9:e1:60:62:d8:f0:f6:4c:3e:71:66:fb:85:53:34:fb:f4:a7: 20:e5:43:ca:84:32:d8:5b:44:ab:9d:45:f4:3e:90:fa:0a:8a: 47:26:c4:85:99:e5:df:4c:68:eb:a2:8c:60:36:8b:07:00:ce: 3b:63:41:4a -----BEGIN CERTIFICATE----- MIID3zCCAsegAwIBAgIBBjANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMjUwNzA3 MjIyNzI5WhcNMzAwNzA2MjIyNzI5WjCBgDELMAkGA1UEBhMCR0IxGDAWBgNVBAgM D05vdHRpbmdoYW1zaGlyZTETMBEGA1UEBwwKTm90dGluZ2hhbTEPMA0GA1UECgwG U2VydmVyMRMwEQYDVQQLDApQcm9kdWN0aW9uMRwwGgYDVQQDDBN0ZXN0IGNsaWVu dCByZXZva2VkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArrZo6MTv dVxs27uiBHhJj7WBnW/nbWAJ+63P02AUst5b8hj7HYpATrB8N3vfMA/JplZe2qa6 gm96ZGv+fcBkJxO7HrpAO78VLc7//h+AMxIfqNJZz3KUpAMHvA0lylN2a5x2f8cb RSQ5MwRuU1TT9cTytlLQ4qqsaytS1glwAD3OYlzlYeeoyx5qk/AOF22m7YEbODSF lKA2fHhEzXukkQCUXpsrw2Ji/u1jYE0Fc7Cn3BJ7BLEYiPR1Ns1ga2eBmZqNF2qZ Qagt/gdkZfGtbCF511s1AN6UbMOe3W0XteAm4XGgeLPslhPYL2tiULrqC3AEF22k eQOI6DPOnbJzxQIDAQABo34wfDAMBgNVHRMBAf8EAjAAMCwGCWCGSAGG+EIBDQQf Fh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUUtLck5Zx jsGtn7TYp23bCMUcx5cwHwYDVR0jBBgwFoAUyGPeKWYklV2yN232ogGFrjEPjkUw DQYJKoZIhvcNAQELBQADggEBAJ4kMoZyCOd5j2whFVK4HwF1pX2oYB742jk9DPmK 4R6XgU12J/qXoXAseSbK5vAg7Br9LtxzWNck0e/I9CzpTynVpWegsMPp7I5nnbYC yxvIjc97gGX4ZbK98Za5nTS6GFG0C+eVmYC5RhnX0qui+2cfgl1zZkALS7Zjeghu WJxRuMMFw4RSzSsgPAN5qL8u/i7WUJxeHyJWEuj1qwEYQb5WIfZTFYOK3jpm8vQP JZH3k4Ul5YA2RRWJqEa7w7rUcT327rApnPnhYGLY8PZMPnFm+4VTNPv0pyDlQ8qE MthbRKudRfQ+kPoKikcmxIWZ5d9MaOuijGA2iwcAzjtjQUo= -----END CERTIFICATE----- ================================================ FILE: test/ssl/client-revoked.key ================================================ -----BEGIN PRIVATE KEY----- MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCutmjoxO91XGzb u6IEeEmPtYGdb+dtYAn7rc/TYBSy3lvyGPsdikBOsHw3e98wD8mmVl7aprqCb3pk a/59wGQnE7seukA7vxUtzv/+H4AzEh+o0lnPcpSkAwe8DSXKU3ZrnHZ/xxtFJDkz BG5TVNP1xPK2UtDiqqxrK1LWCXAAPc5iXOVh56jLHmqT8A4XbabtgRs4NIWUoDZ8 eETNe6SRAJRemyvDYmL+7WNgTQVzsKfcEnsEsRiI9HU2zWBrZ4GZmo0XaplBqC3+ B2Rl8a1sIXnXWzUA3pRsw57dbRe14CbhcaB4s+yWE9gva2JQuuoLcAQXbaR5A4jo M86dsnPFAgMBAAECggEAF5OuHJtW5TOPzSdI+elxo98OmrxbMrtfHYObJB83K9wt 9EHCwX3Cp9vRJ3uj5sx6nePR8RfG24tHrP2V3kp0OYHEIqVnvahPp1rj2NtPZZTw iMu6KvB/dpKiHJJ5oxAYTvVSWHP6Dh6RSX0zljNAV044oroSTkRR+DRkfVXQs3dq a21GlnzhTWvYqz91wPoIczBrJMTh1HUQeyK3a/Po0YHbif4ucUQq0uX1jZ09+evG KtQaD1ijRkoGgD7E+4LThGOVcMAYha7mufqPeuOH9vhuQL3LbmtmudIi9CF3E/jR +mVfSYQjU4Gi/h16L4v1z1kJjbUN8ifC/7NIqG32EQKBgQDoAjMhFpe00HIgfLhw CZpkmfOELuBquOtCKTLAMzowE0fKuIPnYUVXxr9iyGYG4xaF2CCECrLUKCfqbRuP Ma6wtuJQa4vKNg3pn5rIrZe2rH2UwGh4XisJxxtAZyqTRDaKIcFZYeMAAUxpNlrq TpHKy3HnrNaYijdDHbrPwUofIwKBgQDAx3Ox5CndrpG21riwODVnOfCEtUShXH3Q T3lQxP/mCO7x1JYnkaAcCQhb9bkKKuR2z23UJC0zKEIoEtVxhXNfjhtpWsbN86bg MIlH2Zw51NE/QIN2drynyhrbj0HYdkwAdkzFGFaD7A2G1O0Hqumh/a5szqsWYFVU DEm+uXsD9wKBgGH569WhUNeO32NQyCKoK4cobGn50dO/27nI5CG+gGgk/EBjw3BG 55211MTGlC98XtqO9sxMKFDn1FNvWCAUfw0pblE/2Xy/bwil2hu9E0CVf0L+LiAG xG4QozWDW7ttJwsWTiyM5evuoHId/i7Ml0zotWV82/L3C3dQar+phL+5AoGAO3UI rOQXOYUe8gp1ufwMFINdOEEEItR5BWeNnii0WEmHENUlXpzeiecLSfmWkZk7D53Y XOavfii7hsqQREwJkn4s3CigSmMMo/a0UJHASmHmC6ElKsNiWknOUMt1XoLV3Aqg kOV5wYRrg5tmY8gF+O1Z/7saL3OUvbBwij+Avm8CgYBFA5dOfQOEQX7FblFSyXPE lLnObDCCJ0E8YOCXpIc9KDJVbfPzB4rX++79Osb0NMQSYktAUc0CdWcGEdHlXTAA 60ASxq6yg8Y6CbbB8+gnyqP7zBlgojzEViGQBHNu9QW9sGHl1bewWIoQkd/uV7yu hzCM+wks1pHTq+qliobDtw== -----END PRIVATE KEY----- ================================================ FILE: test/ssl/client.crt ================================================ Certificate: 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: Jul 7 22:27:29 2025 GMT Not After : Jul 6 22:27:29 2030 GMT Subject: C=GB, ST=Nottinghamshire, L=Nottingham, O=Server, OU=Production, CN=test client Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: 00:ac:1f:ca:f2:7e:89:98:fe:19:63:e6:c9:d2:0b: 28:95:83:29:55:9a:85:a9:48:5b:a5:6c:0f:a2:ea: 85:93:0a:14:25:2b:5e:aa:f2:2d:e2:d5:a5:37:d0: e5:e3:1e:4f:32:44:a2:46:6f:81:92:13:4c:a6:7b: 2f:27:7c:5f:ae:db:1d:84:78:da:c4:f0:ba:2d:16: 87:15:b7:8f:37:b2:1a:cf:64:38:49:e6:43:f5:a9: 24:78:2d:39:4d:6f:6c:8d:7d:90:c6:07:ec:74:d0: 69:be:c0:93:4a:cb:8a:cc:ba:ba:76:52:8b:33:33: 43:d8:35:15:d7:a6:3e:52:37:3e:cc:3e:95:c5:0e: 24:03:94:d3:8d:b0:2a:db:f5:1d:58:33:ee:f4:a8: 20:88:1d:50:2f:b4:08:3c:11:6f:0a:08:af:67:26: 60:8b:f4:4b:4d:12:3a:a6:b5:26:08:3f:13:a9:5d: 64:48:25:75:a1:a8:ae:45:90:57:3e:c3:f1:d1:d2: 2f:84:c4:d0:16:e4:fc:56:c4:5f:e2:c4:35:c0:fc: 0c:f8:be:2a:45:49:1e:b8:3f:9f:0b:b3:9b:07:9c: fc:f9:e3:4f:4a:12:5f:03:f7:a1:40:70:df:8c:5b: b2:cd:c7:11:ed:b1:ba:4a:96:67:87:30:ac:e8:28: 63:69 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: critical CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: B4:A4:7F:13:73:10:9B:B7:C4:94:64:22:E3:79:02:B0:99:78:D3:73 X509v3 Authority Key Identifier: C8:63:DE:29:66:24:95:5D:B2:37:6D:F6:A2:01:85:AE:31:0F:8E:45 Signature Algorithm: sha256WithRSAEncryption Signature Value: 0b:53:02:33:dc:40:59:0f:4e:00:7e:7e:8d:b0:5d:65:3f:de: fc:bd:f7:6d:c2:38:55:0c:26:97:d6:04:50:af:94:87:20:1e: d8:cb:8f:22:4f:97:0e:f3:f6:89:34:c3:8d:60:f4:c0:a7:24: 23:65:12:10:39:5e:f5:db:10:a1:53:17:b0:90:fa:76:97:00: be:22:2e:9a:8a:e8:a1:f5:b3:44:00:43:33:42:07:90:de:b6: 73:a4:c4:24:d7:c2:c0:e8:3f:fb:79:ef:27:2a:93:d8:5b:e7: f7:d4:3b:55:38:b0:0f:59:9a:c2:52:f6:19:75:45:44:6c:1c: ef:35:6b:23:7f:da:fb:07:94:36:12:1b:f7:7f:88:f4:19:66: 66:60:5f:58:7d:cd:ff:f6:18:96:8d:34:42:a7:fa:ad:42:da: d7:10:b2:57:cd:48:9f:47:d5:a2:5d:fa:33:0c:46:b1:59:50: 03:3c:d8:89:76:d5:2f:b9:48:68:6b:50:c6:e8:0b:8d:a7:4e: 0a:0c:b4:0f:d5:79:30:02:41:4e:13:f5:b2:7c:03:02:9a:df: 77:80:c6:7d:83:72:0f:02:19:7c:57:cb:b6:7d:d5:50:12:44: d4:b3:2f:a0:27:35:f0:11:f1:54:a9:6f:2f:8a:13:18:49:d9: bb:ee:59:ae -----BEGIN CERTIFICATE----- MIID1jCCAr6gAwIBAgIBBDANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMjUwNzA3 MjIyNzI5WhcNMzAwNzA2MjIyNzI5WjB4MQswCQYDVQQGEwJHQjEYMBYGA1UECAwP Tm90dGluZ2hhbXNoaXJlMRMwEQYDVQQHDApOb3R0aW5naGFtMQ8wDQYDVQQKDAZT ZXJ2ZXIxEzARBgNVBAsMClByb2R1Y3Rpb24xFDASBgNVBAMMC3Rlc3QgY2xpZW50 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArB/K8n6JmP4ZY+bJ0gso lYMpVZqFqUhbpWwPouqFkwoUJSteqvIt4tWlN9Dl4x5PMkSiRm+BkhNMpnsvJ3xf rtsdhHjaxPC6LRaHFbePN7Iaz2Q4SeZD9akkeC05TW9sjX2QxgfsdNBpvsCTSsuK zLq6dlKLMzND2DUV16Y+Ujc+zD6VxQ4kA5TTjbAq2/UdWDPu9KggiB1QL7QIPBFv CgivZyZgi/RLTRI6prUmCD8TqV1kSCV1oaiuRZBXPsPx0dIvhMTQFuT8VsRf4sQ1 wPwM+L4qRUkeuD+fC7ObB5z8+eNPShJfA/ehQHDfjFuyzccR7bG6SpZnhzCs6Chj aQIDAQABo34wfDAMBgNVHRMBAf8EAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUtKR/E3MQm7fElGQi43kC sJl403MwHwYDVR0jBBgwFoAUyGPeKWYklV2yN232ogGFrjEPjkUwDQYJKoZIhvcN AQELBQADggEBAAtTAjPcQFkPTgB+fo2wXWU/3vy9923COFUMJpfWBFCvlIcgHtjL jyJPlw7z9ok0w41g9MCnJCNlEhA5XvXbEKFTF7CQ+naXAL4iLpqK6KH1s0QAQzNC B5DetnOkxCTXwsDoP/t57ycqk9hb5/fUO1U4sA9ZmsJS9hl1RURsHO81ayN/2vsH lDYSG/d/iPQZZmZgX1h9zf/2GJaNNEKn+q1C2tcQslfNSJ9H1aJd+jMMRrFZUAM8 2Il21S+5SGhrUMboC42nTgoMtA/VeTACQU4T9bJ8AwKa33eAxn2Dcg8CGXxXy7Z9 1VASRNSzL6AnNfAR8VSpby+KExhJ2bvuWa4= -----END CERTIFICATE----- ================================================ FILE: test/ssl/client.key ================================================ -----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsH8ryfomY/hlj 5snSCyiVgylVmoWpSFulbA+i6oWTChQlK16q8i3i1aU30OXjHk8yRKJGb4GSE0ym ey8nfF+u2x2EeNrE8LotFocVt483shrPZDhJ5kP1qSR4LTlNb2yNfZDGB+x00Gm+ wJNKy4rMurp2UoszM0PYNRXXpj5SNz7MPpXFDiQDlNONsCrb9R1YM+70qCCIHVAv tAg8EW8KCK9nJmCL9EtNEjqmtSYIPxOpXWRIJXWhqK5FkFc+w/HR0i+ExNAW5PxW xF/ixDXA/Az4vipFSR64P58Ls5sHnPz5409KEl8D96FAcN+MW7LNxxHtsbpKlmeH MKzoKGNpAgMBAAECggEACoacMtWdpQM++r7Bj0x65B/D/pXnQBmqbxSLZT9ZwUrv vfEnxiTuvO0rQB1QfaHcHnsXgF6vygbPnGuyj8PZlxgTt0bru/jrrbevtZqG0dVc sduTXKON+t8n2YiMdUmP1hw8ZvvTkDYxjUZ6C2wklg4COpukIxKqvrVKW2hxbbYU +TdnxWDcuBbQRKwVGrFGxn9+uyJLC+VigwTVP05jNh7xcbn0cvctlRDTychFEkrK adg75g8oum11pW9Pq7pS1OMhofLuk4mPH29ybyvr9MxiG627pF8lv1lk6BQmN9OZ yY8EMzlaomPFqEkJYSYiF4cFmV4LPgporUn0olaFXQKBgQDauPHT/uyDttTKN2nj AP5c2u5L/Bee2vBXUhydgOrZQi+9Y17TVNP787nMRtw1sMlrIKG48PsBbVQGsgjG 5JquYSxM7GcyGueVYVNOM2Tw9ZO4Wxvknc+RZ4NTRAptM4KAK/RYz9zHZWa2mbmc tOtHEov1bbNm35lItcNmKJ2q/QKBgQDJdbmSJu1imTU5/uKp+83LF1suIhEHrT5y u0zCshqG/iX52EEYzlRBFsrLf7vibbqyBu1ZduBvWCMlUssvpB1AO5XNkyPCdapa U9y9pfWoPF3wziBHiCgummRKR9MwzOGM8GASM0V1Zenw7GR3iyd1cj66bNJKygr7 zR9qiDcT3QKBgDlIbq1i+naUj65WTPkS7YtMG1TzNQx5srBr5OqrNNapqu8i81bN xKcb8fE6LboyDs5rwW86TcLV60fFoN7WSFybPor27yAEQ9qvnq3AcBNbfdCuq+N4 IUCnp5FLJJ/s+aSv3lLUPbJLMFdqc15DU8tNZDJnBLFQpkiQshgzUvfRAoGBAKpg LoWk+EPXsEURA56gfuWQJiO42dA1OsgLERrjRz39OB65Pix9apH1daJur3YKOMcQ xrBPsfVYg7iv8XikAbzt534JP0fY/S4RGHEnJr+V9hiOKox0YQ8wsTqEzd3Kl8H7 FDSwOcDUZOnE8h6Lh95ytQwythJcFrfnPPd6paHdAoGAZt4wAqga7a50WFq+TTDo VYNOQq6NhSuxMBuuGekhXsjQcwVf2NZ1idahkip3SusgYt5gaQrIH93YA1EEu/hv oek/o898C7MH5myyonknErN5jAhb3Az6sDt9C3FEXia7BO2l4BalX88ujTUgfgYr zb89JL9s+Y9g3RiWdDvx3sw= -----END PRIVATE KEY----- ================================================ FILE: test/ssl/crl-empty.pem ================================================ -----BEGIN X509 CRL----- MIIBwDCBqQIBATANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjETMBEGA1UE CAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3QxEDAOBgNV BAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EXDTI1MDcwNzIyMjcyOVoY DzIxMDcwODI3MjIyNzI5WqAOMAwwCgYDVR0UBAMCAQEwDQYJKoZIhvcNAQELBQAD ggEBAHdkW722SMyoq3g1yYwmAE+KaPbo5PdhZBF7evGmZAfOlIXAgQGSJIVZLcjV R83mG11aN8HaWg05E75sAlBoP/fVnw6Ik7ubQA2aX2XrBkZwHsrkau1uuG9oeppP m6A9N+J2ZevBY3exnwsJYKfZlqWWqRKpr9upySPKcmIKxwawME4SREejmeObJs6H 4Ig0QjUtBm5LXJk9t0KiBefz6yk8wAgw7ztpReBLhMzOyuVYBLLjaEufVvLS2yOt 9D0rdd6/uZxFoze+z7yoVl11ksbIBoMfArxk95uI8zlpKsrjL/jGhTIaecPVu2GT YNCETZ5BQ+wy3d2Ho8Q/VVewbJU= -----END X509 CRL----- ================================================ FILE: test/ssl/crl.pem ================================================ -----BEGIN X509 CRL----- MIIB1jCBvwIBATANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjETMBEGA1UE CAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3QxEDAOBgNV BAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EXDTI1MDcwNzIyMjcyOVoY DzIxMDcwODI3MjIyNzI5WjAUMBICAQYXDTI1MDcwNzIyMjcyOVqgDjAMMAoGA1Ud FAQDAgECMA0GCSqGSIb3DQEBCwUAA4IBAQAFMdOne9AVg3pLPClB2DFRUJYr3BJU vynwJlbm8koDrnHRPf3m3y36fM80sjTFLtE6j3S+2duSItDDx3kZU9Rpy7RGqRu/ 3torSc+MgQkZKLOJKbk8qJx5/zNGTUAxL1abTSdqAvGpA2gRryXbzg6wnQwshViO b4kb346Ag+Oa1Wwl703pCpbgRlltOTGY9UXIY/3+a04aNDUOqYUmJ1uv+i5dS2DZ +CAnKnBSKdjRsDxx2Xxou6aEKnSog7E8L23C9j3EFo5iL7bh27I9pUbAV7lvC2QZ knLKSNDjCvir1556M4Nx4FzirDMqP0OWTqmnVtZG3dIryXgH1dFirt9j -----END X509 CRL----- ================================================ FILE: test/ssl/dhparam ================================================ -----BEGIN DH PARAMETERS----- MIIBDAKCAQEAkfphfOyL/LKjILqlnFmwbxwZYQr7lx3nlxiSqy4g25j/hmADTrJH YzpwrcbNpXCUl6D4b7RtJzNMLwoavemYSdtOeVygMnDHDD1TSnO0ywZ4wlskPNta FL5DMJRDCrc90pLb3kU2fPr2OZLImXRr9WlxF1xipQZqpdcpJ9jjtwZgArc7yotV b6gOVOJa0K3KDb3NJrQD0FD4ZltcueQEfrhBirjfH1Zpb+oe4rHNDd/EDbHFqu1W Frl7igOZs3NJM64rl7dmPWHF9iYp7y0cAZRFD7n9ViKtE8jTSfPfn7jQf+pNRIV+ MwKOk59F6jSRIFPT5Jv9zalagd5A6bLpDwIBAgICAOE= -----END DH PARAMETERS----- ================================================ FILE: test/ssl/gen.sh ================================================ # 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 # Valid server key and certificate, with subjectAltName. openssl genrsa -out server-san.key 2048 openssl req -new -key server-san.key -out server-san.csr -config openssl.cnf -subj "${SBASESUBJ}/CN=san/" openssl ca -batch -config openssl.cnf -name CA_signing -out server-san.crt -extensions test_SAN -infiles server-san.csr rm -f server-san.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 openssl dhparam -out dhparam 2048 ================================================ FILE: test/ssl/openssl.cnf ================================================ # # 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=critical,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 = critical,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 # 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=critical,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) [ test_SAN ] basicConstraints = critical,CA:FALSE subjectKeyIdentifier = hash authorityKeyIdentifier = keyid,issuer subjectAltName = "IP:127.0.0.1,DNS:localhost,IP:::1" keyUsage = nonRepudiation, digitalSignature, keyEncipherment ================================================ FILE: test/ssl/readme.txt ================================================ This directory contains certificates and keys required for SSL testing. The CA key has password "password". ================================================ FILE: test/ssl/server-expired.crt ================================================ Certificate: 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: 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 Public-Key: (2048 bit) Modulus: 00:b3:c1:ba:78:89:96:f8:3d:54:e1:fc:56:8d:d0: 2a:83:ae:8e:f1:76:39:4b:18:fb:4e:fc:36:c1:1e: a3:07:53:71:6a:0e:2e:c1:22:cd:a8:cc:f7:f5:cc: f8:2e:d4:d1:2e:7d:d0:d2:aa:a7:87:1f:4c:31:0f: 96:28:80:d2:52:ea:25:0c:32:e1:bb:64:81:bf:b4: 7b:11:b5:89:31:20:91:00:26:06:2f:09:f6:a7:c1: 6a:00:73:c7:12:d1:dd:88:33:66:54:f0:d6:7f:15: 1c:74:47:29:c7:03:2a:b9:c1:00:36:83:d9:48:b8: 54:f5:bc:df:57:9f:85:2a:91:03:be:c6:4f:5b:03: 68:aa:f8:e9:25:dd:5a:81:f2:c2:e8:0c:93:a0:05: d6:d1:77:49:ca:c5:1e:42:27:25:9d:fd:cc:e2:a7: 4b:28:05:e6:f5:1e:b3:97:3d:c4:25:65:f2:5b:cf: 3e:07:19:33:c0:fd:14:b4:a0:53:e1:6c:90:50:22: 76:29:b0:7a:45:2e:33:cd:c7:39:99:12:7e:d9:15: f9:ec:5f:69:92:d4:1c:2c:57:8a:12:a9:fc:94:da: 04:1a:17:18:7d:82:a3:03:8f:20:e8:f3:be:d2:61: 86:42:49:b5:d5:6e:cd:3d:6d:1d:fb:8b:3e:39:31: df:95 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: critical CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 33:48:15:F4:7F:39:F2:A1:26:77:FB:15:D1:A5:DC:CC:A7:E2:E9:99 X509v3 Authority Key Identifier: C8:63:DE:29:66:24:95:5D:B2:37:6D:F6:A2:01:85:AE:31:0F:8E:45 Signature Algorithm: sha256WithRSAEncryption Signature Value: 30:1e:c8:50:28:e4:10:60:d5:2a:82:65:0d:81:81:7b:bc:5c: 67:83:12:d3:e3:71:9d:91:2e:b9:ff:ca:e0:21:ad:74:45:72: be:49:54:f6:f0:22:09:18:84:67:53:88:51:31:20:e7:0d:52: bc:a9:ce:e2:72:27:b4:b9:da:28:03:19:53:46:46:ef:1e:ad: 3d:b1:21:df:ea:53:36:97:73:a1:a2:84:6e:9b:d1:b7:bc:7d: 3a:81:c9:35:76:fa:cf:70:c4:20:07:f0:c4:dd:c1:6c:0e:e2: 28:33:dc:ac:e5:90:b9:89:9d:8e:a6:2a:3e:36:b3:d7:17:f5: 76:08:96:c0:ca:07:4f:56:82:5b:93:c8:5d:fe:4c:7d:33:92: ee:6e:25:0c:ff:bb:3d:7f:b1:c1:36:dc:d9:aa:1a:4f:88:21: d4:67:77:8c:08:5c:ed:c2:6c:6b:92:78:4b:5a:23:a0:ed:9b: 27:63:d4:f1:0a:b3:b8:eb:95:01:fe:82:67:da:66:c9:51:d8: 5d:40:9f:69:bc:e5:4f:7c:19:45:ea:7c:d2:49:29:b7:b5:c6: 66:b2:66:8d:01:d4:bb:b0:2f:e9:c8:27:d1:93:f9:97:21:25: f3:b2:69:69:0b:d3:40:c4:3e:23:43:6d:8f:9a:7c:2b:c7:44: f0:99:f2:d8 -----BEGIN CERTIFICATE----- MIID3DCCAsSgAwIBAgIBAzANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMTIwODIw MDAwMDAwWhcNMTIwODIxMDAwMDAwWjB+MQswCQYDVQQGEwJHQjEYMBYGA1UECAwP Tm90dGluZ2hhbXNoaXJlMRMwEQYDVQQHDApOb3R0aW5naGFtMQ8wDQYDVQQKDAZT ZXJ2ZXIxGzAZBgNVBAsMElByb2R1Y3Rpb24tZXhwaXJlZDESMBAGA1UEAwwJbG9j YWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs8G6eImW+D1U 4fxWjdAqg66O8XY5Sxj7Tvw2wR6jB1Nxag4uwSLNqMz39cz4LtTRLn3Q0qqnhx9M MQ+WKIDSUuolDDLhu2SBv7R7EbWJMSCRACYGLwn2p8FqAHPHEtHdiDNmVPDWfxUc dEcpxwMqucEANoPZSLhU9bzfV5+FKpEDvsZPWwNoqvjpJd1agfLC6AyToAXW0XdJ ysUeQiclnf3M4qdLKAXm9R6zlz3EJWXyW88+BxkzwP0UtKBT4WyQUCJ2KbB6RS4z zcc5mRJ+2RX57F9pktQcLFeKEqn8lNoEGhcYfYKjA48g6PO+0mGGQkm11W7NPW0d +4s+OTHflQIDAQABo34wfDAMBgNVHRMBAf8EAjAAMCwGCWCGSAGG+EIBDQQfFh1P cGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUM0gV9H858qEm d/sV0aXczKfi6ZkwHwYDVR0jBBgwFoAUyGPeKWYklV2yN232ogGFrjEPjkUwDQYJ KoZIhvcNAQELBQADggEBADAeyFAo5BBg1SqCZQ2BgXu8XGeDEtPjcZ2RLrn/yuAh rXRFcr5JVPbwIgkYhGdTiFExIOcNUrypzuJyJ7S52igDGVNGRu8erT2xId/qUzaX c6GihG6b0be8fTqByTV2+s9wxCAH8MTdwWwO4igz3KzlkLmJnY6mKj42s9cX9XYI lsDKB09WgluTyF3+TH0zku5uJQz/uz1/scE23NmqGk+IIdRnd4wIXO3CbGuSeEta I6Dtmydj1PEKs7jrlQH+gmfaZslR2F1An2m85U98GUXqfNJJKbe1xmayZo0B1Luw L+nIJ9GT+ZchJfOyaWkL00DEPiNDbY+afCvHRPCZ8tg= -----END CERTIFICATE----- ================================================ FILE: test/ssl/server-expired.key ================================================ -----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCzwbp4iZb4PVTh /FaN0CqDro7xdjlLGPtO/DbBHqMHU3FqDi7BIs2ozPf1zPgu1NEufdDSqqeHH0wx D5YogNJS6iUMMuG7ZIG/tHsRtYkxIJEAJgYvCfanwWoAc8cS0d2IM2ZU8NZ/FRx0 RynHAyq5wQA2g9lIuFT1vN9Xn4UqkQO+xk9bA2iq+Okl3VqB8sLoDJOgBdbRd0nK xR5CJyWd/czip0soBeb1HrOXPcQlZfJbzz4HGTPA/RS0oFPhbJBQInYpsHpFLjPN xzmZEn7ZFfnsX2mS1BwsV4oSqfyU2gQaFxh9gqMDjyDo877SYYZCSbXVbs09bR37 iz45Md+VAgMBAAECggEAB+U25uBcoPEpFz1eSN+cKm+cAcrFTlrdzCGWvxZ0wMrf UaVah0Tba/It/V4gILoPKQyOKkUKhpkVkrCvHsuchIqAj5L0wfNMO3Ec/oSVSGYR 8F17MPNuIct3qwCEcMg5tue5DPrzroSTg1KOQqdAaAT5GMV9FJOO6cJx732UDtZz F13awaUuKWgc0MMq6rataIBhk2cnfFHsKmDkP+9LJ4MX4QHCUCep4hUWnqMHcR+Z PTC7K4hUvsjwCpaHUWvUTWRlH+wrHoq3by9dwVe4PsQ9yK/sX4vI1x0ER86iEJVj gNreaPFQIOWsgnoKfNMnLCJ8dyFaehFlzTggxswGyQKBgQDwF8/DSDfMz21VmiiB m13M3A/ZUhXmJCINXgsHvdK8xTihYUgIoyQRJGUvkuDV20ERemXH3t1vNe7AQbLQ aP2QXDLOzvvHGPybapip7VdUMY7Zc4w0zAh8U98A6hle3cnm6GlpwOZZRhrBT2Wl Zg4QESLSZg/MWuFp9oeuypYbqQKBgQC/qo+RnlMV1fHW1c2SmtHerm80hwMg6+Nf AIVLX06m7kv7GCR1pnYNmW2iAxrOW5bYh9czSENI3JnMOhoSvz4o6MwlPQU5wUmv YGuiAPMX+H1jeNi7gmMOsngHhtDLCMHRaOiip3N+BxdpFIF8u+VTlIIBYcoNYfaX QKMINMm4DQKBgQDrfO9zAqp4YBtFEucX+GOQQ2foJ/MCv/4GTm9TMIQ6UtawstIM ZrdBeQkmGFIeb+bqVbrux1E5exSpzcatU80ggs3yumGJbqCVb4A9a2V0VwddkU+7 mUPZbgoUw4gO3ErkCKEb8O/+MByd7losWGUCrUwSQbjNH3ZokD2U229PwQKBgFBX H00Lz4n0nyXNgxkz2kr8VVLwUQhouGsnHbiFX8OrWaAL86R5PTzgFkt1/7OGQsnK zxMI9GNDTRiFNk6raVPemUv2sw0Nj2R7B0LmIP/oQi8DBd47fmg3uQZ2pWil6BBu aC1eAZRPRqneVZTCchNByejoY7iOWr318yDKd8+1AoGAE1i5p5+i48tETX0C5nmW wSXJqGcW+BCK76Y2k8x31jHgcvweRhAx4y2MzIE1964Rm03Q9qsE5D9ZinPhKGCW wszmQ4SRnnrcIInxNe/qlyXu6+VjYkOVrGOPqFO87VapumFIRHacGppO/9ZPy8+i RAryWvRvyfMGYElO4phPDSw= -----END PRIVATE KEY----- ================================================ FILE: test/ssl/server-san.crt ================================================ Certificate: 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: Jul 7 22:27:29 2025 GMT Not After : Jul 6 22:27:29 2030 GMT Subject: C=GB, ST=Nottinghamshire, L=Nottingham, O=Server, OU=Production, CN=san Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: 00:a9:25:cd:2f:17:90:aa:7f:7b:86:d5:ec:2e:1e: 4f:b6:6b:62:87:59:70:b8:69:1d:3d:e4:f6:5e:d2: 49:a5:26:70:c6:78:df:16:66:77:2e:87:8b:81:12: b5:41:46:cb:f2:28:fd:5f:dc:16:20:52:0d:dc:de: 77:97:d8:6d:b2:44:53:3c:cd:c0:50:69:d9:a5:73: b7:48:a7:bd:01:bd:2b:82:f9:8d:3d:a4:94:0b:b9: bb:5a:c7:0b:0c:84:48:ac:3d:ee:dd:72:e7:c0:a8: cc:c5:85:c5:c3:df:6b:90:d7:e2:05:6c:1b:ec:37: 57:57:98:e7:19:1c:19:38:68:97:3d:51:74:33:44: e4:33:3d:dc:a1:de:90:7a:37:fa:d1:95:e9:06:83: 7c:92:6c:42:5c:27:d6:7f:4b:5b:73:4a:be:a7:24: c4:e3:3e:80:ba:7e:d3:c7:ad:80:d6:c4:db:d4:fb: e1:1f:e3:4f:4b:65:aa:1e:ab:ae:65:c1:08:df:1a: 34:d2:a0:56:71:37:e3:cd:5a:c3:22:a9:49:bc:b1: 71:22:59:03:88:2f:b8:2d:b0:a9:a4:53:d8:fd:a0: c3:a5:f2:e0:15:1e:40:22:ff:aa:65:e3:89:e3:8d: 51:ec:b5:08:60:6d:45:a3:7d:82:27:93:e4:86:b4: 3e:5d Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: critical CA:FALSE X509v3 Subject Key Identifier: 24:AB:08:6C:BB:5A:DD:85:4E:A1:8B:E4:66:EA:F2:C8:BE:EE:51:B9 X509v3 Authority Key Identifier: C8:63:DE:29:66:24:95:5D:B2:37:6D:F6:A2:01:85:AE:31:0F:8E:45 X509v3 Subject Alternative Name: IP Address:127.0.0.1, DNS:localhost, IP Address:0:0:0:0:0:0:0:1 X509v3 Key Usage: Digital Signature, Non Repudiation, Key Encipherment Signature Algorithm: sha256WithRSAEncryption Signature Value: 78:4e:c7:8c:b8:96:51:ed:ee:e6:04:c5:61:fd:74:22:2f:00: b7:4c:63:99:ae:35:31:4f:c2:13:f0:aa:64:04:1e:7d:df:bc: 16:27:67:d8:af:cd:8c:4f:d8:c1:48:f7:28:ec:00:25:98:3d: ab:75:33:4c:9a:4d:a6:50:3c:d3:eb:62:d4:e8:32:17:5f:18: 7b:3d:45:d2:16:7c:2c:21:30:aa:75:f4:d0:68:bc:9f:94:2e: f5:36:3b:94:b5:4e:6f:58:f5:8c:0b:ba:d4:f2:d9:01:1a:e3: d1:8b:85:41:e5:95:8a:1b:1e:b2:a4:1f:78:b7:de:80:12:1d: cd:ea:93:b5:1e:39:ad:5e:b8:78:ba:26:40:1e:c8:37:d9:b8: d2:86:6f:5c:a9:5a:27:5b:19:3a:d2:c2:7d:cb:69:96:6c:17: 4c:00:39:2d:d0:6e:08:26:2b:2e:3c:df:9f:8b:29:85:65:bb: b8:9e:4a:5d:ca:5c:91:58:6b:b2:f5:9a:09:37:c8:f7:2e:48: df:a9:9a:ea:de:e5:d2:91:b2:c4:ad:49:0a:24:70:8f:da:e6: 21:8f:67:e4:e8:e4:b1:2f:d2:6e:c0:83:46:37:2a:ee:69:fb: d6:09:b7:a4:0a:46:e8:3d:fc:c3:20:b7:0c:80:a3:a8:be:bd: 33:af:15:c6 -----BEGIN CERTIFICATE----- MIID3TCCAsWgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMjUwNzA3 MjIyNzI5WhcNMzAwNzA2MjIyNzI5WjBwMQswCQYDVQQGEwJHQjEYMBYGA1UECAwP Tm90dGluZ2hhbXNoaXJlMRMwEQYDVQQHDApOb3R0aW5naGFtMQ8wDQYDVQQKDAZT ZXJ2ZXIxEzARBgNVBAsMClByb2R1Y3Rpb24xDDAKBgNVBAMMA3NhbjCCASIwDQYJ KoZIhvcNAQEBBQADggEPADCCAQoCggEBAKklzS8XkKp/e4bV7C4eT7ZrYodZcLhp HT3k9l7SSaUmcMZ43xZmdy6Hi4EStUFGy/Io/V/cFiBSDdzed5fYbbJEUzzNwFBp 2aVzt0invQG9K4L5jT2klAu5u1rHCwyESKw97t1y58CozMWFxcPfa5DX4gVsG+w3 V1eY5xkcGTholz1RdDNE5DM93KHekHo3+tGV6QaDfJJsQlwn1n9LW3NKvqckxOM+ gLp+08etgNbE29T74R/jT0tlqh6rrmXBCN8aNNKgVnE3481awyKpSbyxcSJZA4gv uC2wqaRT2P2gw6Xy4BUeQCL/qmXjieONUey1CGBtRaN9gieT5Ia0Pl0CAwEAAaOB jDCBiTAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBQkqwhsu1rdhU6hi+Rm6vLIvu5R uTAfBgNVHSMEGDAWgBTIY94pZiSVXbI3bfaiAYWuMQ+ORTAsBgNVHREEJTAjhwR/ AAABgglsb2NhbGhvc3SHEAAAAAAAAAAAAAAAAAAAAAEwCwYDVR0PBAQDAgXgMA0G CSqGSIb3DQEBCwUAA4IBAQB4TseMuJZR7e7mBMVh/XQiLwC3TGOZrjUxT8IT8Kpk BB5937wWJ2fYr82MT9jBSPco7AAlmD2rdTNMmk2mUDzT62LU6DIXXxh7PUXSFnws ITCqdfTQaLyflC71NjuUtU5vWPWMC7rU8tkBGuPRi4VB5ZWKGx6ypB94t96AEh3N 6pO1HjmtXrh4uiZAHsg32bjShm9cqVonWxk60sJ9y2mWbBdMADkt0G4IJisuPN+f iymFZbu4nkpdylyRWGuy9ZoJN8j3LkjfqZrq3uXSkbLErUkKJHCP2uYhj2fk6OSx L9JuwINGNyruafvWCbekCkboPfzDILcMgKOovr0zrxXG -----END CERTIFICATE----- ================================================ FILE: test/ssl/server-san.key ================================================ -----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCpJc0vF5Cqf3uG 1ewuHk+2a2KHWXC4aR095PZe0kmlJnDGeN8WZncuh4uBErVBRsvyKP1f3BYgUg3c 3neX2G2yRFM8zcBQadmlc7dIp70BvSuC+Y09pJQLubtaxwsMhEisPe7dcufAqMzF hcXD32uQ1+IFbBvsN1dXmOcZHBk4aJc9UXQzROQzPdyh3pB6N/rRlekGg3ySbEJc J9Z/S1tzSr6nJMTjPoC6ftPHrYDWxNvU++Ef409LZaoeq65lwQjfGjTSoFZxN+PN WsMiqUm8sXEiWQOIL7gtsKmkU9j9oMOl8uAVHkAi/6pl44njjVHstQhgbUWjfYIn k+SGtD5dAgMBAAECggEABan04W9OEk97gOvX4UF1lNuqrHKTwjEO4BwzHcC345ZS b2rruXHL6txyEOvh8uIegSjbNyMFAKcOvMccRRLjtXTxPpd7KZYpyg8CY6XuP8ko VFXr41UH+g6JlgQVPCGP12ipf3PSC9L7LGAK28C29t4rvNe+ZZ4CyDWgA2i79XYJ K94iOVGrMoWfPiFXMHkC3HonLCQIeRP3Us2FtWBpDs0HEouGCTa/BWpkim5hnoCh TRW+ixopQOyN0bVPf1wVIin7UbNiIyF4jJfUNd5WQrstgwdGAlH65V8BaDO+sIsa 1dHDsdzGaPQqsmGLhWJ298UmYDYp5k8jUUoMxQCFZwKBgQDYtvYng7OQDNI2K5yu 2pv9QtobNaZ0ZyVvy/bbaAHvJvej6aKThW30JVk7zkyBk1dQkhSx7GgZoDYylx3E 5CtQiT07GkG8DZiehfv6RZCRHqR3a2VgpqFQnfiFVniFaX4T7p4YB/9uGmxzWU4Q T9fbIge2dfE8O7Drz4wYMpAGRwKBgQDHz2fUTZb8DZgQpasCQBqFwQKnk7ZKAgvO cu3JO41/wUL2ZMfxeFIgMORFk+Xckm7KslykKnmX4etP1gxXqtAqR2JuWqv25Se8 fjZi8TbNm33Poul7nZsYQNBByy9jpLl6PRCYRCB67HPCRYqyGswcw8fXj4wQWYEn pYFJqzDUOwKBgQCX0dUwaXtp9xFtEbB6bnvJOQRC+5rZAUmgwGr32i1AtTPXiN10 K42T9HZHB4dhXy9UKoKFAvEKwso1NtiMDqyphvt2ZDaY342DwKl98y4L/EOLxZkH 1LQ+Hez0vFdCX10L6aanfzLal3hSdsXRd53ozjZJBOczIz4WdRfX+9QaEQKBgH4C tHV0tVqibBtbj5ysts1Rqw3qHxVPcwiw/HtjXlqKlGN1rY8AlbKNgvjKTDWt98dH cxtpWiPKK6++yyviosN3H4F/F2JupH/AjSYa/7ftbwuqr1rxS2WhQnWr4WgS85I+ vp94n49GXb7QQqcONVmSsw6kDe4ltEk/nGjMWNAPAoGAb2ogcxUZN3exlQbqVLeM fw5LVTH2g8vIis1TKyBDaHZqCwsqmyKhEhVExVp8Ipsv6wg3aySgmVeJSddJsMIl TCGFi/Y5NbAsm+8VvcArhiJJkhTH+NXSUN23aS7Wm4NO6Su9NnrAFpEMcIxK6FsJ 45t+LOhdZwXzPtYdJDQHM2s= -----END PRIVATE KEY----- ================================================ FILE: test/ssl/server.crt ================================================ Certificate: 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: Jul 7 22:27:28 2025 GMT Not After : Jul 6 22:27:28 2030 GMT Subject: C=GB, ST=Nottinghamshire, L=Nottingham, O=Server, OU=Production, CN=localhost Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: 00:9e:19:e7:52:51:89:c3:7b:41:a2:02:26:73:21: 06:d8:77:f1:36:b7:0d:5c:94:d9:bb:78:35:c0:aa: 6b:63:4a:3c:ff:c1:c2:0b:76:6e:86:1e:4b:a9:ee: 18:34:b1:40:f1:99:6d:90:3d:5b:3d:eb:2e:c9:e0: bf:ee:37:38:31:a7:26:48:d3:35:59:f2:86:a4:0f: dc:33:c3:9e:b0:8b:b7:0c:2a:67:81:ea:24:4a:a2: 3b:b7:82:93:74:d7:7d:a5:91:90:4d:6d:11:fc:40: 2b:86:94:87:62:8e:46:c2:13:bd:47:96:ca:f4:02: 6c:6b:f2:8b:ba:d9:9e:f5:fa:d5:d2:53:6d:b1:43: 14:02:b4:c4:33:12:93:54:35:8f:7c:d2:41:f9:ab: 13:7c:7e:23:9c:ff:9f:f1:4d:0c:6b:c0:dd:b9:84: 16:b9:19:8a:38:23:87:1f:bd:0f:77:33:b1:91:70: 9d:e4:00:9e:76:76:f0:a9:50:9c:8f:f8:f3:b4:19: d9:cd:26:ca:cb:ad:d4:bf:73:04:a7:c3:79:e1:b4: 99:2c:be:8f:6b:70:3f:4d:8c:1e:28:6a:b6:f4:a7: a9:c2:f0:28:f3:55:86:7f:09:fe:2f:3e:4f:ba:55: ac:7e:7e:77:19:fb:55:44:d0:db:c2:60:99:28:64: d8:67 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: critical CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 7C:CC:33:7E:7A:79:EA:33:7B:56:77:63:2B:B1:CC:28:6F:EA:8A:8E X509v3 Authority Key Identifier: C8:63:DE:29:66:24:95:5D:B2:37:6D:F6:A2:01:85:AE:31:0F:8E:45 Signature Algorithm: sha256WithRSAEncryption Signature Value: 88:87:3b:39:bb:34:f5:2b:15:fc:8d:b2:6c:e2:3e:f6:5f:14: 0a:d4:48:73:1a:ab:08:42:48:a1:d0:ef:ec:b4:3c:f4:b6:f0: d8:42:c1:af:e4:aa:3a:d9:86:7c:55:eb:1b:ae:76:f0:15:ee: ec:b7:fb:d4:7e:0d:5e:dd:f4:6d:ee:71:06:c0:20:87:ba:50: 39:38:0e:79:63:9d:59:46:26:67:4e:41:09:af:75:40:1e:5b: 9d:8d:fa:2b:2a:25:8f:65:c0:21:fe:60:2e:d5:e3:bf:2e:ac: b3:1c:fd:51:d8:bc:70:dd:26:2a:45:a3:2f:3d:26:2c:d0:c8: a9:d5:29:64:84:e4:a8:79:8a:16:ab:3a:97:99:3c:25:af:04: e9:29:1a:83:62:e6:a4:dc:83:2f:95:4a:2e:9d:cb:56:38:c5: 9f:dc:18:67:02:d4:07:11:31:d5:d1:e4:1a:b6:0b:93:b2:e8: 33:5d:62:58:d9:0d:10:27:d0:46:7a:b8:64:de:32:82:e7:d9: e7:76:85:dd:14:d3:0f:bd:a5:05:e9:ed:03:a8:a1:8b:0a:61: bd:51:6c:f1:e8:b0:3a:6c:fa:48:79:d7:da:90:53:96:d4:94: da:fe:df:9c:1b:80:4a:d9:fa:5e:0d:c1:ee:a7:4f:17:64:24: 6e:56:fa:67 -----BEGIN CERTIFICATE----- MIID1DCCArygAwIBAgIBATANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3Qx EDAOBgNVBAsMB1Rlc3RpbmcxEzARBgNVBAMMClNpZ25pbmcgQ0EwHhcNMjUwNzA3 MjIyNzI4WhcNMzAwNzA2MjIyNzI4WjB2MQswCQYDVQQGEwJHQjEYMBYGA1UECAwP Tm90dGluZ2hhbXNoaXJlMRMwEQYDVQQHDApOb3R0aW5naGFtMQ8wDQYDVQQKDAZT ZXJ2ZXIxEzARBgNVBAsMClByb2R1Y3Rpb24xEjAQBgNVBAMMCWxvY2FsaG9zdDCC ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ4Z51JRicN7QaICJnMhBth3 8Ta3DVyU2bt4NcCqa2NKPP/Bwgt2boYeS6nuGDSxQPGZbZA9Wz3rLsngv+43ODGn JkjTNVnyhqQP3DPDnrCLtwwqZ4HqJEqiO7eCk3TXfaWRkE1tEfxAK4aUh2KORsIT vUeWyvQCbGvyi7rZnvX61dJTbbFDFAK0xDMSk1Q1j3zSQfmrE3x+I5z/n/FNDGvA 3bmEFrkZijgjhx+9D3czsZFwneQAnnZ28KlQnI/487QZ2c0mysut1L9zBKfDeeG0 mSy+j2twP02MHihqtvSnqcLwKPNVhn8J/i8+T7pVrH5+dxn7VUTQ28JgmShk2GcC AwEAAaN+MHwwDAYDVR0TAQH/BAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBH ZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFHzMM356eeoze1Z3YyuxzChv 6oqOMB8GA1UdIwQYMBaAFMhj3ilmJJVdsjdt9qIBha4xD45FMA0GCSqGSIb3DQEB CwUAA4IBAQCIhzs5uzT1KxX8jbJs4j72XxQK1EhzGqsIQkih0O/stDz0tvDYQsGv 5Ko62YZ8VesbrnbwFe7st/vUfg1e3fRt7nEGwCCHulA5OA55Y51ZRiZnTkEJr3VA HludjforKiWPZcAh/mAu1eO/LqyzHP1R2Lxw3SYqRaMvPSYs0Mip1SlkhOSoeYoW qzqXmTwlrwTpKRqDYuak3IMvlUounctWOMWf3BhnAtQHETHV0eQatguTsugzXWJY 2Q0QJ9BGerhk3jKC59nndoXdFNMPvaUF6e0DqKGLCmG9UWzx6LA6bPpIedfakFOW 1JTa/t+cG4BK2fpeDcHup08XZCRuVvpn -----END CERTIFICATE----- ================================================ FILE: test/ssl/server.key ================================================ -----BEGIN PRIVATE KEY----- MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCeGedSUYnDe0Gi AiZzIQbYd/E2tw1clNm7eDXAqmtjSjz/wcILdm6GHkup7hg0sUDxmW2QPVs96y7J 4L/uNzgxpyZI0zVZ8oakD9wzw56wi7cMKmeB6iRKoju3gpN0132lkZBNbRH8QCuG lIdijkbCE71Hlsr0Amxr8ou62Z71+tXSU22xQxQCtMQzEpNUNY980kH5qxN8fiOc /5/xTQxrwN25hBa5GYo4I4cfvQ93M7GRcJ3kAJ52dvCpUJyP+PO0GdnNJsrLrdS/ cwSnw3nhtJksvo9rcD9NjB4oarb0p6nC8CjzVYZ/Cf4vPk+6Vax+fncZ+1VE0NvC YJkoZNhnAgMBAAECggEACTSo63oj82Xx5GULqBh8NY6GVRFDjeh85RWSy60go59m /d1iVxiGRvjsnvBmKGtJxMeSQZvQ/EH9b3POuSgt9XYuHH9v09TzUgo6YCk7zDvW ZLbzX/UqN85Ke9z2iQ8jGcjoBhobufxijGuJlouCQzqzAsAdAShC9+YfjLmvL9Nb wgwJvDs6PiVi/GvdFtoF7YPZsRGBChehI344X0GdDVgStwYX+O8hKRFwNjP1o3sJ 5odv45cwxwXtTlvsnRIGSQHgYQmzyUHXnb/PvVfXKuq4n5+lQT5egCcZukyr9vo7 hwDnlNPC1Z5w3ubyQdogv7Q1fBt0JskBjOXK4uiTgQKBgQDKox8/IPnEeFO7dxwf N/+oCamticjM6oAO5/Fb7DwLzzBLZBjiUmfieTSAOUuJU2hOpsWP30I3ySu30UZX bwxmdcRLIMJ7Q1HxOEEYCgCxdushOxOXdzW/H4sOPQspwzMQHibMCw+77igQpqwg QMAGKDZ7cMy+LNouDFdOWVzKjwKBgQDHvF3KL1mDgdEgOilWaQQ1TO81HQUE2maE ql1vqSjdQpgUzzFPTP5C1dZA4vGI3F6dT3nJHpEGusxF+TtyJMWvY1rUyLJX684l CAnXVvI+1xI4dSNlYO7YS67SpKNKZiv6s4Q5o1o1RjKIRxt/7K2gT4IiR/qDn2ZJ fbpp47rgqQKBgHZEYnZL3rrmp6ggSo+F9XazvQ6F/mZq7zbD9MB7zkfuMvetgkCF bBBoQVYdGpMZ1SUifOgNm+5HQXbVc8KQE6KxVVGr2xZqIicxd/x5yhHJoE4S1spu TzYvSM+UnTFQtjrP/kDUq+g5hbTCMm/Ymrp9Od8t5LGSJ/z8QvB9g4TNAoGAGfEd PWVo+uuhfc4QEGkTYtjbOMrMHBVBu3llKVuPMy2zEwDWJraZT5T2fvb66Au3PjdU WgreS0F3xp7YWbrs8hq1cW2fvEukOqsQnCduzzqf4zVTo5czbmRmEHXRv5gFnkoy oknVLZYwegLCT5st8eRhwpIWt4G8h08NJzOs0gECgYAzl0sBMIMuj5GLXhClCoLm XWKjAP8q1rd8nY9oWwzlLoKMsBn26SKZ+/mvhx3Yxr0FNYZR8nTYoFaOE2lEmPrm /tQQBhMS4ZjnF77RKAqM7GZWUA68himDjN6YEobl7GaANn2sCy39FSxpT8DHSGfn 3eKrvNpUlEoGg3KJ26Zsqg== -----END PRIVATE KEY----- ================================================ FILE: test/ssl/test-alt-ca.crt ================================================ Certificate: 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: Jul 7 22:27:28 2025 GMT Not After : Jul 6 22:27:28 2030 GMT Subject: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Alternative Signing CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: 00:af:de:b9:88:7f:45:02:9c:72:21:85:f6:05:7b: 66:2c:67:e1:80:3e:65:65:f8:09:fd:52:f0:53:0d: 33:65:ab:c3:3c:03:ff:8d:ca:b7:d6:88:8e:e5:b8: 2e:66:0e:81:8e:b9:dc:2d:13:22:49:12:5a:be:71: f7:2f:75:bb:aa:af:83:18:f6:ec:00:1d:19:2f:98: d4:44:a6:99:0d:22:be:fd:91:fc:68:58:9a:c4:9a: 75:4a:06:6b:8d:5e:0d:3b:51:f2:bf:88:d7:a1:c3: 30:47:86:4e:cb:30:a5:1b:6d:d7:b0:93:65:0f:b4: 1c:bf:f2:16:a2:0a:4d:f7:1d:76:ba:5b:20:97:a5: a4:9f:4a:f2:4e:9f:7f:e4:19:66:31:5e:69:c8:7d: 32:ae:ae:d5:61:d9:c9:a3:73:b9:81:f9:78:d0:b0: 34:1a:7b:6b:38:01:5b:71:41:23:90:29:56:1d:22: f1:d3:e0:eb:ac:6c:d4:bf:46:fc:c4:78:cb:36:d4: f9:c2:47:98:0a:11:26:c1:26:2e:fc:ec:6b:b4:df: 04:1f:84:36:06:c7:26:ac:bf:bf:e1:ab:62:39:6f: ba:79:5e:01:33:66:e6:13:4f:c7:d5:98:57:04:3e: 28:94:7f:64:2e:92:3c:0c:5b:b0:2e:64:7a:71:e4: 32:2b Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Subject Key Identifier: 42:84:86:43:AC:B2:A4:A9:74:E5:6B:B8:B1:B9:16:03:C4:3F:A2:9C X509v3 Authority Key Identifier: 4F:56:ED:BA:57:12:46:13:CF:96:E3:2C:C1:91:64:69:5B:9A:E7:05 X509v3 Basic Constraints: critical CA:TRUE X509v3 Key Usage: Certificate Sign, CRL Sign Signature Algorithm: sha256WithRSAEncryption Signature Value: ed:20:93:a4:3d:c4:c7:d4:02:45:ce:6a:9b:27:8a:c0:ba:4b: 52:64:e3:0e:e7:72:60:67:8c:ab:88:c4:d9:6f:a7:29:17:1b: d7:2a:23:dd:b9:a4:9c:7a:95:cc:56:a9:09:07:8c:93:e6:52: 07:90:2f:b4:ae:53:39:cd:22:4b:16:80:d4:9d:96:2f:4a:c7: ef:ab:02:1f:f2:8b:a1:3a:5b:e8:56:2d:65:74:a1:32:3d:9a: 5f:67:09:1c:fb:a0:20:76:98:c2:79:ce:1e:3e:0f:e3:16:51: d5:a8:42:96:6c:8e:13:53:68:29:63:45:68:fe:7f:65:34:d7: c0:e3:81:f6:cd:36:91:da:07:bf:ff:00:2e:13:55:af:63:d1: d3:9b:40:44:9e:51:34:7e:0f:7e:01:b7:c2:f6:7c:42:0d:ac: 78:6a:cd:35:f7:06:e3:ac:89:59:b3:54:a2:5c:bb:98:02:0b: e4:f3:1d:74:ab:25:8b:1b:13:5a:bc:74:47:0d:9b:d6:cf:0f: eb:9a:9e:1c:10:82:97:da:df:59:71:9b:9a:2f:4d:e6:8a:f6: fb:b4:af:d9:ee:ba:92:15:33:b0:56:2c:8d:bf:b3:ba:ab:a7: d6:f8:d0:2f:10:8e:85:6d:47:89:5a:b5:49:95:58:7a:ae:60: 5a:c8:f5:67 -----BEGIN CERTIFICATE----- MIIDvjCCAqagAwIBAgIBAjANBgkqhkiG9w0BAQsFADByMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEOMAwGA1UEBwwFRGVyYnkxGjAYBgNVBAoMEU1v c3F1aXR0byBQcm9qZWN0MRAwDgYDVQQLDAdUZXN0aW5nMRAwDgYDVQQDDAdSb290 IENBMB4XDTI1MDcwNzIyMjcyOFoXDTMwMDcwNjIyMjcyOFowcTELMAkGA1UEBhMC R0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxGjAYBgNVBAoMEU1vc3F1aXR0byBQcm9q ZWN0MRAwDgYDVQQLDAdUZXN0aW5nMR8wHQYDVQQDDBZBbHRlcm5hdGl2ZSBTaWdu aW5nIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr965iH9FApxy IYX2BXtmLGfhgD5lZfgJ/VLwUw0zZavDPAP/jcq31oiO5bguZg6BjrncLRMiSRJa vnH3L3W7qq+DGPbsAB0ZL5jURKaZDSK+/ZH8aFiaxJp1SgZrjV4NO1Hyv4jXocMw R4ZOyzClG23XsJNlD7Qcv/IWogpN9x12ulsgl6Wkn0ryTp9/5BlmMV5pyH0yrq7V YdnJo3O5gfl40LA0GntrOAFbcUEjkClWHSLx0+DrrGzUv0b8xHjLNtT5wkeYChEm wSYu/OxrtN8EH4Q2BscmrL+/4atiOW+6eV4BM2bmE0/H1ZhXBD4olH9kLpI8DFuw LmR6ceQyKwIDAQABo2AwXjAdBgNVHQ4EFgQUQoSGQ6yypKl05Wu4sbkWA8Q/opww HwYDVR0jBBgwFoAUT1btulcSRhPPluMswZFkaVua5wUwDwYDVR0TAQH/BAUwAwEB /zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQELBQADggEBAO0gk6Q9xMfUAkXOapsn isC6S1Jk4w7ncmBnjKuIxNlvpykXG9cqI925pJx6lcxWqQkHjJPmUgeQL7SuUznN IksWgNSdli9Kx++rAh/yi6E6W+hWLWV0oTI9ml9nCRz7oCB2mMJ5zh4+D+MWUdWo QpZsjhNTaCljRWj+f2U018DjgfbNNpHaB7//AC4TVa9j0dObQESeUTR+D34Bt8L2 fEINrHhqzTX3BuOsiVmzVKJcu5gCC+TzHXSrJYsbE1q8dEcNm9bPD+uanhwQgpfa 31lxm5ovTeaK9vu0r9nuupIVM7BWLI2/s7qrp9b40C8QjoVtR4latUmVWHquYFrI 9Wc= -----END CERTIFICATE----- ================================================ FILE: test/ssl/test-alt-ca.key ================================================ -----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCv3rmIf0UCnHIh hfYFe2YsZ+GAPmVl+An9UvBTDTNlq8M8A/+NyrfWiI7luC5mDoGOudwtEyJJElq+ cfcvdbuqr4MY9uwAHRkvmNREppkNIr79kfxoWJrEmnVKBmuNXg07UfK/iNehwzBH hk7LMKUbbdewk2UPtBy/8haiCk33HXa6WyCXpaSfSvJOn3/kGWYxXmnIfTKurtVh 2cmjc7mB+XjQsDQae2s4AVtxQSOQKVYdIvHT4OusbNS/RvzEeMs21PnCR5gKESbB Ji787Gu03wQfhDYGxyasv7/hq2I5b7p5XgEzZuYTT8fVmFcEPiiUf2QukjwMW7Au ZHpx5DIrAgMBAAECggEAEb8Cr7BP8VyB87oFwjXacH6m9X7WUny93U8CKw848Xhs geDRZ6hd9orfCHUWUXwDPLiqa+3zVrZAa9kqHSLfJfEB5IH9/GDzSqc8PBUnenjY FtQlSQ4vx8jiLu8I6UHlSegR+5u+TndYps75om0tK+BglFO7LeN5xzCRchZiGZ43 b/dxGiDsyC1JDXiM14pa7EfxdNVFha8MmOo27kBGA6FczspMtUQyMAuyvy4/2u/I 6Nx1CE8kTVfqepVupS16oiNIqNtrOr+wVxpk90j1vmR9kns8kZaTHjDy1liEyi4p xp/b5SKNJGrV456zGqwj3c/5n89rIWFdzGeyfg29EQKBgQDrdeNGEovpanH7dOlX mewskgNF4Ug+cvob9Yh1fowSDhT4shdCJBkCiSSBFX3xr2c1a6212SfxNth5LFLY /MWJecjanRuzq6sNv1VftwReCIOJjFsfhOL8ONJWIDXdV+gKtIDSv/d2fym1qWnl CJWZSk0BRSBFvYUG50PDA3XCswKBgQC/NhxgF3fXu6OIiB9w3txC2ZVfaV2qN+Pd O5ZHsx+e8JtbdCVfJWJQXOA6mama5Tldj8O+31jBnKGQtKzJDhyjHPBzYFHdZOfR IK3ZsuvYlgL8QogVlciTaLy2eIM3vYewM/sCDIXDAOP6dqPKdqLFVUZEalptgkRc 8oYRSmuuqQKBgQCkfROLhTNWmbUM3GySdQYHUO2WaL4GWl4dIBb3NbN2fX3rCsay vvL10Ya94py8NTPdnt6Ydh6wJQdvBybNTTBWTMyi5DRQ/PEfRnXGytzzL/FsKrAR wcysNKnD3vaiLWH98IE6OT8P+d/Sd4pxpOCVWNGYvIjCD5aZ7v9ogcdHfwKBgD5d 5+NvxCcZjL17qMWn6y/iyFXWiDZ9BFWkmd/JDQdKc2HhAE+IYgjUQk7az/c1zQA3 ZCFduBVugUQxqinp8G1DgyoewJT11KbhgdMACO0cAN1G1hw0PrfV8beSlzoXF6rh SX3hl7+DCtkm2UWwbGbw6XpnNheB5cprUE9TdswBAoGBAM62RzHFmwz7Qu9bImFE JE19hM6ib2SD2Llg+/75i6d6Z/X7wOJxHa1u1et8v0wo53uQMBo5A6PvE44HSW9S xgKj/FbDx3OWnrKjP0P1Jx32X5MV6pDAdw7kuCm8TBwTVGgVv34IKuToCBqwUMed lnk7BXKvKq8cCT0qz+9GYRqw -----END PRIVATE KEY----- ================================================ FILE: test/ssl/test-bad-root-ca.crt ================================================ -----BEGIN CERTIFICATE----- MIID2jCCAsKgAwIBAgIUPdXz5ys4khmrwxJhnGnx/jH4rmUwDQYJKoZIhvcNAQEL BQAwdjELMAkGA1UEBhMCR0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxDjAMBgNVBAcM BURlcmJ5MRowGAYDVQQKDBFNb3NxdWl0dG8gUHJvamVjdDEQMA4GA1UECwwHVGVz dGluZzEUMBIGA1UEAwwLQmFkIFJvb3QgQ0EwHhcNMjUwNzA3MjIyNzI4WhcNMzUw NzA1MjIyNzI4WjB2MQswCQYDVQQGEwJHQjETMBEGA1UECAwKRGVyYnlzaGlyZTEO MAwGA1UEBwwFRGVyYnkxGjAYBgNVBAoMEU1vc3F1aXR0byBQcm9qZWN0MRAwDgYD VQQLDAdUZXN0aW5nMRQwEgYDVQQDDAtCYWQgUm9vdCBDQTCCASIwDQYJKoZIhvcN AQEBBQADggEPADCCAQoCggEBAIlSX40YsU38EmwfF4nY9d3D4K0iu25NUGkRwToG FihwY/SRr0DQEyBY9DaDOwUkVW5w2fG/ZEq5UoC9aUH45qfgo/aMHDuJmUv2grJy C/C1+ldaGnYVzv+G+vjYVeclvF+ygEO7UDhF895bHty77ULOtvF6wswgudpg+Q5n iujQq9oTc+POM4R4sITdjvhFxqRjjKYS7AeyEYXy5tkpqmh7BLtmemeyohXfpKsQ kKzE+k97GiVn+7ToG07PH71FZ5mfMjLlDDSiUN7OlVeMs8xOaGJcTtneSmBqmZvq 9wPNYt9nhbuPF6NMlBmgmWWW6t+QCrXWA5bsDRQLYj6iwdsCAwEAAaNgMF4wHQYD VR0OBBYEFGnU3jqeHtH9/EW3156LEIasHd9jMB8GA1UdIwQYMBaAFGnU3jqeHtH9 /EW3156LEIasHd9jMA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMA0GCSqG SIb3DQEBCwUAA4IBAQAYZ9WmExK6sYRvhr/K3Rq/PCivKAmj1DikaqNVJ7xcBqIa wLatT5rx6X117gL5ZGuFxi8linZYZr0BNaPR3xoBIMhxHnClm+egzt3vOtHqWUlZ S/35vHGCpCBr9A7PyXVlyucJdqF5VUM7eNhIj3ihL9UWUe3zQ0GOVQp3fH/NGXd0 kC+uHeCrTIZWKf6KCq2IO6+BbM9JG2EXfnqLcjZ9NelnbkjPsb2wklZkEBZpzfi5 2LMd/FvG/mN//MNUa3YudFDC/b8Qd1Mq+o4QaYcxn3jnz2+lP1bckJNOK1HarMIg vS0999UEWyROHgKRSvLe4aIkq4YgGMu/H2/yWrUO -----END CERTIFICATE----- ================================================ FILE: test/ssl/test-bad-root-ca.key ================================================ -----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCJUl+NGLFN/BJs HxeJ2PXdw+CtIrtuTVBpEcE6BhYocGP0ka9A0BMgWPQ2gzsFJFVucNnxv2RKuVKA vWlB+Oan4KP2jBw7iZlL9oKycgvwtfpXWhp2Fc7/hvr42FXnJbxfsoBDu1A4RfPe Wx7cu+1CzrbxesLMILnaYPkOZ4ro0KvaE3PjzjOEeLCE3Y74RcakY4ymEuwHshGF 8ubZKapoewS7ZnpnsqIV36SrEJCsxPpPexolZ/u06BtOzx+9RWeZnzIy5Qw0olDe zpVXjLPMTmhiXE7Z3kpgapmb6vcDzWLfZ4W7jxejTJQZoJlllurfkAq11gOW7A0U C2I+osHbAgMBAAECggEADCqwbQFUErNgmnqcWX1P0DwSEXHM84MfVCZB9x2II9sZ Y0qJIY/0ZRHpYu8SCp/85cUf7X7MqJ/U3IBrunAOiuJ10Vr51JiZ0xSRrefTtDPo Ob1+lk0GXLa3HXDL46gA3n9W3lyfr4ZOV7qKq606FbvYLHsSliClw61Pdv3bkLCf 91d+QycDkogIAOnV8MuGrJm5dQkRzRKF74+57UbV48z5PUiU5NwZOcFzgfhHZ0L/ dhmIQ+Ks7TzDlwq22KpsczJr4tVBpoTIYSShXqVuzmIWz6zZNShT/9rmLHYw/DVS ISmZ45f7teds37VhiMfyfECorFa7fD1Gz45MJW2d4QKBgQC/p6Kl3xFJrFvJIjPg a266aTFRQ+bi/VgtJpEbgOpzLBh8GRCjRo8zRMEffylUo+UkiJVrlwM6hFEjg4o4 a6gPwGs73yymtlNT0c+sYmy5porQr6jieci49zc9UBM9ikyDaaGq4phZ8v6SU+Zt /jH81i0d+in7FOp8+cAkhUWZcQKBgQC3bOqBIuG9JoJ1XjnR6n9EF/qd+64VcwTR 6eluSv7tr+Rckf7Wq0rKaUWCNTcWYubJZI4pDsVb9ZZkwtXBI8Kgou2D32/cDigZ R23h+r3YIzPm6F7lBo/+KJcPMEEMUMd+0ydf7loed19jJcP9i6O+PtvICNfNcLdw unpE+bLKCwKBgQC8fxqYO1ncdPndS5dsLR29l8JapAcMz5GO7rSfMV7locP/IgPc IoSrLv8mhEHZLk0rbm5PYDpbrlHDNReXwEKOI3kUbL6UxRQVh3DSogc/XM6Ay5O2 E4NYcETTN9OEnmX8hcLsuGqRZU3+CyjCm9T8UIYVSrtJaFvsSRMymCVI8QKBgFgG eeetML4QbA0dQgw+SAMKqugELz/16bs/URnv/bVdcu8F1VF59LN8n7HkDeK9ZdoC WsLTZt1B14HVirVcjvt+FRPzN4BYft/ayp3nMhI2mqLWoyuv4YxsOEo+swjQ/1wa w0ujXDZAvVMcfZkA2XzkN58gt0fNLwt3QlQ1rJqPAoGAeIj7uQZkjNqvK8No3ZCw HFJfi2hKRCDq+NMh9XX0MsnCFYNBytZSJ56iU2myD9fyv0QRykZUnFxo2L9n6QG6 /I3CgxE7TQspJUU0tm8OdKBmjqpMCQj+h4LE0FtTJAl6+fUaaXLRWW/zRaeGxHnr +REogjCnh9r72F/2Hu4Efzw= -----END PRIVATE KEY----- ================================================ FILE: test/ssl/test-fake-root-ca.crt ================================================ -----BEGIN CERTIFICATE----- MIID0jCCArqgAwIBAgIUGHRAnoTqm46p11DZWZXfAJzl2AswDQYJKoZIhvcNAQEL BQAwcjELMAkGA1UEBhMCR0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxDjAMBgNVBAcM BURlcmJ5MRowGAYDVQQKDBFNb3NxdWl0dG8gUHJvamVjdDEQMA4GA1UECwwHVGVz dGluZzEQMA4GA1UEAwwHUm9vdCBDQTAeFw0yNTA3MDcyMjI3MjhaFw0zNTA3MDUy MjI3MjhaMHIxCzAJBgNVBAYTAkdCMRMwEQYDVQQIDApEZXJieXNoaXJlMQ4wDAYD VQQHDAVEZXJieTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3QxEDAOBgNVBAsM B1Rlc3RpbmcxEDAOBgNVBAMMB1Jvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IB DwAwggEKAoIBAQDk+oDCU7JtFeX1k2CcsMGLDQhPNkI6hRDQ58qnke/nl19gyQnh SExfyEr4rCxG1wv3aTcckjOunxjjtLe65XDAVoOKpq/vjF0heaYne/7Fl5IYjkOP 3lPj8YYe0sfd6wG39BYx00dJD0JaC1voTICDMVjxW6QYQtDqU8f21QyTrapd0i+c eMjemG5pyV/bojjgXpyVhkfT6HZvOsETp/HAUYAEFK+fst8m49lCGpZWlnSqjG0i VCyktZ+pKgdkus4y5V0ng4beLTClSF/qSmDZ+6MASy+DyJvZX5JTwMVP74Sc+26O TrNUlGnvDDb1e7GHRv+GF0A4H03ppmnU3VU9AgMBAAGjYDBeMB0GA1UdDgQWBBRb bCvlBYBU16FlTHwMHZv0ra+UvjAfBgNVHSMEGDAWgBRbbCvlBYBU16FlTHwMHZv0 ra+UvjAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsF AAOCAQEAozJv0fV7WCpDDa5oxdpm1k67Yqklwged4/V2CuG5S7wIkLGJqzOldFCR 2wtlDIb3N8aTTEgywo1EcqSjIRCWke+Lrzjof8ypeE6G6qgWkIOsh6UEeUuhUjUc mYcvRxwYLgh6c6reAMIi26SOWvRrvse+MgjJMb8C/j0jF3Ymqw9QiwbD9IsXnhe8 olyxUYW4zgzZgF7Ae5dLJrom3q51J9LWGvEp9KhweG9gSbOxmkoD4IKx4JbVoRBs TaoLAc0LepwvFQchA/mR5r/ppB6GUFEHGvSJDmyMDrcZJ6QV5w+rPkarBZJJsbql 2J+MLkMFsrhBq6ajFau4nOVnDPW2GQ== -----END CERTIFICATE----- ================================================ FILE: test/ssl/test-fake-root-ca.key ================================================ -----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDk+oDCU7JtFeX1 k2CcsMGLDQhPNkI6hRDQ58qnke/nl19gyQnhSExfyEr4rCxG1wv3aTcckjOunxjj tLe65XDAVoOKpq/vjF0heaYne/7Fl5IYjkOP3lPj8YYe0sfd6wG39BYx00dJD0Ja C1voTICDMVjxW6QYQtDqU8f21QyTrapd0i+ceMjemG5pyV/bojjgXpyVhkfT6HZv OsETp/HAUYAEFK+fst8m49lCGpZWlnSqjG0iVCyktZ+pKgdkus4y5V0ng4beLTCl SF/qSmDZ+6MASy+DyJvZX5JTwMVP74Sc+26OTrNUlGnvDDb1e7GHRv+GF0A4H03p pmnU3VU9AgMBAAECggEAC4Is3L3nK5HPsO2U2M51E9LDKac9yE760ha5IH32jSQv 1rktmXIp5u1PgCGEyJSzYcTntueapS3fsUYnSKn45kasethqfFA70akzEpLDv27U S9t1BgyaS8xOV0tBx2Ox5Orly+BLs2s+BJeQj+OuC90vLey5gFl1wmlILuqoJKq1 lkzVRJW1nzGH0FxUUnsI5ya4Eckp3+OG1HTNS+QD5zwV5c1kiP75dDuU/Va/9Msl VrV2VX9Rs1l/91T5PLs84AK1JrBtYJCpR/PfyYkBHOa+H2R2M3cINEOWq+UzziAc v6sBK1Pym5ZTVBn8i5Lt8H1ayXP2gkqskKPcRBaycwKBgQD9zvSKnL4Bx05jDNl4 Ev1VBmIIpHQaoZHdQr1WRMdD6TTPp+LkZLWOqsLFSRziAiLUexm4Ny7dRSq9dbGa H8c51OiFw5pGgn3jzpSErDQayXM6fxG1UZ4RYDVxorgMMvdNg3qn1dHPZ2vJG4iM nwJsoVA+eC1WozmWZ5KJYjfFlwKBgQDm9Kk/osllbbOOQj6y3SRd4T5xiPCgztd+ mlQLBvt+I9ZpmPjKogN9PDPCkVNn76RCkWvNSWZUjT/QLOpjo7d6h4muAUN4gNTn rZG0EjsH/1ZFAfHUC5lm/KadrGNz5OLKPVPZ/heQk89Tz9w/EJMoDB/kkFKyW5Sg tEJURO9eSwKBgBJ7E0tUhnFStd54fQ1FNLUQNeszLlESGrDlvyuc7nV/cZz9OIQw 4Rd2T6BV5oh+Z1LZc9H6EquB8c7B1yDF15fabOPwjjc8ITaJQD842sJokL9dqUhu nPfe7YVMt+ILg/5c6H14EELt4OdP3e1/VonaZSFnVsXMNNFC0WS3hiAZAoGAZfU0 kodG6aQYVIEiNMwztc4uRujxccxejeGLoKKge/tOOKfzjWEgsTTWlNqbO5MrrMeO E76HkmQY+8oYX4xy/4C+Yzbjllspom2ZmSlDLjCm4SgOnlHQkwqOc6Ua8prlE+sn DWGC/ayDJrjovl6O2Gsh2UFtgJe1cYyii5kzIykCgYEAk19ynt7Ndw2fhAOLKp0R bS/B7XHotRsQtEQIo0lYHAWZZZqLh3CKsDsz62NbklKu92DKZVopDUQXWX9LvN5P 3jdyV/6PclhiSgrDy3ogPvHoAJCT9iOktdpLQEgyrwcunTuKB/74rDxfH2EmCj4Y 1f13ff3DuEzMffx+X87/g/s= -----END PRIVATE KEY----- ================================================ FILE: test/ssl/test-root-ca.crt ================================================ -----BEGIN CERTIFICATE----- MIID0jCCArqgAwIBAgIUPWZteXB28AsU7emgSEDG3w7zqd8wDQYJKoZIhvcNAQEL BQAwcjELMAkGA1UEBhMCR0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxDjAMBgNVBAcM BURlcmJ5MRowGAYDVQQKDBFNb3NxdWl0dG8gUHJvamVjdDEQMA4GA1UECwwHVGVz dGluZzEQMA4GA1UEAwwHUm9vdCBDQTAeFw0yNTA3MDcyMjI3MjhaFw0zNTA3MDUy MjI3MjhaMHIxCzAJBgNVBAYTAkdCMRMwEQYDVQQIDApEZXJieXNoaXJlMQ4wDAYD VQQHDAVEZXJieTEaMBgGA1UECgwRTW9zcXVpdHRvIFByb2plY3QxEDAOBgNVBAsM B1Rlc3RpbmcxEDAOBgNVBAMMB1Jvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IB DwAwggEKAoIBAQDyRXMUPa/pLzERcaE+/TkYmiH83MfGhJ2eSeEqY+vjuzePT/p3 GDLuM5IcprukEuif+4HbvLQC8zIdNjO+Xwb/Acg7njQfNTV9b8IzOn3r/k4ZcB2G rK7Kae338xAmkTYjACrTUnbUsdRmbRKZZCIk69fxlC4xhCp+7sZyKc4FOkGI4dOe TVkLN3DQflzR7mF78yCgbr2HBXoF2Eazv008YqTDS2gL3JbXIpt2H7Z8fNZHupbk B0gydAxmMSUnwBeXLkVkKFOJNDjjGtY4nDKOpuirEx8K0GYs6Mo0iFTwi4IDxjzM jP5uarn1hx5bAFpuN1r1jbzb0iopZAOhmG2TAgMBAAGjYDBeMB0GA1UdDgQWBBRP Vu26VxJGE8+W4yzBkWRpW5rnBTAfBgNVHSMEGDAWgBRPVu26VxJGE8+W4yzBkWRp W5rnBTAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsF AAOCAQEAjejhP+g9DbB/vgjUJbk5sRgBeq0sX8ghtq1B+LEgKV+l/h9dmsavChjF RWzEhfxK83iMJX8dAXbloYSgmXNSmh/7RfXQEBPbwzD9CyZXWa+HC4Rfv0YGvdua liyXVxHiND4wGiv/GyTOcGJ9P5zjB+svo7rnIHvC6vJyo0hp17AuBSZDWBWt096U QHwJ3DrLY09OpMwfLZaduEzH9Vpf+rkQrTAo0/jSmhCDPBtLx/c+PKptUiOjvsuc DlaKBh7s5OBjGDUUqWDmFhcQCEy4eg0KDaAfCUrjoXFK4yf+TAxVpNBCoUCaGOqk GvK7TZAfHoGSAxTuls/Y0N/StPSojw== -----END CERTIFICATE----- ================================================ FILE: test/ssl/test-root-ca.key ================================================ -----BEGIN PRIVATE KEY----- MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDyRXMUPa/pLzER caE+/TkYmiH83MfGhJ2eSeEqY+vjuzePT/p3GDLuM5IcprukEuif+4HbvLQC8zId NjO+Xwb/Acg7njQfNTV9b8IzOn3r/k4ZcB2GrK7Kae338xAmkTYjACrTUnbUsdRm bRKZZCIk69fxlC4xhCp+7sZyKc4FOkGI4dOeTVkLN3DQflzR7mF78yCgbr2HBXoF 2Eazv008YqTDS2gL3JbXIpt2H7Z8fNZHupbkB0gydAxmMSUnwBeXLkVkKFOJNDjj GtY4nDKOpuirEx8K0GYs6Mo0iFTwi4IDxjzMjP5uarn1hx5bAFpuN1r1jbzb0iop ZAOhmG2TAgMBAAECggEAB1A2DMVemwu+pR0oq0MaRyDX/SRuWhLEw0jNpZRF7vuc I2pcUDNdzjemUHvEAaGZ020p2rKT6Ibjhg2N0FBZYLdIDmyp0XYEuwL1pMro5DKA CbU1tEwK1rdjOe86Fz/zl2jjjLovi3TMHu9p9qbBf8XSy0sYKIx/JT0bUR+Wmte7 +3LrmbftOOAG+9GRr3twjQnadbncLI5getRtbR6vpOrdX/eYvF29k+UT8earGFp8 gohB0wJUvHyPZUDnbqL96BbxZvOG3ZcRdVlft5PdlPkXY9cPSa0KDq4OabmFFwlt cM+/zIIGyxNc9Yh9yDRa5Da8Xtr/JjV1dmYgHteROQKBgQD7PbQj/rBGCmH0+E54 SZGelSCwb/RifeAOOeG1Obms0gbUcadQ/KQiz5jZEaEKQnC1Ews/HSNKmByLQw0+ 2++2lFpxdpg/8JZoTRVggd05gXgkV9PIRMEvAUaiJiHtjdBAUJ74kbWUkZA3lMDI tVRHIcJgMHLtU3CPaiyq9/AbtwKBgQD23EAkFrl2zDiqwEMx0nNF4XbX8BSon3uk JWRPoGWLPq8ybWE6TgFKzCTjx+zsc0wSaI/lLb62dJq47v7jYRxEfSy/4mZ52gQf S2vZ65iQIKKe79oLPLjENi/A0mjM2df3Fx0CB3LJQwSEazKwe8V4B3KeK81idqkp wR/Qcy01BQKBgEtZUxhkfutSm9RDUA1lSwX7haVEvk93nuXFWDroyBXbm27Fcz+n tXY3OokHb3vLN1AnGP1huL7bZdwiTOuoPHlOft1+iuTKO+GmFJ4v9HAVszl7Gan7 bNCzGkLxGsXK/UT8qOC1mnanPVBeDX9kWpVGu6vre9xPZPeuCR1xZJJ7AoGAc+Iu 5gIY7DCwRU/d+0xsupg9vt7AA+xiEUtQTKTiJjy157k7FDC8II22n4shqFnzkwys yAvyZBpW64ud8cWLjIcqc6VnL7pthvdT2MflJXt8e5nixLWrkshRIHZlpgx5ek/K WUJ/2wTv4O2lrP1dVJxCbQfo8Vj8zlIPij4XMbUCgYAYJIeMgZcxF6kR3GpIbKBh z7lOPy4dSc/vfY9Kr/hn+0Y7wQb0qmRQxD50fsg39jpAVeqdgWppoaSUYX0vRr/w 3od2/VydT2/pcJk6Qcm7lCsnwPgvL1pD0wYO+DlNYGVaXWGKhW4CvxQFnTTMM2ZS 7Kgofn95IuQH3FOWYSMg6Q== -----END PRIVATE KEY----- ================================================ FILE: test/ssl/test-signing-ca.crt ================================================ Certificate: 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: Jul 7 22:27:28 2025 GMT Not After : Jul 6 22:27:28 2030 GMT Subject: C=GB, ST=Derbyshire, O=Mosquitto Project, OU=Testing, CN=Signing CA Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: 00:b8:5b:81:cb:99:5e:85:66:42:fe:c4:f4:c6:ad: f9:9a:b4:c5:29:bb:05:5b:90:b2:a0:7d:ba:00:a3: f3:ec:8f:81:c4:45:98:79:6c:3e:04:77:26:dd:d9: 9f:57:6a:dc:56:25:ba:60:c9:7d:cc:fe:40:e1:e9: 75:02:a7:56:0e:bb:a8:a5:d1:b4:b1:57:62:d1:07: 67:23:77:ae:3e:41:ba:22:6f:b8:f3:3d:ac:5f:1f: 93:cb:62:33:93:61:0b:b1:33:be:ee:67:bb:b1:4b: 2a:3e:c3:99:e9:ea:51:ca:79:ac:91:ce:e6:ee:99: 86:85:f0:a4:11:91:2b:ef:9f:cf:6d:8c:8f:0a:f8: 69:5f:42:c5:ee:90:ca:fe:da:6f:c6:20:56:9d:ac: eb:b0:64:ab:a5:fc:9d:c2:db:ac:a9:a7:40:e1:60: 00:9f:87:f3:51:9f:64:7e:f8:4a:8e:7f:aa:95:f3: 4f:04:b0:ea:ee:77:0b:3e:27:bf:9a:b4:62:1f:76: 6d:a4:be:eb:e2:c3:c6:be:87:6d:f3:fb:ec:a0:09: 41:ef:8d:35:90:3f:fb:88:f8:fe:e2:25:cd:ff:c2: 72:13:d0:bd:fe:40:5e:9d:80:9f:7c:b0:ea:54:bd: 69:70:1f:cf:2f:c3:97:40:ee:ef:97:d6:c6:1d:16: 6b:01 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Subject Key Identifier: C8:63:DE:29:66:24:95:5D:B2:37:6D:F6:A2:01:85:AE:31:0F:8E:45 X509v3 Authority Key Identifier: 4F:56:ED:BA:57:12:46:13:CF:96:E3:2C:C1:91:64:69:5B:9A:E7:05 X509v3 Basic Constraints: critical CA:TRUE X509v3 Key Usage: Certificate Sign, CRL Sign Signature Algorithm: sha256WithRSAEncryption Signature Value: 07:ba:ab:2e:42:0c:ac:98:05:af:a0:49:44:db:36:4f:a1:15: 40:ec:4d:46:ca:ae:f0:ad:aa:1c:d0:99:11:6c:32:ce:62:b5: 3d:71:ab:1d:ed:cb:3e:3a:38:de:20:25:6f:02:fd:1f:b9:d7: 8d:5f:d1:d4:46:ea:a7:c5:fa:70:fc:aa:0f:63:a3:bb:dc:93: 6b:9d:1c:9c:64:f4:3f:ac:09:60:b7:d5:3d:b2:c5:df:58:44: 24:a4:bf:a9:d2:c3:0c:9d:f0:06:b1:20:f6:7d:1b:55:c4:f8: 96:84:1d:b1:b9:3d:06:16:ab:fd:cf:97:1d:ff:6d:e2:6d:fe: da:36:7e:4c:d6:f8:1c:df:b7:79:58:ce:ea:c4:50:3a:14:86: f8:55:21:77:90:ec:bf:af:82:29:c8:a7:5c:91:b9:33:e0:ee: 8a:6c:80:f1:e1:a5:55:26:a1:46:bb:d1:eb:59:d1:1c:90:a4: 19:54:e7:68:0c:b6:c7:9e:b0:d0:e3:12:24:a4:92:96:1c:bd: 82:cc:1f:3d:f4:a6:de:69:77:83:25:3a:02:ee:64:38:f7:ae: ef:06:09:06:3d:c2:19:0f:54:06:d3:e4:0c:e2:bd:be:e3:1c: ac:a7:e0:c2:50:37:b4:8b:4b:0f:58:71:24:00:6b:7a:71:1e: 7b:f5:a2:71 -----BEGIN CERTIFICATE----- MIIDsjCCApqgAwIBAgIBATANBgkqhkiG9w0BAQsFADByMQswCQYDVQQGEwJHQjET MBEGA1UECAwKRGVyYnlzaGlyZTEOMAwGA1UEBwwFRGVyYnkxGjAYBgNVBAoMEU1v c3F1aXR0byBQcm9qZWN0MRAwDgYDVQQLDAdUZXN0aW5nMRAwDgYDVQQDDAdSb290 IENBMB4XDTI1MDcwNzIyMjcyOFoXDTMwMDcwNjIyMjcyOFowZTELMAkGA1UEBhMC R0IxEzARBgNVBAgMCkRlcmJ5c2hpcmUxGjAYBgNVBAoMEU1vc3F1aXR0byBQcm9q ZWN0MRAwDgYDVQQLDAdUZXN0aW5nMRMwEQYDVQQDDApTaWduaW5nIENBMIIBIjAN BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuFuBy5lehWZC/sT0xq35mrTFKbsF W5CyoH26AKPz7I+BxEWYeWw+BHcm3dmfV2rcViW6YMl9zP5A4el1AqdWDruopdG0 sVdi0QdnI3euPkG6Im+48z2sXx+Ty2Izk2ELsTO+7me7sUsqPsOZ6epRynmskc7m 7pmGhfCkEZEr75/PbYyPCvhpX0LF7pDK/tpvxiBWnazrsGSrpfydwtusqadA4WAA n4fzUZ9kfvhKjn+qlfNPBLDq7ncLPie/mrRiH3ZtpL7r4sPGvodt8/vsoAlB7401 kD/7iPj+4iXN/8JyE9C9/kBenYCffLDqVL1pcB/PL8OXQO7vl9bGHRZrAQIDAQAB o2AwXjAdBgNVHQ4EFgQUyGPeKWYklV2yN232ogGFrjEPjkUwHwYDVR0jBBgwFoAU T1btulcSRhPPluMswZFkaVua5wUwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMC AQYwDQYJKoZIhvcNAQELBQADggEBAAe6qy5CDKyYBa+gSUTbNk+hFUDsTUbKrvCt qhzQmRFsMs5itT1xqx3tyz46ON4gJW8C/R+5141f0dRG6qfF+nD8qg9jo7vck2ud HJxk9D+sCWC31T2yxd9YRCSkv6nSwwyd8AaxIPZ9G1XE+JaEHbG5PQYWq/3Plx3/ beJt/to2fkzW+Bzft3lYzurEUDoUhvhVIXeQ7L+vginIp1yRuTPg7opsgPHhpVUm oUa70etZ0RyQpBlU52gMtseesNDjEiSkkpYcvYLMHz30pt5pd4MlOgLuZDj3ru8G CQY9whkPVAbT5Azivb7jHKyn4MJQN7SLSw9YcSQAa3pxHnv1onE= -----END CERTIFICATE----- ================================================ FILE: test/ssl/test-signing-ca.key ================================================ -----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC4W4HLmV6FZkL+ xPTGrfmatMUpuwVbkLKgfboAo/Psj4HERZh5bD4Edybd2Z9XatxWJbpgyX3M/kDh 6XUCp1YOu6il0bSxV2LRB2cjd64+Qboib7jzPaxfH5PLYjOTYQuxM77uZ7uxSyo+ w5np6lHKeayRzubumYaF8KQRkSvvn89tjI8K+GlfQsXukMr+2m/GIFadrOuwZKul /J3C26ypp0DhYACfh/NRn2R++EqOf6qV808EsOrudws+J7+atGIfdm2kvuviw8a+ h23z++ygCUHvjTWQP/uI+P7iJc3/wnIT0L3+QF6dgJ98sOpUvWlwH88vw5dA7u+X 1sYdFmsBAgMBAAECggEACT7eYgfb7SqLo2JDElaCq5PZ3w9kvX3viP8oXZFBxOd0 VXo8cAgR9I0szLh19l9C4JEkAs5oE2h23lckCdEhjqIyDlE97VAZtRKL3upihl3E 4dnV6sdfhllVKXO2n9mglmKNdnOLJRReo7PEjse0RWHxWevVIG2Top9gYwvzdtQ1 A6B7QYclU0J4r1st7XxvaJFJZPaobXkWUZNnzZnui0EIiULDWVgOCq5qaSaKqc6s EdTxG+/jWYBU3DA+/Sz2ZvQvbj1+j1OXJgRedIRW+r8LH2SF9ZQCGxY1Vw9hdfUD 1yTf5nRjdbkh2wt23G1bbLGuhHVUTWylOez6qt+AZwKBgQD6P9vCjOoAFrPA31P7 GOjLtIjrROZ+puRLh00JGZXxW/0A+vgNZuox9mfHlGaJWgg0zIoX9HPuXy3/6ogL QN9QDuX7EONoVcjfWysCQatIGS2kxkPrv0ZEX9dnJ33lA+rc8ByFEib1lsM9PQGK W3BlABIZRcJsXyF+XyTYK0+8MwKBgQC8mAakcNiX2G/OTwgu7SLSI+daSPebLTJ4 iomuZTuoMLsVE6T501389mRyZiEkBw3f6UBb2DZf8KIhMk9Y9Ba7uQRpMpo8Cd9N PHAs+Rv9UnWunw9HpKCqWyKiYwtBunKlQg5yQSvWe9j3VtUSszzX6XetuYm4DYqn 3QK7la6H+wKBgH5LiipGmbYPvwpA645XBO4Bn/Q0oqsaqS7hCuTjz8OurCI5hsSk wt8SP0//Ojxpfqi+7ZanXXbY/Esi3yPmyo0J59FstYgreyQWS79oyvupEVsOYKry rpDFWd2KlcPl1TtJxur1vUnGm6QlTMi52yBuB7RPe47b9/hiJiMewK/3AoGAJUHX VhchAuZ0OAqu8C5SybbkFpcBq3tDVELyLiy7m199Jg3KcrxJ/hZjA6Kfe3GVUR3Q ZBSTsWJldS9uM4GNGCrV7z5a7+93WNfOxWO1HtdyfjvYFew0/VKhxfjRGXwO+AzT s8iiM24mD77suxQDuhfaV8ymo2CxerYTuyE36I8CgYEAgXAAjUxGLPG11KvgzyOI HXBzg1/84vURHE6VsxcPWq6mw887qpmqkf6FJ9cU/J4r4PU3aGc1b8Ts0dGW2O+H DwEOE6ZeXinPO4mMif3eOt80zc4REF00cJjTNgE4bDPubhFFMXN6kLi9GO6pkdlc 9c8/rdrxzTv16tvuveO28G4= -----END PRIVATE KEY----- ================================================ FILE: test/unit/CMakeLists.txt ================================================ find_package(CUnit REQUIRED) add_library(common-unit-test-header INTERFACE) target_include_directories(common-unit-test-header INTERFACE "${mosquitto_SOURCE_DIR}/include" "${mosquitto_SOURCE_DIR}/common" "${mosquitto_SOURCE_DIR}/deps" "${mosquitto_SOURCE_DIR}/lib" "${mosquitto_SOURCE_DIR}/src" "${mosquitto_SOURCE_DIR}/test" ) target_link_libraries(common-unit-test-header INTERFACE common-options cJSON CUnit::CUnit ) add_subdirectory(libcommon) add_subdirectory(broker) add_subdirectory(lib) ================================================ FILE: test/unit/Makefile ================================================ R=../.. include ${R}/config.mk .PHONY: all check test test-compile ptest clean all : test-compile: $(MAKE) -C libcommon $@ $(MAKE) -C broker $@ $(MAKE) -C lib $@ check : test ptest : test test : test-compile $(MAKE) -C libcommon $@ $(MAKE) -C broker $@ $(MAKE) -C lib $@ reallyclean : clean clean : $(MAKE) -C libcommon $@ $(MAKE) -C broker $@ $(MAKE) -C lib $@ ================================================ FILE: test/unit/broker/CMakeLists.txt ================================================ # bridge-topic-test add_library(bridge-topic-obj OBJECT ../../../src/bridge_topic.c ) target_compile_definitions(bridge-topic-obj PRIVATE WITH_BRIDGE WITH_BROKER) target_include_directories(bridge-topic-obj PRIVATE ${mosquitto_SOURCE_DIR}/libcommon) target_link_libraries(bridge-topic-obj PUBLIC common-unit-test-header) add_executable(bridge-topic-test bridge_topic_test.c stubs.c ) target_compile_definitions(bridge-topic-test PRIVATE WITH_BRIDGE WITH_BROKER) target_link_libraries(bridge-topic-test PRIVATE bridge-topic-obj common-unit-test-header libmosquitto_common OpenSSL::SSL) add_test(NAME unit-bridge-topic-test COMMAND bridge-topic-test) # keepalive-test add_executable(keepalive-test keepalive_test.c keepalive_stubs.c ) target_compile_definitions(keepalive-test PRIVATE WITH_BROKER) target_link_libraries(keepalive-test PRIVATE common-unit-test-header libmosquitto_common OpenSSL::SSL) add_test(NAME unit-keepalive-test COMMAND keepalive-test) # persist-read-test add_library(persistence-read-obj OBJECT ../../../src/database.c ../../../src/persist_read_v234.c ../../../src/persist_read_v5.c ../../../src/persist_read.c ../../../src/retain.c ../../../src/topic_tok.c ) target_compile_definitions(persistence-read-obj PRIVATE WITH_PERSISTENCE WITH_BROKER) target_link_libraries(persistence-read-obj PUBLIC common-unit-test-header OpenSSL::SSL) add_executable(persist-read-test persist_read_test.c persist_read_stubs.c ../../../lib/packet_datatypes.c ../../../lib/property_mosq.c ../../../lib/util_mosq.c ) target_compile_definitions(persist-read-test PRIVATE TEST_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}" WITH_PERSISTENCE WITH_BROKER) target_include_directories(persist-read-test PRIVATE ${mosquitto_SOURCE_DIR}/libcommon) target_link_libraries(persist-read-test PRIVATE persistence-read-obj libmosquitto_common) add_test(NAME unit-persist-read-test COMMAND persist-read-test) # persist-write-test add_library(persistence-write-obj OBJECT ../../../src/database.c ../../../src/persist_read_v234.c ../../../src/persist_read_v5.c ../../../src/persist_read.c ../../../src/persist_write_v5.c ../../../src/persist_write.c ../../../src/retain.c ../../../src/subs.c ../../../src/topic_tok.c ) target_compile_definitions(persistence-write-obj PRIVATE WITH_PERSISTENCE WITH_BROKER) target_include_directories(persistence-write-obj PRIVATE ${mosquitto_SOURCE_DIR}/libcommon) target_link_libraries(persistence-write-obj PUBLIC common-unit-test-header) add_executable(persist-write-test persist_write_test.c persist_write_stubs.c ../../../lib/packet_datatypes.c ../../../lib/property_mosq.c ../../../lib/util_mosq.c ../../../lib/packet_mosq.c ) target_compile_definitions(persist-write-test PRIVATE TEST_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}" WITH_PERSISTENCE WITH_BROKER WITH_SYS_TREE) target_include_directories(persist-write-test PRIVATE ${mosquitto_SOURCE_DIR}/libcommon) target_link_libraries(persist-write-test PRIVATE persistence-write-obj OpenSSL::SSL libmosquitto_common) add_test(NAME unit-persist-write-test COMMAND persist-write-test) # subs-test add_library(subs-obj OBJECT ../../../lib/property_mosq.c ../../../lib/packet_datatypes.c ../../../src/database.c ../../../src/subs.c ../../../src/topic_tok.c ) target_compile_definitions(subs-obj PRIVATE WITH_BROKER) target_include_directories(subs-obj PRIVATE ${mosquitto_SOURCE_DIR}/libcommon) target_link_libraries(subs-obj PUBLIC common-unit-test-header) add_executable(subs-test subs_stubs.c subs_test.c ) target_compile_definitions(subs-test PRIVATE WITH_PERSISTENCE WITH_BROKER WITH_SYS_TREE) target_link_libraries(subs-test PRIVATE common-unit-test-header subs-obj libmosquitto_common OpenSSL::SSL) add_test(NAME unit-subs-test COMMAND subs-test) ================================================ FILE: test/unit/broker/Makefile ================================================ R=../../.. include ${R}/config.mk include ${R}/make/broker.mk include ${R}/make/unit-test.mk .PHONY: all check test test-compile clean coverage LOCAL_CFLAGS+=-coverage -ggdb LOCAL_CPPFLAGS+=-DWITH_BROKER -I${R}/src -I${R}/test -I${R}/lib -DTEST_SOURCE_DIR='"$(realpath .)"' -I${R}/lib -I${R}/libcommon LOCAL_LDFLAGS+=-coverage LOCAL_LDADD+=-lcunit ${LIBMOSQ_COMMON} ALL_TESTS:=keepalive_test subs_test ifeq ($(WITH_BRIDGE),yes) ALL_TESTS+=bridge_topic_test endif ifeq ($(WITH_PERSISTENCE),yes) ALL_TESTS+=persist_read_test persist_write_test endif ifeq ($(WITH_TLS),yes) LOCAL_LDADD+=-lssl -lcrypto endif BRIDGE_TOPIC_TEST_OBJS = \ bridge_topic_test.o \ stubs.o \ BRIDGE_TOPIC_OBJS = \ ${R}/src/bridge_topic.o \ ${R}/src/packet_datatypes.o \ ${R}/src/property_mosq.o KEEPALIVE_TEST_OBJS = \ keepalive_stubs.o \ keepalive_test.o KEEPALIVE_OBJS = PERSIST_READ_TEST_OBJS = \ persist_read_test.o \ persist_read_stubs.o PERSIST_READ_OBJS = \ ${R}/src/database.o \ ${R}/src/packet_datatypes.o \ ${R}/src/persist_read.o \ ${R}/src/persist_read_v234.o \ ${R}/src/persist_read_v5.o \ ${R}/src/property_mosq.o \ ${R}/src/retain.o \ ${R}/src/topic_tok.o \ ${R}/src/util_mosq.o PERSIST_WRITE_TEST_OBJS = \ persist_write_test.o \ persist_write_stubs.o PERSIST_WRITE_OBJS = \ ${R}/src/database.o \ ${R}/src/packet_datatypes.o \ ${R}/src/packet_mosq.o \ ${R}/src/persist_read.o \ ${R}/src/persist_read_v234.o \ ${R}/src/persist_read_v5.o \ ${R}/src/persist_write.o \ ${R}/src/persist_write_v5.o \ ${R}/src/property_mosq.o \ ${R}/src/retain.o \ ${R}/src/subs.o \ ${R}/src/topic_tok.o \ ${R}/src/util_mosq.o SUBS_TEST_OBJS = \ subs_test.o \ subs_stubs.o SUBS_OBJS = \ ${R}/src/database.o \ ${R}/src/packet_datatypes.o \ ${R}/src/property_mosq.o \ ${R}/src/subs.o \ ${R}/src/topic_tok.o all : test-compile check : test bridge_topic_test : ${BRIDGE_TOPIC_TEST_OBJS} ${BRIDGE_TOPIC_OBJS} $(CROSS_COMPILE)$(CC) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LDADD) keepalive_test : ${KEEPALIVE_TEST_OBJS} ${KEEPALIVE_OBJS} $(CROSS_COMPILE)$(CC) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LDADD) persist_read_test : ${PERSIST_READ_TEST_OBJS} ${PERSIST_READ_OBJS} $(CROSS_COMPILE)$(CC) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LDADD) persist_write_test : ${PERSIST_WRITE_TEST_OBJS} ${PERSIST_WRITE_OBJS} $(CROSS_COMPILE)$(CC) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LDADD) subs_test : ${SUBS_TEST_OBJS} ${SUBS_OBJS} $(CROSS_COMPILE)$(CC) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LDADD) ${BRIDGE_TOPIC_TEST_OBJS} : %.o: %.c ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ ${KEEPALIVE_TEST_OBJS} : %.o: %.c ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ ${PERSIST_READ_TEST_OBJS} : %.o: %.c ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ ${PERSIST_WRITE_TEST_OBJS} : %.o: %.c ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ ${SUBS_TEST_OBJS} : %.o: %.c ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ ${R}/src/bridge_topic.o : ${R}/src/bridge_topic.c $(MAKE) -C ${R}/src/ bridge_topic.o ${R}/src/database.o : ${R}/src/database.c $(MAKE) -C ${R}/src/ database.o ${R}/src/packet_datatypes.o : ${R}/lib/packet_datatypes.c $(MAKE) -C ${R}/src/ packet_datatypes.o ${R}/src/packet_mosq.o : ${R}/lib/packet_mosq.c $(MAKE) -C ${R}/src/ packet_mosq.o ${R}/src/persist_read.o : ${R}/src/persist_read.c $(MAKE) -C ${R}/src/ persist_read.o ${R}/src/persist_read_v234.o : ${R}/src/persist_read_v234.c $(MAKE) -C ${R}/src/ persist_read_v234.o ${R}/src/persist_read_v5.o : ${R}/src/persist_read_v5.c $(MAKE) -C ${R}/src/ persist_read_v5.o ${R}/src/persist_write.o : ${R}/src/persist_write.c $(MAKE) -C ${R}/src/ persist_write.o ${R}/src/persist_write_v5.o : ${R}/src/persist_write_v5.c $(MAKE) -C ${R}/src/ persist_write_v5.o ${R}/src/property_mosq.o : ${R}/lib/property_mosq.c $(MAKE) -C ${R}/src/ property_mosq.o ${R}/src/retain.o : ${R}/src/retain.c $(MAKE) -C ${R}/src/ retain.o ${R}/src/subs.o : ${R}/src/subs.c $(MAKE) -C ${R}/src/ subs.o ${R}/src/topic_tok.o : ${R}/src/topic_tok.c $(MAKE) -C ${R}/src/ topic_tok.o ${R}/src/util_mosq.o : ${R}/lib/util_mosq.c $(MAKE) -C ${R}/src/ util_mosq.o build : ${ALL_TESTS} test : build set -e; for t in ${ALL_TESTS}; do ${SANITIZER_COMMAND} ./$${t}; done test-compile: build clean : -rm -rf ${ALL_TESTS} -rm -rf *.o *.gcda *.gcno coverage.info *.vglog out/ coverage : lcov --capture --directory . --output-file coverage.info genhtml coverage.info --output-directory out ================================================ FILE: test/unit/broker/bridge_topic_test.c ================================================ #include "config.h" #include #include #include #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(map_topic){ CU_ASSERT_STRING_EQUAL(map_topic, expected); free(map_topic); } bridge__cleanup_topics(&bridge); } 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); bridge__cleanup_topics(&bridge); } 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", "remote", "local"); } 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; } ================================================ FILE: test/unit/broker/files/persist_read/corrupt-header-long.test-db ================================================ corruptcorruptcorruptcorruptcorruptcorrupt ================================================ FILE: test/unit/broker/files/persist_read/corrupt-header-short.test-db ================================================ corrupt ================================================ FILE: test/unit/broker/files/persist_read/empty.test-db ================================================ ================================================ FILE: test/unit/broker/keepalive_stubs.c ================================================ #include #include #include #include #include int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { UNUSED(mosq); UNUSED(priority); UNUSED(fmt); return 0; } bool net__is_connected(struct mosquitto *mosq) { UNUSED(mosq); return true; } void loop__update_next_event(time_t new_ms) { UNUSED(new_ms); } ================================================ FILE: test/unit/broker/keepalive_test.c ================================================ /* Tests for keepalive add/remove/update. */ #include #include #include "keepalive.c" #include "mosquitto_internal.h" #include "mosquitto_broker_internal.h" struct mosquitto_db db; void do_disconnect(struct mosquitto *context, int reason) { UNUSED(reason); #ifndef WITH_OLD_KEEPALIVE keepalive__remove(context); #else UNUSED(context); #endif } #ifndef WITH_OLD_KEEPALIVE static void TEST_single_client(void) { struct mosquitto context; int rc; memset(&db, 0, sizeof(db)); memset(&context, 0, sizeof(context)); db.now_s = 1000; db.config = calloc(1, sizeof(struct mosquitto__config)); CU_ASSERT_PTR_NOT_NULL(db.config); if(db.config == NULL){ return; } db.config->max_keepalive = 2000; context.id = strdup("clientid1"); context.keepalive = 60; context.last_msg_in = db.now_s; rc = keepalive__init(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ free(context.id); return; } CU_ASSERT_EQUAL(keepalive_list_max, 3001); CU_ASSERT_PTR_NOT_NULL(keepalive_list); rc = keepalive__add(&context); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(keepalive_list[context.last_msg_in + context.keepalive*3/2]); keepalive__check(); CU_ASSERT_PTR_NOT_NULL(keepalive_list[context.last_msg_in + context.keepalive*3/2]); /* Should be just before the client expires */ db.now_s = 1090; keepalive__check(); CU_ASSERT_PTR_NOT_NULL(keepalive_list[context.last_msg_in + context.keepalive*3/2]); /* Should be just as the client expires */ db.now_s = 1091; keepalive__check(); CU_ASSERT_PTR_NULL(keepalive_list[context.last_msg_in + context.keepalive*3/2]); keepalive__cleanup(); free(db.config); free(context.id); } static void TEST_single_client_update(void) { struct mosquitto context; int rc; memset(&db, 0, sizeof(db)); memset(&context, 0, sizeof(context)); db.now_s = 1000; db.config = calloc(1, sizeof(struct mosquitto__config)); CU_ASSERT_PTR_NOT_NULL(db.config); if(db.config == NULL){ return; } db.config->max_keepalive = 2000; context.id = strdup("clientid1"); context.keepalive = 60; context.last_msg_in = db.now_s; rc = keepalive__init(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ free(context.id); return; } CU_ASSERT_EQUAL(keepalive_list_max, 3001); CU_ASSERT_PTR_NOT_NULL(keepalive_list); rc = keepalive__add(&context); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(keepalive_list[context.last_msg_in + context.keepalive*3/2]); keepalive__check(); CU_ASSERT_PTR_NOT_NULL(keepalive_list[context.last_msg_in + context.keepalive*3/2]); db.now_s = 1090; keepalive__check(); CU_ASSERT_PTR_NOT_NULL(keepalive_list[context.last_msg_in + context.keepalive*3/2]); /* Receive a new message and do an update */ keepalive__update(&context); CU_ASSERT_PTR_NOT_NULL(keepalive_list[context.last_msg_in + context.keepalive*3/2]); keepalive__cleanup(); free(db.config); free(context.id); } static void TEST_over_max_keepalive(void) { struct mosquitto context; int rc; memset(&db, 0, sizeof(db)); memset(&context, 0, sizeof(context)); db.now_s = 1000; db.config = calloc(1, sizeof(struct mosquitto__config)); CU_ASSERT_PTR_NOT_NULL(db.config); if(db.config == NULL){ return; } db.config->max_keepalive = 2000; context.id = strdup("clientid1"); /* Client keepalive too big. This won't be allowed at connection time, but * may occur if max_keepalive is lowered and the config reloaded only. The * client will end up being expired most likely. */ context.keepalive = 2001; context.last_msg_in = db.now_s; rc = keepalive__init(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ free(context.id); return; } CU_ASSERT_EQUAL(keepalive_list_max, 3001); CU_ASSERT_PTR_NOT_NULL(keepalive_list); rc = keepalive__add(&context); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(keepalive_list[(context.last_msg_in + context.keepalive*3/2) % keepalive_list_max]); keepalive__cleanup(); free(db.config); free(context.id); } static void TEST_100k_random_clients(void) { struct mosquitto *contexts; int rc; const int client_count = 100000; int /*client_total,*/ cur_count; /* This is a very crude test, adding 100k clients with random keepalive and * random last message in. */ srand((unsigned int)time(NULL)); memset(&db, 0, sizeof(db)); contexts = calloc((size_t)client_count, sizeof(struct mosquitto)); db.now_s = 1000; db.config = calloc(1, sizeof(struct mosquitto__config)); if(db.config == NULL){ free(contexts); return; } CU_ASSERT_PTR_NOT_NULL(db.config); db.config->max_keepalive = 0; for(int i=0; i max_keepalive", TEST_over_max_keepalive) || !CU_add_test(test_suite, "100k random clients", TEST_100k_random_clients) ){ printf("Error adding keepalive CUnit tests.\n"); return 1; } return 0; } #endif int main(int argc, char *argv[]) { unsigned int fails = 0; UNUSED(argc); UNUSED(argv); #ifndef WITH_OLD_KEEPALIVE if(CU_initialize_registry() != CUE_SUCCESS){ printf("Error initializing CUnit registry.\n"); return 1; } if(0 || init_keepalive_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(); #endif return (int)fails; } ================================================ FILE: test/unit/broker/persist_read_stubs.c ================================================ #include #include #include #include #include #include #ifndef WITH_SYS_TREE # define WITH_SYS_TREE #endif #include extern char *last_sub; extern int last_qos; extern uint32_t last_identifier; struct mosquitto *context__init(void) { struct mosquitto *m; m = mosquitto_calloc(1, sizeof(struct mosquitto)); if(m){ m->msgs_in.inflight_maximum = 20; m->msgs_out.inflight_maximum = 20; m->msgs_in.inflight_quota = 20; m->msgs_out.inflight_quota = 20; } return m; } int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { UNUSED(mosq); UNUSED(priority); UNUSED(fmt); return 0; } bool net__is_connected(struct mosquitto *mosq) { UNUSED(mosq); return false; } int net__socket_close(struct mosquitto *mosq) { UNUSED(mosq); return MOSQ_ERR_SUCCESS; } int net__socket_shutdown(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, mosquitto_property *properties, int access) { UNUSED(context); UNUSED(topic); UNUSED(payloadlen); UNUSED(payload); UNUSED(qos); UNUSED(retain); UNUSED(properties); 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 struct mosquitto_subscription *sub) { UNUSED(context); last_sub = strdup(sub->topic_filter); last_qos = sub->options & 0x03; last_identifier = sub->identifier; return MOSQ_ERR_SUCCESS; } void callback__on_disconnect(struct mosquitto *mosq, int rc, const mosquitto_property *props) { UNUSED(mosq); UNUSED(rc); UNUSED(props); } void context__add_to_by_id(struct mosquitto *context) { if(context->in_by_id == false){ context->in_by_id = true; HASH_ADD_KEYPTR(hh_id, db.contexts_by_id, context->id, strlen(context->id), context); } } void context__send_will(struct mosquitto *context) { UNUSED(context); } void plugin_persist__handle_retain_msg_set(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_retain_msg_delete(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_base_msg_add(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__process_retain_events(bool force) { UNUSED(force); } void plugin_persist__queue_retain_event(struct mosquitto__base_msg *msg, int event) { UNUSED(msg); UNUSED(event); } int session_expiry__add_from_persistence(struct mosquitto *context, time_t expiry_time) { UNUSED(context); UNUSED(expiry_time); return 0; } void mosquitto_log_printf(int level, const char *fmt, ...) { UNUSED(level); UNUSED(fmt); } struct mosquitto__subhier *sub__add_hier_entry(struct mosquitto__subhier *parent, struct mosquitto__subhier **sibling, const char *topic, uint16_t len) { UNUSED(parent); UNUSED(sibling); UNUSED(topic); UNUSED(len); return NULL; } void plugin_persist__handle_client_msg_add(struct mosquitto *context, const struct mosquitto__client_msg *cmsg) { UNUSED(context); UNUSED(cmsg); } void plugin_persist__handle_client_msg_delete(struct mosquitto *context, const struct mosquitto__client_msg *cmsg) { UNUSED(context); UNUSED(cmsg); } void plugin_persist__handle_client_msg_update(struct mosquitto *context, const struct mosquitto__client_msg *cmsg) { UNUSED(context); UNUSED(cmsg); } void plugin_persist__handle_client_msg_clear(struct mosquitto *context, uint8_t direction) { UNUSED(context); UNUSED(direction); } void plugin_persist__handle_base_msg_delete(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_subscription_delete(struct mosquitto *context, char *sub) { UNUSED(context); UNUSED(sub); } int sub__messages_queue(const char *source_id, const char *topic, uint8_t qos, int retain, struct mosquitto__base_msg **base_msg) { UNUSED(source_id); UNUSED(topic); UNUSED(qos); UNUSED(retain); *base_msg = NULL; return 0; } #ifdef WITH_SYS_TREE void metrics__int_inc(enum mosq_metric_type m, int64_t value) { UNUSED(m); UNUSED(value); } void metrics__int_dec(enum mosq_metric_type m, int64_t value) { UNUSED(m); UNUSED(value); } #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, uint32_t subscription_identifier, 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(subscription_identifier); 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 sub__init(void) { return MOSQ_ERR_SUCCESS; } ================================================ FILE: test/unit/broker/persist_read_test.c ================================================ /* 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 #include "path_helper.h" #include "mosquitto.h" #include "mosquitto_broker_internal.h" #include "persist.h" #include "property_mosq.h" #include "property_common.h" char *last_sub = NULL; int last_qos; uint32_t last_identifier; struct mosquitto_db db; static void dummy_vprintf(const char *fmt, va_list va) { UNUSED(fmt); UNUSED(va); } static void test_cleanup(void) { struct mosquitto *ctxt, *ctxt_tmp; HASH_ITER(hh_id, db.contexts_by_id, ctxt, ctxt_tmp){ HASH_DELETE(hh_id, db.contexts_by_id, ctxt); mosquitto_free(ctxt->username); mosquitto_free(ctxt->id); db__messages_delete(ctxt, true); mosquitto_free(ctxt); } db__close(); } 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); test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/empty.test-db"); config.persistence_filepath = persistence_filepath; rc = persist__restore(); test_cleanup(); 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/corrupt-header-short.test-db"); config.persistence_filepath = persistence_filepath; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_ERRNO); cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/corrupt-header-long.test-db"); config.persistence_filepath = persistence_filepath; 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/unsupported-version.test-db"); config.persistence_filepath = persistence_filepath; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v3-cfg.test-db"); config.persistence_filepath = persistence_filepath; 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v4-cfg.test-db"); config.persistence_filepath = persistence_filepath; 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v3-cfg-truncated.test-db"); config.persistence_filepath = persistence_filepath; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_UNKNOWN); 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v3-cfg-bad-dbid.test-db"); config.persistence_filepath = persistence_filepath; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v3-bad-chunk.test-db"); config.persistence_filepath = persistence_filepath; 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v3-message-store.test-db"); config.persistence_filepath = persistence_filepath; 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->data.store_id, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->data.source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->data.source_mid, 2); CU_ASSERT_EQUAL(db.msg_store->data.qos, 2); CU_ASSERT_EQUAL(db.msg_store->data.retain, 1); CU_ASSERT_PTR_NOT_NULL(db.msg_store->data.topic); if(db.msg_store->data.topic){ CU_ASSERT_STRING_EQUAL(db.msg_store->data.topic, "topic"); } CU_ASSERT_EQUAL(db.msg_store->data.payloadlen, 7); if(db.msg_store->data.payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(db.msg_store->data.payload, "payload", 7); } } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v3-client.test-db"); config.persistence_filepath = persistence_filepath; 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); } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v3-client-message.test-db"); config.persistence_filepath = persistence_filepath; 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->base_msg); if(context->msgs_out.inflight->base_msg){ CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->ref_count, 1); CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->base_msg->data.source_id, "source_id"); CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.source_mid, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.qos, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.retain, 1); CU_ASSERT_PTR_NOT_NULL(context->msgs_out.inflight->base_msg->data.topic); if(context->msgs_out.inflight->base_msg->data.topic){ CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->base_msg->data.topic, "topic"); } CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.payloadlen, 7); if(context->msgs_out.inflight->base_msg->data.payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(context->msgs_out.inflight->base_msg->data.payload, "payload", 7); } } CU_ASSERT_EQUAL(context->msgs_out.inflight->data.mid, 0x73); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.qos, 1); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.retain, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.direction, mosq_md_out); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.state, mosq_ms_wait_for_puback); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.dup, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.subscription_identifier, 0); } } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v3-retain.test-db"); config.persistence_filepath = persistence_filepath; 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->data.store_id, 0x54); CU_ASSERT_STRING_EQUAL(db.msg_store->data.source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->data.source_mid, 2); CU_ASSERT_EQUAL(db.msg_store->data.qos, 2); CU_ASSERT_EQUAL(db.msg_store->data.retain, 1); CU_ASSERT_PTR_NOT_NULL(db.msg_store->data.topic); if(db.msg_store->data.topic){ CU_ASSERT_STRING_EQUAL(db.msg_store->data.topic, "topic"); } CU_ASSERT_EQUAL(db.msg_store->data.payloadlen, 7); if(db.msg_store->data.payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(db.msg_store->data.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"); } } } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v3-sub.test-db"); config.persistence_filepath = persistence_filepath; 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); } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v4-message-store.test-db"); config.persistence_filepath = persistence_filepath; 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->data.store_id, 0xFEDCBA9876543210); CU_ASSERT_STRING_EQUAL(db.msg_store->data.source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->data.source_mid, 0x88); CU_ASSERT_EQUAL(db.msg_store->data.qos, 1); CU_ASSERT_EQUAL(db.msg_store->data.retain, 0); CU_ASSERT_PTR_NOT_NULL(db.msg_store->data.topic); if(db.msg_store->data.topic){ CU_ASSERT_STRING_EQUAL(db.msg_store->data.topic, "topic"); } CU_ASSERT_EQUAL(db.msg_store->data.payloadlen, 7); if(db.msg_store->data.payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(db.msg_store->data.payload, "payload", 7); } } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-cfg.test-db"); config.persistence_filepath = persistence_filepath; 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v5-cfg-truncated.test-db"); config.persistence_filepath = persistence_filepath; 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v5-bad-chunk.test-db"); config.persistence_filepath = persistence_filepath; 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-message-store.test-db"); config.persistence_filepath = persistence_filepath; 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->data.store_id, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->data.source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->data.source_mid, 2); CU_ASSERT_EQUAL(db.msg_store->data.qos, 2); CU_ASSERT_EQUAL(db.msg_store->data.retain, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->data.topic, "topic"); CU_ASSERT_EQUAL(db.msg_store->data.payloadlen, 7); if(db.msg_store->data.payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(db.msg_store->data.payload, "payload", 7); } CU_ASSERT_PTR_NULL(db.msg_store->data.properties); } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-message-store-props.test-db"); config.persistence_filepath = persistence_filepath; 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->data.store_id, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->data.source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->data.source_mid, 2); CU_ASSERT_EQUAL(db.msg_store->data.qos, 2); CU_ASSERT_EQUAL(db.msg_store->data.retain, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->data.topic, "topic"); CU_ASSERT_EQUAL(db.msg_store->data.payloadlen, 7); if(db.msg_store->data.payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(db.msg_store->data.payload, "payload", 7); } CU_ASSERT_PTR_NOT_NULL(db.msg_store->data.properties); if(db.msg_store->data.properties){ CU_ASSERT_EQUAL(db.msg_store->data.properties->identifier, 1); CU_ASSERT_EQUAL(db.msg_store->data.properties->value.i8, 1); } CU_ASSERT_PTR_NOT_NULL(db.msg_store->source_listener); } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v5-client.test-db"); config.persistence_filepath = persistence_filepath; 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); } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-client.test-db"); config.persistence_filepath = persistence_filepath; 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"); } } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-client-message.test-db"); config.persistence_filepath = persistence_filepath; 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->base_msg); if(context->msgs_out.inflight->base_msg){ CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->ref_count, 1); CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->base_msg->data.source_id, "source_id"); CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.source_mid, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.qos, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.retain, 1); CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->base_msg->data.topic, "topic"); CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.payloadlen, 7); if(context->msgs_out.inflight->base_msg->data.payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(context->msgs_out.inflight->base_msg->data.payload, "payload", 7); } } CU_ASSERT_EQUAL(context->msgs_out.inflight->data.mid, 0x73); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.qos, 1); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.retain, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.direction, mosq_md_out); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.state, mosq_ms_wait_for_puback); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.dup, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.subscription_identifier, 0); } } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-client-message-props.test-db"); config.persistence_filepath = persistence_filepath; 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->base_msg); if(context->msgs_out.inflight->base_msg){ CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->ref_count, 1); CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->base_msg->data.source_id, "source_id"); CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.source_mid, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.qos, 2); CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.retain, 1); CU_ASSERT_STRING_EQUAL(context->msgs_out.inflight->base_msg->data.topic, "topic"); CU_ASSERT_EQUAL(context->msgs_out.inflight->base_msg->data.payloadlen, 7); if(context->msgs_out.inflight->base_msg->data.payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(context->msgs_out.inflight->base_msg->data.payload, "payload", 7); } } CU_ASSERT_EQUAL(context->msgs_out.inflight->data.mid, 0x73); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.qos, 1); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.retain, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.direction, mosq_md_out); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.state, mosq_ms_wait_for_puback); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.dup, 0); CU_ASSERT_EQUAL(context->msgs_out.inflight->data.subscription_identifier, 1); } } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-retain.test-db"); config.persistence_filepath = persistence_filepath; 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->data.store_id, 0x54); CU_ASSERT_STRING_EQUAL(db.msg_store->data.source_id, "source_id"); CU_ASSERT_EQUAL(db.msg_store->data.source_mid, 2); CU_ASSERT_EQUAL(db.msg_store->data.qos, 2); CU_ASSERT_EQUAL(db.msg_store->data.retain, 1); CU_ASSERT_STRING_EQUAL(db.msg_store->data.topic, "topic"); CU_ASSERT_EQUAL(db.msg_store->data.payloadlen, 7); if(db.msg_store->data.payloadlen == 7){ CU_ASSERT_NSTRING_EQUAL(db.msg_store->data.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"); } } } test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-sub.test-db"); config.persistence_filepath = persistence_filepath; 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_cleanup(); } static void TEST_v6_base_msg_topic_0(void) { struct mosquitto__config config; 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-base-msg-topic-0.test-db"); config.persistence_filepath = persistence_filepath; rc = persist__restore(); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); test_cleanup(); } /* ======================================================================== * 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) || !CU_add_test(test_suite, "v6 base msg topic 0", TEST_v6_base_msg_topic_0) ){ printf("Error adding persist CUnit tests.\n"); return 1; } return 0; } int main(int argc, char *argv[]) { unsigned int fails; UNUSED(argc); UNUSED(argv); libcommon_vprintf = dummy_vprintf; 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; } ================================================ FILE: test/unit/broker/persist_write_stubs.c ================================================ #include #include #include #include #include #include #include extern uint64_t last_retained; extern char *last_sub; extern int last_qos; struct mosquitto *context__init(void) { 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; } bool net__is_connected(struct mosquitto *mosq) { UNUSED(mosq); return false; } int net__socket_close(struct mosquitto *mosq) { UNUSED(mosq); return MOSQ_ERR_SUCCESS; } int net__socket_shutdown(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, mosquitto_property *properties, int access) { UNUSED(context); UNUSED(topic); UNUSED(payloadlen); UNUSED(payload); UNUSED(qos); UNUSED(retain); UNUSED(properties); 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, uint32_t subscription_identifier, 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(subscription_identifier); 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; } void callback__on_disconnect(struct mosquitto *mosq, int rc, const mosquitto_property *props) { UNUSED(mosq); UNUSED(rc); UNUSED(props); } void callback__on_publish(struct mosquitto *mosq, int mid, int reason_code, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(mid); UNUSED(reason_code); UNUSED(properties); } void do_client_disconnect(struct mosquitto *mosq, int reason_code, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(reason_code); UNUSED(properties); } int handle__packet(struct mosquitto *context) { UNUSED(context); return MOSQ_ERR_SUCCESS; } ssize_t net__read(struct mosquitto *mosq, void *buf, size_t count) { UNUSED(mosq); UNUSED(buf); UNUSED(count); return 1; } ssize_t net__write(struct mosquitto *mosq, const void *buf, size_t count) { UNUSED(mosq); UNUSED(buf); UNUSED(count); return 1; } void context__add_to_by_id(struct mosquitto *context) { if(context->in_by_id == false){ context->in_by_id = true; HASH_ADD_KEYPTR(hh_id, db.contexts_by_id, context->id, strlen(context->id), context); } } void context__send_will(struct mosquitto *context) { UNUSED(context); } void plugin_persist__handle_client_msg_add(struct mosquitto *context, const struct mosquitto__client_msg *cmsg) { UNUSED(context); UNUSED(cmsg); } void plugin_persist__handle_client_msg_delete(struct mosquitto *context, const struct mosquitto__client_msg *cmsg) { UNUSED(context); UNUSED(cmsg); } void plugin_persist__handle_client_msg_update(struct mosquitto *context, const struct mosquitto__client_msg *cmsg) { UNUSED(context); UNUSED(cmsg); } void plugin_persist__handle_client_msg_clear(struct mosquitto *context, uint8_t direction) { UNUSED(context); UNUSED(direction); } void plugin_persist__handle_base_msg_add(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_base_msg_delete(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_retain_msg_set(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_retain_msg_delete(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_subscription_delete(struct mosquitto *context, char *sub) { UNUSED(context); UNUSED(sub); } void plugin_persist__process_retain_events(bool force) { UNUSED(force); } void plugin_persist__queue_retain_event(struct mosquitto__base_msg *msg, int event) { UNUSED(msg); UNUSED(event); } int session_expiry__add_from_persistence(struct mosquitto *context, time_t expiry_time) { UNUSED(context); UNUSED(expiry_time); return 0; } void mosquitto_log_printf(int level, const char *fmt, ...) { UNUSED(level); UNUSED(fmt); } int keepalive__update(struct mosquitto *context) { UNUSED(context); return 0; } int mux__add_out(struct mosquitto *context) { UNUSED(context); return 0; } int mux__remove_out(struct mosquitto *context) { UNUSED(context); return 0; } ssize_t net__read_ws(struct mosquitto *mosq, void *buf, size_t count) { UNUSED(mosq); UNUSED(buf); UNUSED(count); return 0; } void ws__prepare_packet(struct mosquitto *mosq, struct mosquitto__packet *packet) { UNUSED(mosq); UNUSED(packet); } int send__disconnect(struct mosquitto *mosq, uint8_t reason_code, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(reason_code); UNUSED(properties); return 0; } #ifdef WITH_SYS_TREE void metrics__int_inc(enum mosq_metric_type m, int64_t value) { UNUSED(m); UNUSED(value); } void metrics__int_dec(enum mosq_metric_type m, int64_t value) { UNUSED(m); UNUSED(value); } #endif ================================================ FILE: test/unit/broker/persist_write_test.c ================================================ /* 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 #include "path_helper.h" #include "mosquitto_broker_internal.h" #include "persist.h" uint64_t last_retained; char *last_sub = NULL; int last_qos; struct mosquitto_db db; static void dummy_vprintf(const char *fmt, va_list va) { UNUSED(fmt); UNUSED(va); } static void test_cleanup(void) { struct mosquitto *ctxt, *ctxt_tmp; HASH_ITER(hh_id, db.contexts_by_id, ctxt, ctxt_tmp){ HASH_DELETE(hh_id, db.contexts_by_id, ctxt); mosquitto_free(ctxt->username); mosquitto_free(ctxt->id); db__messages_delete(ctxt, true); sub__clean_session(ctxt); mosquitto_free(ctxt); } db__close(); } /* read entire file into memory */ static int file_read(const char *filename, uint8_t **data, size_t *len) { FILE *fptr; size_t rc; long llen; fptr = fopen(filename, "rb"); if(!fptr){ return 1; } fseek(fptr, 0, SEEK_END); llen = ftell(fptr); if(llen < 0){ fclose(fptr); return 1; } *len = (size_t)llen; *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); test_cleanup(); } 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); char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_write/empty.test-db"); CU_ASSERT_EQUAL(0, file_diff(persistence_filepath, "empty.db")); unlink("empty.db"); test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-cfg.test-db"); config.persistence_filepath = persistence_filepath; 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(persistence_filepath, "v6-cfg.db")); unlink("v6-cfg.db"); test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-message-store.test-db"); config.persistence_filepath = persistence_filepath; 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); char persistence_filepath_no_ref[4096]; cat_sourcedir_with_relpath(persistence_filepath_no_ref, "/files/persist_write/v6-message-store-no-ref.test-db"); CU_ASSERT_EQUAL(0, file_diff(persistence_filepath_no_ref, "v6-message-store-no-ref.db")); unlink("v6-message-store-no-ref.db"); test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-message-store-props.test-db"); config.persistence_filepath = persistence_filepath; 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(persistence_filepath, "v6-message-store-props.db")); unlink("v6-message-store-props.db"); test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-client.test-db"); config.persistence_filepath = persistence_filepath; 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(persistence_filepath, "v6-client.db")); unlink("v6-client.db"); test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-client-message.test-db"); config.persistence_filepath = persistence_filepath; 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(persistence_filepath, "v6-client-message.db")); unlink("v6-client-message.db"); test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-client-message-props.test-db"); config.persistence_filepath = persistence_filepath; 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(persistence_filepath, "v6-client-message-props.db")); //unlink("v6-client-message-props.db"); test_cleanup(); } 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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_read/v6-sub.test-db"); config.persistence_filepath = persistence_filepath; 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(persistence_filepath, "v6-sub.db")); unlink("v6-sub.db"); test_cleanup(); } #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; char persistence_filepath[4096]; cat_sourcedir_with_relpath(persistence_filepath, "/files/persist_write/v5-full.test-db"); config.persistence_filepath = persistence_filepath; 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(persistence_filepath, "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); libcommon_vprintf = dummy_vprintf; 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; } ================================================ FILE: test/unit/broker/stubs.c ================================================ #include "config.h" #include #include "callbacks.h" #include "logging_mosq.h" #include "net_mosq.h" #include "read_handle.h" #include "send_mosq.h" struct mosquitto_db { }; struct mosquitto__base_msg { }; int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { UNUSED(mosq); UNUSED(priority); UNUSED(fmt); return 0; } 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; } bool net__is_connected(struct mosquitto *mosq) { UNUSED(mosq); return false; } 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; } void callback__on_disconnect(struct mosquitto *mosq, int rc, const mosquitto_property *props) { UNUSED(mosq); UNUSED(rc); UNUSED(props); } void callback__on_publish(struct mosquitto *mosq, int mid, int reason_code, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(mid); UNUSED(reason_code); UNUSED(properties); } void do_client_disconnect(struct mosquitto *mosq, int reason_code, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(reason_code); UNUSED(properties); } int handle__packet(struct mosquitto *context) { UNUSED(context); return MOSQ_ERR_SUCCESS; } ssize_t net__read(struct mosquitto *mosq, void *buf, size_t count) { UNUSED(mosq); UNUSED(buf); UNUSED(count); return 1; } ssize_t net__write(struct mosquitto *mosq, const void *buf, size_t count) { UNUSED(mosq); UNUSED(buf); UNUSED(count); return 1; } void plugin_persist__handle_retain_set(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_retain_remove(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__process_retain_events(bool force) { UNUSED(force); } void plugin_persist__queue_retain_event(struct mosquitto__base_msg *msg, int event) { UNUSED(msg); UNUSED(event); } void ws__prepare_packet(struct mosquitto *mosq, struct mosquitto__packet *packet) { UNUSED(mosq); UNUSED(packet); } ssize_t net__read_ws(struct mosquitto *mosq, void *buf, size_t count) { UNUSED(mosq); UNUSED(buf); UNUSED(count); return 0; } ================================================ FILE: test/unit/broker/subs_stubs.c ================================================ #include #include #include #include #include #include #include #include #include int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { UNUSED(mosq); UNUSED(priority); UNUSED(fmt); return 0; } bool net__is_connected(struct mosquitto *mosq) { UNUSED(mosq); return false; } 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, uint32_t subscription_identifier, 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(subscription_identifier); 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, mosquitto_property *properties, int access) { UNUSED(context); UNUSED(topic); UNUSED(payloadlen); UNUSED(payload); UNUSED(qos); UNUSED(retain); UNUSED(properties); UNUSED(access); return MOSQ_ERR_SUCCESS; } uint16_t mosquitto__mid_generate(struct mosquitto *mosq) { static uint16_t mid = 1; UNUSED(mosq); return ++mid; } int persist__backup(bool shutdown) { UNUSED(shutdown); return MOSQ_ERR_SUCCESS; } int persist__restore(void) { return MOSQ_ERR_SUCCESS; } int retain__init(void) { return MOSQ_ERR_SUCCESS; } void retain__expiry_check(void) { } void retain__clean(struct mosquitto__retainhier **retainhier) { UNUSED(retainhier); } int retain__queue(struct mosquitto *context, const struct mosquitto_subscription *sub) { UNUSED(context); UNUSED(sub); return MOSQ_ERR_SUCCESS; } int retain__store(const char *topic, struct mosquitto__base_msg *stored, char **split_topics, bool persist) { UNUSED(topic); UNUSED(stored); UNUSED(split_topics); UNUSED(persist); 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++; } void plugin_persist__handle_client_msg_add(struct mosquitto *context, const struct mosquitto__client_msg *cmsg) { UNUSED(context); UNUSED(cmsg); } void plugin_persist__handle_client_msg_delete(struct mosquitto *context, const struct mosquitto__client_msg *cmsg) { UNUSED(context); UNUSED(cmsg); } void plugin_persist__handle_client_msg_update(struct mosquitto *context, const struct mosquitto__client_msg *cmsg) { UNUSED(context); UNUSED(cmsg); } void plugin_persist__handle_client_msg_clear(struct mosquitto *context, uint8_t direction) { UNUSED(context); UNUSED(direction); } void plugin_persist__handle_base_msg_add(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_base_msg_delete(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_retain_msg_add(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_retain_msg_delete(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_subscription_delete(struct mosquitto *context, char *sub) { UNUSED(context); UNUSED(sub); } int session_expiry__add_from_persistence(struct mosquitto *context, time_t expiry_time) { UNUSED(context); UNUSED(expiry_time); return 0; } #ifdef WITH_SYS_TREE void metrics__int_inc(enum mosq_metric_type m, int64_t value) { UNUSED(m); UNUSED(value); } void metrics__int_dec(enum mosq_metric_type m, int64_t value) { UNUSED(m); UNUSED(value); } #endif ================================================ FILE: test/unit/broker/subs_test.c ================================================ /* Tests for subscription adding/removing * * FIXME - these need to be aggressive about finding failures, at the moment * they are just confirming that good behaviour works. */ #include #include #include "mosquitto_broker_internal.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_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 *subhier; struct mosquitto_subscription 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)); memset(&sub, 0, sizeof(sub)); context.id = "client"; db.config = &config; listener.port = 1883; config.listeners = &listener; config.listener_count = 1; db__open(&config); sub.topic_filter = "a/b/c/d/e"; rc = sub__add(&context, &sub); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(db.shared_subs); CU_ASSERT_PTR_NOT_NULL(db.normal_subs); if(db.normal_subs){ subhier = db.normal_subs; hier_quick_check(&subhier, NULL, ""); hier_quick_check(&subhier, NULL, ""); hier_quick_check(&subhier, NULL, "a"); hier_quick_check(&subhier, NULL, "b"); hier_quick_check(&subhier, NULL, "c"); hier_quick_check(&subhier, NULL, "d"); hier_quick_check(&subhier, &context, "e"); CU_ASSERT_PTR_NULL(subhier); } 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; } ================================================ FILE: test/unit/lib/CMakeLists.txt ================================================ add_executable(lib-test datatype_read.c datatype_write.c property_read.c property_user_read.c property_write.c stubs.c # main test files test.c ../../../lib/packet_datatypes.c ../../../lib/packet_mosq.c ../../../lib/property_mosq.c ../../../lib/util_mosq.c ) target_include_directories(lib-test PRIVATE ${mosquitto_SOURCE_DIR}/libcommon) target_link_libraries(lib-test PRIVATE common-unit-test-header OpenSSL::SSL libmosquitto_common) add_test(NAME unit-lib-test COMMAND lib-test) ================================================ FILE: test/unit/lib/Makefile ================================================ R=../../.. include ${R}/config.mk .PHONY: all check test test-compile clean coverage LOCAL_CFLAGS+=-coverage LOCAL_CPPFLAGS+=-I${R}/src -I${R}/test -I${R}/lib -I${R}/libcommon -DTEST_SOURCE_DIR='"$(realpath .)"' LOCAL_LDFLAGS+=-coverage LOCAL_LDADD+=-lcunit ${LIBMOSQ_COMMON} ifeq ($(WITH_TLS),yes) LOCAL_LDADD+=-lssl -lcrypto endif TEST_OBJS = \ test.o \ datatype_read.o \ datatype_write.o \ property_read.o \ property_user_read.o \ property_write.o \ stubs.o \ LIB_OBJS = \ ${R}/lib/packet_datatypes.o \ ${R}/lib/packet_mosq.o \ ${R}/lib/property_mosq.o \ ${R}/lib/util_mosq.o all : test-compile check : test lib_test : ${TEST_OBJS} ${LIB_OBJS} $(CROSS_COMPILE)$(CC) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LDADD) ${TEST_OBJS} : %.o: %.c ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ lib_stubs.o : stubs.c ${CROSS_COMPILE}$(CC) $(LIB_LOCAL_CPPFLAGS) $(LIB_LOCAL_CFLAGS) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ ${R}/lib/misc_mosq.o : ${R}/common/misc_mosq.c $(MAKE) -C ${R}/lib/ misc_mosq.o ${R}/lib/packet_datatypes.o : ${R}/lib/packet_datatypes.c $(MAKE) -C ${R}/lib/ packet_datatypes.o ${R}/lib/packet_mosq.o : ${R}/lib/packet_mosq.c $(MAKE) -C ${R}/lib/ packet_mosq.o ${R}/lib/property_mosq.o : ${R}/lib/property_mosq.c $(MAKE) -C ${R}/lib/ property_mosq.o ${R}/lib/util_mosq.o : ${R}/lib/util_mosq.c $(MAKE) -C ${R}/lib/ util_mosq.o ${R}/lib/utf8_mosq.o : ${R}/common/utf8_mosq.c $(MAKE) -C ${R}/lib/ utf8_mosq.o build : lib_test test : build ./lib_test test-compile: build clean : -rm -rf lib_test -rm -rf *.o *.gcda *.gcno coverage.info out/ coverage : lcov --capture --directory . --output-file coverage.info genhtml coverage.info --output-directory out ================================================ FILE: test/unit/lib/datatype_read.c ================================================ #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_in packet; uint8_t value = 0; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; uint16_t value = 0; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; uint32_t value = 0; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; uint32_t value = UINT32_MAX; uint8_t bytes = UINT8_MAX; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; uint8_t *value = NULL; uint16_t length = UINT16_MAX; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; uint8_t *value = NULL; uint16_t length = UINT16_MAX; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; uint8_t value[count]; int rc; int i; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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, (uint32_t)count); } if(value_expected){ for(i=0; i #include #include #include "packet_mosq.h" /* ======================================================================== * BYTE TESTS * ======================================================================== */ /* This tests writing a Byte to an incoming packet. */ static void TEST_byte_write(void) { struct mosquitto__packet *packet; int i; int rc; rc = packet__alloc(&packet, 0, 260); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } packet->pos = 0; /* We don't need the command or RL parts, so make indexing easier below */ 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(packet->payload[i], (uint8_t)(255-i)); } free(packet); } /* ======================================================================== * TWO BYTE INTEGER TESTS * ======================================================================== */ /* This tests writing a Two Byte Integer to an incoming packet. */ static void TEST_uint16_write(void) { uint16_t *payload16; struct mosquitto__packet *packet; int i; int rc; rc = packet__alloc(&packet, 0, 650); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } packet->pos = 0; /* We don't need the command or RL parts, so make indexing easier below */ for(i=0; i<325; i++){ packet__write_uint16(packet, (uint16_t)(100*i)); } CU_ASSERT_EQUAL(packet->pos, 650); payload16 = (uint16_t *)packet->payload; for(i=0; i<325; i++){ CU_ASSERT_EQUAL(payload16[i], htons((uint16_t)(100*i))); } free(packet); } /* ======================================================================== * FOUR BYTE INTEGER TESTS * ======================================================================== */ /* This tests writing a Four Byte Integer to an incoming packet. */ static void TEST_uint32_write(void) { uint32_t *payload32; struct mosquitto__packet *packet; int i; packet = calloc(1, sizeof(struct mosquitto__packet) + 42000); CU_ASSERT_PTR_NOT_NULL(packet); if(packet == NULL){ return; } 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 *)packet->payload; for(i=0; i<10500; i++){ CU_ASSERT_EQUAL(payload32[i], htonl((uint32_t)(1000*i))); } free(packet); } /* ======================================================================== * UTF-8 STRING TESTS * ======================================================================== */ /* This tests writing a UTF-8 String to an incoming packet. */ static void TEST_string_write(void) { struct mosquitto__packet *packet; packet = calloc(1, sizeof(struct mosquitto__packet) + 100); CU_ASSERT_PTR_NOT_NULL(packet); if(packet == NULL){ return; } 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(packet->payload[0], 0); CU_ASSERT_EQUAL(packet->payload[1], 10); CU_ASSERT_NSTRING_EQUAL(packet->payload+2, "first test", 10); CU_ASSERT_EQUAL(packet->payload[2+10+0], 0); CU_ASSERT_EQUAL(packet->payload[2+10+1], 11); CU_ASSERT_NSTRING_EQUAL(packet->payload+2+10+2, "second test", 11); free(packet); } /* ======================================================================== * 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; } ================================================ FILE: test/unit/lib/property_read.c ================================================ #include #include #include "mosquitto/mqtt_protocol.h" #include "property_common.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_in packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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(mosquitto_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_in packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); packet.payload = payload; packet.remaining_length = remaining_length; rc = property__read_all(command, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); if(rc != rc_expected){ printf("%d / %d\n", 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(mosquitto_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_in packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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(mosquitto_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_in packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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(mosquitto_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_in packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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(mosquitto_property_get_length_all(properties), 1+2+(unsigned int)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_in packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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(mosquitto_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_in packet; mosquitto_property *properties; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); packet.payload = payload; packet.remaining_length = remaining_length; rc = property__read_all(CMD_PUBLISH, &packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); if(rc != rc_expected){ printf("%d / %d\n", 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(mosquitto_property_get_length_all(properties), mosquitto_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_in packet; mosquitto_property *properties, *p; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; mosquitto_property *properties = NULL; uint8_t payload[5]; int rc; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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); if(properties){ mosquitto_property_free_all(&properties); } } static void TEST_truncated(void) { struct mosquitto__packet_in packet; mosquitto_property *properties = NULL; uint8_t payload[5]; int rc; /* Zero length packet */ memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_MALFORMED_PACKET); 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_in)); 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_MALFORMED_PACKET); 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_in)); 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_MALFORMED_PACKET); CU_ASSERT_PTR_EQUAL(properties, NULL); CU_ASSERT_EQUAL(packet.pos, 2); if(properties){ mosquitto_property_free_all(&properties); } } /* ======================================================================== * INVALID PROPERTY ID * ======================================================================== */ static void TEST_invalid_property_id(void) { struct mosquitto__packet_in packet; mosquitto_property *properties = NULL; uint8_t payload[5]; int rc; /* ID = 0 */ memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in)); 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); if(properties){ mosquitto_property_free_all(&properties); } } /* ======================================================================== * 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_MALFORMED_PACKET, 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_MALFORMED_PACKET, 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_in packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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_in packet; mosquitto_property *properties, *p; int rc; payload[0] = sizeof(payload)-1; memset(&packet, 0, sizeof(struct mosquitto__packet_in)); 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; } ================================================ FILE: test/unit/lib/property_user_read.c ================================================ #include #include #include "mosquitto/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, const 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); if(expected_value){ CU_ASSERT_PTR_NOT_NULL(value); if(value){ CU_ASSERT_NSTRING_EQUAL(value, expected_value, expected_length); } }else{ CU_ASSERT_PTR_NULL(value); } SAFE_FREE(value); } static void read_string_helper(const mosquitto_property *proplist, int identifier, const 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); if(expected_value){ CU_ASSERT_PTR_NOT_NULL(value); if(value){ CU_ASSERT_STRING_EQUAL(value, expected_value); } }else{ CU_ASSERT_PTR_NULL(value); } SAFE_FREE(value); } static void read_string_pair_helper(const mosquitto_property *proplist, int identifier, const char *expected_key, const 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); if(expected_key){ CU_ASSERT_PTR_NOT_NULL(key); if(key){ CU_ASSERT_STRING_EQUAL(key, expected_key); } }else{ CU_ASSERT_PTR_NULL(key); } if(expected_value){ CU_ASSERT_PTR_NOT_NULL(value); if(value){ CU_ASSERT_STRING_EQUAL(value, expected_value); } }else{ CU_ASSERT_PTR_NULL(value); } SAFE_FREE(key); SAFE_FREE(value); } static void TEST_read_null_binary(void) { int rc; mosquitto_property *proplist = NULL, *proplist_copy = NULL; rc = mosquitto_property_add_binary(&proplist, MQTT_PROP_CORRELATION_DATA, NULL, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } read_binary_helper(proplist, MQTT_PROP_CORRELATION_DATA, NULL, 0); rc = mosquitto_property_copy_all(&proplist_copy, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist_copy); read_binary_helper(proplist_copy, MQTT_PROP_CORRELATION_DATA, NULL, 0); mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&proplist_copy); } static void TEST_read_null_string(void) { int rc; mosquitto_property *proplist = NULL, *proplist_copy = NULL; rc = mosquitto_property_add_string(&proplist, MQTT_PROP_CONTENT_TYPE, NULL); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } read_string_helper(proplist, MQTT_PROP_CONTENT_TYPE, NULL); rc = mosquitto_property_copy_all(&proplist_copy, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist_copy); read_string_helper(proplist_copy, MQTT_PROP_CONTENT_TYPE, NULL); mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&proplist_copy); } static void TEST_read_null_string_pair(void) { int rc; mosquitto_property *proplist = NULL, *proplist_copy = NULL; rc = mosquitto_property_add_string_pair(&proplist, MQTT_PROP_USER_PROPERTY, NULL, NULL); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } read_string_pair_helper(proplist, MQTT_PROP_USER_PROPERTY, NULL, NULL); rc = mosquitto_property_copy_all(&proplist_copy, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(proplist_copy); read_string_pair_helper(proplist_copy, MQTT_PROP_USER_PROPERTY, NULL, NULL); mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&proplist_copy); } 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); SAFE_FREE(value); /* 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"); SAFE_FREE(value); } /* MISSING */ prop = mosquitto_property_read_binary(proplist, MQTT_PROP_CORRELATION_DATA, (void **)&value, &length, false); CU_ASSERT_PTR_NULL(prop); CU_ASSERT_PTR_NULL(value); SAFE_FREE(value); /* 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"); SAFE_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")); SAFE_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); SAFE_FREE(key); SAFE_FREE(value); 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, "Read NULL binary", TEST_read_null_binary) || !CU_add_test(test_suite, "Read NULL string", TEST_read_null_string) || !CU_add_test(test_suite, "Read NULL string pair", TEST_read_null_string_pair) || !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; } ================================================ FILE: test/unit/lib/property_write.c ================================================ #include #include #include "mosquitto/mqtt_protocol.h" #include "property_common.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; struct mosquitto__packet_in in_packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.value.i8 = value_expected; property.property_type = MQTT_PROP_TYPE_BYTE; rc = packet__alloc(&packet, 0, mosquitto_property_get_length_all(&property)+11); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } packet->pos = 0; /* Make indexing easier */ property__write_all(packet, &property, true); in_packet.remaining_length = packet->remaining_length; in_packet.packet_length = packet->packet_length; in_packet.pos = 0; in_packet.payload = packet->payload; rc = property__read_all(command, &in_packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(in_packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(mosquitto_property_identifier(properties), identifier); CU_ASSERT_EQUAL(properties->value.i8, value_expected); CU_ASSERT_EQUAL(properties->property_type, MQTT_PROP_TYPE_BYTE); CU_ASSERT_EQUAL(mosquitto_property_type(properties), MQTT_PROP_TYPE_BYTE); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_PTR_EQUAL(mosquitto_property_next(properties), NULL); CU_ASSERT_EQUAL(mosquitto_property_get_length_all(properties), 2); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); free(packet); } 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; struct mosquitto__packet_in in_packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.value.i32 = value_expected; property.property_type = MQTT_PROP_TYPE_INT32; rc = packet__alloc(&packet, 0, mosquitto_property_get_length_all(&property)+11); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } packet->pos = 0; /* Make indexing easier */ property__write_all(packet, &property, true); in_packet.remaining_length = packet->remaining_length; in_packet.packet_length = packet->packet_length; in_packet.pos = 0; in_packet.payload = packet->payload; rc = property__read_all(command, &in_packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(in_packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(mosquitto_property_identifier(properties), identifier); CU_ASSERT_EQUAL(properties->value.i32, value_expected); CU_ASSERT_EQUAL(properties->property_type, MQTT_PROP_TYPE_INT32); CU_ASSERT_EQUAL(mosquitto_property_type(properties), MQTT_PROP_TYPE_INT32); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_PTR_EQUAL(mosquitto_property_next(properties), NULL); CU_ASSERT_EQUAL(mosquitto_property_get_length_all(properties), 5); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); free(packet); } 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; struct mosquitto__packet_in in_packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.value.i16 = value_expected; property.property_type = MQTT_PROP_TYPE_INT16; rc = packet__alloc(&packet, 0, mosquitto_property_get_length_all(&property)+11); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } packet->pos = 0; /* Make indexing easier */ property__write_all(packet, &property, true); in_packet.remaining_length = packet->remaining_length; in_packet.packet_length = packet->packet_length; in_packet.pos = 0; in_packet.payload = packet->payload; rc = property__read_all(command, &in_packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(in_packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(mosquitto_property_identifier(properties), identifier); CU_ASSERT_EQUAL(properties->value.i16, value_expected); CU_ASSERT_EQUAL(properties->property_type, MQTT_PROP_TYPE_INT16); CU_ASSERT_EQUAL(mosquitto_property_type(properties), MQTT_PROP_TYPE_INT16); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_PTR_EQUAL(mosquitto_property_next(properties), NULL); CU_ASSERT_EQUAL(mosquitto_property_get_length_all(properties), 3); mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_EQUAL(properties, NULL); free(packet); } 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; struct mosquitto__packet_in in_packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.property_type = MQTT_PROP_TYPE_STRING; 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); rc = packet__alloc(&packet, 0, mosquitto_property_get_length_all(&property)+11); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } packet->pos = 0; /* Make indexing easier */ property__write_all(packet, &property, true); in_packet.remaining_length = packet->remaining_length; in_packet.packet_length = packet->packet_length; in_packet.pos = 0; in_packet.payload = packet->payload; rc = property__read_all(command, &in_packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(in_packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(mosquitto_property_identifier(properties), identifier); CU_ASSERT_EQUAL(properties->value.s.len, strlen(value_expected)); CU_ASSERT_STRING_EQUAL(properties->value.s.v, value_expected); CU_ASSERT_EQUAL(properties->property_type, MQTT_PROP_TYPE_STRING); CU_ASSERT_EQUAL(mosquitto_property_type(properties), MQTT_PROP_TYPE_STRING); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_PTR_EQUAL(mosquitto_property_next(properties), NULL); CU_ASSERT_EQUAL(mosquitto_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); } 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; struct mosquitto__packet_in in_packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.property_type = MQTT_PROP_TYPE_BINARY; 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; rc = packet__alloc(&packet, 0, mosquitto_property_get_length_all(&property)+11); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } packet->pos = 0; /* Make indexing easier */ property__write_all(packet, &property, true); in_packet.remaining_length = packet->remaining_length; in_packet.packet_length = packet->packet_length; in_packet.pos = 0; in_packet.payload = packet->payload; rc = property__read_all(command, &in_packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(in_packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(mosquitto_property_identifier(properties), 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_EQUAL(properties->property_type, MQTT_PROP_TYPE_BINARY); CU_ASSERT_EQUAL(mosquitto_property_type(properties), MQTT_PROP_TYPE_BINARY); CU_ASSERT_PTR_EQUAL(properties->next, NULL); CU_ASSERT_PTR_EQUAL(mosquitto_property_next(properties), NULL); CU_ASSERT_EQUAL(mosquitto_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); } 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; struct mosquitto__packet_in in_packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.property_type = MQTT_PROP_TYPE_STRING_PAIR; 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); rc = packet__alloc(&packet, 0, mosquitto_property_get_length_all(&property)+11); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } packet->pos = 0; /* Make indexing easier */ property__write_all(packet, &property, true); in_packet.remaining_length = packet->remaining_length; in_packet.packet_length = packet->packet_length; in_packet.pos = 0; in_packet.payload = packet->payload; rc = property__read_all(CMD_CONNECT, &in_packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); CU_ASSERT_EQUAL(in_packet.pos, remaining_length); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(mosquitto_property_identifier(properties), 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); CU_ASSERT_EQUAL(properties->property_type, MQTT_PROP_TYPE_STRING_PAIR); CU_ASSERT_EQUAL(mosquitto_property_type(properties), MQTT_PROP_TYPE_STRING_PAIR); if(expect_multiple){ CU_ASSERT_PTR_NOT_NULL(properties->next); CU_ASSERT_PTR_NOT_NULL(mosquitto_property_next(properties)); }else{ CU_ASSERT_PTR_NULL(properties->next); CU_ASSERT_PTR_NULL(mosquitto_property_next(properties)); CU_ASSERT_EQUAL(mosquitto_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); } 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; struct mosquitto__packet_in in_packet; mosquitto_property *properties; int rc; memset(&property, 0, sizeof(mosquitto_property)); property.identifier = identifier; property.property_type = MQTT_PROP_TYPE_VARINT; property.value.varint = value_expected; CU_ASSERT_EQUAL(remaining_length, mosquitto_property_get_length_all(&property)+1); rc = packet__alloc(&packet, 0, mosquitto_property_get_length_all(&property)+11); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); if(rc != MOSQ_ERR_SUCCESS){ return; } packet->pos = 0; /* Make indexing easier */ property__write_all(packet, &property, true); in_packet.remaining_length = packet->remaining_length; in_packet.packet_length = packet->packet_length; in_packet.pos = 0; in_packet.payload = packet->payload; rc = property__read_all(CMD_PUBLISH, &in_packet, &properties); CU_ASSERT_EQUAL(rc, rc_expected); if(properties){ CU_ASSERT_EQUAL(properties->identifier, identifier); CU_ASSERT_EQUAL(mosquitto_property_identifier(properties), identifier); CU_ASSERT_EQUAL(properties->property_type, MQTT_PROP_TYPE_VARINT); CU_ASSERT_EQUAL(mosquitto_property_type(properties), MQTT_PROP_TYPE_VARINT); CU_ASSERT_EQUAL(properties->value.varint, value_expected); CU_ASSERT_PTR_NULL(properties->next); CU_ASSERT_PTR_NULL(mosquitto_property_next(properties)); if(value_expected < 128){ CU_ASSERT_EQUAL(mosquitto_property_get_length_all(properties), 2); }else if(value_expected < 16384){ CU_ASSERT_EQUAL(mosquitto_property_get_length_all(properties), 3); }else if(value_expected < 2097152){ CU_ASSERT_EQUAL(mosquitto_property_get_length_all(properties), 4); }else if(value_expected < 268435456){ CU_ASSERT_EQUAL(mosquitto_property_get_length_all(properties), 5); }else{ CU_FAIL("Incorrect varint value."); } mosquitto_property_free_all(&properties); } CU_ASSERT_PTR_NULL(properties); free(packet); } /* ======================================================================== * BAD IDENTIFIER * ======================================================================== */ static void TEST_bad_identifier(void) { mosquitto_property property; struct mosquitto__packet *packet; int rc; memset(&property, 0, sizeof(property)); packet = calloc(1, sizeof(struct mosquitto__packet) + 10); CU_ASSERT_PTR_NOT_NULL(packet); if(packet == NULL){ return; } property.identifier = 0xFFFF; property.property_type = MQTT_PROP_TYPE_BYTE; packet->packet_length = 10; packet->remaining_length = 8; rc = property__write_all(packet, &property, true); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); // We don't check invalid identifier types here free(packet); } /* ======================================================================== * 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; } ================================================ FILE: test/unit/lib/publish_test.c ================================================ #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; } ================================================ FILE: test/unit/lib/stubs.c ================================================ #include "config.h" #include #include "callbacks.h" #include "logging_mosq.h" #include "net_mosq.h" #include "read_handle.h" #include "send_mosq.h" struct mosquitto_db { }; struct mosquitto__base_msg { }; int log__printf(struct mosquitto *mosq, unsigned int priority, const char *fmt, ...) { UNUSED(mosq); UNUSED(priority); UNUSED(fmt); return 0; } bool net__is_connected(struct mosquitto *mosq) { UNUSED(mosq); return false; } int net__socket_close(struct mosquitto *mosq) { UNUSED(mosq); return MOSQ_ERR_SUCCESS; } int net__socket_shutdown(struct mosquitto *mosq) { UNUSED(mosq); return MOSQ_ERR_SUCCESS; } int send__pingreq(struct mosquitto *mosq) { UNUSED(mosq); return MOSQ_ERR_SUCCESS; } void callback__on_disconnect(struct mosquitto *mosq, int rc, const mosquitto_property *props) { UNUSED(mosq); UNUSED(rc); UNUSED(props); } void callback__on_publish(struct mosquitto *mosq, int mid, int reason_code, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(mid); UNUSED(reason_code); UNUSED(properties); } void do_client_disconnect(struct mosquitto *mosq, int reason_code, const mosquitto_property *properties) { UNUSED(mosq); UNUSED(reason_code); UNUSED(properties); } int handle__packet(struct mosquitto *context) { UNUSED(context); return MOSQ_ERR_SUCCESS; } ssize_t net__read(struct mosquitto *mosq, void *buf, size_t count) { UNUSED(mosq); UNUSED(buf); UNUSED(count); return 1; } ssize_t net__write(struct mosquitto *mosq, const void *buf, size_t count) { UNUSED(mosq); UNUSED(buf); UNUSED(count); return 1; } void plugin_persist__handle_retain_set(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__handle_retain_remove(struct mosquitto__base_msg *msg) { UNUSED(msg); } void plugin_persist__process_retain_events(bool force) { UNUSED(force); } void plugin_persist__queue_retain_event(struct mosquitto__base_msg *msg, int event) { UNUSED(msg); UNUSED(event); } void ws__prepare_packet(struct mosquitto *mosq, struct mosquitto__packet *packet) { UNUSED(mosq); UNUSED(packet); } ssize_t net__read_ws(struct mosquitto *mosq, void *buf, size_t count) { UNUSED(mosq); UNUSED(buf); UNUSED(count); return 0; } ================================================ FILE: test/unit/lib/test.c ================================================ #include "config.h" #include #include #include int init_datatype_read_tests(void); int init_datatype_write_tests(void); int init_property_read_tests(void); int init_property_user_read_tests(void); int init_property_write_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_datatype_read_tests() || init_datatype_write_tests() || init_property_read_tests() || init_property_user_read_tests() || init_property_write_tests() ){ CU_cleanup_registry(); return 1; } CU_basic_set_mode(CU_BRM_NORMAL); CU_basic_run_tests(); fails = CU_get_number_of_failures(); CU_cleanup_registry(); return (int)fails; } ================================================ FILE: test/unit/libcommon/CMakeLists.txt ================================================ add_executable(libcommon-test base64_test.c file_test.c property_add.c property_value.c strings_test.c test.c topic_test.c trim_test.c utf8.c ) target_include_directories(libcommon-test PRIVATE ${mosquitto_SOURCE_DIR}/libcommon ) target_link_libraries(libcommon-test PRIVATE common-unit-test-header OpenSSL::SSL libmosquitto_common ) add_test(NAME unit-libcommon-test COMMAND libcommon-test) ================================================ FILE: test/unit/libcommon/Makefile ================================================ R=../../.. include ${R}/config.mk .PHONY: all check test test-compile clean coverage LOCAL_CFLAGS+=-coverage LOCAL_CPPFLAGS+=-I${R}/libcommon -DTEST_SOURCE_DIR='"$(realpath .)"' LOCAL_LDFLAGS+=-coverage LOCAL_LDADD+=-lcunit ${LIBMOSQ_COMMON} ifeq ($(WITH_TLS),yes) LOCAL_LDADD+=-lssl -lcrypto endif TEST_OBJS = \ base64_test.o \ file_test.o \ property_add.o \ property_value.o \ strings_test.o \ test.o \ topic_test.o \ trim_test.o \ utf8.o LIB_OBJS = all : test-compile check : test libcommon_test : ${TEST_OBJS} ${LIB_OBJS} $(CROSS_COMPILE)$(CC) $(LOCAL_LDFLAGS) -o $@ $^ $(LOCAL_LDADD) ${TEST_OBJS} : %.o: %.c ${CROSS_COMPILE}${CC} $(LOCAL_CPPFLAGS) $(LOCAL_CFLAGS) -c $< -o $@ lib_stubs.o : stubs.c ${CROSS_COMPILE}$(CC) $(LIB_LOCAL_CPPFLAGS) $(LIB_LOCAL_CFLAGS) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ build : libcommon_test test : build ./libcommon_test test-compile: build clean : -rm -rf libcommon_test -rm -rf *.o *.gcda *.gcno coverage.info ================================================ FILE: test/unit/libcommon/base64_test.c ================================================ #include #include #include "mosquitto/mqtt_protocol.h" #include "property_common.h" //int mosquitto_base64_encode(const unsigned char *in, size_t in_len, char **encoded); //int mosquitto_base64_decode(const char *in, unsigned char **decoded, unsigned int *decoded_len); #ifdef WITH_TLS static void check_encode(const char *input, size_t in_len, const char *expected_output) { char *encoded; int rc = mosquitto_base64_encode((const unsigned char *)input, in_len, &encoded); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_STRING_EQUAL(encoded, expected_output); if(strcmp(encoded, expected_output)){ printf("%s || %s\n", encoded, expected_output); } mosquitto_free(encoded); } static void check_decode(const char *input, int expected_rc, const char *expected_output, unsigned int expected_len) { unsigned char *decoded; unsigned int len; int rc = mosquitto_base64_decode(input, &decoded, &len); CU_ASSERT_EQUAL(rc, expected_rc); if(rc != expected_rc){ printf("rc: %d||%d\n", rc, expected_rc); } if(len != expected_len){ printf("len: %d||%d\n", len, expected_len); } CU_ASSERT_EQUAL(len, expected_len); if(decoded){ CU_ASSERT_EQUAL(memcmp(decoded, expected_output, len), 0); mosquitto_free(decoded); } } static void TEST_encode_empty(void) { check_encode("", 0, ""); } static void TEST_encode_string_lengths(void) { check_encode("a", 1, "YQ=="); check_encode("ab", 2, "YWI="); check_encode("abc", 3, "YWJj"); check_encode("abcd", 4, "YWJjZA=="); check_encode("abcde", 5, "YWJjZGU="); check_encode("abcdef", 6, "YWJjZGVm"); check_encode("abcdefg", 7, "YWJjZGVmZw=="); } static void TEST_encode_binary(void) { const char a[1] = {0}; const char b[2] = {0, 1}; const char c[3] = {0, 1, 2}; const char d[4] = {0, 1, 2, 3}; const char e[5] = {0, 1, 2, 3, 4}; const char f[6] = {0, 1, 2, 3, 4, 5}; const char g[7] = {0, 1, 2, 3, 4, 5, 6}; check_encode(a, 1, "AA=="); check_encode(b, 2, "AAE="); check_encode(c, 3, "AAEC"); check_encode(d, 4, "AAECAw=="); check_encode(e, 5, "AAECAwQ="); check_encode(f, 6, "AAECAwQF"); check_encode(g, 7, "AAECAwQFBg=="); } static void TEST_decode_empty(void) { check_decode("", 1, "", 0); } static void TEST_decode_invalid(void) { check_decode("abc", 1, "", 0); } static void TEST_decode_string_lengths(void) { check_decode("YQ==", MOSQ_ERR_SUCCESS, "a", 1); check_decode("YWI=", MOSQ_ERR_SUCCESS, "ab", 2); check_decode("YWJj", MOSQ_ERR_SUCCESS, "abc", 3); check_decode("YWJjZA==", MOSQ_ERR_SUCCESS, "abcd", 4); check_decode("YWJjZGU=", MOSQ_ERR_SUCCESS, "abcde", 5); check_decode("YWJjZGVm", MOSQ_ERR_SUCCESS, "abcdef", 6); check_decode("YWJjZGVmZw==", MOSQ_ERR_SUCCESS, "abcdefg", 7); } static void TEST_decode_binary(void) { const char a[1] = {0}; const char b[2] = {0, 1}; const char c[3] = {0, 1, 2}; const char d[4] = {0, 1, 2, 3}; const char e[5] = {0, 1, 2, 3, 4}; const char f[6] = {0, 1, 2, 3, 4, 5}; const char g[7] = {0, 1, 2, 3, 4, 5, 6}; check_decode("AA==", MOSQ_ERR_SUCCESS, a, 1); check_decode("AAE=", MOSQ_ERR_SUCCESS, b, 2); check_decode("AAEC", MOSQ_ERR_SUCCESS, c, 3); check_decode("AAECAw==", MOSQ_ERR_SUCCESS, d, 4); check_decode("AAECAwQ=", MOSQ_ERR_SUCCESS, e, 5); check_decode("AAECAwQF", MOSQ_ERR_SUCCESS, f, 6); check_decode("AAECAwQFBg==", MOSQ_ERR_SUCCESS, g, 7); } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_base64_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("base64", NULL, NULL); if(!test_suite){ printf("Error adding CUnit base64 test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "Encode Empty", TEST_encode_empty) || !CU_add_test(test_suite, "Encode String lengths", TEST_encode_string_lengths) || !CU_add_test(test_suite, "Encode Binary", TEST_encode_binary) || !CU_add_test(test_suite, "Decode Empty", TEST_decode_empty) || !CU_add_test(test_suite, "Decode Invalid", TEST_decode_invalid) || !CU_add_test(test_suite, "Decode String lengths", TEST_decode_string_lengths) || !CU_add_test(test_suite, "Decode Binary", TEST_decode_binary) ){ printf("Error adding Property Add CUnit tests.\n"); return 1; } return 0; } #endif ================================================ FILE: test/unit/libcommon/file_test.c ================================================ #include #include #ifndef WIN32 # include #endif #include #include "mosquitto.h" #define ALLOW_SYMLINKS "MOSQUITTO_UNSAFE_ALLOW_SYMLINKS" #define SYMLINK "test_symlink" #define DATAFILE "test_data" #ifndef WIN32 static bool symlink_test_init(void) { unsetenv(ALLOW_SYMLINKS); /* Create a file to open */ FILE *fptr = mosquitto_fopen(DATAFILE, "wb", false); CU_ASSERT_PTR_NOT_NULL(fptr); if(!fptr){ return false; } fclose(fptr); /* Add a symlink */ int rc = symlink(DATAFILE, SYMLINK); CU_ASSERT_EQUAL(rc, 0); return rc == 0?true:false; } static void symlink_test_cleanup(void) { unlink(SYMLINK); unlink(DATAFILE); unsetenv(ALLOW_SYMLINKS); } #endif #ifndef WIN32 static void TEST_restrict_read_default(void) { FILE *fptr; if(!symlink_test_init()){ return; } /* No restrict read, so symlink ok */ fptr = mosquitto_fopen(SYMLINK, "rb", false); CU_ASSERT_PTR_NOT_NULL(fptr); if(fptr){ fclose(fptr); } /* Restricted read, so symlink not allowed */ fptr = mosquitto_fopen(SYMLINK, "rb", true); CU_ASSERT_PTR_NULL(fptr); if(fptr){ fclose(fptr); } symlink_test_cleanup(); } static void TEST_restrict_read_with_symlinks(void) { FILE *fptr; if(!symlink_test_init()){ return; } int rc = setenv(ALLOW_SYMLINKS, "1", true); CU_ASSERT_EQUAL(rc, 0); /* No restrict read, so symlink ok */ fptr = mosquitto_fopen(SYMLINK, "rb", false); CU_ASSERT_PTR_NOT_NULL(fptr); if(fptr){ fclose(fptr); } /* Restricted read but with override so symlink ok */ fptr = mosquitto_fopen(SYMLINK, "rb", true); CU_ASSERT_PTR_NOT_NULL(fptr); if(fptr){ fclose(fptr); } symlink_test_cleanup(); } #endif /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_file_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("file", NULL, NULL); if(!test_suite){ printf("Error adding CUnit file test suite.\n"); return 1; } if(0 #ifndef WIN32 || !CU_add_test(test_suite, "Restrict read default", TEST_restrict_read_default) || !CU_add_test(test_suite, "Restrict read with symlinks", TEST_restrict_read_with_symlinks) #endif ){ printf("Error adding file CUnit tests.\n"); return 1; } return 0; } ================================================ FILE: test/unit/libcommon/property_add.c ================================================ #include #include #include "mosquitto/mqtt_protocol.h" #include "property_common.h" static void check_count(mosquitto_property *proplist, int expected) { mosquitto_property *p; int count; if(proplist == NULL){ CU_ASSERT_EQUAL(expected, 0); return; } p = proplist; count = 0; while(p){ count++; p = p->next; } CU_ASSERT_EQUAL(count, expected); } /* ======================================================================== * 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; 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); check_count(proplist, 9); mosquitto_property_free_all(&proplist); } static void TEST_add_all_connack(void) { mosquitto_property *proplist = NULL; 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); check_count(proplist, 17); mosquitto_property_free_all(&proplist); } static void TEST_check_length(void) { mosquitto_property *proplist = NULL; int rc; unsigned int len; unsigned int varbytes; unsigned int i; len = mosquitto_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 = mosquitto_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); } static void TEST_remove_single(void) { mosquitto_property *proplist = NULL, *property; int rc; unsigned int len; len = mosquitto_property_get_remaining_length(proplist); CU_ASSERT_EQUAL(len, 1); for(int i=1; i<10; 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); } check_count(proplist, 9); /* Remove end item */ property = proplist; while(property && property->next){ property = property->next; } rc = mosquitto_property_remove(&proplist, property); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); mosquitto_property_free_all(&property); check_count(proplist, 8); /* Remove middle item */ property = proplist; for(int i=0; i<4; i++){ property = property->next; } rc = mosquitto_property_remove(&proplist, property); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); mosquitto_property_free_all(&property); check_count(proplist, 7); /* Remove front item */ property = proplist; rc = mosquitto_property_remove(&proplist, property); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_EQUAL(proplist, property); mosquitto_property_free_all(&property); check_count(proplist, 6); mosquitto_property_free_all(&proplist); } static void TEST_remove_all(void) { mosquitto_property *proplist = NULL, *property; int rc; for(int i=0; i<100; 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); } for(int i=0; i<100; i++){ property = proplist; rc = mosquitto_property_remove(&proplist, property); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); mosquitto_property_free_all(&property); check_count(proplist, 100-i-1); } CU_ASSERT_PTR_NULL(proplist); mosquitto_property_free_all(&proplist); } static void TEST_remove_non_existent(void) { mosquitto_property *proplist = NULL, *property = NULL; int rc; unsigned int len; len = mosquitto_property_get_remaining_length(proplist); CU_ASSERT_EQUAL(len, 1); 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){ rc = mosquitto_property_add_byte(&property, MQTT_PROP_SHARED_SUB_AVAILABLE, 0); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ rc = mosquitto_property_remove(&proplist, property); CU_ASSERT_EQUAL(rc, MOSQ_ERR_NOT_FOUND); } } mosquitto_property_free_all(&proplist); mosquitto_property_free_all(&property); } static void TEST_remove_invalid(void) { mosquitto_property *proplist = NULL; int rc; unsigned int len; rc = mosquitto_property_remove(NULL, NULL); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); len = mosquitto_property_get_remaining_length(proplist); CU_ASSERT_EQUAL(len, 1); 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){ rc = mosquitto_property_remove(&proplist, NULL); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); rc = mosquitto_property_remove(NULL, proplist); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); } 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) || !CU_add_test(test_suite, "Remove single", TEST_remove_single) || !CU_add_test(test_suite, "Remove all", TEST_remove_all) || !CU_add_test(test_suite, "Remove non-existent", TEST_remove_non_existent) || !CU_add_test(test_suite, "Remove invalid", TEST_remove_invalid) ){ printf("Error adding Property Add CUnit tests.\n"); return 1; } return 0; } ================================================ FILE: test/unit/libcommon/property_value.c ================================================ #include #include #include "mosquitto/mqtt_protocol.h" #include "property_common.h" static void TEST_value_byte_success(void) { mosquitto_property *property = NULL; uint8_t value, value_set = 1; int rc; rc = mosquitto_property_add_byte(&property, MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, value_set); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ value = mosquitto_property_byte_value(property); CU_ASSERT_EQUAL(value, value_set); mosquitto_property_free_all(&property); } } static void TEST_value_byte_fail(void) { mosquitto_property *property = NULL; uint8_t value, value_set = 1; int rc; rc = mosquitto_property_add_int16(&property, MQTT_PROP_RECEIVE_MAXIMUM, value_set); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ value = mosquitto_property_byte_value(property); CU_ASSERT_EQUAL(value, 0); mosquitto_property_free_all(&property); } } static void TEST_value_int16_success(void) { mosquitto_property *property = NULL; uint16_t value, value_set = 65535; int rc; rc = mosquitto_property_add_int16(&property, MQTT_PROP_RECEIVE_MAXIMUM, value_set); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ value = mosquitto_property_int16_value(property); CU_ASSERT_EQUAL(value, value_set); mosquitto_property_free_all(&property); } } static void TEST_value_int16_fail(void) { mosquitto_property *property = NULL; uint16_t value, value_set = 65535; int rc; rc = mosquitto_property_add_int32(&property, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, value_set); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ value = mosquitto_property_int16_value(property); CU_ASSERT_EQUAL(value, 0); mosquitto_property_free_all(&property); } } static void TEST_value_int32_success(void) { mosquitto_property *property = NULL; uint32_t value, value_set = 123456; int rc; rc = mosquitto_property_add_int32(&property, MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, value_set); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ value = mosquitto_property_int32_value(property); CU_ASSERT_EQUAL(value, value_set); mosquitto_property_free_all(&property); } } static void TEST_value_int32_fail(void) { mosquitto_property *property = NULL; uint32_t value, value_set = 123456; int rc; rc = mosquitto_property_add_varint(&property, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, value_set); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ value = mosquitto_property_int32_value(property); CU_ASSERT_EQUAL(value, 0); mosquitto_property_free_all(&property); } } static void TEST_value_varint_success(void) { mosquitto_property *property = NULL; uint32_t value, value_set = 654321; int rc; rc = mosquitto_property_add_varint(&property, MQTT_PROP_SUBSCRIPTION_IDENTIFIER, value_set); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ value = mosquitto_property_varint_value(property); CU_ASSERT_EQUAL(value, value_set); mosquitto_property_free_all(&property); } } static void TEST_value_varint_fail(void) { mosquitto_property *property = NULL; uint32_t value; int rc; rc = mosquitto_property_add_int16(&property, MQTT_PROP_RECEIVE_MAXIMUM, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ value = mosquitto_property_varint_value(property); CU_ASSERT_EQUAL(value, 0); mosquitto_property_free_all(&property); } } static void TEST_value_binary_success(void) { mosquitto_property *property = NULL; uint8_t value_set[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; const uint8_t *value; uint16_t len; int rc; rc = mosquitto_property_add_binary(&property, MQTT_PROP_AUTHENTICATION_DATA, value_set, sizeof(value_set)); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ len = mosquitto_property_binary_value_length(property); value = mosquitto_property_binary_value(property); CU_ASSERT_EQUAL(len, sizeof(value_set)); CU_ASSERT_NSTRING_EQUAL(value, value_set, sizeof(value_set)); mosquitto_property_free_all(&property); } } static void TEST_value_binary_fail(void) { mosquitto_property *property = NULL; const uint8_t *value; uint16_t len; int rc; rc = mosquitto_property_add_int16(&property, MQTT_PROP_RECEIVE_MAXIMUM, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ len = mosquitto_property_binary_value_length(property); value = mosquitto_property_binary_value(property); CU_ASSERT_EQUAL(len, 0); CU_ASSERT_PTR_NULL(value); mosquitto_property_free_all(&property); } } static void TEST_value_string_success(void) { mosquitto_property *property = NULL; char value_set[] = "test"; const char *value; uint16_t len; int rc; rc = mosquitto_property_add_string(&property, MQTT_PROP_AUTHENTICATION_METHOD, value_set); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ len = mosquitto_property_string_value_length(property); value = mosquitto_property_string_value(property); CU_ASSERT_EQUAL(len, strlen(value_set)); CU_ASSERT_NSTRING_EQUAL(value, value_set, strlen(value_set)); mosquitto_property_free_all(&property); } } static void TEST_value_string_fail(void) { mosquitto_property *property = NULL; const char *value; uint16_t len; int rc; rc = mosquitto_property_add_int16(&property, MQTT_PROP_RECEIVE_MAXIMUM, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ len = mosquitto_property_string_value_length(property); value = mosquitto_property_string_value(property); CU_ASSERT_EQUAL(len, 0); CU_ASSERT_PTR_NULL(value); mosquitto_property_free_all(&property); } } static void TEST_value_string_pair_success(void) { mosquitto_property *property = NULL; char value_set[] = "value"; const char *value; uint16_t len; char name_set[] = "name"; const char *name; int rc; rc = mosquitto_property_add_string_pair(&property, MQTT_PROP_USER_PROPERTY, name_set, value_set); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ len = mosquitto_property_string_value_length(property); value = mosquitto_property_string_value(property); CU_ASSERT_EQUAL(len, strlen(value_set)); CU_ASSERT_NSTRING_EQUAL(value, value_set, strlen(value_set)); len = mosquitto_property_string_name_length(property); name = mosquitto_property_string_name(property); CU_ASSERT_EQUAL(len, strlen(name_set)); CU_ASSERT_NSTRING_EQUAL(name, name_set, strlen(name_set)); mosquitto_property_free_all(&property); } } static void TEST_value_string_pair_fail(void) { mosquitto_property *property = NULL; const char *value; uint16_t len; const char *name; int rc; rc = mosquitto_property_add_int16(&property, MQTT_PROP_RECEIVE_MAXIMUM, 1); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_PTR_NOT_NULL(property); if(property){ len = mosquitto_property_string_value_length(property); value = mosquitto_property_string_value(property); CU_ASSERT_EQUAL(len, 0); CU_ASSERT_PTR_NULL(value); len = mosquitto_property_string_name_length(property); name = mosquitto_property_string_name(property); CU_ASSERT_EQUAL(len, 0); CU_ASSERT_PTR_NULL(name); mosquitto_property_free_all(&property); } } /* ======================================================================== * TEST SUITE SETUP * ======================================================================== */ int init_property_value_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("Property value", NULL, NULL); if(!test_suite){ printf("Error adding CUnit Property value test suite.\n"); return 1; } if(0 || !CU_add_test(test_suite, "Byte value success", TEST_value_byte_success) || !CU_add_test(test_suite, "Int16 value success", TEST_value_int16_success) || !CU_add_test(test_suite, "Int32 value success", TEST_value_int32_success) || !CU_add_test(test_suite, "Varint value success", TEST_value_varint_success) || !CU_add_test(test_suite, "Binary value success", TEST_value_binary_success) || !CU_add_test(test_suite, "String value success", TEST_value_string_success) || !CU_add_test(test_suite, "String pair value success", TEST_value_string_pair_success) || !CU_add_test(test_suite, "Byte value fail", TEST_value_byte_fail) || !CU_add_test(test_suite, "Int16 value fail", TEST_value_int16_fail) || !CU_add_test(test_suite, "Int32 value fail", TEST_value_int32_fail) || !CU_add_test(test_suite, "Varint value fail", TEST_value_varint_fail) || !CU_add_test(test_suite, "Binary value fail", TEST_value_binary_fail) || !CU_add_test(test_suite, "String value fail", TEST_value_string_fail) || !CU_add_test(test_suite, "String pair value fail", TEST_value_string_pair_fail) ){ printf("Error adding Property Value CUnit tests.\n"); return 1; } return 0; } ================================================ FILE: test/unit/libcommon/strings_test.c ================================================ /* Tests for int to string functions. */ #include #include #include "mosquitto.h" struct prop_id { const char *name; int proptype; }; static void TEST_string_to_property_info(void) { const struct prop_id checks[50] = { { NULL, 0 }, { "payload-format-indicator", MQTT_PROP_TYPE_BYTE }, { "message-expiry-interval", MQTT_PROP_TYPE_INT32 }, { "content-type", MQTT_PROP_TYPE_STRING }, { NULL, 0 }, { NULL, 0 }, { NULL, 0 }, { NULL, 0 }, { "response-topic", MQTT_PROP_TYPE_STRING }, { "correlation-data", MQTT_PROP_TYPE_BINARY }, { NULL, 0 }, { "subscription-identifier", MQTT_PROP_TYPE_VARINT }, { NULL, 0 }, { NULL, 0 }, { NULL, 0 }, { NULL, 0 }, { NULL, 0 }, { "session-expiry-interval", MQTT_PROP_TYPE_INT32 }, { "assigned-client-identifier", MQTT_PROP_TYPE_STRING }, { "server-keep-alive", MQTT_PROP_TYPE_INT16 }, { NULL, 0 }, { "authentication-method", MQTT_PROP_TYPE_STRING }, { "authentication-data", MQTT_PROP_TYPE_BINARY }, { "request-problem-information", MQTT_PROP_TYPE_BYTE }, { "will-delay-interval", MQTT_PROP_TYPE_INT32 }, { "request-response-information", MQTT_PROP_TYPE_BYTE }, { "response-information", MQTT_PROP_TYPE_STRING }, { NULL, 0 }, { "server-reference", MQTT_PROP_TYPE_STRING }, { NULL, 0 }, { NULL, 0 }, { "reason-string", MQTT_PROP_TYPE_STRING }, { NULL, 0 }, { "receive-maximum", MQTT_PROP_TYPE_INT16 }, { "topic-alias-maximum", MQTT_PROP_TYPE_INT16 }, { "topic-alias", MQTT_PROP_TYPE_INT16 }, { "maximum-qos", MQTT_PROP_TYPE_BYTE }, { "retain-available", MQTT_PROP_TYPE_BYTE }, { "user-property", MQTT_PROP_TYPE_STRING_PAIR }, { "maximum-packet-size", MQTT_PROP_TYPE_INT32 }, { "wildcard-subscription-available", MQTT_PROP_TYPE_BYTE }, { "subscription-identifier-available", MQTT_PROP_TYPE_BYTE }, { "shared-subscription-available", MQTT_PROP_TYPE_BYTE }, { NULL, 0 }, { NULL, 0 }, { NULL, 0 }, { NULL, 0 }, { NULL, 0 }, { NULL, 0 }, { NULL, 0 }, }; for(int i=0; i<50; i++){ int rc, identifier, proptype; rc = mosquitto_string_to_property_info(checks[i].name, &identifier, &proptype); if(checks[i].name == NULL){ CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); }else{ CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(identifier, i); CU_ASSERT_EQUAL(proptype, checks[i].proptype); } } } static void TEST_mosquitto_strerror(void) { const char *str; int used[] = { -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, /* 13, */ 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 31, 32, 33, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162 }; /* Iterate over all possible errors, checking we have a place holder for all * unused errors, and that all used errors do not have place holder text. */ for(int err=-256; err<256; err++){ str = mosquitto_strerror(err); CU_ASSERT_PTR_NOT_NULL(str); if(str){ bool is_used = false; for(size_t i=0; i= 128){ errstr = "Unknown reason"; }else{ errstr = "Unknown error"; } if(is_used){ CU_ASSERT_STRING_NOT_EQUAL(str, errstr); if(!strcmp(str, errstr)){ printf("%d: %s (!=)\n", err, str); } }else{ CU_ASSERT_STRING_EQUAL(str, errstr); if(strcmp(str, errstr)){ printf("%d: %s (==)\n", err, str); } } } } } static void TEST_mosquitto_connack_string(void) { const char *str; uint8_t used[] = {0, 1, 2, 3, 4, 5}; /* Iterate over all possible codes, checking we have a place holder for all * unused codes, and that all used codes do not have place holder text. */ for(int code=0; code<256; code++){ str = mosquitto_connack_string(code); CU_ASSERT_PTR_NOT_NULL(str); if(str){ bool is_used = false; for(size_t i=0; i #include #include int init_base64_tests(void); int init_file_tests(void); int init_property_add_tests(void); int init_property_value_tests(void); int init_strings_tests(void); int init_topic_tests(void); int init_trim_tests(void); int init_utf8_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 #ifdef WITH_TLS || init_base64_tests() #endif || init_file_tests() || init_property_add_tests() || init_property_value_tests() || init_strings_tests() || init_topic_tests() || init_trim_tests() || init_utf8_tests() ){ CU_cleanup_registry(); return 1; } CU_basic_set_mode(CU_BRM_NORMAL); CU_basic_run_tests(); fails = CU_get_number_of_failures(); CU_cleanup_registry(); return (int)fails; } ================================================ FILE: test/unit/libcommon/topic_test.c ================================================ #include #include #include struct topic_test { const char *topic_filter; const char *topic; const char *clientid; const char *username; int rc; bool match; }; 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); if(match == false){ printf("1: %s:%s\n", sub, topic); } rc = mosquitto_topic_matches_sub2(sub, strlen(sub), topic, strlen(topic), &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); if(match == false){ printf("2: %s:%s\n", sub, topic); } } 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); rc = mosquitto_topic_matches_sub2(sub, strlen(sub), topic, strlen(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); } static void TEST_topic_pattern_empty_input(void) { int rc; bool match; rc = mosquitto_topic_matches_sub_with_pattern(NULL, NULL, NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("sub", NULL, NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern(NULL, "topic", NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern(NULL, NULL, "clientid", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern(NULL, NULL, NULL, "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("sub", "", "", "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("", "topic", "", "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("", "", "clientid", "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("", "", "", "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("%c", "topic", NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("%u", "topic", NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("%c", "", "", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("%u", "", NULL, "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("test/%c/test", "test//test", "", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("test/%u/test", "test//test", NULL, "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); } static void TEST_acl_pattern_empty_input(void) { int rc; bool match; rc = mosquitto_sub_matches_acl_with_pattern(NULL, NULL, NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern("acl", NULL, NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern(NULL, "sub", NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern(NULL, NULL, "clientid", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern(NULL, NULL, NULL, "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern("acl", "", "", "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern("", "sub", "", "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern("", "", "clientid", "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern("", "", "", "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern("%c", "sub", NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern("%u", "sub", NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern("%c", "", "", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern("%u", "", NULL, "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern("test/%c/test", "test//test", "", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl_with_pattern("test/%u/test", "test//test", NULL, "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); } static void TEST_sub_match_empty_input(void) { int rc; bool match; rc = mosquitto_sub_matches_acl("sub", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl(NULL, "topic", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl(NULL, NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl("sub", "", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl("", "topic", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_INVAL); CU_ASSERT_EQUAL(match, false); rc = mosquitto_sub_matches_acl("", "", &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"); } /* ======================================================================== * TOPIC MATCHES SUB PATTERNS * ======================================================================== */ static void TEST_topic_pattern_clientid(void) { int rc; bool match; /* Sole pattern */ rc = mosquitto_topic_matches_sub_with_pattern("%c", "clientid", "clientid", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("%c", "clientid", "nomatch", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Pattern at beginning */ rc = mosquitto_topic_matches_sub_with_pattern("%c/test", "clientid/test", "clientid", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("%c/test", "clientid/test", "nomatch", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Pattern at end */ rc = mosquitto_topic_matches_sub_with_pattern("test/%c", "test/clientid", "clientid", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("test/%c", "test/clientid", "nomatch", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Pattern in middle */ rc = mosquitto_topic_matches_sub_with_pattern("test/%c/test", "test/clientid/test", "clientid", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("test/%c/test", "test/clientid/test", "nomatch", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Repeated pattern */ rc = mosquitto_topic_matches_sub_with_pattern("test/%c/%c/test", "test/clientid/clientid/test", "clientid", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("test/%c/%c/test", "test/clientid/clientid/test", "nomatch", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Not a pattern */ rc = mosquitto_topic_matches_sub_with_pattern("test/%count", "test/clientid", "clientid", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); } static void TEST_topic_pattern_username(void) { int rc; bool match; /* Sole pattern */ rc = mosquitto_topic_matches_sub_with_pattern("%u", "username", NULL, "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("%u", "username", NULL, "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Pattern at beginning */ rc = mosquitto_topic_matches_sub_with_pattern("%u/test", "username/test", NULL, "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("%u/test", "username/test", NULL, "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Pattern at end */ rc = mosquitto_topic_matches_sub_with_pattern("test/%u", "test/username", NULL, "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("test/%u", "test/username", NULL, "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Pattern in middle */ rc = mosquitto_topic_matches_sub_with_pattern("test/%u/test", "test/username/test", NULL, "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("test/%u/test", "test/username/test", NULL, "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Repeated pattern */ rc = mosquitto_topic_matches_sub_with_pattern("test/%u/%u/test", "test/username/username/test", NULL, "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("test/%u/%u/test", "test/username/username/test", NULL, "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Not a pattern */ rc = mosquitto_topic_matches_sub_with_pattern("test/%username", "test/username", NULL, "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); } static void TEST_topic_pattern_both(void) { int rc; bool match; /* Sole pattern */ rc = mosquitto_topic_matches_sub_with_pattern("%u/%c", "username/clientid", "clientid", "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("%u/%c", "username/clientid", "clientid", "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("%u/%c", "username/clientid", "nomatch", "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("%u/%c", "username/clientid", "nomatch", "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Pattern in middle */ rc = mosquitto_topic_matches_sub_with_pattern("test/%c/%u/test", "test/clientid/username/test", "clientid", "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("test/%c/%u/test", "test/clientid/username/test", "clientid", "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("test/%c/%u/test", "test/clientid/username/test", "nomatch", "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("test/%c/%u/test", "test/clientid/username/test", "nomatch", "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Repeated pattern */ rc = mosquitto_topic_matches_sub_with_pattern("test/%u/%c/%c/%u/test", "test/username/clientid/clientid/username/test", "clientid", "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); /* Not a pattern */ rc = mosquitto_topic_matches_sub_with_pattern("test/%username/%client", "test/username/clientid", "clientid", "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Not a pattern */ rc = mosquitto_topic_matches_sub_with_pattern("test/a%u/a%c", "test/ausername/aclientid", "clientid", "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); } static void TEST_topic_pattern_wildcard(void) { int rc; bool match; /* Malicious */ /* ========= */ /* / in client id */ rc = mosquitto_topic_matches_sub_with_pattern("%c", "clientid/test", "clientid/test", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* / in username */ rc = mosquitto_topic_matches_sub_with_pattern("%u", "username/test", NULL, "username/test", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* + in client id */ rc = mosquitto_topic_matches_sub_with_pattern("%c", "clientid", "+", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* + in username */ rc = mosquitto_topic_matches_sub_with_pattern("username/%u/+", "username/test/+", NULL, "+", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Valid */ /* ========= */ /* Ends in + */ rc = mosquitto_topic_matches_sub_with_pattern("clientid/%c/+", "clientid/test/topic", "test", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("clientid/%c/+", "clientid/test/topic", "nomatch", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("username/%u/+", "username/test/topic", NULL, "test", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("username/%u/+", "username/test/topic", NULL, "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); /* Ends in # */ rc = mosquitto_topic_matches_sub_with_pattern("clientid/%c/#", "clientid/test/topic", "test", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("clientid/%c/#", "clientid/test/topic", "nomatch", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("username/%u/#", "username/test/topic", NULL, "test", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("username/%u/#", "username/test/topic", NULL, "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("clientid/%c/#", "clientid/test", "test", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("clientid/%c/#", "clientid/test", "nomatch", NULL, &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); rc = mosquitto_topic_matches_sub_with_pattern("pattern/%u/#", "pattern/username", NULL, "username", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, true); rc = mosquitto_topic_matches_sub_with_pattern("username/%u/#", "username/test", NULL, "nomatch", &match); CU_ASSERT_EQUAL(rc, MOSQ_ERR_SUCCESS); CU_ASSERT_EQUAL(match, false); } static void TEST_topic_pattern_substring_beginning(void) { const struct topic_test tests[] = { /* topic part matching substring of client id */ {"%c/#", "g/test", "guest", NULL, MOSQ_ERR_SUCCESS, false}, {"%c/#", "gu/test", "guest", NULL, MOSQ_ERR_SUCCESS, false}, {"%c/#", "gue/test", "guest", NULL, MOSQ_ERR_SUCCESS, false}, {"%c/#", "gues/test", "guest", NULL, MOSQ_ERR_SUCCESS, false}, {"%c/#", "guest/test", "guest", NULL, MOSQ_ERR_SUCCESS, true}, {"%c/#", "guestt/test", "guest", NULL, MOSQ_ERR_SUCCESS, false}, /* topic part partial matching substring of client id */ {"%c/#", "geest/test", "guest", NULL, MOSQ_ERR_SUCCESS, false}, /* topic part matching substring of client id */ {"%u/#", "g/test", NULL, "guest", MOSQ_ERR_SUCCESS, false}, {"%u/#", "gu/test", NULL, "guest", MOSQ_ERR_SUCCESS, false}, {"%u/#", "gue/test", NULL, "guest", MOSQ_ERR_SUCCESS, false}, {"%u/#", "gues/test", NULL, "guest", MOSQ_ERR_SUCCESS, false}, {"%u/#", "guest/test", NULL, "guest", MOSQ_ERR_SUCCESS, true}, {"%u/#", "guestt/test", NULL, "guest", MOSQ_ERR_SUCCESS, false}, /* topic part partial matching substring of client id */ {"%u/#", "geest/test", NULL, "guest", MOSQ_ERR_SUCCESS, false}, }; for(size_t i=0; i #include #include static void rtrim_helper(const char *expected, char *buf) { char *res; res = mosquitto_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 = mosquitto_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 = mosquitto_trimblanks(NULL); CU_ASSERT_PTR_NULL(res); } static void TEST_empty_input(void) { char buf[10]; char *res; memset(buf, 0, sizeof(buf)); res = mosquitto_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_trim_tests(void) { CU_pSuite test_suite = NULL; test_suite = CU_add_suite("String trim", NULL, NULL); if(!test_suite){ printf("Error adding CUnit 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 string trim CUnit tests.\n"); return 1; } return 0; } ================================================ FILE: test/unit/libcommon/utf8.c ================================================ #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': \"\xCE\xBA\xE1\xBD\xB9\xCF\x83\xCE\xBC\xCE\xB5\"", 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): \"\x00\"", 39, MOSQ_ERR_MALFORMED_UTF8); utf8_helper("2.1.2 2 bytes (U-00000080): \"\xC2\x80\"", MOSQ_ERR_MALFORMED_UTF8); /* control char */ utf8_helper("2.1.3 3 bytes (U-00000800): \"\xE0\xA0\x80\"", MOSQ_ERR_SUCCESS); utf8_helper("2.1.4 4 bytes (U-00010000): \"\xF0\x90\x80\x80\"", MOSQ_ERR_SUCCESS); /* 2.2 Last possible sequence of a certain length */ utf8_helper("2.2.1 1 byte (U-0000007F): \"\x7F\"", MOSQ_ERR_MALFORMED_UTF8); /* control char */ utf8_helper("2.2.2 2 bytes (U-000007FF): \"\xDF\xBF\"", MOSQ_ERR_SUCCESS); /* Non character */ utf8_helper("2.2.3 3 bytes (U-0000FFFF): \"\xEF\xBF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); /* Non character */ utf8_helper("2.2.4 4 bytes (U-0010FFFF): \"\xF7\xBF\xBF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); /* 2.3 Other boundary conditions */ utf8_helper("2.3.1 U-0000D7FF = ed 9f bf = \"\xED\x9F\xBF\"", MOSQ_ERR_SUCCESS); utf8_helper("2.3.2 U-0000E000 = ee 80 80 = \"\xEE\x80\x80\"", MOSQ_ERR_SUCCESS); utf8_helper("2.3.3 U-0000FFFD = ef bf bd = \"\xEF\xBF\xBD\"", MOSQ_ERR_SUCCESS); /* Non character */ utf8_helper("2.3.4 U-0010FFFF = f4 8f bf bf = \"\xF4\x8F\xBF\xBF\"", 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 = \"\xF4\x90\x80\x80\"", 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: \"\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.2 Last continuation byte 0xbf: \"\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.3 2 continuation bytes: \"\x80\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.4 3 continuation bytes: \"\x80\xBF\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.5 4 continuation bytes: \"\x80\xBF\x80\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.6 5 continuation bytes: \"\x80\xBF\x80\xBF\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.7 6 continuation bytes: \"\x80\xBF\x80\xBF\x80\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.1.8 7 continuation bytes: \"\x80\xBF\x80\xBF\x80\xBF\x80\"", 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: */ 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: */ 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: */ 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: */ 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: */ 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): \"\xC0\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.2 3-byte sequence with last byte missing (U+0000): \"\xE0\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.3 4-byte sequence with last byte missing (U+0000): \"\xF0\x80\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.4 5-byte sequence with last byte missing (U+0000): \"\xF8\x80\x80\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.5 6-byte sequence with last byte missing (U+0000): \"\xFC\x80\x80\x80\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.6 2-byte sequence with last byte missing (U-000007FF): \"\xDF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.7 3-byte sequence with last byte missing (U-0000FFFF): \"\xEF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.8 4-byte sequence with last byte missing (U-001FFFFF): \"\xF7\xBF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.9 5-byte sequence with last byte missing (U-03FFFFFF): \"\xFB\xBF\xBF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.3.10 6-byte sequence with last byte missing (U-7FFFFFFF): \"\xFD\xBF\xBF\xBF\xBF\"", 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("\"\xC0\xE0\x80\xF0\x80\x80\xF8\x80\x80\x80\xFC\x80\x80\x80\x80\xDF\xEF\xBF\xF7\xBF\xBF\xFB\xBF\xBF\xBF\xFD\xBF\xBF\xBF\xBF\"", 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 = \"\xFE\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.5.2 ff = \"\xFF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("3.5.3 fe fe ff ff = \"\xFE\xFE\xFF\xFF\"", 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 = \"\xC0\xAF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.1.2 U+002F = e0 80 af = \"\xE0\x80\xAF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.1.3 U+002F = f0 80 80 af = \"\xF0\x80\x80\xAF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.1.4 U+002F = f8 80 80 80 af = \"\xF8\x80\x80\x80\xAF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.1.5 U+002F = fc 80 80 80 80 af = \"\xFC\x80\x80\x80\x80\xAF\"", 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 = \"\xC1\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.2.2 U-000007FF = e0 9f bf = \"\xE0\x9F\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.2.3 U-0000FFFF = f0 8f bf bf = \"\xF0\x8F\xBF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.2.4 U-001FFFFF = f8 87 bf bf bf = \"\xF8\x87\xBF\xBF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.2.5 U-03FFFFFF = fc 83 bf bf bf bf = \"\xFC\x83\xBF\xBF\xBF\xBF\"", 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 = \"\xC0\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.3.2 U+0000 = e0 80 80 = \"\xE0\x80\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.3.3 U+0000 = f0 80 80 80 = \"\xF0\x80\x80\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.3.4 U+0000 = f8 80 80 80 80 = \"\xF8\x80\x80\x80\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("4.3.5 U+0000 = fc 80 80 80 80 80 = \"\xFC\x80\x80\x80\x80\x80\"", 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 = \"\xED\xA0\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.2 U+DB7F = ed ad bf = \"\xED\xAD\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.3 U+DB80 = ed ae 80 = \"\xED\xAE\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.4 U+DBFF = ed af bf = \"\xED\xAF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.5 U+DC00 = ed b0 80 = \"\xED\xB0\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.6 U+DF80 = ed be 80 = \"\xED\xBE\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.1.7 U+DFFF = ed bf bf = \"\xED\xBF\xBF\"", 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 = \"\xED\xA0\x80\xED\xB0\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.2 U+D800 U+DFFF = ed a0 80 ed bf bf = \"\xED\xA0\x80\xED\xBF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.3 U+DB7F U+DC00 = ed ad bf ed b0 80 = \"\xED\xAD\xBF\xED\xB0\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.4 U+DB7F U+DFFF = ed ad bf ed bf bf = \"\xED\xAD\xBF\xED\xBF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.5 U+DB80 U+DC00 = ed ae 80 ed b0 80 = \"\xED\xAE\x80\xED\xB0\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.6 U+DB80 U+DFFF = ed ae 80 ed bf bf = \"\xED\xAE\x80\xED\xBF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.7 U+DBFF U+DC00 = ed af bf ed b0 80 = \"\xED\xAF\xBF\xED\xB0\x80\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.2.8 U+DBFF U+DFFF = ed af bf ed bf bf = \"\xED\xAF\xBF\xED\xBF\xBF\"", 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 = \"\xEF\xBF\xBE\"", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("5.3.2 U+FFFF = ef bf bf = \"\xEF\xBF\xBF\"", MOSQ_ERR_MALFORMED_UTF8); /* Other noncharacters: */ /* FIXME - these need splitting up into separate tests. */ utf8_helper("\xEF\xB7\x90", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x91", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x92", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x93", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x94", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x95", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x96", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x97", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x98", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x99", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x9A", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x9B", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x9C", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x9D", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x9E", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\x9F", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xA0", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xA1", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xA2", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xA3", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xA4", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xA5", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xA6", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xA7", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xA8", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xA9", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xAA", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xAB", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xAC", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xAD", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xAE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xEF\xB7\xAF", MOSQ_ERR_MALFORMED_UTF8); /* 5.3.4 U+nFFFE U+nFFFF (for n = 1..10) */ utf8_helper("\xF0\x9F\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF0\x9F\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF0\xAF\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF0\xAF\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF0\xBF\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF0\xBF\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF1\x8F\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF1\x8F\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF1\x9F\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF1\x9F\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF1\xAF\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF1\xAF\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF1\xBF\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF1\xBF\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF2\x8F\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF2\x8F\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF2\x9F\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF2\x9F\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF2\xAF\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF2\xAF\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF2\xBF\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF2\xBF\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF3\x8F\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF3\x8F\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF3\x9F\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF3\x9F\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF3\xAF\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF3\xAF\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF3\xBF\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF3\xBF\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF4\x8F\xBF\xBE", MOSQ_ERR_MALFORMED_UTF8); utf8_helper("\xF4\x8F\xBF\xBF", MOSQ_ERR_MALFORMED_UTF8); } static 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+0080 to U+009F are two byte control characters */ for(i=0x80; i<0xA0; i++){ buf[0] = 0xC2; buf[1] = (uint8_t)i; buf[2] = '\0'; utf8_helper((char *)buf, MOSQ_ERR_MALFORMED_UTF8); } } static 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); } static 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; } ================================================ FILE: test/unit/tls_stubs.c ================================================ #include "config.h" #include #include int tls_ex_index_mosq; 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; } ================================================ FILE: test/unit/tls_test.c ================================================ #include #include #define WITH_TLS #include "tls_mosq.c" //static int mosquitto__cmp_hostname_wildcard(char *certname, const char *hostname) void hostname_cmp_helper(char *certname, const char *hostname, int expected) { int rc = mosquitto__cmp_hostname_wildcard(certname, hostname); CU_ASSERT_EQUAL(rc, expected); if(rc != expected){ printf("%d || %d\n", rc, expected); } } void TEST_tls_hostname_compare_null(void) { hostname_cmp_helper(NULL, "localhost", 1); hostname_cmp_helper("localhost", NULL, 1); hostname_cmp_helper(NULL, NULL, 1); } void TEST_tls_hostname_compare_simple(void) { hostname_cmp_helper("localhost", "localhost", 0); hostname_cmp_helper("localhost", "localhose", 15); } void TEST_tls_hostname_compare_bad_wildcard_format(void) { hostname_cmp_helper("**localhost", "localhost", 1); hostname_cmp_helper("*,localhost", "localhost", 1); hostname_cmp_helper("*.", "localhost", 1); } void TEST_tls_hostname_compare_invalid_wildcard(void) { hostname_cmp_helper("*.com", "example.com", 1); hostname_cmp_helper("*.com", "example.org", 1); hostname_cmp_helper("*.org", "example.org", 1); } void TEST_tls_hostname_compare_good_wildcard(void) { hostname_cmp_helper("*.example.com", "test.example.com", 0); hostname_cmp_helper("*.example.com", "test.example.org", -12); hostname_cmp_helper("*.example.org", "test.example.org", 0); } /* ======================================================================== * 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 TLS test suite.\n"); CU_cleanup_registry(); return 1; } if(0 || !CU_add_test(test_suite, "TLS hostname compare null", TEST_tls_hostname_compare_null) || !CU_add_test(test_suite, "TLS hostname compare simple", TEST_tls_hostname_compare_simple) || !CU_add_test(test_suite, "TLS hostname compare bad wildcard format", TEST_tls_hostname_compare_bad_wildcard_format) || !CU_add_test(test_suite, "TLS hostname compare invalid wildcard", TEST_tls_hostname_compare_invalid_wildcard) || !CU_add_test(test_suite, "TLS hostname compare good wildcard", TEST_tls_hostname_compare_good_wildcard) ){ printf("Error adding TLS 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; } ================================================ FILE: vcpkg.json ================================================ { "name": "mosquitto", "version-string": "2.1.2", "dependencies": [ "argon2", "cjson", "libmicrohttpd", "openssl", "pthreads", "sqlite3" ] } ================================================ FILE: www/README.md ================================================ This is the mosquitto website, it can be built with `nikola`: `nikola build` ================================================ FILE: www/conf.py ================================================ # -*- coding: utf-8 -*- from __future__ import unicode_literals import time # !! This is the configuration of Nikola. !! # # !! You should edit it to your liking. !! # # ! Some settings can be different in different languages. # ! A comment stating (translatable) is used to denote those. # ! There are two ways to specify a translatable setting: # ! (a) BLOG_TITLE = "My Blog" # ! (b) BLOG_TITLE = {"en": "My Blog", "es": "Mi Blog"} # ! Option (a) is used when you don't want that setting translated. # ! Option (b) is used for settings that are different in different languages. # Data about this site BLOG_AUTHOR = "Mosquitto Project" # (translatable) BLOG_TITLE = "Eclipse Mosquitto" # (translatable) # This is the main URL for your site. It will be used # in a prominent link. Don't forget the protocol (http/https)! SITE_URL = "https://mosquitto.org/" # This is the URL where Nikola's output will be deployed. # If not set, defaults to SITE_URL # BASE_URL = "https://example.com/" BLOG_EMAIL = "roger@atchoo.org" BLOG_DESCRIPTION = "An open source MQTT server" # (translatable) # What is the default language? DEFAULT_LANG = "en" # What other languages do you have? # The format is {"translationcode" : "path/to/translation" } # the path will be used as a prefix for the generated pages location TRANSLATIONS = { DEFAULT_LANG: "", # Example for another language: # "es": "./es", } # What will translated input files be named like? # If you have a page something.rst, then something.pl.rst will be considered # its Polish translation. # (in the above example: path == "something", ext == "rst", lang == "pl") # this pattern is also used for metadata: # something.meta -> something.pl.meta TRANSLATIONS_PATTERN = "{path}.{lang}.{ext}" # Links for the sidebar / navigation bar. (translatable) # This is a dict. The keys are languages, and values are tuples. # # For regular links: # ('https://getnikola.com/', 'Nikola Homepage') # # For submenus: # ( # ( # ('https://apple.com/', 'Apple'), # ('https://orange.com/', 'Orange'), # ), # 'Fruits' # ) # # WARNING: Support for submenus is theme-dependent. # Only one level of submenus is supported. # WARNING: Some themes, including the default Bootstrap 3 theme, # may present issues if the menu is too large. # (in bootstrap3, the navbar can grow too large and cover contents.) # WARNING: If you link to directories, make sure to follow # ``STRIP_INDEXES``. If it’s set to ``True``, end your links # with a ``/``, otherwise end them with ``/index.html`` — or # else they won’t be highlighted when active. NAVIGATION_LINKS = { DEFAULT_LANG: ( ("/", "Home"), #("/about/", "About"), ("/blog/", "Blog"), ("/download/", "Download"), #("/development/", "Development"), #("/community/", "Community"), #("/sponsoring/", "Sponsoring"), ( ( ("/documentation/", "All"), ("/roadmap/", "Roadmap"), ("/api/", "API"), ("/man/libmosquitto-3.html", "libmosquitto"), ("/man/mosquitto-8.html", "mosquitto"), ("/man/mosquitto-conf-5.html", "mosquitto.conf"), ("/man/mosquitto_ctrl-1.html", "mosquitto_ctrl"), ("/man/mosquitto_ctrl_dynsec-1.html", "mosquitto_ctrl_dynsec"), ("/man/mosquitto_ctrl_shell-1.html", "mosquitto_ctrl_shell"), ("/man/mosquitto_passwd-1.html", "mosquitto_passwd"), ("/man/mosquitto_pub-1.html", "mosquitto_pub"), ("/man/mosquitto_rr-1.html", "mosquitto_rr"), ("/man/mosquitto_signal-1.html", "mosquitto_signal"), ("/man/mosquitto_sub-1.html", "mosquitto_sub"), ("/man/mosquitto-tls-7.html", "mosquitto-tls"), ("/man/mqtt-7.html", "mqtt"), ), "Documentation", ) ), } # Name of the theme to use. THEME = "mosquitto" #THEME = "bootstrap3" # Primary color of your theme. This will be used to customize your theme and # auto-generate related colors in POSTS_SECTION_COLORS. Must be a HEX value. THEME_COLOR = '#3c5280' # POSTS and PAGES contains (wildcard, destination, template) tuples. # (translatable) # # The wildcard is used to generate a list of source files # (whatever/thing.rst, for example). # # That fragment could have an associated metadata file (whatever/thing.meta), # and optionally translated files (example for Spanish, with code "es"): # whatever/thing.es.rst and whatever/thing.es.meta # # This assumes you use the default TRANSLATIONS_PATTERN. # # From those files, a set of HTML fragment files will be generated: # cache/whatever/thing.html (and maybe cache/whatever/thing.html.es) # # These files are combined with the template to produce rendered # pages, which will be placed at # output/TRANSLATIONS[lang]/destination/pagename.html # # where "pagename" is the "slug" specified in the metadata file. # The page might also be placed in /destination/pagename/index.html # if PRETTY_URLS are enabled. # # The difference between POSTS and PAGES is that POSTS are added # to feeds, indexes, tag lists and archives and are considered part # of a blog, while PAGES are just independent HTML pages. # # Finally, note that destination can be translated, i.e. you can # specify a different translation folder per language. Example: # PAGES = ( # ("pages/*.rst", {"en": "pages", "de": "seiten"}, "story.tmpl"), # ("pages/*.md", {"en": "pages", "de": "seiten"}, "story.tmpl"), # ) POSTS = ( ("posts/*.rst", "blog", "post.tmpl"), ("posts/*.txt", "blog", "post.tmpl"), ("posts/*.html", "blog", "post.tmpl"), ("posts/*.md", "blog", "post.tmpl"), ) PAGES = ( ("pages/*.rst", "", "story.tmpl"), ("pages/*.txt", "", "story.tmpl"), ("pages/*.html", "", "story.tmpl"), ("pages/*.md", "", "story.tmpl"), ("pages/documentation/*.md", "", "story.tmpl"), ("man/*.xml", "man", "story.tmpl"), ) # Below this point, everything is optional # Post's dates are considered in UTC by default, if you want to use # another time zone, please set TIMEZONE to match. Check the available # list from Wikipedia: # https://en.wikipedia.org/wiki/List_of_tz_database_time_zones # (e.g. 'Europe/Zurich') # Also, if you want to use a different time zone in some of your posts, # you can use the ISO 8601/RFC 3339 format (ex. 2012-03-30T23:00:00+02:00) TIMEZONE = "Europe/London" # If you want to use ISO 8601 (also valid RFC 3339) throughout Nikola # (especially in new_post), set this to True. # Note that this does not affect DATE_FORMAT. # FORCE_ISO8601 = False # Date format used to display post dates. (translatable) # (str used by datetime.datetime.strftime) # DATE_FORMAT = '%Y-%m-%d %H:%M' # Date format used to display post dates, if local dates are used. (translatable) # (str used by moment.js) # JS_DATE_FORMAT = 'YYYY-MM-DD HH:mm' # Date fanciness. # # 0 = using DATE_FORMAT and TIMEZONE # 1 = using JS_DATE_FORMAT and local user time (via moment.js) # 2 = using a string like “2 days ago” # # Your theme must support it, bootstrap and bootstrap3 already do. # DATE_FANCINESS = 0 # While Nikola can select a sensible locale for each language, # sometimes explicit control can come handy. # In this file we express locales in the string form that # python's locales will accept in your OS, by example # "en_US.utf8" in Unix-like OS, "English_United States" in Windows. # LOCALES = dict mapping language --> explicit locale for the languages # in TRANSLATIONS. You can omit one or more keys. # LOCALE_FALLBACK = locale to use when an explicit locale is unavailable # LOCALE_DEFAULT = locale to use for languages not mentioned in LOCALES; if # not set the default Nikola mapping is used. # LOCALES = {} # LOCALE_FALLBACK = None # LOCALE_DEFAULT = None # One or more folders containing files to be copied as-is into the output. # The format is a dictionary of {source: relative destination}. # Default is: # FILES_FOLDERS = {'files': ''} # Which means copy 'files' into 'output' # One or more folders containing code listings to be processed and published on # the site. The format is a dictionary of {source: relative destination}. # Default is: # LISTINGS_FOLDERS = {'listings': 'listings'} # Which means process listings from 'listings' into 'output/listings' # A mapping of languages to file-extensions that represent that language. # Feel free to add or delete extensions to any list, but don't add any new # compilers unless you write the interface for it yourself. # # 'rest' is reStructuredText # 'markdown' is MarkDown # 'html' assumes the file is HTML and just copies it COMPILERS = { "rest": ('.rst', '.txt'), "markdown": ('.md', '.mdown', '.markdown'), "textile": ('.textile',), "txt2tags": ('.t2t',), "bbcode": ('.bb',), "wiki": ('.wiki',), "ipynb": ('.ipynb',), "html": ('.html', '.htm'), # PHP files are rendered the usual way (i.e. with the full templates). # The resulting files have .php extensions, making it possible to run # them without reconfiguring your server to recognize them. "php": ('.php',), # Pandoc detects the input from the source filename # but is disabled by default as it would conflict # with many of the others. "docbookmanpage": ('.xml',), } # Create by default posts in one file format? # Set to False for two-file posts, with separate metadata. # ONE_FILE_POSTS = True # Use date-based path when creating posts? # Can be enabled on a per-post basis with `nikola new_post -d`. # The setting is ignored when creating pages (`-d` still works). NEW_POST_DATE_PATH = True # What format to use when creating posts with date paths? # Default is '%Y/%m/%d', other possibilities include '%Y' or '%Y/%m'. NEW_POST_DATE_PATH_FORMAT = '%Y/%m' # If this is set to True, the DEFAULT_LANG version will be displayed for # untranslated posts. # If this is set to False, then posts that are not translated to a language # LANG will not be visible at all in the pages in that language. # Formerly known as HIDE_UNTRANSLATED_POSTS (inverse) # SHOW_UNTRANSLATED_POSTS = True # Nikola supports logo display. If you have one, you can put the URL here. # Final output is . # The URL may be relative to the site root. # LOGO_URL = '' # If you want to hide the title of your website (for example, if your logo # already contains the text), set this to False. SHOW_BLOG_TITLE = False # Writes tag cloud data in form of tag_cloud_data.json. # Warning: this option will change its default value to False in v8! WRITE_TAG_CLOUD = True # Generate pages for each section. The site must have at least two sections # for this option to take effect. It wouldn't build for just one section. #POSTS_SECTIONS = True # Setting this to False generates a list page instead of an index. Indexes # are the default and will apply GENERATE_ATOM if set. # POSTS_SECTIONS_ARE_INDEXES = True # Final locations are: # output / TRANSLATION[lang] / SECTION_PATH / SECTION_NAME / index.html (list of posts for a section) # output / TRANSLATION[lang] / SECTION_PATH / SECTION_NAME / rss.xml (RSS feed for a section) # (translatable) # SECTION_PATH = "" # Each post and section page will have an associated color that can be used # to style them with a recognizable color detail across your site. A color # is assigned to each section based on shifting the hue of your THEME_COLOR # at least 7.5 % while leaving the lightness and saturation untouched in the # HUSL colorspace. You can overwrite colors by assigning them colors in HEX. # POSTS_SECTION_COLORS = { # DEFAULT_LANG: { # 'posts': '#49b11bf', # 'reviews': '#ffe200', # }, # } # Associate a description with a section. For use in meta description on # section index pages or elsewhere in themes. # POSTS_SECTION_DESCRIPTIONS = { # DEFAULT_LANG: { # 'how-to': 'Learn how-to things properly with these amazing tutorials.', # }, # } # Sections are determined by their output directory as set in POSTS by default, # but can alternatively be determined from file metadata instead. # POSTS_SECTION_FROM_META = False # Names are determined from the output directory name automatically or the # metadata label. Unless overwritten below, names will use title cased and # hyphens replaced by spaces. # POSTS_SECTION_NAME = { # DEFAULT_LANG: { # 'posts': 'Blog Posts', # 'uncategorized': 'Odds and Ends', # }, # } # Titles for per-section index pages. Can be either one string where "{name}" # is substituted or the POSTS_SECTION_NAME, or a dict of sections. Note # that the INDEX_PAGES option is also applied to section page titles. # POSTS_SECTION_TITLE = { # DEFAULT_LANG: { # 'how-to': 'How-to and Tutorials', # }, # } # Paths for different autogenerated bits. These are combined with the # translation paths. # Final locations are: # output / TRANSLATION[lang] / TAG_PATH / index.html (list of tags) # output / TRANSLATION[lang] / TAG_PATH / tag.html (list of posts for a tag) # output / TRANSLATION[lang] / TAG_PATH / tag.xml (RSS feed for a tag) # (translatable) TAG_PATH = "blog/categories" # By default, the list of tags is stored in # output / TRANSLATION[lang] / TAG_PATH / index.html # (see explanation for TAG_PATH). This location can be changed to # output / TRANSLATION[lang] / TAGS_INDEX_PATH # with an arbitrary relative path TAGS_INDEX_PATH. # (translatable) # TAGS_INDEX_PATH = "tags.html" # If TAG_PAGES_ARE_INDEXES is set to True, each tag's page will contain # the posts themselves. If set to False, it will be just a list of links. # TAG_PAGES_ARE_INDEXES = False # Set descriptions for tag pages to make them more interesting. The # default is no description. The value is used in the meta description # and displayed underneath the tag list or index page’s title. # TAG_PAGES_DESCRIPTIONS = { # DEFAULT_LANG: { # "blogging": "Meta-blog posts about blogging about blogging.", # "open source": "My contributions to my many, varied, ever-changing, and eternal libre software projects." # }, # } # Set special titles for tag pages. The default is "Posts about TAG". # TAG_PAGES_TITLES = { # DEFAULT_LANG: { # "blogging": "Meta-posts about blogging", # "open source": "Posts about open source software" # }, # } # If you do not want to display a tag publicly, you can mark it as hidden. # The tag will not be displayed on the tag list page, the tag cloud and posts. # Tag pages will still be generated. HIDDEN_TAGS = ['mathjax'] # Only include tags on the tag list/overview page if there are at least # TAGLIST_MINIMUM_POSTS number of posts or more with every tag. Every tag # page is still generated, linked from posts, and included in the sitemap. # However, more obscure tags can be hidden from the tag index page. # TAGLIST_MINIMUM_POSTS = 1 # Final locations are: # output / TRANSLATION[lang] / CATEGORY_PATH / index.html (list of categories) # output / TRANSLATION[lang] / CATEGORY_PATH / CATEGORY_PREFIX category.html (list of posts for a category) # output / TRANSLATION[lang] / CATEGORY_PATH / CATEGORY_PREFIX category.xml (RSS feed for a category) # (translatable) # CATEGORY_PATH = "categories" # CATEGORY_PREFIX = "cat_" # By default, the list of categories is stored in # output / TRANSLATION[lang] / CATEGORY_PATH / index.html # (see explanation for CATEGORY_PATH). This location can be changed to # output / TRANSLATION[lang] / CATEGORIES_INDEX_PATH # with an arbitrary relative path CATEGORIES_INDEX_PATH. # (translatable) # CATEGORIES_INDEX_PATH = "categories.html" # If CATEGORY_ALLOW_HIERARCHIES is set to True, categories can be organized in # hierarchies. For a post, the whole path in the hierarchy must be specified, # using a forward slash ('/') to separate paths. Use a backslash ('\') to escape # a forward slash or a backslash (i.e. '\//\\' is a path specifying the # subcategory called '\' of the top-level category called '/'). CATEGORY_ALLOW_HIERARCHIES = False # If CATEGORY_OUTPUT_FLAT_HIERARCHY is set to True, the output written to output # contains only the name of the leaf category and not the whole path. CATEGORY_OUTPUT_FLAT_HIERARCHY = False # If CATEGORY_PAGES_ARE_INDEXES is set to True, each category's page will contain # the posts themselves. If set to False, it will be just a list of links. # CATEGORY_PAGES_ARE_INDEXES = False # Set descriptions for category pages to make them more interesting. The # default is no description. The value is used in the meta description # and displayed underneath the category list or index page’s title. # CATEGORY_PAGES_DESCRIPTIONS = { # DEFAULT_LANG: { # "blogging": "Meta-blog posts about blogging about blogging.", # "open source": "My contributions to my many, varied, ever-changing, and eternal libre software projects." # }, # } # Set special titles for category pages. The default is "Posts about CATEGORY". # CATEGORY_PAGES_TITLES = { # DEFAULT_LANG: { # "blogging": "Meta-posts about blogging", # "open source": "Posts about open source software" # }, # } # If you do not want to display a category publicly, you can mark it as hidden. # The category will not be displayed on the category list page. # Category pages will still be generated. HIDDEN_CATEGORIES = [] # If ENABLE_AUTHOR_PAGES is set to True and there is more than one # author, author pages are generated. # ENABLE_AUTHOR_PAGES = True # Path to author pages. Final locations are: # output / TRANSLATION[lang] / AUTHOR_PATH / index.html (list of authors) # output / TRANSLATION[lang] / AUTHOR_PATH / author.html (list of posts by an author) # output / TRANSLATION[lang] / AUTHOR_PATH / author.xml (RSS feed for an author) # (translatable) AUTHOR_PATH = "blog/authors" # If AUTHOR_PAGES_ARE_INDEXES is set to True, each author's page will contain # the posts themselves. If set to False, it will be just a list of links. # AUTHOR_PAGES_ARE_INDEXES = False # Set descriptions for author pages to make them more interesting. The # default is no description. The value is used in the meta description # and displayed underneath the author list or index page’s title. # AUTHOR_PAGES_DESCRIPTIONS = { # DEFAULT_LANG: { # "Juanjo Conti": "Python coder and writer.", # "Roberto Alsina": "Nikola father." # }, # } # If you do not want to display an author publicly, you can mark it as hidden. # The author will not be displayed on the author list page and posts. # Tag pages will still be generated. HIDDEN_AUTHORS = ['Guest'] # Final location for the main blog page and sibling paginated pages is # output / TRANSLATION[lang] / INDEX_PATH / index-*.html # (translatable) INDEX_PATH = "blog" # Optional HTML that displayed on “main” blog index.html files. # May be used for a greeting. (translatable) FRONT_INDEX_HEADER = { DEFAULT_LANG: '' } # Create per-month archives instead of per-year # CREATE_MONTHLY_ARCHIVE = False # Create one large archive instead of per-year # CREATE_SINGLE_ARCHIVE = False # Create year, month, and day archives each with a (long) list of posts # (overrides both CREATE_MONTHLY_ARCHIVE and CREATE_SINGLE_ARCHIVE) # CREATE_FULL_ARCHIVES = False # If monthly archives or full archives are created, adds also one archive per day # CREATE_DAILY_ARCHIVE = False # Create previous, up, next navigation links for archives # CREATE_ARCHIVE_NAVIGATION = False # Final locations for the archives are: # output / TRANSLATION[lang] / ARCHIVE_PATH / ARCHIVE_FILENAME # output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / index.html # output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / MONTH / index.html # output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / MONTH / DAY / index.html # ARCHIVE_PATH = "" # ARCHIVE_FILENAME = "archive.html" # If ARCHIVES_ARE_INDEXES is set to True, each archive page which contains a list # of posts will contain the posts themselves. If set to False, it will be just a # list of links. # ARCHIVES_ARE_INDEXES = False # URLs to other posts/pages can take 3 forms: # rel_path: a relative URL to the current page/post (default) # full_path: a URL with the full path from the root # absolute: a complete URL (that includes the SITE_URL) # URL_TYPE = 'rel_path' # If USE_BASE_TAG is True, then all HTML files will include # something like to help # the browser resolve relative links. # Most people don’t need this tag; major websites don’t use it. Use # only if you know what you’re doing. If this is True, your website # will not be fully usable by manually opening .html files in your web # browser (`nikola serve` or `nikola auto` is mandatory). Also, if you # have mirrors of your site, they will point to SITE_URL everywhere. USE_BASE_TAG = False # Final location for the blog main RSS feed is: # output / TRANSLATION[lang] / RSS_PATH / rss.xml # (translatable) # RSS_PATH = "" # Slug the Tag URL. Easier for users to type, special characters are # often removed or replaced as well. # SLUG_TAG_PATH = True # Slug the Author URL. Easier for users to type, special characters are # often removed or replaced as well. # SLUG_AUTHOR_PATH = True # A list of redirection tuples, [("foo/from.html", "/bar/to.html")]. # # A HTML file will be created in output/foo/from.html that redirects # to the "/bar/to.html" URL. notice that the "from" side MUST be a # relative URL. # # If you don't need any of these, just set to [] REDIRECTIONS = [ \ ["2009/12/version-0-2-released/index.html", "/blog/2009/12/version-0-2-released"], \ ["2009/12/version-0-3-released/index.html", "/blog/2009/12/version-0-3-released"], \ ["2010/01/mailing-list-irc/index.html", "/blog/2010/01/mailing-list-irc"], \ ["2010/01/version-0-4-1-released/index.html", "/blog/2010/01/version-0-4-1-released"], \ ["2010/01/version-0-4-released/index.html", "/blog/2010/01/version-0-4-released"], \ ["2010/02/version-0-4-2-released/index.html", "/blog/2010/02/version-0-4-2-released"], \ ["2010/03/google-powermeter/index.html", "/blog/2010/03/google-powermeter"], \ ["2010/03/upgrading-to-0-5-1/index.html", "/blog/2010/03/upgrading-to-0-5-1"], \ ["2010/03/version-0-5-1-released/index.html", "/blog/2010/03/version-0-5-1-released"], \ ["2010/03/version-0-5-2-released/index.html", "/blog/2010/03/version-0-5-2-released"], \ ["2010/03/version-0-5-3-released/index.html", "/blog/2010/03/version-0-5-3-released"], \ ["2010/03/version-0-5-4-released/index.html", "/blog/2010/03/version-0-5-4-released"], \ ["2010/04/help-wanted-rpm-packaging/index.html", "/blog/2010/04/help-wanted-rpm-packaging"], \ ["2010/04/mind-control-mqtt/index.html", "/blog/2010/04/mind-control-mqtt"], \ ["2010/04/oggcamp/index.html", "/blog/2010/04/oggcamp"], \ ["2010/05/fedora-packages-available/index.html", "/blog/2010/05/fedora-packages-available"], \ ["2010/05/gentoo-ebuilds-available/index.html", "/blog/2010/05/gentoo-ebuilds-available"], \ ["2010/05/mosquitto-org/index.html", "/blog/2010/05/mosquitto-org"], \ ["2010/05/mqtt-push-on-android/index.html", "/blog/2010/05/mqtt-push-on-android"], \ ["2010/05/mqtt-wiki/index.html", "/blog/2010/05/mqtt-wiki"], \ ["2010/05/version-0-6-1-released/index.html", "/blog/2010/05/version-0-6-1-released"], \ ["2010/05/version-0-6-released/index.html", "/blog/2010/05/version-0-6-released"], \ ["2010/06/automation-has-the-oven-warmed-up-yet/index.html", "/blog/2010/06/automation-has-the-oven-warmed-up-yet"], \ ["2010/06/google-powermeter-step-by-step/index.html", "/blog/2010/06/google-powermeter-step-by-step"], \ ["2010/06/mosquitto-0-7rc1/index.html", "/blog/2010/06/mosquitto-0-7rc1"], \ ["2010/06/version-0-7-released/index.html", "/blog/2010/06/version-0-7-released"], \ ["2010/07/mosquitto-on-opensuse-11-3/index.html", "/blog/2010/07/mosquitto-on-opensuse-11-3"], \ ["2010/07/mqtt-client-library/index.html", "/blog/2010/07/mqtt-client-library"], \ ["2010/08/compiling-mosquitto-on-mac-os-x/index.html", "/blog/2010/08/compiling-mosquitto-on-mac-os-x"], \ ["2010/08/mosquitto-running-on-mac-os-x/index.html", "/blog/2010/08/mosquitto-running-on-mac-os-x"], \ ["2010/08/mqtt-v3-1/index.html", "/blog/2010/08/mqtt-v3-1"], \ ["2010/08/version-0-8-1-released/index.html", "/blog/2010/08/version-0-8-1-released"], \ ["2010/08/version-0-8-2/index.html", "/blog/2010/08/version-0-8-2"], \ ["2010/08/version-0-8-released/index.html", "/blog/2010/08/version-0-8-released"], \ ["2010/09/debian-packages/index.html", "/blog/2010/09/debian-packages"], \ ["2010/09/mqtt-with-php/index.html", "/blog/2010/09/mqtt-with-php"], \ ["2010/10/man-page-translations/index.html", "/blog/2010/10/man-page-translations"], \ ["2010/10/one-year-old/index.html", "/blog/2010/10/one-year-old"], \ ["2010/10/version-0-8-3-released/index.html", "/blog/2010/10/version-0-8-3-released"], \ ["2010/11/distro-packaging/index.html", "/blog/2010/11/distro-packaging"], \ ["2010/11/mosquitto-0-9test2/index.html", "/blog/2010/11/mosquitto-0-9test2"], \ ["2010/11/version-0-9-released/index.html", "/blog/2010/11/version-0-9-released"], \ ["2010/12/version-0-9-1-released/index.html", "/blog/2010/12/version-0-9-1-released"], \ ["2011/01/mosquitto-for-slackware/index.html", "/blog/2011/01/mosquitto-for-slackware"], \ ["2011/01/mqtt-news/index.html", "/blog/2011/01/mqtt-news"], \ ["2011/02/lightweight-messaging-and-linux/index.html", "/blog/2011/02/lightweight-messaging-and-linux"], \ ["2011/02/mosquitto-on-maemo/index.html", "/blog/2011/02/mosquitto-on-maemo"], \ ["2011/02/mqtt-on-android/index.html", "/blog/2011/02/mqtt-on-android"], \ ["2011/02/version-0-9-2-released/index.html", "/blog/2011/02/version-0-9-2-released"], \ ["2011/03/api-documentation/index.html", "/blog/2011/03/api-documentation"], \ ["2011/03/mosquitto-in-mac-homebrew/index.html", "/blog/2011/03/mosquitto-in-mac-homebrew"], \ ["2011/03/version-0-9-3-released/index.html", "/blog/2011/03/version-0-9-3-released"], \ ["2011/04/version-0-10-released/index.html", "/blog/2011/04/version-0-10-released"], \ ["2011/05/mqtt-ontology/index.html", "/blog/2011/05/mqtt-ontology"], \ ["2011/05/version-0-10-1-released/index.html", "/blog/2011/05/version-0-10-1-released"], \ ["2011/06/nanode-a-cheap-networked-arduino-clone/index.html", "/blog/2011/06/nanode-a-cheap-networked-arduino-clone"], \ ["2011/06/version-0-10-2-released/index.html", "/blog/2011/06/version-0-10-2-released"], \ ["2011/06/version-0-11-1-released/index.html", "/blog/2011/06/version-0-11-1-released"], \ ["2011/06/version-0-11-2-released/index.html", "/blog/2011/06/version-0-11-2-released"], \ ["2011/06/version-0-11-released/index.html", "/blog/2011/06/version-0-11-released"], \ ["2011/07/debian-and-ubuntu-packaging/index.html", "/blog/2011/07/debian-and-ubuntu-packaging"], \ ["2011/07/lua-mqtt-client/index.html", "/blog/2011/07/lua-mqtt-client"], \ ["2011/07/mosquitto-on-qnx/index.html", "/blog/2011/07/mosquitto-on-qnx"], \ ["2011/07/version-0-11-3-released/index.html", "/blog/2011/07/version-0-11-3-released"], \ ["2011/07/version-0-12-released/index.html", "/blog/2011/07/version-0-12-released"], \ ["2011/07/wireshark-mqtt-decoder/index.html", "/blog/2011/07/wireshark-mqtt-decoder"], \ ["2011/08/arch-linux-package/index.html", "/blog/2011/08/arch-linux-package"], \ ["2011/08/facebook-using-mqtt/index.html", "/blog/2011/08/facebook-using-mqtt"], \ ["2011/08/mosquitto-on-openwrt/index.html", "/blog/2011/08/mosquitto-on-openwrt"], \ ["2011/08/mqtt-standardisation/index.html", "/blog/2011/08/mqtt-standardisation"], \ ["2011/09/version-0-13-released/index.html", "/blog/2011/09/version-0-13-released"], \ ["2011/10/mqtt-power-usage-on-android/index.html", "/blog/2011/10/mqtt-power-usage-on-android"], \ ["2011/10/two/index.html", "/blog/2011/10/two"], \ ["2011/11/android-mqtt-example-project/index.html", "/blog/2011/11/android-mqtt-example-project"], \ ["2011/11/ibm-java-and-c-clients-to-be-open-source/index.html", "/blog/2011/11/ibm-java-and-c-clients-to-be-open-source"], \ ["2011/11/new-linux-repositories/index.html", "/blog/2011/11/new-linux-repositories"], \ ["2011/11/version-0-14-1-released/index.html", "/blog/2011/11/version-0-14-1-released"], \ ["2011/11/version-0-14-2-released/index.html", "/blog/2011/11/version-0-14-2-released"], \ ["2011/11/version-0-14-released/index.html", "/blog/2011/11/version-0-14-released"], \ ["2011/12/mqtt-on-nanode/index.html", "/blog/2011/12/mqtt-on-nanode"], \ ["2011/12/version-0-14-3-released/index.html", "/blog/2011/12/version-0-14-3-released"], \ ["2012/01/challenge-web-based-mqtt-graphing/index.html", "/blog/2012/01/challenge-web-based-mqtt-graphing"], \ ["2012/01/do-you-use-mqtt/index.html", "/blog/2012/01/do-you-use-mqtt"], \ ["2012/01/mosquitto-test-server/index.html", "/blog/2012/01/mosquitto-test-server"], \ ["2012/01/version-0-14-4-released/index.html", "/blog/2012/01/version-0-14-4-released"], \ ["2012/02/mqtt2pachube/index.html", "/blog/2012/02/mqtt2pachube"], \ ["2012/02/version-0-15-released/index.html", "/blog/2012/02/version-0-15-released"], \ ["2012/03/quick-start-guide-for-mqtt-with-pachube/index.html", "/blog/2012/03/quick-start-guide-for-mqtt-with-pachube"], \ ["2012/03/upcoming-incompatible-library-changes/index.html", "/blog/2012/03/upcoming-incompatible-library-changes"], \ ["2012/05/python-client-module-available-for-testing/index.html", "/blog/2012/05/python-client-module-available-for-testing"], \ ["2012/06/ipv6-on-test-server/index.html", "/blog/2012/06/ipv6-on-test-server"], \ ["2012/06/ssl-support-on-test-server/index.html", "/blog/2012/06/ssl-support-on-test-server"], \ ["2012/07/upcoming-release/index.html", "/blog/2012/07/upcoming-release"], \ ["2012/08/baby/index.html", "/blog/2012/08/baby"], \ ["2012/08/bugfix-coming-soon/index.html", "/blog/2012/08/bugfix-coming-soon"], \ ["2012/08/version-1-0-1-released/index.html", "/blog/2012/08/version-1-0-1-released"], \ ["2012/08/version-1-0-2-released/index.html", "/blog/2012/08/version-1-0-2-released"], \ ["2012/08/version-1-0-released/index.html", "/blog/2012/08/version-1-0-released"], \ ["2012/09/updating-password-files/index.html", "/blog/2012/09/updating-password-files"], \ ["2012/09/version-1-0-3-released/index.html", "/blog/2012/09/version-1-0-3-released"], \ ["2012/10/version-1-0-4-released/index.html", "/blog/2012/10/version-1-0-4-released"], \ ["2012/11/making-mosquitto-packages-for-debian-yourself/index.html", "/blog/2012/11/making-mosquitto-packages-for-debian-yourself"], \ ["2012/11/version-1-0-5-released/index.html", "/blog/2012/11/version-1-0-5-released"], \ ["2012/12/libmosquitto-go-bindings/index.html", "/blog/2012/12/libmosquitto-go-bindings"], \ ["2012/12/version-1-1-released/index.html", "/blog/2012/12/version-1-1-released"], \ ["2013/01/mosquitto-debian-repository/index.html", "/blog/2013/01/mosquitto-debian-repository"], \ ["2013/01/version-1-1-1-released/index.html", "/blog/2013/01/version-1-1-1-released"], \ ["2013/01/version-1-1-2-released/index.html", "/blog/2013/01/version-1-1-2-released"], \ ["2013/02/mqtt-standardisation-oasis-call-for-participation/index.html", "/blog/2013/02/mqtt-standardisation-oasis-call-for-participation"], \ ["2013/02/version-1-1-3-released/index.html", "/blog/2013/02/version-1-1-3-released"], \ ["2013/04/some-interesting-mqtt-things/index.html", "/blog/2013/04/some-interesting-mqtt-things"], \ ["2013/05/mosquitto-javascript-client-deprecated/index.html", "/blog/2013/05/mosquitto-javascript-client-deprecated"], \ ["2013/07/authentication-plugins/index.html", "/blog/2013/07/authentication-plugins"], \ ["2013/07/version-1-2-near-complete/index.html", "/blog/2013/07/version-1-2-near-complete"], \ ["2013/08/mosquitto-on-fedora/index.html", "/blog/2013/08/mosquitto-on-fedora"], \ ["2013/08/mqtt-watchdir/index.html", "/blog/2013/08/mqtt-watchdir"], \ ["2013/08/version-1-2-released/index.html", "/blog/2013/08/version-1-2-released"], \ ["2013/09/version-1-2-1-released/index.html", "/blog/2013/09/version-1-2-1-released"], \ ["2013/10/version-1-2-2-released/index.html", "/blog/2013/10/version-1-2-2-released"], \ ["2013/12/paho-mqtt-python-client/index.html", "/blog/2013/12/paho-mqtt-python-client"], \ ["2013/12/version-1-2-3-released/index.html", "/blog/2013/12/version-1-2-3-released"], \ ["2014/03/version-1-3-1-released/index.html", "/blog/2014/03/version-1-3-1-released"], \ ["2014/03/version-1-3-released/index.html", "/blog/2014/03/version-1-3-released"], \ ["2014/05/new-arrival/index.html", "/blog/2014/05/new-arrival"], \ ["2014/07/version-1-3-2-released/index.html", "/blog/2014/07/version-1-3-2-released"], \ ["2014/08/version-1-3-3-released/index.html", "/blog/2014/08/version-1-3-3-released"], \ ["2014/08/version-1-3-4-released/index.html", "/blog/2014/08/version-1-3-4-released"], \ ["2014/10/mosquitto-and-poodle/index.html", "/blog/2014/10/mosquitto-and-poodle"], \ ["2014/10/unintended-change-of-behaviour-in-1-3-4/index.html", "/blog/2014/10/unintended-change-of-behaviour-in-1-3-4"], \ ["2014/10/version-1-3-5-released/index.html", "/blog/2014/10/version-1-3-5-released"], \ ["2015/01/seeking-sponsorship/index.html", "/blog/2015/01/seeking-sponsorship"], \ ["2015/02/version-1-4-released/index.html", "/blog/2015/02/version-1-4-released"], \ ["2015/04/version-1-4-1-released/index.html", "/blog/2015/04/version-1-4-1-released"], \ ["2015/05/mosquitto-and-current-unreleased-libwebsockets-branch/index.html", "/blog/2015/05/mosquitto-and-current-unreleased-libwebsockets-branch"], \ ["2015/05/version-1-4-2-released/index.html", "/blog/2015/05/version-1-4-2-released"], \ ["2015/08/version-1-4-3-released/index.html", "/blog/2015/08/version-1-4-3-released"], \ ["2015/09/version-1-4-4-released/index.html", "/blog/2015/09/version-1-4-4-released"], \ ["2015/11/version-1-4-5-released/index.html", "/blog/2015/11/version-1-4-5-released"], \ ["2015/12/using-lets-encrypt-certificates-with-mosquitto/index.html", "/blog/2015/12/using-lets-encrypt-certificates-with-mosquitto"], \ ["2015/12/version-1-4-7-released/index.html", "/blog/2015/12/version-1-4-7-released"], \ ["2016/01/test6-mosquitto-org/index.html", "/blog/2016/01/test6-mosquitto-org"], \ ["2016/02/version-1-4-8-released/index.html", "/blog/2016/02/version-1-4-8-released"], \ ["2016/03/logo-contest-results-for-shortlisting/index.html", "/blog/2016/03/logo-contest-results-for-shortlisting"], \ ["2016/03/logo-contest/index.html", "/blog/2016/03/logo-contest"], \ ["2016/03/repository-moved-to-github/index.html", "/blog/2016/03/repository-moved-to-github"], \ ["2016/05/stickers/index.html", "/blog/2016/05/stickers"], \ ["2016/06/version-1-4-9-released/index.html", "/blog/2016/06/version-1-4-9-released"], \ ["2016/08/mqtt-v5-draft-features/index.html", "/blog/2016/08/mqtt-v5-draft-features"], \ ["2016/08/version-1-4-10-released/index.html", "/blog/2016/08/version-1-4-10-released"], \ ["2016/12/pre-christmas-update/index.html", "/blog/2016/12/pre-christmas-update"], \ ["2017/02/version-1-4-11-released/index.html", "/blog/2017/02/version-1-4-11-released"], \ ["2017/03/for-the-final-time/index.html", "/blog/2017/03/for-the-final-time"], \ ["2017/05/security-advisory-cve-2017-7650/index.html", "/blog/2017/05/security-advisory-cve-2017-7650"], \ ["2017/06/citing-eclipse-mosquitto/index.html", "/blog/2017/06/citing-eclipse-mosquitto"], \ ["2017/06/security-advisory-cve-2017-9868/index.html", "/blog/2017/06/security-advisory-cve-2017-9868"], \ ["2017/07/version-1-4-13-released/index.html", "/blog/2017/07/version-1-4-13-released"], \ ["2017/07/version-1-4-14-released/index.html", "/blog/2017/07/version-1-4-14-released"], \ ["2018/01/mosquitto-debian-repo-key-updated/index.html", "/blog/2018/01/mosquitto-debian-repo-key-updated"] \ ] ## Presets of commands to execute to deploy. Can be anything, for # example, you may use rsync: # "rsync -rav --delete output/ joe@my.site:/srv/www/site" # And then do a backup, or run `nikola ping` from the `ping` # plugin (`nikola plugin -i ping`). Or run `nikola check -l`. # You may also want to use github_deploy (see below). # You can define multiple presets and specify them as arguments # to `nikola deploy`. If no arguments are specified, a preset # named `default` will be executed. You can use as many presets # in a `nikola deploy` command as you like. # DEPLOY_COMMANDS = { # 'default': [ # "rsync -rav --delete output/ joe@my.site:/srv/www/site", # ] # } # github_deploy configuration # For more details, read the manual: # https://getnikola.com/handbook.html#deploying-to-github # You will need to configure the deployment branch on GitHub. GITHUB_SOURCE_BRANCH = 'src' GITHUB_DEPLOY_BRANCH = 'master' # The name of the remote where you wish to push to, using github_deploy. GITHUB_REMOTE_NAME = 'origin' # Whether or not github_deploy should commit to the source branch automatically # before deploying. GITHUB_COMMIT_SOURCE = True # Where the output site should be located # If you don't use an absolute path, it will be considered as relative # to the location of conf.py OUTPUT_FOLDER = '/home/mosqorg/site/mosquitto.org' # where the "cache" of partial generated content should be located # default: 'cache' # CACHE_FOLDER = 'cache' # Filters to apply to the output. # A directory where the keys are either: a file extensions, or # a tuple of file extensions. # # And the value is a list of commands to be applied in order. # # Each command must be either: # # A string containing a '%s' which will # be replaced with a filename. The command *must* produce output # in place. # # Or: # # A python callable, which will be called with the filename as # argument. # # By default, only .php files uses filters to inject PHP into # Nikola’s templates. All other filters must be enabled through FILTERS. # # Many filters are shipped with Nikola. A list is available in the manual: # # # from nikola import filters # FILTERS = { # ".html": [filters.typogrify], # ".js": [filters.closure_compiler], # ".jpg": ["jpegoptim --strip-all -m75 -v %s"], # } # Executable for the "yui_compressor" filter (defaults to 'yui-compressor'). # YUI_COMPRESSOR_EXECUTABLE = 'yui-compressor' # Executable for the "closure_compiler" filter (defaults to 'closure-compiler'). # CLOSURE_COMPILER_EXECUTABLE = 'closure-compiler' # Executable for the "optipng" filter (defaults to 'optipng'). # OPTIPNG_EXECUTABLE = 'optipng' # Executable for the "jpegoptim" filter (defaults to 'jpegoptim'). # JPEGOPTIM_EXECUTABLE = 'jpegoptim' # Executable for the "html_tidy_withconfig", "html_tidy_nowrap", # "html_tidy_wrap", "html_tidy_wrap_attr" and "html_tidy_mini" filters # (defaults to 'tidy5'). # HTML_TIDY_EXECUTABLE = 'tidy5' # Expert setting! Create a gzipped copy of each generated file. Cheap server- # side optimization for very high traffic sites or low memory servers. # GZIP_FILES = False # File extensions that will be compressed # GZIP_EXTENSIONS = ('.txt', '.htm', '.html', '.css', '.js', '.json', '.atom', '.xml') # Use an external gzip command? None means no. # Example: GZIP_COMMAND = "pigz -k {filename}" # GZIP_COMMAND = None # Make sure the server does not return a "Accept-Ranges: bytes" header for # files compressed by this option! OR make sure that a ranged request does not # return partial content of another representation for these resources. Do not # use this feature if you do not understand what this means. # Compiler to process LESS files. # LESS_COMPILER = 'lessc' # A list of options to pass to the LESS compiler. # Final command is: LESS_COMPILER LESS_OPTIONS file.less # LESS_OPTIONS = [] # Compiler to process Sass files. # SASS_COMPILER = 'sass' # A list of options to pass to the Sass compiler. # Final command is: SASS_COMPILER SASS_OPTIONS file.s(a|c)ss # SASS_OPTIONS = [] # ############################################################################# # Image Gallery Options # ############################################################################# # One or more folders containing galleries. The format is a dictionary of # {"source": "relative_destination"}, where galleries are looked for in # "source/" and the results will be located in # "OUTPUT_PATH/relative_destination/gallery_name" # Default is: # GALLERY_FOLDERS = {"galleries": "galleries"} # More gallery options: # THUMBNAIL_SIZE = 180 # MAX_IMAGE_SIZE = 1280 # USE_FILENAME_AS_TITLE = True # EXTRA_IMAGE_EXTENSIONS = [] # # If set to False, it will sort by filename instead. Defaults to True # GALLERY_SORT_BY_DATE = True # If set to True, EXIF data will be copied when an image is thumbnailed or # resized. (See also EXIF_WHITELIST) # PRESERVE_EXIF_DATA = False # If you have enabled PRESERVE_EXIF_DATA, this option lets you choose EXIF # fields you want to keep in images. (See also PRESERVE_EXIF_DATA) # # For a full list of field names, please see here: # http://www.cipa.jp/std/documents/e/DC-008-2012_E.pdf # # This is a dictionary of lists. Each key in the dictionary is the # name of a IDF, and each list item is a field you want to preserve. # If you have a IDF with only a '*' item, *EVERY* item in it will be # preserved. If you don't want to preserve anything in a IDF, remove it # from the setting. By default, no EXIF information is kept. # Setting the whitelist to anything other than {} implies # PRESERVE_EXIF_DATA is set to True # To preserve ALL EXIF data, set EXIF_WHITELIST to {"*": "*"} # EXIF_WHITELIST = {} # Some examples of EXIF_WHITELIST settings: # Basic image information: # EXIF_WHITELIST['0th'] = [ # "Orientation", # "XResolution", # "YResolution", # ] # If you want to keep GPS data in the images: # EXIF_WHITELIST['GPS'] = ["*"] # Embedded thumbnail information: # EXIF_WHITELIST['1st'] = ["*"] # Folders containing images to be used in normal posts or pages. # IMAGE_FOLDERS is a dictionary of the form {"source": "destination"}, # where "source" is the folder containing the images to be published, and # "destination" is the folder under OUTPUT_PATH containing the images copied # to the site. Thumbnail images will be created there as well. # To reference the images in your posts, include a leading slash in the path. # For example, if IMAGE_FOLDERS = {'images': 'images'}, write # # .. image:: /images/tesla.jpg # # See the Nikola Handbook for details (in the “Embedding Images” and # “Thumbnails” sections) # Images will be scaled down according to IMAGE_THUMBNAIL_SIZE and MAX_IMAGE_SIZE # options, but will have to be referenced manually to be visible on the site # (the thumbnail has ``.thumbnail`` added before the file extension by default, # but a different naming template can be configured with IMAGE_THUMBNAIL_FORMAT). IMAGE_FOLDERS = {'images': 'images'} # IMAGE_THUMBNAIL_SIZE = 400 # IMAGE_THUMBNAIL_FORMAT = '{name}.thumbnail{ext}' # ############################################################################# # HTML fragments and diverse things that are used by the templates # ############################################################################# # Data about post-per-page indexes. # INDEXES_PAGES defaults to ' old posts, page %d' or ' page %d' (translated), # depending on the value of INDEXES_PAGES_MAIN. # # (translatable) If the following is empty, defaults to BLOG_TITLE: # INDEXES_TITLE = "" # # (translatable) If the following is empty, defaults to ' [old posts,] page %d' (see above): # INDEXES_PAGES = "" # # If the following is True, INDEXES_PAGES is also displayed on the main (the # newest) index page (index.html): # INDEXES_PAGES_MAIN = False # # If the following is True, index-1.html has the oldest posts, index-2.html the # second-oldest posts, etc., and index.html has the newest posts. This ensures # that all posts on index-x.html will forever stay on that page, now matter how # many new posts are added. # If False, index-1.html has the second-newest posts, index-2.html the third-newest, # and index-n.html the oldest posts. When this is active, old posts can be moved # to other index pages when new posts are added. # INDEXES_STATIC = True # # (translatable) If PRETTY_URLS is set to True, this setting will be used to create # prettier URLs for index pages, such as page/2/index.html instead of index-2.html. # Valid values for this settings are: # * False, # * a list or tuple, specifying the path to be generated, # * a dictionary mapping languages to lists or tuples. # Every list or tuple must consist of strings which are used to combine the path; # for example: # ['page', '{number}', '{index_file}'] # The replacements # {number} --> (logical) page number; # {old_number} --> the page number inserted into index-n.html before (zero for # the main page); # {index_file} --> value of option INDEX_FILE # are made. # Note that in case INDEXES_PAGES_MAIN is set to True, a redirection will be created # for the full URL with the page number of the main page to the normal (shorter) main # page URL. # INDEXES_PRETTY_PAGE_URL = False # # If the following is true, a page range navigation will be inserted to indices. # Please note that this will undo the effect of INDEXES_STATIC, as all index pages # must be recreated whenever the number of pages changes. # SHOW_INDEX_PAGE_NAVIGATION = False # If the following is True, a meta name="generator" tag is added to pages. The # generator tag is used to specify the software used to generate the page # (it promotes Nikola). # META_GENERATOR_TAG = True # Color scheme to be used for code blocks. If your theme provides # "assets/css/code.css" this is ignored. Leave empty to disable. # Can be any of: # algol, algol_nu, autumn, borland, bw, colorful, default, emacs, friendly, # fruity, igor, lovelace, manni, monokai, murphy, native, paraiso-dark, # paraiso-light, pastie, perldoc, rrt, tango, trac, vim, vs, xcode # This list MAY be incomplete since pygments adds styles every now and then. # Check with list(pygments.styles.get_all_styles()) in an interpreter. # CODE_COLOR_SCHEME = 'default' # FAVICONS contains (name, file, size) tuples. # Used to create favicon link like this: # FAVICONS = ( ("icon", "/favicon-16x16.png", "16x16"), ("icon", "/favicon-32x32.png", "32x32"), ) # Show teasers (instead of full posts) in indexes? Defaults to False. # INDEX_TEASERS = False # HTML fragments with the Read more... links. # The following tags exist and are replaced for you: # {link} A link to the full post page. # {read_more} The string “Read more” in the current language. # {reading_time} An estimate of how long it will take to read the post. # {remaining_reading_time} An estimate of how long it will take to read the post, sans the teaser. # {min_remaining_read} The string “{remaining_reading_time} min remaining to read” in the current language. # {paragraph_count} The amount of paragraphs in the post. # {remaining_paragraph_count} The amount of paragraphs in the post, sans the teaser. # {post_title} The title of the post. # {{ A literal { (U+007B LEFT CURLY BRACKET) # }} A literal } (U+007D RIGHT CURLY BRACKET) # 'Read more...' for the index page, if INDEX_TEASERS is True (translatable) INDEX_READ_MORE_LINK = '

{read_more}…

' # 'Read more...' for the feeds, if FEED_TEASERS is True (translatable) FEED_READ_MORE_LINK = '

{read_more}… ({min_remaining_read})

' # Append a URL query to the FEED_READ_MORE_LINK in Atom and RSS feeds. Advanced # option used for traffic source tracking. # Minimum example for use with Piwik: "pk_campaign=feed" # The following tags exist and are replaced for you: # {feedRelUri} A relative link to the feed. # {feedFormat} The name of the syndication format. # Example using replacement for use with Google Analytics: # "utm_source={feedRelUri}&utm_medium=nikola_feed&utm_campaign={feedFormat}_feed" FEED_LINKS_APPEND_QUERY = False # A HTML fragment describing the license, for the sidebar. # (translatable) LICENSE = "" # I recommend using the Creative Commons' wizard: # https://creativecommons.org/choose/ # LICENSE = """ # # Creative Commons License BY-NC-SA""" # A small copyright notice for the page footer (in HTML). # (translatable) CONTENT_FOOTER = 'Contents © {date} {author} - Powered by Nikola {license}' # Things that will be passed to CONTENT_FOOTER.format(). This is done # for translatability, as dicts are not formattable. Nikola will # intelligently format the setting properly. # The setting takes a dict. The keys are languages. The values are # tuples of tuples of positional arguments and dicts of keyword arguments # to format(). For example, {'en': (('Hello'), {'target': 'World'})} # results in CONTENT_FOOTER['en'].format('Hello', target='World'). # WARNING: If you do not use multiple languages with CONTENT_FOOTER, this # still needs to be a dict of this format. (it can be empty if you # do not need formatting) # (translatable) CONTENT_FOOTER_FORMATS = { DEFAULT_LANG: ( (), { "email": BLOG_EMAIL, "author": BLOG_AUTHOR, "date": time.gmtime().tm_year, "license": LICENSE } ) } # A simple copyright tag for inclusion in RSS feeds that works just # like CONTENT_FOOTER and CONTENT_FOOTER_FORMATS RSS_COPYRIGHT = 'Contents © {date} {author} {license}' RSS_COPYRIGHT_PLAIN = 'Contents © {date} {author} {license}' RSS_COPYRIGHT_FORMATS = CONTENT_FOOTER_FORMATS # To use comments, you can choose between different third party comment # systems. The following comment systems are supported by Nikola: # disqus, facebook, googleplus, intensedebate, isso, livefyre, muut # You can leave this option blank to disable comments. COMMENT_SYSTEM = "" # And you also need to add your COMMENT_SYSTEM_ID which # depends on what comment system you use. The default is # "nikolademo" which is a test account for Disqus. More information # is in the manual. #COMMENT_SYSTEM_ID = "mosquitto" # Enable annotations using annotateit.org? # If set to False, you can still enable them for individual posts and pages # setting the "annotations" metadata. # If set to True, you can disable them for individual posts and pages using # the "noannotations" metadata. # ANNOTATIONS = False # Create index.html for page folders? # WARNING: if a page would conflict with the index file (usually # caused by setting slug to `index`), the PAGE_INDEX # will not be generated for that directory. # PAGE_INDEX = False # Enable comments on pages (i.e. not posts)? # COMMENTS_IN_PAGES = False # Enable comments on picture gallery pages? # COMMENTS_IN_GALLERIES = False # What file should be used for directory indexes? # Defaults to index.html # Common other alternatives: default.html for IIS, index.php # INDEX_FILE = "index.html" # If a link ends in /index.html, drop the index.html part. # http://mysite/foo/bar/index.html => http://mysite/foo/bar/ # (Uses the INDEX_FILE setting, so if that is, say, default.html, # it will instead /foo/default.html => /foo) # (Note: This was briefly STRIP_INDEX_HTML in v 5.4.3 and 5.4.4) STRIP_INDEXES = True # Should the sitemap list directories which only include other directories # and no files. # Default to True # If this is False # e.g. /2012 includes only /01, /02, /03, /04, ...: don't add it to the sitemap # if /2012 includes any files (including index.html)... add it to the sitemap # SITEMAP_INCLUDE_FILELESS_DIRS = True # List of files relative to the server root (!) that will be asked to be excluded # from indexing and other robotic spidering. * is supported. Will only be effective # if SITE_URL points to server root. The list is used to exclude resources from # /robots.txt and /sitemap.xml, and to inform search engines about /sitemapindex.xml. # ROBOTS_EXCLUSIONS = ["/archive.html", "/category/*.html"] # Instead of putting files in .html, put them in /index.html. # No web server configuration is required. Also enables STRIP_INDEXES. # This can be disabled on a per-page/post basis by adding # .. pretty_url: False # to the metadata. PRETTY_URLS = True # If True, publish future dated posts right away instead of scheduling them. # Defaults to False. # FUTURE_IS_NOW = False # If True, future dated posts are allowed in deployed output # Only the individual posts are published/deployed; not in indexes/sitemap # Generally, you want FUTURE_IS_NOW and DEPLOY_FUTURE to be the same value. # DEPLOY_FUTURE = False # If False, draft posts will not be deployed # DEPLOY_DRAFTS = True # Allows scheduling of posts using the rule specified here (new_post -s) # Specify an iCal Recurrence Rule: http://www.kanzaki.com/docs/ical/rrule.html # SCHEDULE_RULE = '' # If True, use the scheduling rule to all posts by default # SCHEDULE_ALL = False # Do you want a add a Mathjax config file? # MATHJAX_CONFIG = "" # If you want support for the $.$ syntax (which may conflict with running # text!), just use this config: # MATHJAX_CONFIG = """ # # """ # Want to use KaTeX instead of MathJax? While KaTeX may not support every # feature yet, it's faster and the output looks better. # USE_KATEX = False # KaTeX auto-render settings. If you want support for the $.$ syntax (which may # conflict with running text!), just use this config: # KATEX_AUTO_RENDER = """ # delimiters: [ # {left: "$$", right: "$$", display: true}, # {left: "\\\[", right: "\\\]", display: true}, # {left: "$", right: "$", display: false}, # {left: "\\\(", right: "\\\)", display: false} # ] # """ # Do you want to customize the nbconversion of your IPython notebook? # IPYNB_CONFIG = {} # With the following example configuration you can use a custom jinja template # called `toggle.tpl` which has to be located in your site/blog main folder: # IPYNB_CONFIG = {'Exporter':{'template_file': 'toggle'}} # What Markdown extensions to enable? # You will also get gist, nikola and podcast because those are # done in the code, hope you don't mind ;-) # Note: most Nikola-specific extensions are done via the Nikola plugin system, # with the MarkdownExtension class and should not be added here. # The default is ['fenced_code', 'codehilite'] #MARKDOWN_EXTENSIONS = ['fenced_code', 'codehilite', 'extra', 'toc'] MARKDOWN_EXTENSIONS = ['markdown.extensions.fenced_code', 'markdown.extensions.codehilite', 'markdown.extensions.extra', 'markdown.extensions.toc'] # Options to be passed to markdown extensions (See https://python-markdown.github.io/reference/) # Default is {} (no config at all) MARKDOWN_EXTENSION_CONFIGS = { DEFAULT_LANG: { 'markdown.extensions.toc':{ 'toc_depth':2 } } } # Extra options to pass to the pandoc command. # by default, it's empty, is a list of strings, for example # ['-F', 'pandoc-citeproc', '--bibliography=/Users/foo/references.bib'] # Pandoc does not demote headers by default. To enable this, you can use, for example # ['--base-header-level=2'] # PANDOC_OPTIONS = [] # Social buttons. This is sample code for AddThis (which was the default for a # long time). Insert anything you want here, or even make it empty (which is # the default right now) # (translatable) # SOCIAL_BUTTONS_CODE = """ # #
# Share #
  • #
  • #
  • #
  • #
#
# # # """ # Show link to source for the posts? # Formerly known as HIDE_SOURCELINK (inverse) SHOW_SOURCELINK = False # Copy the source files for your pages? # Setting it to False implies SHOW_SOURCELINK = False COPY_SOURCES = False # Modify the number of Post per Index Page # Defaults to 10 # INDEX_DISPLAY_POST_COUNT = 10 # By default, Nikola generates RSS files for the website and for tags, and # links to it. Set this to False to disable everything RSS-related. # GENERATE_RSS = True # By default, Nikola does not generates Atom files for indexes and links to # them. Generate Atom for tags by setting TAG_PAGES_ARE_INDEXES to True. # Atom feeds are built based on INDEX_DISPLAY_POST_COUNT and not FEED_LENGTH # Switch between plain-text summaries and full HTML content using the # FEED_TEASER option. FEED_LINKS_APPEND_QUERY is also respected. Atom feeds # are generated even for old indexes and have pagination link relations # between each other. Old Atom feeds with no changes are marked as archived. # GENERATE_ATOM = False # Only include teasers in Atom and RSS feeds. Disabling include the full # content. Defaults to True. # FEED_TEASERS = True # Strip HTML from Atom and RSS feed summaries and content. Defaults to False. # FEED_PLAIN = False # Number of posts in Atom and RSS feeds. # FEED_LENGTH = 10 # Include preview image as a
at the top of the entry. # Requires FEED_PLAIN = False. If the preview image is found in the content, # it will not be included again. Image will be included as-is, aim to optimize # the image source for Feedly, Apple News, Flipboard, and other popular clients. # FEED_PREVIEWIMAGE = True # RSS_LINK is a HTML fragment to link the RSS or Atom feeds. If set to None, # the base.tmpl will use the feed Nikola generates. However, you may want to # change it for a FeedBurner feed or something else. # RSS_LINK = None # A search form to search this site, for the sidebar. You can use a Google # custom search (https://www.google.com/cse/) # Or a DuckDuckGo search: https://duckduckgo.com/search_box.html # Default is no search form. # (translatable) # SEARCH_FORM = "" # # This search form works for any site and looks good in the "site" theme where # it appears on the navigation bar: # # SEARCH_FORM = """ # # # # """ % SITE_URL # # If you prefer a Google search form, here's an example that should just work: # SEARCH_FORM = """ # # # # """ % SITE_URL # Use content distribution networks for jQuery, twitter-bootstrap css and js, # and html5shiv (for older versions of Internet Explorer) # If this is True, jQuery and html5shiv are served from the Google CDN and # Bootstrap is served from BootstrapCDN (provided by MaxCDN) # Set this to False if you want to host your site without requiring access to # external resources. # USE_CDN = False # Check for USE_CDN compatibility. # If you are using custom themes, have configured the CSS properly and are # receiving warnings about incompatibility but believe they are incorrect, you # can set this to False. # USE_CDN_WARNING = True # Extra things you want in the pages HEAD tag. This will be added right # before # (translatable) # EXTRA_HEAD_DATA = "" # Google Analytics or whatever else you use. Added to the bottom of # in the default template (base.tmpl). # (translatable) # BODY_END = "" # The possibility to extract metadata from the filename by using a # regular expression. # To make it work you need to name parts of your regular expression. # The following names will be used to extract metadata: # - title # - slug # - date # - tags # - link # - description # # An example re is the following: # '.*\/(?P\d{4}-\d{2}-\d{2})-(?P.*)-(?P.*)\.rst' # (Note the '.*\/' in the beginning -- matches source paths relative to conf.py) # FILE_METADATA_REGEXP = None # If you hate "Filenames with Capital Letters and Spaces.md", you should # set this to true. FILE_METADATA_UNSLUGIFY_TITLES = True # Additional metadata that is added to a post when creating a new_post # ADDITIONAL_METADATA = {} # Nikola supports Open Graph Protocol data for enhancing link sharing and # discoverability of your site on Facebook, Google+, and other services. # Open Graph is enabled by default. # USE_OPEN_GRAPH = True # Nikola supports Twitter Card summaries, but they are disabled by default. # They make it possible for you to attach media to Tweets that link # to your content. # # IMPORTANT: # Please note, that you need to opt-in for using Twitter Cards! # To do this please visit https://cards-dev.twitter.com/validator # # Uncomment and modify to following lines to match your accounts. # Images displayed come from the `previewimage` meta tag. # You can specify the card type by using the `card` parameter in TWITTER_CARD. # TWITTER_CARD = { # # 'use_twitter_cards': True, # enable Twitter Cards # # 'card': 'summary', # Card type, you can also use 'summary_large_image', # # see https://dev.twitter.com/cards/types # # 'site': '@website', # twitter nick for the website # # 'creator': '@username', # Username for the content creator / author. # } # If webassets is installed, bundle JS and CSS into single files to make # site loading faster in a HTTP/1.1 environment but is not recommended for # HTTP/2.0 when caching is used. Defaults to True. USE_BUNDLES = False # Plugins you don't want to use. Be careful :-) # DISABLED_PLUGINS = ["render_galleries"] # Special settings to disable only parts of the indexes plugin (to allow RSS # but no blog indexes, or to allow blog indexes and Atom but no site-wide RSS). # Use with care. # DISABLE_INDEXES_PLUGIN_INDEX_AND_ATOM_FEED = False # DISABLE_INDEXES_PLUGIN_RSS_FEED = False # Add the absolute paths to directories containing plugins to use them. # For example, the `plugins` directory of your clone of the Nikola plugins # repository. EXTRA_PLUGINS_DIRS = ['plugins'] # Add the absolute paths to directories containing themes to use them. # For example, the `v7` directory of your clone of the Nikola themes # repository. # EXTRA_THEMES_DIRS = [] # List of regular expressions, links matching them will always be considered # valid by "nikola check -l" # LINK_CHECK_WHITELIST = [] # If set to True, enable optional hyphenation in your posts (requires pyphen) # Enabling hyphenation has been shown to break math support in some cases, # use with caution. # HYPHENATE = False # The <hN> tags in HTML generated by certain compilers (reST/Markdown) # will be demoted by that much (1 → h1 will become h2 and so on) # This was a hidden feature of the Markdown and reST compilers in the # past. Useful especially if your post titles are in <h1> tags too, for # example. # (defaults to 1.) # DEMOTE_HEADERS = 1 # Docutils, by default, will perform a transform in your documents # extracting unique titles at the top of your document and turning # them into metadata. This surprises a lot of people, and setting # this option to True will prevent it. # NO_DOCUTILS_TITLE_TRANSFORM = False # If you don’t like slugified file names ([a-z0-9] and a literal dash), # and would prefer to use all the characters your file system allows. # USE WITH CARE! This is also not guaranteed to be perfect, and may # sometimes crash Nikola, your web server, or eat your cat. # USE_SLUGIFY = True # Templates will use those filters, along with the defaults. # Consult your engine's documentation on filters if you need help defining # those. # TEMPLATE_FILTERS = {} # Put in global_context things you want available on all your templates. # It can be anything, data, functions, modules, etc. GLOBAL_CONTEXT = {} # Add functions here and they will be called with template # GLOBAL_CONTEXT as parameter when the template is about to be # rendered GLOBAL_CONTEXT_FILLER = [] ================================================ FILE: www/files/manifest.json ================================================ { "name": "Mosquitto", "icons": [ { "src": "/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/android-chrome-512x512.png", "sizes": "512x512", "type": "image/png" } ], "theme_color": "#ffffff", "background_color": "#ffffff", "display": "standalone" } ================================================ FILE: www/files/stickers/index.html ================================================ <!DOCTYPE html> <html> <head> <title>Eclipse Mosquitto™ Sticker Generator

Eclipse Mosquitto™ Sticker Generator

This page used to allow you to create a book of square stickers to buy from Moo. Unfortunately they have discontinued their API, so if you want Mosquitto stickers you can use the images and create your own sticker book manually.

Click the logos to choose which to include, then click submit to be taken to the Moo site with a stickerbook ready in your basket. If you choose both logos you will get 45 of each, otherwise you will get 90 of the one you choose.

================================================ FILE: www/pages/documentation/authentication-methods.md ================================================ It is important to configure authentication on your Mosquitto instance, so unauthorised clients cannot connect. In Mosquitto 2.0 and up, you must choose your authentication options explicitly before clients can connect. In earlier versions the default is to allow clients to connect without authentication. There are three choices for authentication: password files, authentication plugins, and unauthorised/anonymous access. It is possible to use a combination of all three choices. It is possible to have different listeners use different authentication methods by setting `per_listener_settings true` in your configuration file. As well as authentication you should also consider some form of access control to determine what clients can access which topics. ## Password files Password files are a simple mechanism of storing usernames and passwords in a single file. They are good if you have a relatively small number of fairly static users. If you make changes to the password file you must trigger the broker to reload the file by sending a SIGHUP message: ``` kill -HUP ``` ### Creating a password file To create a password file, use the `mosquitto_passwd` utility, use the line below. You will be asked for the password. Note that `-c` means an existing file will be overwritten: ``` mosquitto_passwd -c ``` To add more users to an existing password file, or to change the password for an existing user, leave out the `-c` argument: ``` mosquitto_passwd ``` To remove a user from a password file: ``` mosquitto_passwd -D ``` You can also add/update a username and password in a single line, but be aware that this means the password is visible on the command line and in any command history: ``` mosquitto_passwd ``` ### Configuring the broker To start using your password file you must add the `password_file` option to your configuration file: ``` password_file ``` The password file must be able to be read by whatever user Mosquitto is running as. On Linux/POSIX systems this will typically be the `mosquitto` user, and `/etc/mosquitto/password_file` is a good place for the file itself. If you are using the `per_listener_settings true` option to have separate security settings per listener, you must place the password file option *after* the listener it is for: ``` listener 1883 password_file /etc/mosquitto/password_file ``` ## Authentication plugins If you want more control over authentication of your users than is offered by a password file, then an authentication plugin may be suitable for you. The features offered depend on which plugin you use. ### Configuring the plugin Configuring a plugin varies depending on the version of Mosquitto plugin interface the plugin was written for, either version 2.0 and up, or 1.6.x and earlier. For 1.6.x and below, use the `auth_plugin` option. These plugins are also supported by version 2.0: ``` listener 1883 auth_plugin ``` Some plugins require extra configuration which will be described in their documentation. For 2.0 and up, use the `plugin` option: ``` listener 1883 plugin ``` ### Available plugins * [Dynamic security](https://mosquitto.org/documentation/dynamic-security/), for 2.0 and up only, provided by the Mosquitto project to give flexible in-broker clients, groups, and roles that can be administered remotely. * [mosquitto-go-auth](https://github.com/iegomez/mosquitto-go-auth), which offers the use of a variety of backends to store user data, such as mysql, jwt, or redis. ## Unauthenticated access To configure unauthenticated access, use the `allow_anonymous` option: ``` listener 1883 allow_anonymous true ``` It is valid to allow anonmous and authenticated access on the same broker. In particular the dynamic security plugin allows you to assign different rights to anonymous users than to authenticated users, which may be useful for read-only access to data for example. ================================================ FILE: www/pages/documentation/dynamic-security.md ================================================ [TOC] ## Introduction The Dynamic Security plugin is a Mosquitto plugin which provides role based authentication and access control features that can be updated whilst the broker is running, using a special topic based API. It is supported since Mosquitto 2.0, and should be available in all installations, but will not be activated by default. ## Concepts This section describes the concepts of how the plugin operates. If you want to find out how to use the plugin features, look in the [Installation] section below. The plugin allows you to create three main objects, `clients`, `groups`, and `roles`. This document will use the term `clients` to mean the clients defined in the plugin, and `devices` or `users` to mean the MQTT clients that connect to the broker. --- ### Clients When you want a device or user to be able to connect and authenticate to the broker, you create a client. Each client has the following attributes: #### Username The client username maps to the username provided in the CONNECT packet when a device connects. The username is unique across the plugin, so attempting to create a client with a duplicate username will result in an error. The username acts as the primary key if you want to change anything about the client. #### Password The client password maps to the password provided in the CONNECT packet when a device connects. The password may be unset when a client is created, this will mean that devices will be unable to connect as the corresponding client. The password can be updated at any point, but only by a client with the correct access. Devices typically cannot update their own passwords. #### Client ID The client id maps to the client id provided in the CONNECT packet when a device connects. This is an optional attribute. If the client id is empty or not provided, then any device can connect with the username for this client regardless of its client id. This means that multiple devices could connect with the same credentials at the same time, but sharing credentials between devices is not recommended. If the client id is set, then a device can only connect as this client if the triple of username, password, and client id all match those in the client. #### Groups A client can be a member of any number of groups. #### Roles A client can be assigned to any number of roles. A role gives the client access to different topics. #### Text name This is an optional text field to give a human friendly name to this client. #### Text description This is an optional text field to give a human friendly description to this client. #### Disabled A client can be set to be enabled/disabled at any point. Disabling a client means that any devices currently connected using the credentials for that client will be disconnected and unable to reconnect. --- ### Groups Multiple clients can be placed in a group. Groups can have roles assigned to them, so using groups is appropriate where you have a number of clients that need to have the same access. Groups have the following attributes: #### Group name The group name is the primary name for the group. It is used when modifying the group in any way, such as adding a client or a role. #### Roles A group can be assigned to any number of roles. A role gives the group access to different topics. #### Text name This is an optional text field to give a human friendly name to this group. #### Text description This is an optional text field to give a human friendly description to this group. --- ### Roles Roles contain multiple access control lists (ACLs), and can be assigned to clients and/or groups. Roles have the following attributes: #### Role name The role name is the primary name for the role. It is used when modifying the role in any way, such as adding an ACL. #### Access Control Lists ACLs are the feature which allows access to topics to be controlled. Checks are made on different events as they happen: `publishClientSend`, `publishClientReceive`, `subscribe`, and `unsubscribe`. The `publishClientSend` event occurs when a device sends a PUBLISH message to the broker, i.e. "is the device allowed to publish to this topic". The `publishClientReceive` event occurs when a device is due to receive a PUBLISH message from the broker, i.e. it has a valid subscription and a matching message has been published to the broker. The `subscribe` event occurs in response to a device sending a SUBSCRIBE message, and the `unsubscribe` event occurs in response to a device sending an UNSUBSCRIBE packet. The default behaviour of the different events can be set to allow or deny access. The default behaviour applies if no matching ACL is found. The default behaviour for the different events when the plugin has first been configured is: * `publishClientSend`: deny * `publishClientReceive`: allow * `subscribe`: deny * `unsubscribe`: allow There is some overlap between `publishClientReceive` and `subscribe`. In most cases, using a `subscribe` ACL is sufficient to provide the control you need, however by combining the two types it is possible to e.g. allow subscriptions to a wildcard topic like `topic/#`, but deny access for device to receive messages on a specific topic within that hierarchy like 'topic/secret'. The different events have ACL types associated with them, and it is these ACLs that you will add to your roles. Each ACL has a `topic`, a `priority`, and can be set to `allow` or `deny`. The `publishClientSend` and `publishClientReceive` ACL types map directly to the events of the same name. The topic can contain wildcards, so allowing send access to `topic/#` will allow devices to publish to all topics in the `topic/#` hierarchy, including `topic`. The `subscribe` and `unsubscribe` events have two ACL types each: `subscribeLiteral`, `subscribePattern`, `unsubscribeLiteral`, and `unsubscribePattern`. The `*Literal` ACL types make a literal comparison between the topic filter provided for the ACL and the topic filter provided in the SUBSCRIBE or UNSUBSCRIBE message. This means that setting a `subscribeLiteral` ACL with topic filter `#` to deny would prevent matching devices from subscribing the the `#` topic filter only, but still allow them to subscribe to `topic/#`, for example. The `*Pattern` ACL types allow or deny access based on a wildcard comparison of the ACL topic filter and the topic provided in the SUBSCRIBE or UNSUBSCRIBE message. This means that setting a `subscribePattern` ACL with topic filter `#` to deny would prevent matching devices from subscribing to any topic at all. #### ACL pattern substitution The `publishClientSend`, `publishClientReceive`, `subscribePattern`, and `unsubscribePattern` ACL types can make use of pattern substitution. This means that the strings `%c` and `%u` will be replaced with the client id and username of the client being checked, respectively. The pattern strings must be the only item in that level of hierarchy, so the ACL `topic/%count` will not be considered as a pattern. For example, with an ACL of `room/%c/temperature`, a client connecting with client id `kitchen` would be allowed to use the topic `room/kitchen/temperature` only. If a client does not have a username, a pattern that includes `%u` will always fail to match against that client. #### Text name This is an optional text field to give a human friendly name to this role. #### Text description This is an optional text field to give a human friendly description to this role. --- ### Priorities If you are working with more than one role per client or group, or more than one group per client, then it is crucial to understand how roles and ACLs are applied. The order in which checks are made is determined in part by the `priority` of groups, roles and ACLs. Each client group has a priority, each client role and group role has a priority, and each ACL within a role has a priority. If not set explicitly, priorities will default to -1. Priority has a maximum of 100000. For each of the group, role, and ACL objects, checks are made in priority order from the highest numerical value to the lowest numerical value. If two objects of the same type have the same priority, then they will be checked in lexicographical order according to the username/groupname/rolename, but it is advised to use unique priorities per object type. When an event occurs that needs an ACL check, the ACLs for that ACL type are checked in order until there is a matching ACL for the topic in question. Within each role that is checked, the ACLs are checked in priority order. If ACLs have identical priority, they are evaluated in the order shown in the `getRole` command. The roles assigned to a client are checked first, in priority order. Each client group is checked in priority order, with all of the roles in a group being checked in priority order before the next group is checked. As an example, let us assume we have the following client, groups, and roles: Client: `sensor` Groups: `temperature` (priority 2), `humidity` (priority 1) Roles: `hallway` Group: `temperature` Roles: `input` (priority 5), `output` (priority 1) Group: `humidity` Roles: `humidity` Role: `hallway` ACLs: `Z` (priority 3), `A` (priority 1) Role: `input` ACLs: `Z` (priority 3), `A` (priority 3) Role: `output` ACLs: `Z` (priority 3), `A` (priority 1) Role: `humidity` ACLs: `Z` (priority 3), `A` (priority 1) We are also assuming we are only looking at single ACL type. If our client `sensor` triggers an ACL check, the ACLs will be checked in this order, and the first matching ACL will be used to allow/reject the event: 1. sensor/hallway Z 2. sensor/hallway A 3. temperature/input A (alphabetical sort) 4. temperature/input Z (alphabetical sort) 5. temperature/output Z 6. temperature/output A 7. humidity/humidity Z 8. humidity/humidity A This is provided as an example that covers all combinations of roles, it is recommended to use as simple a setup as possible for your situation. ### Anonymous access All of the documentation so far assumes that you do not allow anonymous unauthenticated access - meaning devices or users that connect without a username. You may wish to allow anonymous access, but still make use of the dynamic security plugin, and this is supported through the automatic anonymous group. If allowed, anything connecting without a username will be assigned to a group that you define. By assigning roles to that group, you can control what anonymous devices can access. ## Installation To use the Dynamic Security plugin, it must be configured in the broker and an initial plugin configuration must be generated. To configure the broker, add the following to your configuration file. Linux/BSD: ``` plugin path/to/mosquitto_dynamic_security.so plugin_opt_config_file path/to/dynamic-security.json ``` Windows: ``` plugin path\to\mosquitto_dynamic_security.dll plugin_opt_config_file path\to\dynamic-security.json ``` On Linux you would expect the plugin library to be installed to `/usr/lib/x86_64-linux-gnu/mosquitto_dynamic_security.so` or a similar path, but this will vary depending on the particular distribution and hardware in use. It is recommended to use `per_listener_settings false` with this plugin, so all listeners use the same authentication and access control. The `dynamic-security.json` file is where the plugin configuration will be stored. This file will be updated each time you make client/group/role changes, during normal operation the configuration stays in memory. ### Generating the configuration file - 2.1 onwards To generate your initial configuration file there are a few choices. In version 2.0.x, you must use the `mosquitto_ctrl` utility as described below. From version 2.1 onwards, if the configuration file does not exist, the plugin will attempt to generate a default configuration file with some sensible defaults. The roles created are: * `broker-admin` - grants access to administer general broker settings * `client` - read/write access to the full application topic hierarchy '#' * `dynsec-admin` - grants access to administer clients/groups/roles * `super-admin` - grants access to administer any `$CONTROL` APIs * `sys-notify` - allow bridges to publish connection state messages * `sys-observe` - allow read only access to the $SYS/# topic hierarchy * `topic-observe` - allow read only access to the full application topic hierarchy '#' The groups created are: * `unauthenticated` - automatic group that anonymous/unauthenticated clients are placed in, if anonymous access is allowed. The initial users can be generated in three different ways, as described below. #### Initialisation file Create a text file with a single line. This line will be used as the password for the `admin` user, which will have access to administer the dynamic security plugin. Set the configuration option to trigger the use of this file: ``` plugin_opt_password_init_file path/to/init-file ``` Once the initial run of the broker has been done, the init file can be deleted. This method is well suited to use with e.g. docker secrets inside a container. #### Environment variable Set the `MOSQUITTO_DYNSEC_PASSWORD` environment variable to a string text and it will be used as the password for the `admin` user, which will have access to administer the dynamic security plugin. #### Default If neither `plugin_opt_password_init_file` nor `MOSQUITTO_DYNSEC_PASSWORD` are set, then the plugin will generate random passwords and store them in *plain text* at `.pw`, for example `dynamic-security.json.pw`. This file should be deleted once the passwords are known. Two users will be created, `admin`, which will have access to administer the dynamic security plugin, and `democlient`, which will have read/write access to the application topic hierarchy `#`. ### Generating the configuration file - 2.0 onwards To generate an initial file using the `mosquitto_ctrl` utility: ``` mosquitto_ctrl dynsec init path/to/dynamic-security.json admin-user ``` Choose your own `admin-user` username. You will be asked for a password for the client. This user will be assigned the `admin` role, which has the following access: * publishClientSend: `$CONTROL/dynamic-security/#` - this allows the client to control the Dynamic security plugin. * publishClientReceive: `$CONTROL/dynamic-security/#` - this allows the client to receive information from the plugin. This is not necessary in the default configuration, but is included in case the default behaviour for `publishClientReceive` is set to `deny`. * subscribePattern: `$CONTROL/dynamic-security/#` - this allows the client to receive information from the plugin. * publishClientReceive: `$SYS/#` - this allows the client to see the broker metrics. * subscribePattern: `$SYS/#` - this allows the client to see the broker metrics. * publishClientReceive: `#` - this allows the client to examine the messages being published by other clients. * subscribePattern: `#` - this allows the client to examine the messages being published by other clients. * unsubscribePattern: `#` - this allows the client to undo previous subscriptions. This is not necessary in the default configuration, but is included in case the default behaviour for `unsubscribe` is set to `deny`. The admin user does not have access to publish to normal application topics in the `#` hierarchy by default. You are strongly encouraged to keep the admin user purely for administering the plugin, and create other clients for your application. ## Usage All control of the plugin after initial installation is through the MQTT topic API at `$CONTROL/dynamic-security/v1`. This allows integrations to be built, but isn't the best choice for people to use directly. The `mosquitto_ctrl` command provided with Mosquitto implements support for the dynamic security plugin API, as described below. Other options include the [Management Center for Mosquitto](https://docs.cedalo.com/latest/) which is an open source web based tool for controlling the plugin and other features. The Management Center is not part of the Mosquitto project. ### Using mosquitto_ctrl with a running broker The initial configuration is the only time that `mosquitto_ctrl` does not connect to a broker to carry out the configuration. All other commands require a connection to a broker, and hence a username, password, and whatever else is required for that particular connection. It is strongly recommended that your broker connection uses encryption so that your configuration, including new passwords, is not transmitted in plain text. The connection options must be given before the `dynsec` part of the command line: ``` mosquitto_ctrl dynsec ... ``` For example: ``` mosquitto_ctrl -u admin -h localhost dynsec ... ``` It is possible to provide the admin password on the command line using `-P password`, but this is not recommended. If you do not provide a password, mosquitto_ctrl will ask you to enter the password when it is needed. ### Using an options file For convenience, mosquitto_ctrl can load an options file which contains a list of options it should use. This means you can set the encryption options, host, admin username and any other options once and not have to add them to the command line every time. mosquitto_ctrl will try to load a configuration file from a default location. For Windows this is at `%USER_PROFILE%\mosquitto_ctrl`. For other systems, it will try `$XDG_CONFIG_HOME/mosquitto_ctrl` or `$HOME/.config/mosquitto_ctrl`. You may override this behaviour by manually specifying an options file with `-o `. The options file should contain a list of options, one per line, exactly as they would be provided on the command line. For example: ``` --cafile /path/to/my/CA.crt --cert /path/to/my/client.crt --key /path/to/my/client.key -u admin -h mosquitto.example.com ``` ### mosquitto_ctrl options * `-A address` : Bind the outgoing connection to a local ip address/hostname. Use this argument if you need to restrict network communication to a particular interface. * `--cafile path-to-ca.crt` : Define the path to a file containing PEM encoded CA certificates that are trusted. Used to enable SSL communication. See also `--capath` * `--capath` : Define the path to a directory containing PEM encoded CA certificates that are trusted. Used to enable SSL communication. 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. See also `--cafile`. * `--cert path-to-client.crt` : Define the path to a file containing a PEM encoded certificate for this client, if required by the server. See also `--key`. * `--ciphers` : An openssl compatible list of TLS ciphers to support in the client. See ciphers(1) for more information. * `-d` : Enable debug messages. * `--help` : Display usage information. * `-h hostname` : Specify the host to connect to. Defaults to localhost. * `-i client-id` : 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 mosq-XXXXXXXXXXXXXXXXXX, where the X 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. * `--insecure` : 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. * `--key path-to-client.key` : Define the path to a file containing a PEM encoded private key for this client, if required by the server. See also `--cert`. * `-L url` : 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]`. If the scheme is mqtt:// then the port defaults to 1883. If the scheme is mqtts:// then the port defaults to 8883. * `--nodelay` : 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. * `-p port` : Connect to the port specified. If not given, the default of 1883 for plain MQTT or 8883 for MQTT over TLS will be used. * `-P password` : 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 `-u` option. * `--proxy proxy-url` : Specify a SOCKS5 proxy to connect through. "None" and "username" authentication types are supported. The socks-url must be of the form `socks5h://[username[:password]@]host[:port]`. The protocol prefix socks5h 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. * `--psk key` : Provide the hexadecimal (no leading 0x) pre-shared-key matching the one used on the broker to use TLS-PSK encryption support. `--psk-identity` must also be provided to enable TLS-PSK. * `--psk-identity identify` : 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. * `-q qos` : Specify the quality of service to use for messages, from 0, 1 and 2. Defaults to 1. * `--quiet` : 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 `-p` without a port). * `--tls-version version` : Choose which TLS protocol version to use when communicating with the broker. Valid options are tlsv1.3 and tlsv1.2. The default value is tlsv1.2. Must match the protocol version used by the broker. * `-u username` : Provide a username to be used for authenticating with the broker. See also the `-P` argument. * `--unix path` : Connect to a broker through a local unix domain socket instead of a TCP socket. This is a replacement for `-h` and `-L`. For example: `mosquitto_ctrl --unix /tmp/mosquitto.sock ...`. * `-V protocol-version` : Specify which version of the MQTT protocol should be used when connecting to the remote broker. Can be `5`, `311`, `31`, or the more verbose `mqttv5`, `mqttv311`, or `mqttv31`. Defaults to `311`. ## Configuring default access The initial configuration sets the default ACL type behaviours to: * `publishClientSend`: deny * `publishClientReceive`: allow * `subscribe`: deny * `unsubscribe`: allow If you wish to change these, use `mosquitto_ctrl`. ``` mosquitto_ctrl dynsec setDefaultACLAccess publishClientSend deny mosquitto_ctrl dynsec setDefaultACLAccess publishClientReceive deny mosquitto_ctrl dynsec setDefaultACLAccess subscribe deny mosquitto_ctrl dynsec setDefaultACLAccess unsubscribe deny ``` You can examine the current default access with the `getDefaultACLAccess` command: ``` mosquitto_ctrl dynsec getDefaultACLAccess unsubscribe ``` ## Creating and modifying clients To create a new client: ``` mosquitto_ctrl dynsec createClient ``` This creates a client which does not have a client id associated with it. You will be asked for the password for the new client before you are asked for the admin user password. Pay attention to the messages on the command line. ``` mosquitto_ctrl dynsec createClient -i ``` This creates a client which has a client id associated with it. To delete a client (clients connected with these credentials will be disconnected from the broker): ``` mosquitto_ctrl dynsec deleteClient ``` To disable a client (clients connected with these credentials will be disconnected from the broker): ``` mosquitto_ctrl dynsec disableClient ``` To enable a client (clients will be able to use these credentials to log in again): ``` mosquitto_ctrl dynsec enableClient ``` To set a client password: ``` mosquitto_ctrl dynsec setClientPassword mosquitto_ctrl dynsec setClientPassword ``` To add/remove a role to/from a client: ``` mosquitto_ctrl dynsec addClientRole mosquitto_ctrl dynsec removeClientRole ``` To get information on a client: ``` mosquitto_ctrl dynsec getClient ``` To list all clients: ``` mosquitto_ctrl dynsec listClients ``` This gives an output that is a list of client usernames: ``` client1 client2 ``` The `modifyClient` command also exists in the topic API, but is not currently available in `mosquitto_ctrl`. ## Creating and modifying groups To create a new group: ``` mosquitto_ctrl dynsec createGroup ``` To delete a group: ``` mosquitto_ctrl dynsec deleteGroup ``` To add/remove a client to/from a group: ``` mosquitto_ctrl dynsec addGroupClient mosquitto_ctrl dynsec removeGroupClient ``` In this case the `priority` refers to the priority of the group within the client's list of groups. To add/remove a role to/from a group: ``` mosquitto_ctrl dynsec addGroupRole mosquitto_ctrl dynsec removeGroupRole ``` To set/get the group that anonymous devices are assigned to: ``` mosquitto_ctrl dynsec setAnonymousGroup mosquitto_ctrl dynsec getAnonymousGroup ``` To get information on a group: ``` mosquitto_ctrl dynsec getGroup ``` To list all groups: ``` mosquitto_ctrl dynsec listGroups ``` The `modifyGroup` command also exists in the topic API, but is not currently available in `mosquitto_ctrl`. ## Creating and modifying roles To create a new role: ``` mosquitto_ctrl dynsec createRole ``` To delete a role: ``` mosquitto_ctrl dynsec deleteRole ``` To add an ACL to a role: ``` mosquitto_ctrl dynsec addRoleACL allow|deny ``` Where `acltype` is one of `publishClientSend`, `publishClientReceive`, `subscribeLiteral`, `subscribePattern`, `unsubscribeLiteral`, and `unsubscribePattern`. For example: ``` mosquitto_ctrl dynsec addRoleACL publishClientSend client/topic allow 5 ``` To remove an ACL from a role using the topic filter as the key: ``` mosquitto_ctrl dynsec removeRoleACL ``` For example: ``` mosquitto_ctrl dynsec removeRoleACL publishClientSend client/topic ``` To get information on a role: ``` mosquitto_ctrl dynsec getRole ``` To list all roles: ``` mosquitto_ctrl dynsec listRoles ``` The `modifyRole` command also exists in the topic API, but is not currently available in `mosquitto_ctrl`. ================================================ FILE: www/pages/documentation/listeners/haproxy.md ================================================ [TOC] ## Introduction Using Mosquitto as an entirely standalone broker works very well, but sometimes you may wish to place it behind a load balancer / proxy such as [HAProxy]. This provides certain advantages such as carrying out TLS termination in the proxy to reduce load on the broker. It does have one disadvantage which is that only the proxy IP address is found in the broker logs - the client IP addresses are not seen. Since Mosquitto 2.1, this can be fixed using the PROXY protocol v2 support, which can be enabled using the `enable_proxy_protocol 2` option. This is the recommended mode when using HAProxy. The PROXY protocol v1 is also supported with `enable_proxy_protocol 1`. This version of the protocol has a reduced feature set, particularly around sending on TLS related information, however it is more widely supported than v2. This document describes some different ways you can combine Mosquitto and HAProxy. It is not a complete guide to HAProxy. **Important:** Enabling PROXY protocol support requires that the broker itself is not directly accessible on its network port. All communication must go through the broker. If a client is able to connect to the broker directly, it is trivial to spoof connection information and this is especially important when using client certificates for mutual TLS on HAProxy. In that case, the contents of the PROXY header can directly indicate whether a client is allowed to connect so it must be protected. It may be desirable to use a firewall to restrict access to the broker port. ## General setup All examples presented will be of the `haproxy.cfg` file, typically located at `/etc/haproxy/haproxy.cfg` on a native Linux installation. The first part of the config file contains the `global` and `defaults` sections which are going to be common to all of the examples and not repeated. ### Global section This is a fairly standard global section, presented without comment. ``` global log /dev/log local0 log /dev/log local1 notice user haproxy group haproxy daemon # Default SSL material locations ca-base /etc/ssl/certs crt-base /etc/ssl/private # See: https://ssl-config.mozilla.org/#server=haproxy&server-version=2.0.3&config=intermediate ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384 ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256 ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets ``` ### Defaults section ``` defaults mode tcp timeout connect 5000 timeout client 60000 timeout server 60000 ``` * `mode tcp` - set TCP mode rather than HTTP mode by default. MQTT is not HTTP. * `timeout connect 5000` - the timeout allowed for a client to connect, in milliseconds. * `timeout client 60000` - if a client does not communicate in this interval, the connection will be closed by HAProxy. * `timeout server 60000` - if the broker does not communicate in this interval, the connection will be closed by HAProxy. The client and server timeout intervals should be chosen based on the intervals you expect to have communication occurring in your clients. If your communication is typically very sparse, the timeout should be chosen based on the keepalive interval you are using, otherwise the quiet clients will be disconnected before they have chance to send a keepalive request. ## Direct pass through, without PROXY protocol The most basic approach is to pass connections directly through HAProxy to Mosquitto without being modified. This means that if an unencrypted MQTT connection is made, it will pass throughas an unencrypted connection, and if an encrypted MQTT connection is made it will pass through as an encrypted MQTT connection. Likewise, websockets connections are passed through unaffected. Create a frontend, which is where HAProxy will listen for connections, and a backend which is where the broker that HAProxy will connect to is defined. ``` frontend mqtt_frontend bind *:1883 default_backend mqtt_backend backend mqtt_backend server server1 127.0.0.1:1884 check on-marked-down shutdown-sessions ``` In this case, HAProxy is listening on all interfaces on port 1883 and will attempt to connect to the broker on address 127.0.0.1 on port 1884. In other words, HAProxy and Mosquitto are running on the same instance. This is not required. The broker configuration could be with an encrypted or unencrypted listener: Unencrypted: ``` listener 1884 # Further listener settings ``` Encrypted: ``` listener 1884 certfile keyfile # Further listener settings ``` ## TLS termination with server certificate only, without PROXY protocol Place your server certificate and private key in `/etc/haproxy/certs/`. ``` frontend mqtts_frontend bind 0.0.0.0:8883 ssl crt /etc/haproxy/certs/ backend mqtt_backend server server1 127.0.0.1:1883 check on-marked-down shutdown-sessions ``` The broker configuration should declare an unencrypted listener: ``` listener 1883 # Further listener settings ``` ## TLS termination with mutual TLS - client and server certificates, without PROXY protocol In addition to the server certificate, you must also provide the CA certificate that will sign the client certificates, ask for verification of the client certificate and make the certificate required. ``` frontend mqtts_frontend bind *:8883 ssl crt /etc/haproxy/certs/ verify required ca-file /etc/haproxy/client-ca.crt default_backend mqtt_backend backend mqtt_backend server server1 127.0.0.1:1883 check on-marked-down shutdown-sessions ``` The broker configuration should declare an unencrypted listener: ``` listener 1883 # Further listener settings ``` ## Direct pass through, with PROXY protocol v2 To enable PROXY protocol v2 on HAProxy, add the `send-proxy-v2` option to the backend. ``` frontend mqtt_frontend bind *:1883 default_backend mqtt_backend backend mqtt_backend server server1 127.0.0.1:1884 check on-marked-down shutdown-sessions send-proxy-v2 ``` The broker configuration should declare an unencrypted listener and enable PROXY protocol v2 support. It is not possible to have direct pass through with encrypted connections on the broker. ``` listener 1883 enable_proxy_protocol 2 # Further listener settings ``` ## Direct pass through, with PROXY protocol v1 To enable PROXY protocol v1 on HAProxy, add the `send-proxy` option to the backend. ``` frontend mqtt_frontend bind *:1883 default_backend mqtt_backend backend mqtt_backend server server1 127.0.0.1:1884 check on-marked-down shutdown-sessions send-proxy ``` The broker configuration should declare an unencrypted listener and enable PROXY protocol v1 support. It is not possible to have direct pass through with encrypted connections on the broker. ``` listener 1883 enable_proxy_protocol 1 # Further listener settings ``` ## TLS termination with server certificate only, with PROXY protocol v2 For TLS connections, use `send-proxy-v2-ssl` instead of `send-proxy-v2`. This ensures that TLS information is added to the PROXY header. ``` frontend mqtts_frontend bind *:8883 ssl crt /etc/haproxy/certs/ default_backend mqtt_backend backend mqtt_backend server server1 127.0.0.1:1883 check on-marked-down shutdown-sessions send-proxy-v2-ssl ``` On the broker side, use `proxy_protocol_v2_require_tls true` to ensure that only connections that were made using TLS are accepted on the broker. No other TLS configuration is required. ``` listener 1883 enable_proxy_protocol 2 proxy_protocol_v2_require_tls true ``` ## TLS termination with mutual TLS - client and server certificate, with PROXY protocol v2 For TLS connections, use `send-proxy-v2-ssl` instead of `send-proxy-v2`. This ensures that TLS information is added to the PROXY header. ``` frontend mqtts_frontend bind *:8883 ssl crt /etc/haproxy/certs/ verify required ca-file /etc/haproxy/client-ca.crt default_backend mqtt_backend backend mqtt_backend server server1 127.0.0.1:1883 check on-marked-down shutdown-sessions send-proxy-v2-ssl ``` The broker configuration uses `require_certificate true` to indicate that the broker should check the PROXY protocol header for the valid certificate result. No other TLS configuration is required. ``` listener 1883 enable_proxy_protocol 2 proxy_protocol_v2_require_tls true require_certificate true ``` ## TLS termination with mutual TLS - client and server certificate, with username and PROXY protocol v2 The Mosquitto option `use_identity_as_username true` can be used with the PROXY protocol support. This requires that the `send-proxy-v2-ssl-cn` option is used on HAProxy. It is not possible to use `use_subject_as_username` with the PROXY protocol. ``` frontend mqtts_frontend bind *:8883 ssl crt /etc/haproxy/certs/ verify required ca-file /etc/haproxy/client-ca.crt default_backend mqtt_backend backend mqtt_backend server server1 127.0.0.1:1883 check on-marked-down shutdown-sessions send-proxy-v2-ssl-cn ``` The broker configuration uses `require_certificate` and `use_identity_as_username`. No other TLS configuration is required. ``` listener 1883 enable_proxy_protocol 2 proxy_protocol_v2_require_tls true require_certificate true use_identity_as_username true ``` [HAProxy]:https://www.haproxy.org/ ================================================ FILE: www/pages/documentation/listeners/per_listener_settings.md ================================================ [TOC] ## Introduction The `per_listener_settings` option was introduced in version 1.5 as a way to allow security options such as `allow_anonymous` and `password_file` to be applied on a per-listener basis, rather than globally as was the only option before. It was however a poorly thought out idea that has lead to a great deal of confusion, and since version 2.1 is deprecated. It will be removed in version 3.0. This document sets out how to remove the use of this option whilst keeping the same functionality in your configuration. These changes require version 2.1. ## Authentication * Replace the `acl_file` option with the [mosquitto_acl_file](/documentation/plugins/acl-file/) plugin. * Replace the `password_file` option with the [mosquitto_password_file](/documentation/plugins/password-file/) plugin. * Replace the use of `allow_anonymous` with the listener specific `listener_allow_anonymous`. If `listener_allow_anonymous` is set for a listener, this overrides any value set by `allow_anonymous`. * Replace `auto_id_prefix` with `listener_auto_id_prefix`. `allow_zero_length_clientid` has no replacement. ## Plugins Prior to 2.1, plugins could be loaded with the `plugin` or `global_plugin` options, where `plugin` would be applied to all plugins or a single plugin, depending on the `per_listener_setting` value, and `global_plugin` would always apply to all listeners. `global_plugin` should still be used to load a plugin across all listener. To use a plugin on some listeners only, use `plugin_load`, which loads a plugin into the broker, and `plugin_use` which applies it to a listener. For example: ``` plugin_load dynsec /usr/lib/mosquitto_dynamic_security.so plugin_opt_config_file /mosquitto/data/dynamic-security.json listener 1883 plugin_use dynsec listener 1884 listener_allow_anonymous true listener 1885 plugin_use dynsec ``` This configuration loads the dynamic-security plugin and uses it with the listeners on ports 1883 and 1885. The listener on port 1884 does not have the plugin applied, and also allows anonymous connections (so is very insecure, anything connecting to that port can publish/subscribe to anything). ================================================ FILE: www/pages/documentation/migrating-to-2-0.md ================================================ [TOC] ## Introduction Mosquitto 2.0 introduces a number of changes to the behaviour of the broker which new users need to be aware of, and which this document explains. If you are packaging Mosquitto for distribution, see the Packaging and Distribution section. If you are a plugin author, see the Plugins section. ## Listener behaviour changes The way in which Mosquitto configures listeners has been changed to help encourage end users to take an informed choice about security, rather than just relying on the previously very forgiving defaults. ### Listener without configuration When Mosquitto is run without a configuration file, or 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. This mode allows automated or manual testing on a local machine without the need for a configuration file. In this mode only, anonymous/unauthenticated users are allowed by default. This applies to you if you run your broker in a similar way to one of these examples: * `mosquitto` * `mosquitto -p 1883`. If you use this mode and wish to have clients connect from a remote machine, then you will need to use a configuration file: ``` listener 1883 # Note that this will not allow anonymous access by default. ``` This configuration binds the listener for port 1883 to the `0.0.0.0` or `::` interface by default, i.e. allows connections on all interfaces. It is still possible to bind to a specific interface manually, e.g. `listener 1883 192.168.1.1`. ### Authentication requires configuration All listeners now require authentication to be configured. This is with the exception of the case where no listener configuration is provided and hence the listener is bound to the loopback interface, as described above. This means that `allow_anonymous` now defaults to false. If you currently have a broker running that has a listener configured in the configuration file, but has no other authentication configured and no explicit `allow_anonymous` setting, then your clients will be unable to connect after upgrading to Mosquitto 2.0. There are three choices : * Configure the in-built `password_file` and `acl_file` options for authentication. * Use an authentication plugin, such as the new [dynamic-security plugin], or the third party [mosquitto-go-auth plugin]. * Set `allow_anonymous true` - this should be done only if you have a specific need for unauthenticated clients. ### Listener TLS protocol version changes The listener `tls_version` option now defines the *minimum* TLS protocol version to be used, rather than the exact version. For example, setting `tls_version tlsv1.2` would allow both TLS v1.2 and TLS v1.3. Support for TLS v1.0 has been disabled. ### Mixing configuration files with -p If you configure a listener in your configuration file *and* use e.g. `-p 1883` on the command line at the same time, you will need to add all listeners to the configuration file because this behaviour is no longer supported - the port provided on the command line will be ignored. If you have a configuration file like this: ``` listener 1883 # ... ``` And run Mosquitto like this: `mosquitto -c mosquitto.conf -p 1884` Then you should instead run Mosquitto as `mosquitto -c mosquitto.conf`, and use a configuration file with both listeners in: ``` listener 1883 # ... listener 1884 # ... ``` ## Use of root/privileged user In versions prior to 2.0, if Mosquitto was run as root it would load TLS certificates, start listeners, and start logging, before dropping to the unprivileged mosquitto user. This behaviour has changed. In 2.0, Mosquitto load the configuration file and immediately drop to the configured unprivileged user, which defaults to `mosquitto`. If the `mosquitto` or manually configured user is not available, the broker will attempt to drop to the `nobody` user. This means that the only files Mosquitto will access as root are the configuration files, and hence any other files that Mosquitto needs to access or write must be accessible by 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]. It is still possible to force Mosquitto to run as root, but this is strongly recommended against. ## Other behaviour 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 `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. ## Packaging and Distribution The components that Mosquitto provides can be categorised as follows: ### Client libraries C/C++ libraries for creating MQTT clients. * lib/libmosquitto.so.1 * lib/cpp/libmosquittopp.so.1 * include/mosquitto.h * include/mqtt_protocol.h ### Clients General purpose command line MQTT clients. These depend upon libmosquitto.so.1. * client/mosquitto_pub * client/mosquitto_sub * client/mosquitto_rr ### Broker The main offering of the project, the Mosquitto broker, plus associated utilities and plugins. * apps/mosquitto_ctrl/mosquitto_ctrl * apps/mosquitto_passwd/mosquitto_passwd * plugins/dynamic-security/mosquitto_dynamic_security.so * src/mosquitto * include/mosquitto_broker.h * include/mosquitto_plugin.h Changes: * The mosquitto_passwd utility has changed location. * The mosquitto_ctrl utility has been added. * The mosquitto_dynamic_security plugin has been added, this is a Mosquitto specific shared library. * The mosquitto_ctrl utility requires libmosquitto.so.1. * Plugin developers would expect to have the header files from libmosquitto available, as well as those from the broker.. ### Dependencies mosquitto_ctrl and mosquitto_dynamic_security.so require the cJSON library. If it is not detected or desired, those features can be disabled. ## Plugins Mosquitto 2.0 introduces a new plugin interface which should be simpler to develop for, and is more easily extendable. A separate document will describe the new plugin interface. If you have an existing plugin that followed the guidelines in `mosquitto_plugin.h`, then it will continue to work with Mosquitto 2.0 *unless* it is compiled using the Mosquitto 2.0 header files, which contained a mistake in the documentation. To modify your plugin so that it will work on both of Mosquitto 1.6 and Mosquitto 2.0, you should change your instance of `mosquitto_auth_plugin_version` so that it returns the version of the plugin interface that you support, i.e. `4`. [misc/letsencrypt/mosquitto-copy.sh]:https://github.com/eclipse/mosquitto/tree/master/misc/letsencrypt [dynamic-security plugin]:/documentation/dynamic-security/ [mosquitto-go-auth plugin]:https://github.com/iegomez/mosquitto-go-auth ================================================ FILE: www/pages/documentation/persistence/sqlite.md ================================================ ## Introduction Available since version 2.1. This plugin provides a replacement for the traditional mosquitto persistence normally enabled with `persistence true`. This plugin should be preferred when you are interested in persistence, because it saves changes to disk as they are made, where as the traditional persistence only takes periodic snapshots. Note that it is not possible to run both the traditional persistence and the sqlite persistence plugin at the same time. ## Usage The plugin requires minimal configuration. The database is stored at the location specified by the `persistence_location` option and is named `mosquitto.sqlite3. As an alternative, the file can be specified directly using the `plugin_opt_db_file` option. The `plugin_opt_sync` option can be set to `extra`, `full`, `normal`, or `off`, with a default of `normal`. This option controls how hard sqlite works to ensure data is on the disk before continuing. This is better described by [sqlite themselves](https://www.sqlite.org/pragma.html#pragma_synchronous). The `plugin_opt_page_size` option sets the database page size, as described [here](https://www.sqlite.org/pragma.html#pragma_page_size). The `plugin_opt_flush_period` option is a positive integer number of seconds, defaulting to 5, that the plugin will batch database updates over in order to improve performance. # Config Windows: ``` persistence_location global_plugin C:\Program Files\Mosquitto\mosquitto_persist_sqlite.dll ``` Other: ``` persistence_location global_plugin /path/to/mosquitto_persist_sqlite.so ``` # Migration A [script](https://raw.githubusercontent.com/eclipse-mosquitto/mosquitto/refs/heads/master/plugins/persist-sqlite/migrate_to_persist_sqlite.py) is available to help migrate from the traditional persistence. ================================================ FILE: www/pages/documentation/plugins/acl-file.md ================================================ ## Introduction Available since version 2.1. This plugin provides the same functionality as the `acl_file` option, and should be the preferred way of using an ACL file. The [dynamic-security plugin](/documentation/dynamic-security/) provides a more powerful approach to authentication and authorisation. ## Usage 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 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 anonymous access is allowed. User specific topic ACLs are added after a user line as follows: ``` user ``` The username referred to here is the same as provided in the CONNECT packet. It is not the clientid. If is also possible to define ACLs based on pattern substitution within the topic. ``` pattern [read|write|readwrite] ``` The patterns available for substitution 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 ``` Example: ``` pattern write sensor/%u/data ``` # Config Windows: ``` global_plugin C:\Program Files\Mosquitto\mosquitto_acl_file.dll plugin_opt_acl_file ``` Other: ``` global_plugin /path/to/mosquitto_acl_file.so plugin_opt_acl_file ``` ================================================ FILE: www/pages/documentation/plugins/password-file.md ================================================ ## Introduction Available since version 2.1. This plugin provides the same functionality as the `password_file` option, and should be the preferred way of using an password file. The [dynamic-security plugin](/documentation/dynamic-security/) provides a more powerful approach to authentication and authorisation. ## Usage Generate password files using the [mosquitto_passwd](/man/mosquitto_passwd-1.html) utility. # Config Windows: ``` global_plugin C:\Program Files\Mosquitto\mosquitto_password_file.dll plugin_opt_password_file ``` Other: ``` global_plugin /path/to/mosquitto_password_file.so plugin_opt_password_file ``` ================================================ FILE: www/pages/documentation/plugins/sparkplug-aware.md ================================================ Available since version 2.1. The [Sparkplug protocol](https://sparkplug.eclipse.org/) provides a unified way to manage topics, device lifetime, and payload format. It is typically intended for use in Industrial Internet of Things applications, such as in factories. The Sparkplug specification makes certain requirements on clients and brokers. For brokers there are two levels of conformance: Sparkplug Compliant and Sparkplug Aware. Any MQTT broker that conforms to the MQTT v3.1.1 or v5.0 protocol meets the requirements to be Sparkplug Compliant. A Sparkplug Aware broker also needs to monitor birth messages from Sparkplug nodes and devices, and republish them to the appropriate topic within `$sparkplug/certificates/spBv1.0/` Loading this plugin makes provides Sparkplug Aware support for Mosquitto. ## Config Windows: ``` global_plugin C:\Program Files\Mosquitto\mosquitto_sparkplug_aware.dll ``` Other: ``` global_plugin /path/to/mosquitto_sparkplug_aware.so ``` ================================================ FILE: www/pages/documentation/using-the-snap.md ================================================ On Linux systems that have snap support, Mosquitto can be installed from the graphical software installer, or with `snap install mosquitto`. After installing the Mosquitto snap, the Mosquitto broker will be running with the default configuration, which means it is listening for connections on port 1883 on the local computer only. If you want to allow connections from other computers you must configure a listener and an [authentication method]. To test the broker, you can use the `mosquitto_pub` and `mosquitto_sub` command line utilities, which are also provided in the snap. `mosquitto_pub` allows you to publish messages to an MQTT broker, and `mosquitto_sub` allows you to subscribe to messages from an MQTT broker. Both tools have a large number of options to control how they are used and as such are useful for a wide variety of tasks. In this case, we will just use them for some simple testing. To subscribe to all messages being published to the MQTT broker on the `snap/example` topic, use the following command. If your MQTT broker is not running on the same machine as `mosquitto_sub`, you will need to change the `localhost` argument to match your MQTT broker host or IP address. ``` mosquitto_sub -h localhost -t 'snap/example' -v ``` The `-t snap/example` option sets the topic to subscribe to, and can be provided multiple times. The `-v` option means to print both the topic of the message as well as its payload. Now to publish a message to the same topic, use the very similar `mosquitto_pub` command: ``` mosquitto_pub -h localhost -t 'snap/example' -m 'Hello from mosquitto_pub' ``` In this case the `-m` option provides the message payload to be published. If everything works as planned, you should see `mosquitto_sub` print ``` snap/example Hello from mosquitto_pub ``` This is of course a very simple example, but it does allow testing of the broker operation. Other things you may wish to try are subscribing to wildcard topics that include `#` or `+`, or subscribing to the `$SYS/#` topic to see information the broker is publishing about itself. Beware that the command line treats `#` as a special character, and `$SYS` will be expanded as a environment variable if you do not surround them with single quotes. Once you have finished your testing, you will want to configure your broker to have encrypted connections and use authentication, possibly configuring bridges, which allow different brokers to share topics, or many other options. To do this, you need to provide a new configuration file. The snap provides an example configuration file at `/var/snap/mosquitto/common/mosquitto_example.conf`. This file contains all of the broker configuration, in a similar manner to the man page. To create your own configuration, copy the example file to `/var/snap/mosquitto/common/mosquitto.conf` and edit according to your needs. Any additional files required by the configuration, such as TLS certificates and keys, must also be placed in `/var/snap/mosquitto/common/` - in new folders if wanted. This directory is the only place accessible by Mosquitto when running as a snap. Starting and stopping the broker service can be done with the snap command: ``` snap start mosquitto snap stop mosquitto ``` Or via systemd: ``` systemctl start snap.mosquitto.mosquitto systemctl stop snap.mosquitto.mosquitto ``` All other aspects of running Mosquitto are the same as with any other installation methods. ## Client configuration files If you use the mosquitto_pub, mosquitto_rr, or mosquitto_sub configuration files they should be placed in `$HOME/snap/mosquitto/current/.config`: * `$HOME/snap/mosquitto/current/.config/mosquitto_pub` * `$HOME/snap/mosquitto/current/.config/mosquitto_rr` * `$HOME/snap/mosquitto/current/.config/mosquitto_sub` [authentication method]:/documentation/authentication-methods ================================================ FILE: www/pages/documentation.md ================================================ # Man pages * [mosquitto] - running the Mosquitto broker * [mosquitto.conf] - the Mosquitto broker configuration file * [mosquitto_ctrl] - command line utility for managing Mosquitto broker configuration * [mosquitto_ctrl_dynsec] - `mosquitto_ctrl` batch mode for the dynamic-security plugin * [mosquitto_ctrl_shell] - `mosquitto_ctrl` interactive shell mode (recommended) * [mosquitto_passwd] - command line utility for generating Mosquitto password files * [mosquitto_pub] - command line utility for publishing messages to a broker * [mosquitto_rr] - command line utility for simple request/response with a broker * [mosquitto_signal] - command line utility for sending signals to a broker, most useful on Windows * [mosquitto_sub] - command line utility for subscribing to topics on a broker * [mosquitto-tls] - brief cheat sheet for creating x509 certificates * [mqtt] - description of MQTT features # Listeners * [Using Mosquitto with HAProxy] - using Mosquitto with HAProxy with or without TLS termination. * [Replacing the per_listener_settings option](/documentation/listeners/per_listener_settings/) # Persistence * [Sqlite](/documentation/persistence/sqlite/) # Plugins * [ACL file] - replacement for the `acl_file` option. * [Password file] - replacement for the `password_file` option. * [Dynamic Security] - details of using the Dynamic Security authentication and access control plugin. * [Sparkplug Aware] - make Mosquitto fully compliant with the Sparkplug protocol. # Other * [Authentication methods] - details on the different authentication options available. * [Using the snap package] - specific instructions on installing and configuring the Mosquitto snap package. * [Migrating from 1.x to 2.0] - details of changes needed to migrate to version 2.0. # libmosquitto API * [libmosquitto API documentation] # Third party These are some Mosquitto documentation hosted by third parties. * [Steve's internet guide] - a broad range of documentation and examples covering Mosquitto and the Paho Python client, amongst others. * [docs.cedalo.com] - includes documentation for both Mosquitto and Eclipse Streamsheets [mosquitto]:/man/mosquitto-8.html [mosquitto.conf]:/man/mosquitto-conf-5.html [mosquitto_ctrl]:/man/mosquitto_ctrl-1.html [mosquitto_ctrl_dynsec]:/man/mosquitto_ctrl_dynsec-1.html [mosquitto_ctrl_shell]:/man/mosquitto_ctrl_shell-1.html [mosquitto_passwd]:/man/mosquitto_passwd-1.html [mosquitto_pub]:/man/mosquitto_pub-1.html [mosquitto_rr]:/man/mosquitto_rr-1.html [mosquitto_signal]:/man/mosquitto_signal-1.html [mosquitto_sub]:/man/mosquitto_sub-1.html [mosquitto-tls]:/man/mosquitto-tls-7.html [mqtt]:/man/mqtt-7.html [libmosquitto API documentation]:/api/ [Authentication methods]:/documentation/authentication-methods/ [Using the snap package]:/documentation/using-the-snap/ [Dynamic Security]:/documentation/dynamic-security/ [ACL file]:/documentation/plugins/acl-file/ [Password file]:/documentation/plugins/password-file/ [Sparkplug Aware]:/documentation/plugins/sparkplug-aware/ [Using Mosquitto with HAProxy]:/documentation/listeners/haproxy/ [Migrating from 1.x to 2.0]:/documentation/migrating-to-2-0/ [Steve's internet guide]: http://www.steves-internet-guide.com/ [docs.cedalo.com]: https://docs.cedalo.com/ ================================================ FILE: www/pages/download.md ================================================ # Source * [mosquitto-2.1.2.tar.gz](https://mosquitto.org/files/source/mosquitto-2.1.2.tar.gz) ([GPG signature](https://mosquitto.org/files/source/mosquitto-2.1.2.tar.gz.asc)) * [Git source code repository](https://github.com/eclipse-mosquitto/mosquitto) (github.com) Older downloads are available at [https://mosquitto.org/files/](../files/) # Binary Installation The binary packages listed below are supported by the Mosquitto project. In many cases Mosquitto is also available directly from official Linux/BSD distributions. ## Windows * [mosquitto-2.1.2-install-windows-x64.exe](https://mosquitto.org/files/binary/win64/mosquitto-2.1.2-install-windows-x64.exe) * [mosquitto-2.1.2-install-windows-x86.exe](https://mosquitto.org/files/binary/win32/mosquitto-2.1.2-install-windows-x86.exe) Older installers can be found at [https://mosquitto.org/files/binary/](https://mosquitto.org/files/binary/). See also README-windows.md after installing. ## Mac Mosquitto can be installed from the homebrew project. See [brew.sh](https://brew.sh/) and then use `brew install mosquitto` ## Linux distributions with snap support * `snap install mosquitto` ## Debian * Mosquitto is now in Debian proper. There will be a short delay between a new release and it appearing in Debian as part of the normal Debian procedures. The tracker for the package is at . * There are also Debian repositories provided by the mosquitto project, as described at ## Raspberry Pi Mosquitto is available through the main repository. There are also Debian repositories provided by the mosquitto project, as described at ## Ubuntu Mosquitto is available in the Ubuntu repositories so you can install as with any other package. If you are on an earlier version of Ubuntu or want a more recent version of mosquitto, add the [mosquitto-dev PPA](https://launchpad.net/%7Emosquitto-dev/+archive/mosquitto-ppa/) to your repositories list - see the link for details. mosquitto can then be installed from your package manager. * `sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa` * `sudo apt-get update` ================================================ FILE: www/pages/index.html ================================================

Eclipse Mosquitto is an open source (EPL/EDL licensed) message broker that implements the MQTT protocol versions 5.0, 3.1.1 and 3.1. Mosquitto is lightweight and is suitable for use on all devices from low power single board computers to full servers.

The MQTT protocol provides a lightweight method of carrying out messaging using a publish/subscribe model. This makes it suitable for Internet of Things messaging such as with low power sensors or mobile devices such as phones, embedded computers or microcontrollers.

The Mosquitto project also provides a C library for implementing MQTT clients, and the very popular mosquitto_pub and mosquitto_sub command line MQTT clients.

Mosquitto is part of the Eclipse Foundation, and is an iot.eclipse.org project. The development is driven by Cedalo.


Download and Security

Mosquitto is highly portable and available for a wide range of platforms. Go to the dedicated download page to find the source or binaries for your platform.

Read the Change Log to find out about recent releases.

Use the security page to find out how to report vulnerabilities or responses to past security issues.

Test

You can have your own instance of Mosquitto running in minutes, but to make testing even easier, the Mosquitto Project runs a test server at test.mosquitto.org where you can test your clients in a variety of ways: plain MQTT, MQTT over TLS, MQTT over TLS (with client certificate), MQTT over WebSockets and MQTT over WebSockets with TLS.

Community

Support

Support is always available from the community channels on a best effort basis. If you require commercial support, Cedalo can offer support for hosted or on-premise instances, consulting on the use of Mosquitto, and custom development to your needs.

Related Projects

Paho provides MQTT client library implementations in a wide variety of languages.

Streamsheets is an easy to use web based real time spreadsheet interface that can be used to process incoming data from a variety of sources, such as MQTT, OPC-UA, and REST. Developers and non-developers can use Streamsheets to control processes and build dashboards, for example. Mosquitto is a core component of Streamsheets.

================================================ FILE: www/pages/roadmap.md ================================================ # Roadmap ## Version 1.6 The next minor release. The focus of this release is on providing support for version 5 of the MQTT protocol. This release will provide a feature complete implementation, but does not represent the final interface for all features. In particular, functions are being added to libmosquitto to provide support for MQTT 5 features, but these will be consolidated with the API changes planned for version 2.0. ### Deprecation notices #### libmosquittopp libmosquittopp, the C++ wrapper around libmosquitto is now deprecated and will be removed in the next major release (2.0). The wrapper came about by an external request and at the time it was created there were no other C++ solutions for MQTT. This has changed in the past years and this wrapper provides no benefit over true C++ libraries or using the pure C libmosquitto. #### libmosquitto API changes The Mosquitto project has maintained API and ABI compatibility in libmosquitto since version 1.0, and has dealt with the introduction of new specification features by adding new functions which duplicate the behaviour of existing functions, but with additional arguments to support the new features. Particularly with regards to adding support for MQTT version 5, this has lead to a proliferation of functions which offer small variations on a theme. The libmosquitto functions listed below (which includes some new functions included in 1.6) are going to be updated for version 2.0. Functions not listed here should still be considered at risk of being updated. * mosquitto\_will\_set * mosquitto\_connect\* * mosquitto\_reconnect\* * mosquitto\_disconnect * mosquitto\_publish\* * mosquitto\_subscribe\* * mosquitto\_unsubscribe\* * mosquitto\_loop\* * mosquitto\_\*\_callback\_set * All callbacks * mosquitto\_\*\_topic\_check\* ## Version 2.0 This is the next major release and includes breaking changes. Other features planned include: ## Disk persistence improvements A new disk persistence interface will be created to allow persistence to occur immediately, rather than periodically. This will allow queued messages for disconnected clients to be removed from memory, and reduce the periodic pause caused when writing the persistence file. ## Breaking changes ### libmosquitto The libmosquitto API is being consolidated to better support the new MQTT 5 features whilst reducing the number of function variants. ### libmosquittopp The C++ wrapper around libmosquitto will be removed in this release. ================================================ FILE: www/pages/security.md ================================================ # Reporting security vulnerabilities If you think you have found a security vulnerability in Mosquitto, please follow the steps on [Eclipse Security] page to report it. # Past vulnerabilities Listed with most recent first. Further information on security related issues can be found in the [security category]. * August 2023: [CVE-2023-0809]: Fix excessive memory being allocated based on malicious initial packets that are not CONNECT packets. Affecting versions **1.5.0** to **2.0.15**. Fixed in **2.0.16**. * August 2023: [CVE-2023-3592]: Fix memory leak when clients send v5 CONNECT packets with a will message that contains invalid property types. Affecting version **1.6.0** to **2.0.15** Fixed in **2.0.16**. * August 2023: [CVE-2023-28366]: Clients sending unacknowledged QoS 2 messages with duplicate message ids cause a memory leak. Affecting versions **1.3.2** to **2.0.15** inclusive, fixed in **2.0.16**. * August 2022: Deleting the anonymous group in the dynamic security plugin could lead to a crash. Affecting versions **2.0.0** to **2.0.14** inclusive, fixed in **2.0.15**. * August 2021: [CVE-2021-34434] Affecting versions **2.0.0** to **2.0.11** inclusive, fixed in **2.0.12**. * April 2021: [CVE-2021-28166] Affecting versions **2.0.0** to **2.0.9** inclusive, fixed in **2.0.10**. * December 2020: 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. Affecting versions **2.0.0** to **2.0.2** inclusive, fixed in **2.0.3**. * September 2019: [CVE-2019-11779]. Affecting versions **1.5** to **1.6.5** inclusive, fixed in **1.6.6** and **1.5.9**. More details at [version-166-released]. * September 2019: [CVE-2019-11778]. Affecting versions **1.6** to **1.6.4** inclusive, fixed in **1.6.5**. More details at [version-166-released]. * April 2019: No CVE assigned. Affecting versions **1.6** and **1.6.1**, fixed in **1.6.2**. More details at [version-162-released]. * December 2018: [CVE-2018-20145]. Affecting versions **1.5** to **1.5.4** inclusive, fixed in **1.5.5.**. More details at [version-155-released]. * November 2018: No CVE assigned. Affecting versions **1.4** to **1.5.3** inclusive, fixed in **1.5.4**. More details at [version-154-released]. * September 2018: [CVE-2018-12543] affecting versions **1.5** to **1.5.2** inclusive, fixed in **1.5.3**. * April 2018: [CVE-2017-7655] affecting versions **1.0** to **1.4.15** inclusive, fixed in **1.5**. * April 2018: [CVE-2017-7654] affecting versions **1.0** to **1.4.15** inclusive, fixed in **1.5**. [security-advisory-cve-2017-7653-cve-2017-7654]. * April 2018: [CVE-2017-7653] affecting versions **1.0** to **1.4.15** inclusive, fixed in **1.5**. * February 2018: [CVE-2017-7651] affecting versions **0.15** to **1.4.14** inclusive, fixed in **1.4.15**. More details at [security-advisory-cve-2017-7651-cve-2017-7652]. * February 2018: [CVE-2017-7652] affecting versions **1.0** to **1.4.14** inclusive, fixed in **1.4.15**. More details at [security-advisory-cve-2017-7651-cve-2017-7652]. * June 2017: [CVE-2017-9868] affecting versions **0.15** to **1.4.12** inclusive, fixed in **1.4.13**. More details at [security-advisory-cve-2017-9868]. * May 2017: [CVE-2017-7650] affecting versions **0.15** to **1.4.11** inclusive, fixed in **1.4.12**. More details at [security-advisory-cve-2017-7650]. [version-166-released]: /blog/2019/09/version-1-6-6-released/ [version-162-released]: /blog/2019/04/version-1-6-2-released/ [version-155-released]: /blog/2018/11/version-155-released/ [version-154-released]: /blog/2018/11/version-154-released/ [security-advisory-cve-2018-12543]: /blog/2018/09/security-advisory-cve-2018-12543/ [security-advisory-cve-2017-7651-cve-2017-7652]: /blog/2018/02/security-advisory-cve-2017-7651-cve-2017-7652/ [security-advisory-cve-2017-7650]: /blog/2017/05/security-advisory-cve-2017-7650/ [security-advisory-cve-2017-9868]: /blog/2017/06/security-advisory-cve-2017-9868/ [Eclipse Security]: https://www.eclipse.org/security/ [security category]: /blog/categories/security/ [CVE-2021-34434]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34434 [CVE-2021-28166]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28166 [CVE-2019-11779]: https://nvd.nist.gov/vuln/detail/CVE-2019-11779 [CVE-2019-11778]: https://nvd.nist.gov/vuln/detail/CVE-2019-11778 [CVE-2018-20145]: https://nvd.nist.gov/vuln/detail/CVE-2018-20145 [CVE-2018-12543]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-12543 [CVE-2017-9868]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-9868 [CVE-2017-7655]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-7655 [CVE-2017-7654]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-7654 [CVE-2017-7653]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-7653 [CVE-2017-7652]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-7652 [CVE-2017-7651]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-7651 [CVE-2017-7650]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-7650 ================================================ FILE: www/plugins/__init__.py ================================================ # Plugin modules go here. ================================================ FILE: www/plugins/docbookmanpage/docbookmanpage.plugin ================================================ [Core] Name = docbookmanpage Module = docbookmanpage [Nikola] PluginCategory = PageCompiler [Documentation] Author = Roger Light (asciidoc code by Roberto Alsina) Version = 0.4 Website = https://github.com/ralight/nikola-docbook-manpage Description = Compile Docbook manpages into html, based on asciidoc plugin. ================================================ FILE: www/plugins/docbookmanpage/docbookmanpage.py ================================================ # -*- coding: utf-8 -*- # Copyright © 2012-2014 Roberto Alsina and others. # Permission is hereby granted, free of charge, to any # person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the # Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the # Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice # shall be included in all copies or substantial portions of # the Software. # # 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. 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. """Implementation of compile_html based on asciidoc. You will need, of course, to install asciidoc """ import codecs import os import subprocess from nikola.plugin_categories import PageCompiler from nikola.utils import makedirs, req_missing, write_metadata try: from collections import OrderedDict except ImportError: OrderedDict = dict # NOQA class CompileDocbookManpage(PageCompiler): """Compile docbookmanpage into HTML.""" name = "docbookmanpage" demote_headers = True def compile(self, source, dest, is_two_file=True, post=None, lang=None): """Compile the source file into HTML and save as dest.""" makedirs(os.path.dirname(dest)) if "common/" in source and post is not None: post.write_depfile(dest, [], post, lang) with open(dest, "wt") as f: pass return [] binary = self.site.config.get('XSLTPROC_BINARY', 'xsltproc') xslpath = os.path.join(os.path.split(__file__)[0], 'html.xsl') try: source = os.path.abspath(source) dest = os.path.abspath(dest) xslpath = os.path.abspath(xslpath) subprocess.check_call((binary, '--xinclude', '-o', dest, xslpath, source)) if post is None: if shortcode_deps: self.logger.error( "Cannot save dependencies for post {0} (post unknown)", source) except OSError as e: print(e) req_missing(['xsltproc'], 'build this site (compile with xsltproc)', python=False) def create_post(self, path, content=None, onefile=False, is_page=False, **kw): """Create post file with optional metadata.""" metadata = OrderedDict() metadata.update(self.default_metadata) metadata.update(kw) makedirs(os.path.dirname(path)) if not content.endswith('\n'): content += '\n' with codecs.open(path, "wb+", "utf8") as fd: if onefile: fd.write("////\n") fd.write(write_metadata(metadata)) fd.write("////\n") fd.write(content) ================================================ FILE: www/plugins/docbookmanpage/html.xsl ================================================ man.css ansi ansi ansi 1 ================================================ FILE: www/posts/2009/12/version-0-2-released.md ================================================ Version 0.2 released - please see the [change log](/ChangeLog.txt). ================================================ FILE: www/posts/2009/12/version-0-3-released.md ================================================ * Added logging support. * Now restarts much more quickly even when the network socket was in use. * Can now be configured to run on multiple network ports and restricted to specific network addresses. * Added host access control in the form of tcp-wrappers support. See the [change log](/ChangeLog.txt) for full details. Wild card support in topics is coming in the next version. ================================================ FILE: www/posts/2010/01/mailing-list-irc.md ================================================ We've created some new support channels for mosquitto - a mailing list and an irc channel. Although they are both intended for providing support for mosquitto itself, general discussion of anything to do with mqtt is strongly encouraged. We want to reduce the barrier to getting started and provide a place where people can share their experiences. The mailing list is at The irc channel is #mqtt on the [freenode network] [freenode network]: http://freenode.net/ ================================================ FILE: www/posts/2010/01/version-0-4-1-released.md ================================================ This is a bugfix release: * Fix regex used for finding retained messages to send on new subscription. ================================================ FILE: www/posts/2010/01/version-0-4-released.md ================================================ * 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. * Keepalive==0 is now correctly treated as "never disconnect". * 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. See the [changelog] for full details. [changelog]: /ChangeLog.txt ================================================ FILE: www/posts/2010/02/version-0-4-2-released.md ================================================ This is a bugfix release. * Fix segfault on client connect with invalid protocol name/version. Get it at the [download page]. [download page]: /download ================================================ FILE: www/posts/2010/03/google-powermeter.md ================================================ A popular use for mqtt brokers seems to be coupling them with a [CurrentCost] (or similar) energy monitor to then log energy data and produce pretty (and useful!) graphs. Google recently opened up their PowerMeter API which looks to provide very nice graphing of energy data. They are working with utility companies directly with in home monitors, but it's also possible to use it as an individual. Toby Evans got to the bottom of registering a device (see his [explanatory blog post]) which just leaves getting data to Google. If you're already logging energy data to an MQTT broker, it's as simple as adding another subscriber to send the data to Google. You could use the mosquitto_sub client and a script I wrote for posting to google, [google_powermeter_update_mqtt.pl] like so: ``` mosquitto_sub -t sensors/cc128/ch1 | google_powermeter_update_mqtt.pl ``` This assumes that the data appearing on the sensors/cc128/ch1 topic is in the format `<unix timestamp> <power reading in Watts>`. If you're not logging your energy data to a broker, you should probably consider doing so :) There is another script [google_powermeter_update.pl] which may be more suitable and can be used as: ``` google_powermeter_update.pl <unix timestamp> <power in Watts> ``` Both of the scripts need your user details adding and should be easy to modify to match your own particular need. They also assume you're using a single cumulative variable with your device and will need modifying if you're using more than one variable or aren't using cumulative variables. For reference, I use the script [cc128.pl] to read data from my CurrentCost CC128 (Envi). # Update: Google has a limit of 6 API requests per hour, so the above description will only work for a short while (the 6 request limit doesn't appear to be a hard limit when you first exceed it, but becomes increasingly stricter). I'm now logging my CC128 data to a mysql database and sending batch updates every 15 minutes with [google_powermeter_update_mysql.pl]. [CurrentCost]: http://currentcost.com/ [explanatory blog post]: http://2cheap2meter.blogspot.com/2010/03/setting-up-google-powermeter.html [google_powermeter_update_mqtt.pl]: /files/perl/google_powermeter_update_mqtt.pl [google_powermeter_update.pl]: /files/perl/google_powermeter_update.pl [cc128.pl]: /files/perl/cc128.pl">cc128.pl [google_powermeter_update_mysql.pl]: /files/perl/google_powermeter_update_mysql.pl ================================================ FILE: www/posts/2010/03/upgrading-to-0-5-1.md ================================================ When upgrading to 0.5.1 from 0.4 or higher, there is an important change in the location of the sqlite3-pcre library used. On Linux, the expected location of this library has changed from /usr/lib/sqlite3-pcre.so to /usr/lib/sqlite3/pcre.so. This is because the library is an extension specifically for sqlite3, not a general use shared library. If you installed sqlite3-pcre manually, or are not using Ubuntu, you should either modify the `ext_sqlite3_regex` option in /etc/mosquitto.conf to point to your library path, or move the library to the new location. If you are using Ubuntu and have installed mosquitto from the launchpad ppa, this will largely be taken care of. However, due to a mistake in the packaging of sqlite3-pcre, you must first remove sqlite3-pcre with your package manager and then reinstall it before updating mosquitto. You will only ever need to do this once. Sorry for the inconvenience caused by this change. If you have any problem or questions, feel free to get in touch on the [mqtt users mailing list]. [mqtt users mailing list]: https://launchpad.net/~mqtt-users ================================================ FILE: www/posts/2010/03/version-0-5-1-released.md ================================================ This announcement summarises the changes in both 0.5 and 0.5.1. The interesting changes: * Add mosquitto_sub and mosquitto_pub, simple clients for subscribe/publish. * 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. This makes persistence more suitable when being used on devices with a limited number of writes, such as flash. * Default sqlite3-pcre path on Linux is now /usr/lib/sqlite3/pcre.so to match new sqlite3-pcre packages. The less interesting/bug fixes: * 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. * 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. * 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. ================================================ FILE: www/posts/2010/03/version-0-5-2-released.md ================================================ This is a bugfix release; it is recommended that you upgrade to this version: * 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 [#530099] and [#530369]. Mosquitto is now also available for Linux x86 statically compiled against sqlite3, which makes it usable on older distributions such as Ubuntu Hardy that are still supported but do not have a sufficiently new version of sqlite3. To download this package, go to the [download page]. [#529990]: https://bugs.launchpad.net/mosquitto/+bug/529990 [#530099]: https://bugs.launchpad.net/mosquitto/+bug/530099 [#530369]: https://bugs.launchpad.net/mosquitto/+bug/530369 [download page]: /download ================================================ FILE: www/posts/2010/03/version-0-5-3-released.md ================================================ This is a bugfix release. * 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 (//). This should finally fix bug [#530099]. * Do actually disconnect client when it sends an empty subscription/topic string. * Add missing $SYS/broker/clients/total to man page. [#530099]: https://bugs.launchpad.net/mosquitto/+bug/530099 ================================================ FILE: www/posts/2010/03/version-0-5-4-released.md ================================================ This is a bugfix release. * 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]). [bug #531861]: https://bugs.launchpad.net/mosquitto/+bug/531861 [bug #537061]: https://bugs.launchpad.net/mosquitto/+bug/537061 ================================================ FILE: www/posts/2010/04/help-wanted-rpm-packaging.md ================================================ I'm currently working on the finishing touches of mosquitto 0.6 and will hopefully be releasing it some time this week in time for oggcamp. Mosquitto is pretty usable now so I'm keen on making it as easy as possible for people to get and use. The ultimate goal is of course to get it into the major Linux distros so it appears in the normal package repositories. Until then, other solutions are possible. I can provide Windows executables and have a PPA to support Ubuntu Linux users, but don't have anything for rpm based distros. Can you help? I'm quite happy using the opensuse build service to build and host the final packages, but the creation of the rpm build script isn't something I know how to do at the moment. Given the amount of time I've spent on the Debian style packaging, I thought I'd ask for help with rpms! :) If you've got familiarity with rpm and would like to help, please [get in touch]. If you aren't familiar with creating rpms but want a reason to learn, that would suit me fine as well. Thanks in advance! [get in touch]: /support ================================================ FILE: www/posts/2010/04/mind-control-mqtt.md ================================================ If you're in the UK, you may be interested in watching the Wednesday 21st April episode of "Bang Goes the Theory". IBM employees [Nicholas O'Leary] and [Kevin Brown] will be in one of the segments, on controlling remote control cars with their minds - all with MQTT under the covers! * [BBC programme link] [Nicholas O'Leary]: http://twitter.com/knolleary [Kevin Brown]: http://twitter.com/kevinxbrown [BBC programme link]: https://www.bbc.co.uk/programmes/b00s5fvq ================================================ FILE: www/posts/2010/04/oggcamp.md ================================================ I'm going to be at [oggcamp] this coming weekend. If you're there, try and find me and say hello! I'm planning a talk on mosquitto/mqtt with Andy Stanford-Clark, so should be relatively easy to find. [oggcamp]: http://oggcamp.org/ ================================================ FILE: www/posts/2010/05/fedora-packages-available.md ================================================ Thanks to help from Chris Procter, there are now rpm packages available for Fedora Linux. As these are the first rpm packages, there may be problems so please report back if you find any. There are details on where to get the packages on the [download page]. Users of other rpm based distributions are currently out of luck - the versions of sqlite that they provide are typically either too old or else don't have support for some required features compiled in. Thanks to everybody else who got in touch about rpms as well! [download page]: /download ================================================ FILE: www/posts/2010/05/gentoo-ebuilds-available.md ================================================ Thanks to Neil Bothwick, there are now some Gentoo ebuilds available for mosquitto and sqlite3-pcre. You can grab them from the links below - hopefully they'll be integrated in the near future. * * ================================================ FILE: www/posts/2010/05/mosquitto-org.md ================================================ I'm pleased to announce that the mosquitto website is now available at so please update your bookmarks! I'll be updating the links here in a few days when the change has propagated. ================================================ FILE: www/posts/2010/05/mqtt-push-on-android.md ================================================ If you want to use MQTT for push in Android apps, you'll probably want to head over to Anton L's blog post [How to Implement Push Notifications for Android]. He has a sample Android app that uses the IBM Java library to implement push notifications using MQTT, as well as a web page solution to demo pushing notifications to your phone. [How to Implement Push Notifications for Android]: http://tokudu.com/2010/how-to-implement-push-notifications-for-android/ ================================================ FILE: www/posts/2010/05/mqtt-wiki.md ================================================ A new wiki has been created, devoted to MQTT. If you want to share what you're doing with MQTT and how to do it, or want to find any of that out, head over to . ================================================ FILE: www/posts/2010/05/version-0-6-1-released.md ================================================ This fixes an important bug that didn't get caught for 0.6 that can prevent old database versions being upgraded. From 0.7 onwards, mosquitto will be using release candidates to ensure this kind of problem doesn't occur in the future. ================================================ FILE: www/posts/2010/05/version-0-6-released.md ================================================ This is a new features release. It offers quite a bit of change over the previous version. More details of the new features can be found in the [man pages]. The substantial changes are: * 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. * 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 support for automatic upgrading of the mosquitto DB from v1 to v2. * If a retained message is received with a zero length payload, the retained message for that topic is deleted. * Implement the `max_inflight_messages` and `max_queued_messages` features in the broker. The less visible features and bug fixes are as follows: * Add support for disabling `clean session` for the sub client. * mosquitto will now correctly run VACUUM on the persistent database on exit. * Add the `store_cleanup_interval` config option for dealing with the internal message store. * 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). * Send through zero length messages. * Produce a warning on unsupported rsmb options instead of quitting. * Describe clean session flag in the mqtt man page. Get it from the [download page]. Windows and Ubuntu binaries will follow along shortly. [man pages]: /documentation [download page]: /download ================================================ FILE: www/posts/2010/06/automation-has-the-oven-warmed-up-yet.md ================================================ In the Bang Goes the Theory episode [The Human Power Station] a family of four people had their electricity supplied by a large group of cyclists on cycles hooked up to generators, the point being to highlight the amount of energy that is used and wasted on a daily basis. There's a video on [youtube]. One example that seemed to waste a lot of energy was cooking roast dinner. The oven was turned on to preheat (this is often the first instruction in a recipe), but it wasn't actually used until a significant time later, wasting a lot of energy. An example which may be more common is turning the oven on to preheat before cooking frozen food (which requires no preparation), then forgetting to check to see if it has preheated. This used to happen to me, but I've solved the problem by using my electricity monitor (I have an electric oven), mqtt and asterisk. First off, we need to monitor electricity usage. I do this with a [CurrentCost] CC128 (note that EON customers in the UK can apply to get one of these for free in an [Energy Fit] pack) hooked up to a low power computer that is running mosquitto. If you're running Linux, you can use [cc128_read.py] or [cc128_read.pl] to read the data coming from the monitor and publish it to an mqtt broker. A second client, [cc128_parse.pl], takes the data from the monitor and republishes it to the broker in a friendlier format - the Unix timestamp of the reading and the power usage, separated by a single space. To figure out when the oven has warmed up, I look at the electricity usage with the oven heater on - approximately 2.4kW. If the energy usage drops below this value, I know that the oven heater has turned off and so the oven has warmed up. This is of course slightly simplistic - I'm not actually measuring the oven, just the electricity usage so if I turned on the kettle at the same time it could cause my guess to be incorrect. When CurrentCost produce their individual appliance monitors, I'll be able to be certain of how much electricity just the oven is using. This uncertainty means that I only want to turn the oven monitor on when I've actually turned the oven on. Looking for an easy way to start the monitor, I spotted my house phone - a Siemens C460IP - which is a "normal" land line phone and an IP phone all in one. I've got Asterisk running on the same server as mosquitto, so it's an ideal solution for controlling things. Configuring Asterisk is way beyond the scope of this text, so I'm only going to talk about the bits I changed. I added a new extension number 100 which, when called, starts the oven monitor: ``` exten => 100,1,Answer() exten => 100,n,System(echo "/usr/local/bin/oven_pub.pl" | at now) exten => 100,n,Playback(oven-trigger) exten => 100,n,Hangup ``` This answers the call, starts the monitor, plays a sound clip so the person calling knows what has happened and then hangs up. I'm using the "at" command here as a simple way of putting the job into the background, thanks to [Ed] for the suggestion. The script [oven_monitor.pl] looks for the electricity usage to drop beneath 2kW, then runs `oven_warmed_up.sh` and exits. The final step is to do something in [oven_warmed_up.sh] to give feedback. I make use of asterisk once again and initiate a call to the phone - so when the oven has warmed up I get a phone call with a message that tells me so. The outgoing call is initiated by moving [oven.call] to /var/spool/asterisk/outgoing/, as shown in the script. Do you have any suggestions on how to improve this? Or other ways of using asterisk or mqtt like this? Let me know in the comments! [The Human Power Station]: http://www.bbc.co.uk/programmes/b00p8469 [youtube]: http://www.youtube.com/watch?v=C93cL_zDVIM [CurrentCost]: http://www.currentcost.com/ [Energy Fit]: http://www.eon-uk.com/media/energyfit.aspx [cc128_read.py]: http://bitbucket.org/oojah/mosquitto/src/tip/misc/currentcost/cc128_read.py [cc128_read.pl]: http://bitbucket.org/oojah/mosquitto/src/tip/misc/currentcost/cc128_read.pl [parse.pl]: http://bitbucket.org/oojah/mosquitto/src/tip/misc/currentcost/cc128_parse.pl [Ed]: http://twitter.com/ribzlike [oven_monitor.pl]: /files/examples/oven-asterisk/oven_monitor.pl [oven_warmed_up.sh]: /files/examples/oven-asterisk/oven_warmed_up.sh [oven.call]: /files/examples/oven-asterisk/oven.call ================================================ FILE: www/posts/2010/06/google-powermeter-step-by-step.attachments.json ================================================ {"54": {"wordpress_user_name": "roger", "title": "powermeter-example", "date_utc": "2010-06-15 13:52:24", "files_meta": [{"height": 292, "width": 632}, {"height": 138, "size": "medium", "width": 300}, {"height": 150, "size": "thumbnail", "width": 150}], "files": ["/wp-content/uploads/2010/06/powermeter-example.png", "/wp-content/uploads/2010/06/powermeter-example-300x138.png", "/wp-content/uploads/2010/06/powermeter-example-150x150.png"]}} ================================================ FILE: www/posts/2010/06/google-powermeter-step-by-step.md ================================================ # Note: Google Powermeter is now defunct but this post will remain here for those interested. This is a follow up to my previous [post on using Google Powermeter], but this time I'm going to give a step by step guide to getting your data uploaded. The only assumptions are that you have a CurrentCost monitor (note that CurrentCost monitors are often rebadged by electricity suppliers such as EON in the UK so check yours) and have already connected it to your computer, want to use MQTT and that you're using Linux, or another Unix operating system. # Retrieving the data The first step is to get the data from the CurrentCost into the MQTT broker. This is straightforward - simply read data from the serial port and send it all to the broker. I have scripts to do this with mosquitto in both [perl] and [python]. The data coming from the CurrentCost is in XML format and as well as providing the real time power reading every 6 seconds, will also send historical data periodically. I'm only going to deal with the real time readings here. The next step is to reprocess the incoming data into something more manageable, then republish it. An example of doing that is the script [cc128_parse.pl], which assumes you're only using the main channel from the CurrentCost. If you have multiple monitoring channels, you'll need to modify it to suit. # Logging the data Google limits the number of times we can send data to 6 per hour, so we have to log the data and then send amalgamated updates. I use mysql for this - I'm going to assume that you've got it installed and running. Log into the mysql console using "mysql -u root",  "mysql -u root -p" if you know the password, or possibly "sudo mysql". We're now going to create a database and table to hold the powermeter data, then add a user to access and update the data. To create the database and table enter the following: ``` 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; ``` Note that there's a column there for the temperature as well. To add the user and grant access to the database: ``` CREATE USER 'powermeter'@'localhost' IDENTIFIED BY '<your password>'; GRANT ALL ON powermeter.* to 'powermeter'@'localhost'; ``` Finally, you'll need to get data into this database. My script [cc128_log_mysql.pl] subscribes to the data from cc128_parse.pl and logs it into the database. You'll need to edit it to have the correct database details. If you already have your power data published to an MQTT topic, it's quite likely that you won't have it in the same format that I use above. If this is the case, you will need to modify cc128_log_mysql.pl. Assuming your data coming in over MQTT is just the power reading, then you can replace this: ``` @vals = split(/,/, $line); $timestamp = @vals[0]; $temperature = @vals[1]; $ch1 = @vals[2]; ``` with this: ``` $timestamp = time(); $temperature = 0; $ch1 = $line; ``` You can of course leave the temperature column out completely if you prefer. # Registering with Google Powermeter Before you can send any data to Google, you need to register your device with them. This would normally be done automatically by your device, but because we're doing things ourselves we need to do it manually. See [2cheap2meter] and the links it provides for more details. We first need to decide on a few parameters for our device: * Manufacturer (e.g. CurrentCost) * Device model (e.g. CC128 or Envi) * Device id (e.g. Serial number or your own made up string, 1234) * Number of channels to log (e.g. 1) We can then construct an address which you will paste into your web browser: ``` https://www.google.com/powermeter/device/activate?mfg=CurrentCost&model=CC128&did=1234&dvars=1 ``` `dvars` here is the number of channels (or monitors) that we wish to register. If you have more than one channel logging, change the number accordingly - bear in mind that you'll have to modify just about everything else in this post to match. You will need to remember the values you put here for later. Visiting that link will take you to the activation page, which you should complete. After you have done this, you will be presented with authorisation information for your new device. The piece of information we need is the 32 character string contained between "token=" and "&path" (the authorisation token) as well as the 20 digit number after "&path=/user/" (your google powermeter id). # Sending the data I have a script [google_powermeter_update.pl] that will query the database for readings from the past 15 minutes and then send them. You'll need to edit the script to put the correct database details, power meter id, authorisation token and device details. To set it to run every fifteen minutes, I use cron. Either add an entry to your own crontab by running "crontab -e" then entering the following line: ``` */15 * * * * /path/to/google_powermeter_update.pl > /dev/null ``` Or by creating a file containing the line below and copying it to /etc/cron.d/powermeter_update.cron. ``` */15 * * * * nobody /path/to/google_powermeter_update.pl > /dev/null ``` In both cases, you can change the output redirection from "/dev/null" to e.g. "/tmp/powermeter" to allow you to check any error codes in case of a problem. Now go to to check your data! Here's an example of mine: [![powermeter example](/blog/uploads/2010/06/powermeter-example-300x138.png)](/blog/uploads/2010/06/powermeter-example.png) # Possible changes The above description and scripts aren't ideal - if you lose your internet connection then data will still be recorded but won't be sent to google. One possible change would be to add a column to the database to list whether that particular piece of data had been sent or not, which would allow all data to eventually be sent and deleted afterwards if desired. A second way around this would be to make use of the historical data that the CurrentCost monitors use. This could also be a way of reducing the need to log things ourselves. # Conclusion I hope this is of use to you - please let me know if you have any problems with any of the above steps. [post on using Google Powermeter]: /blog/2010/03/google-powermeter/ [perl]: http://bitbucket.org/oojah/mosquitto/src/tip/misc/currentcost/cc128_read.pl [python]: http://bitbucket.org/oojah/mosquitto/src/tip/misc/currentcost/cc128_read.py [cc128_parse.pl]: http://bitbucket.org/oojah/mosquitto/src/tip/misc/currentcost/cc128_parse.pl [cc128_log_mysql.pl]: http://bitbucket.org/oojah/mosquitto/src/tip/misc/currentcost/cc128_log_mysql.pl [2cheap2meter]: http://2cheap2meter.blogspot.com/2010/03/setting-up-google-powermeter.html [google_powermeter_update.pl]: http://bitbucket.org/oojah/mosquitto/src/tip/misc/currentcost/google_powermeter_update.pl ================================================ FILE: www/posts/2010/06/mosquitto-0-7rc1.md ================================================ Mosquitto 0.7 release candidate 1 is available for testing. Please give it a try and report back any problems you find. The source code is available at  and I'll hopefully have various binaries available soon. ================================================ FILE: www/posts/2010/06/version-0-7-released.md ================================================ This is a new features release. Note that although the number of changes is relatively small, there is a fairly major change in the network socket handling (to allow >1024 clients) , which is one reason this has been treated as a separate release. Changes: * Use poll() instead of select() to allow >1024 clients. * Implement `max_connections`. * Run VACUUM on in-memory database on receiving SIGUSR2. * mosquitto_pub can now send null (zero length) messages. * Add option to print debug messages in pub and sub clients. * hg revision is now exported via $SYS/broker/changeset * Add compile time option to disable heap memory tracking. Bug fixes: * 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 (performance advantage) * 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. * 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). Source downloads are available at the [download page] Links for binary packages on Ubuntu and Fedora can be found on the same page. [download page]: /download ================================================ FILE: www/posts/2010/07/mosquitto-on-opensuse-11-3.md ================================================ The upcoming release of [openSUSE], version 11.3, includes extension support for sqlite3 which means it now has everything required for mosquitto. I've created packages for this new version of openSUSE and details can be found on the [download page]. You just need to wait three days until the release of 11.3! [openSUSE]: http://www.opensuse.org/ [download page]: /download ================================================ FILE: www/posts/2010/07/mqtt-client-library.md ================================================ I have been working on a client library for MQTT for the next release of Mosquitto. It is now at a stage where it is usable and ready for wider testing. There isn't any documentation yet (!) so it's only available in the source repository at . Use the "get source" link in the top right corner of the page to download a snapshot. If you're interested in developing your own open source MQTT clients, it'd be great if you could take a look to make sure the interface is sane before I make a release! The library itself is written in C, with bindings for C++ and Python. I plan to package it up in a more easy to access form in the not too distant future, hopefully with some documentation as well. # Update I've put the start of a man page online, which shows an example of using libmosquitto to subscribe to a topic and print the results: [libmosquitto.3]. [libmosquitto.3]: http://mosquitto.org/man/libmosquitto-3.html ================================================ FILE: www/posts/2010/08/compiling-mosquitto-on-mac-os-x.md ================================================ In a follow up to his screencast [demoing mosquitto on Mac OS X], Andy Piper has written a blog post detailing how he got compiled mosquitto and, more importantly, the dependencies, on the Mac. Take a look over at [OS X mosquitto "bites"...] [demoing mosquitto on Mac OS X]: /blog/2010/08/mosquitto-running-on-mac-os-x/ [OS X mosquitto "bites"...]: http://andypiper.co.uk/2010/08/08/os-x-mosquitto-bites/ ================================================ FILE: www/posts/2010/08/mosquitto-running-on-mac-os-x.md ================================================ Andy Piper has put together a 2 minute screencast demoing mosquitto running on Mac OS X and showing publishing and subscribing using the mosquitto command line clients and the IBM java gui client. View the screen cast here: . Thanks Andy! ================================================ FILE: www/posts/2010/08/mqtt-v3-1.md ================================================ The MQTT v3 spec has been updated to v3.1. The significant change is the inclusion of the option to send a username and password as part of the connect command. The new spec is available at and is a lot more readable and clear than the original. Mosquitto will support the v3.1 spec in a future release, along with the ability to control both broker and topic access by username. In the meantime, if you need this functionality, the IBM proprietary [RSMB] broker may be suitable for testing purposes. The RSMB package now also includes an MQTT client library, a simple publish client and a simple subscribe client, just like mosquitto. Be sure to check the license terms before using it! [RSMB]: http://www.alphaworks.ibm.com/tech/rsmb ================================================ FILE: www/posts/2010/08/version-0-8-1-released.md ================================================ This is a minor release. The primary reason for it is the amount of interest in the Python interface to libmosquitto. This release tidies up the Python interface considerably (it is now more "Pythonic" and easier to use), and significantly, brings the promised packages. This release also provides a few fixes, including to the packaging and installation scripts. Unfortunately, it does also include a known bug that was fixed prior to release, but accidentally left unmerged. This affects mosquitto_pub client when using the -l option (publish line by line input from stdin), causing it to exhibit high cpu load. I'll make a new bug fix release in a few days with this and any other fixes that come up. This release also provides improved packaging options. All of the available options are now packaged for Ubuntu, including the libmosquitto0-python package. Because there are now multiple packages, it is possible to provide some mosquitto functionality on distributions where the version of sqlite3 is too old. The packages available on these systems are listed as "clients only": * Fedora 12, 13 (full support) * openSUSE 11.3 (full support) * openSUSE 11.1, 11.2 (clients only) * Redhat Enterprise Linux 5 (clients only) * CentOS 5 (clients only) Details are available on the [download page]. Please note that some distributions have different naming schemes, so the Python module can be called both python-mosquitto and libmosquitto0-mosquitto for example. [download page]: /download ================================================ FILE: www/posts/2010/08/version-0-8-2.md ================================================ This is a bugfix release. * 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. See the [download page]. Includes Windows 32-bit binaries for the broker compiled with Cygwin, and the client library and clients compiled natively with Visual Studio to allow developing native Windows MQTT clients. [download page]: /download ================================================ FILE: www/posts/2010/08/version-0-8-released.md ================================================ This is the library release. There are a few bug fixes and changes of behaviour for the mosquitto and the clients, but the significant part of this release is the new mosquitto MQTT client library. The library comes in three flavours: the C library, which is the main library, and C++ and Python bindings. If you're interested in helping add bindings for your favourite language, please get in touch. The library interface (API) is to be considered experimental, although I believe the C and C++ APIs to be complete and sane. The Python bindings are a naïve attempt by a C programmer and will definitely be changing in the future to something more pythonic. I'd be extremely grateful for help from experienced python programmers to this end. The documentation of the library is currently ongoing... There is an overview of most of the function calls and an example in the [libmosquitto.3] man page, but complete coverage can be found in the mosquitto.h man page. This, combined with the class details in mosquittopp.h can be used to help use the C++ library. The python module isn't documented due to its extremely changeable state, but there is an example in the python directory. Other changes: * 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. Get it from the [download page]. The change to using a library means that packaging mosquitto for distros is a lot more complex. This is stretching my packaging experience, so please bear with me on that front! Mosquitto will now likely consist of a number of different packages on Ubuntu at least: * mosquitto (the broker) * mosquitto-clients (mosquitto_sub, mosquitto_pub) * libmosquitto0 (C library) * libmosquitto0-dev (C library development files) * libmosquittopp0 (C++ library) * libmosquittopp0-dev (C++ library development files) * libmosquitto-python (Python binding) # Update I've been getting a few questions about the python interface. This isn't currently packaged for Ubuntu, but hopefully will be soon. There are basic python examples in the downloads at lib/python/sub.py and misc/currentcost/gnome-panel/CurrentCostMQTT.py [libmosquitto.3]: /man/libmosquitto-3.html [download page]: /download ================================================ FILE: www/posts/2010/09/debian-packages.md ================================================ I've created some packages for Debian on i386 and amd64. They can be found at . They are almost identical to the Ubuntu packages (Debian doesn't use upstart, so there is a different init script), but compiled against Debian testing (Squeeze) instead. This is because Debian 5 (Lenny) doesn't include a recent enough version of sqlite3. Please let me know if you have any problems with the packages. ================================================ FILE: www/posts/2010/09/mqtt-with-php.md ================================================ Using MQTT in PHP has been possible for a long time using the [Simple Asynchronous Messaging] MQTT class. Unfortunately this is an imperfect solution due to unclear licensing, some slightly dubious design decisions and bugs. Thankfully, [Andrew Milstead] has started creating an alternative implementation. It is MIT licensed and available on [github]. It's very new, so if you have problems check back to see if there have been updates and then let Andrew know. [Simple Asynchronous Messaging]: http://project-sam.awardspace.com/ [Andrew Milstead]: http://twitter.com/bluerhinos [github]: http://github.com/bluerhinos/phpMQTT ================================================ FILE: www/posts/2010/10/man-page-translations.md ================================================ Something that is very much in the back of my mind whilst developing mosquitto is that it should have support for language translations. I've been reluctant to start this effort until development was a little bit more settled, to avoid wasting translators time. I think it's now time to start the ball rolling. I'm going to approach this in two stages - the man pages and the programs. Man pages are first. I've imported the translation templates to launchpad, so if your native tongue is anything other than English and you'd like to translate them - please go ahead. I'll be putting any translated man pages (with credits :) into the upcoming 0.9 release. I think I've finished making changes but if I haven't, the one most likely to change is for mosquitto.conf The translation page can be found at Thanks in advance, and please get in touch if you find any strings that don't make sense. ================================================ FILE: www/posts/2010/10/one-year-old.md ================================================ On the 25th October 2009, at 21:40:51 (just five hours and forty minutes after the first [oggcamp] ended :), I made the first commit to what would become the mosquitto source code repository. Although there was no code committed until the next day, and the first release wasn't until almost six weeks later, I consider this to be when mosquitto was born. It's been a good year. Thanks to everybody who has helped out and been in touch! I had hoped to release version 0.9 today, but it isn't to be. Nevertheless, I hope you'll join me in hoping for an even more successful year ahead. I'm aiming for a 1.0 release before this time next year with full MQTT 3.1 support, full rsmb feature set (except where inappropriate), IPv6 support, SSL support, language translation for the programs and man pages, full API documentation and examples, and whatever I think of in the meantime. Have a feature you're particularly interested in? Leave a comment! :) [oggcamp]: http://oggcamp.org/ ================================================ FILE: www/posts/2010/10/version-0-8-3-released.md ================================================ This is a bugfix release. * Fix compliance with the MQTT protocol for messages published at QoS 2. This means that messages that time out are dealt with correctly and duplicate messages are also dealt with correctly. See the [download page] for the update. [download page]: /download ================================================ FILE: www/posts/2010/11/distro-packaging.md ================================================ Starting with version 0.9, I plan on getting mosquitto packaged in the major Linux distributions. By this I mean Debian, Fedora, openSUSE and Ubuntu.  This is my understanding of the current state of play of those distributions. Feel free to correct me! * Debian is currently in freeze for the Squeeze release. Mosquitto will have to go into Squeeze+1, although it can still be uploaded to Unstable. * Fedora 14 has just been released, Fedora 15 will have feature freeze on the 8th of February. * openSUSE 11.4 will have feature freeze at the start of December. * Ubuntu 11.04 has its Debian import freeze on the 30th of December and feature freeze on 24th of February. The plan is therefore to release 0.9 around the 14th of November and aim to be packaged for Debian unstable before 30th of December and openSUSE before the start of December, with packaging for Fedora 15 coming at some point later. If packaging for Debian unstable isn't possible before the Ubuntu import freeze, then package for Ubuntu separately. If you can help out with the packaging process for any of the above, I'd love to hear from you. If your distribution isn't included and you'd like it to be, get in touch as well and we'll see what's possible. Finally, this won't stop me producing Ubuntu PPA or openSUSE build service packaged binaries for those that prefer to stay at the cutting edge. ================================================ FILE: www/posts/2010/11/mosquitto-0-9test2.md ================================================ Mosquitto 0.9, which I hope to release mid November, represents the most significant change to mosquitto to date - the removal of sqlite as an absolute dependency. In addition, this removes the dependency on the sqlite3-pcre extension and on pcre. This gives a definite performance improvement, reduces the amount of object code that needs loading by around 95%, reduces memory usage and also makes it lots easier to compile on more unusual systems. It's quite a substantial change though, so I've made a test release to hopefully get some external testing. If you could give it a try and report back that'd be great. The source is at . (use the highest numbered version available). There are also Ubuntu packages available at the [mosquitto-expt ppa] and binaries for Fedora, Mandriva,  SLES and openSUSE at the [openSUSE build service]. If you'd like binaries for other systems, please get in touch. Note that this is a test release, not a release candidate - there are definitely things that still need changing. The following list shows the points I'm currently aware of: * Old style sqlite will be imported when the option is compiled in (enabled by default). This import currently only imports retained messages and durable subscriptions, but not queued messages. * ~~The `max_inflight_messages` and `max_queued_messages` config options are ignored and no maximum is applied.~~ * ~~The CMake compilation scripts aren't updated.~~ # Update I've uploaded test3 with a python fix, updated CMake scripts and fixed `max_inflight_messages` and `max_queued_messages`. [mosquitto-expt ppa]: https://launchpad.net/~mosquitto-dev/+archive/mosquitto-expt [openSUSE build service]: https://build.opensuse.org/project/show?project=home%3Aoojah%3Amqtt_expt ================================================ FILE: www/posts/2010/11/version-0-9-released.md ================================================ This is a features release. It is probably the most significant change for mosquitto so far. The important change is the removal of the sqlite dependency, along with the associated pcre and sqlite3-pcre dependencies. This results in better performance both in terms of messages handled per second and memory usage. Optional support for importing existing persistent databases in sqlite3 format is provided, with the option compiled in by default. This will be set to not be compiled by default in 0.10 and then removed in 0.11. This release also provides support for the recently updated MQTT v3.1 spec - most notably offering username/password authentication support. The client library and clients have full v3.1 support. The broker is fully compatible with v3.1, but doesn't provide any mechanism for controlling username/password control. This will come in 0.10. One goal of mosquitto is to be a drop in replacement for the IBM rsmb broker. Another goal is to do more than rsmb :) I'm still working on the first goal, but this release helps with the second as mosquitto now has IPv6 support, which isn't supported in rsmb. A detailed list of changes is given below: * 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. See the [download page] for the update. Debian and Ubuntu users should note that the package libmosquitto0-python has been renamed python-mosquitto to comply with Debian naming policies. The Debian packages aren't yet ready. [download page]: /download ================================================ FILE: www/posts/2010/12/version-0-9-1-released.md ================================================ This is a bugfix release. * 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. Source code is on the [download page], binary packages will follow on later. [download page]: /download ================================================ FILE: www/posts/2011/01/mosquitto-for-slackware.md ================================================ Chris Willing of the University of Queensland has very kindly put together some mosquitto packages for Slackware 13.0 and 13.1 as well as instruction on how to build your own packages. The packages and instructions are here: I've also put the link on the downloads page. Thanks Chris! ================================================ FILE: www/posts/2011/01/mqtt-news.md ================================================ Here are some MQTT updates from out there on the internet: A new perl client implementation by Mark Hindess * A [homebrew] recipe for installing mosquitto on Mac by Adam Rudd * MQTT implemented for the mbed processor by Yiluin Fan * [homebrew]: http://brew.sh/ ================================================ FILE: www/posts/2011/02/lightweight-messaging-and-linux.md ================================================ Andy Piper was at [Linux Conf Australia] this year and gave a talk on MQTT. His blog post Lightweight Messaging and Linux] gives a few details and has a link to the slides. The video can be seen at [Linux Conf Australia]: http://linux.conf.au/ [Lightweight Messaging and Linux]: http://andypiper.co.uk/2011/01/28/lightweight-messaging-and-linux/ ================================================ FILE: www/posts/2011/02/mosquitto-on-maemo.md ================================================ Yuvraaj Kelkar got in touch to say he's packaged up mosquitto and the client libraries for Maemo. If you want to use MQTT on your Maemo device then take a look at the details on Thanks Yuvraaj! ================================================ FILE: www/posts/2011/02/mqtt-on-android.md ================================================ Dale Lane has written an enormous blog post [Using MQTT in Android Mobile Applications in which he talks about a lot of the points you are likely to want to consider if you're writing MQTT applications for Android. There's lots of useful information and he even includes a complete source code implementation. [Using MQTT in Android Mobile Applications]: http://dalelane.co.uk/blog/?p=1599 ================================================ FILE: www/posts/2011/02/version-0-9-2-released.md ================================================ This is a bugfix release: * 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. Thanks to Mark Hindess, Joshua Lock, Adam Rudd and Ben Davenport for their help. The source code is available as always on the [download page]. Binaries will appear shortly. [download page]: /download ================================================ FILE: www/posts/2011/03/api-documentation.md ================================================ I've rewritten the API documentation for the C library using the [NaturalDocs] format. This covers the whole C library and so should give enough information for anybody using the C++ or Python wrappers as well. The documentation generated from mosquitto.h is available at [NaturalDocs]: http://www.naturaldocs.org/ ================================================ FILE: www/posts/2011/03/mosquitto-in-mac-homebrew.md ================================================ Thanks to work done by Adam Rudd, mosquitto is now available in the Mac [homebrew](https://brew.sh) package manager. Once you've installed homebrew (see the link), you can install mosquitto with: ``` brew install mosquitto ``` ================================================ FILE: www/posts/2011/03/version-0-9-3-released.md ================================================ This is a bugfix release: * 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. Please see the [download page]. Thanks to Joe B, David Monro,  Yuvraaj Kelkar and Colin Jones. [download page]: /download ================================================ FILE: www/posts/2011/04/version-0-10-released.md ================================================ This release brings the new MQTT v3.1 features to the broker - client authentication and topic access control. See [mosquitto.conf(5)] or the included example password and ACL files. * 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. Please see the [download page]. Thanks to Adam Rudd, Joshua Lock,  Sang Kyeong Nam and Yuvraaj Kelkar. [mosquitto.conf(5)]: /man/mosquitto-conf-5.html [download page]: /download ================================================ FILE: www/posts/2011/05/mqtt-ontology.md ================================================ Mark Hindess has written a blog post titled [Home Automation Protocols: MQTT], where he asks for suggestions on how to go forward making "a specification for topic usage and semantics". I think this kind of work is really valuable to make it easy to have different MQTT systems that can interoperate. If you've got any suggestions you can make, please go and leave a comment there. [Home Automation Protocols: MQTT]: http://www.temporalanomaly.com/blog/2011/05/02/home-automation-protocols:-mqtt ================================================ FILE: www/posts/2011/05/version-0-10-1-released.md ================================================ This is a bugfix release primarily for Windows users. * 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). Please see the [download page]. Thanks to Karl Palsson. [download page]: /download ================================================ FILE: www/posts/2011/06/nanode-a-cheap-networked-arduino-clone.md ================================================ The arduino, the open source microcontroller board, has had MQTT support for a long time in the form of [Nick O'Leary's arduino client]. It does however require networking support which has traditionally provided by an add on shield, which increases the cost of the system. The [Nanode] is an arduino compatible board which includes network support and can be built for approximately the same cost as a normal arduino board. It's still a work in progress, but is definitely worth a look if you want to use low power MQTT capable sensors/controllers. [Nick O'Leary's arduino client]: http://knolleary.net/arduino-client-for-mqtt/ [Nanode]: http://nanode.eu/ ================================================ FILE: www/posts/2011/06/version-0-10-2-released.md ================================================ This is a bugfix release. * 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). Please see the [download page]. Thanks again to Karl Palsson and Yuvraaj Kelkar. [download page]: /download ================================================ FILE: www/posts/2011/06/version-0-11-1-released.md ================================================ This is an important bugfix release. It fixes a buffer overrun that affects 0.11 only. Users of 0.11 should upgrade immediately. * Fix buffer overrun when checking for + and # in topics (bug #799688). * Pub client now quits if publish fails. Thanks to Karl Palsson. ================================================ FILE: www/posts/2011/06/version-0-11-2-released.md ================================================ This is a bugfix release. * Don't free contexts in mqtt3_context_disconnect() (bug #799688 / #801678). * Only free will if present when freeing a client context. ================================================ FILE: www/posts/2011/06/version-0-11-released.md ================================================ This is an update with some fairly minor changes and some bug fixes. I had planned on more exciting features but my time has been occupied getting ready for the 25th, when I'm getting married. Those changes will just have to wait until 0.12! * 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). Thanks to Sebastian Kroll and Karl Palsson. ================================================ FILE: www/posts/2011/07/debian-and-ubuntu-packaging.md ================================================ I'm very pleased to say that Mosquitto is very nearly packaged in Debian and Ubuntu. In truth, 0.10 is packaged and uploaded for both Debian testing (Wheezy) and Ubuntu Oneiric Ocelot, but there is a problem with the config that means it won't restart properly. That is fixed with the 0.11.3 upload which is now in unstable. That means after 10 days and it will be in Debian testing for all to use. I've also submitted a sync request with Ubuntu ([bug #808530]) to ensure it makes it across. I'll still be maintaining the Launchpad PPA for older versions of Ubuntu. Thanks to the Debian developer Michael Tautschnig for reviewing my package and doing the upload. [bug #808530]: https://bugs.launchpad.net/ubuntu/+source/mosquitto/+bug/808530 ================================================ FILE: www/posts/2011/07/lua-mqtt-client.md ================================================ Andy Gelme [reports] that his Lua MQTT client is ready for use. The downloads, installation and usage instructions, example code and api information are all available at . I particularly like the image of it running on a PSP. Well done Andy! I wonder what the next language to get MQTT support will be? [reports]: https://twitter.com/#%21/geekscape/status/96710950979256323 ================================================ FILE: www/posts/2011/07/mosquitto-on-qnx.md ================================================ Andrea asked a [question on launchpad] about problems compiling Mosquitto on QNX. I've now managed to get an evaluation version of QNX and fix the compilation problems. These fixes will be in 0.12, but you can get them in the current snapshot if it's urgent. I've also put compiled binaries in the [downloads directory] but they are completely untested, so use at your own risk. Although I've provided these binaries I don't intend to keep doing so for each version of Mosquitto. I will endeavour to fix any other problems that arise in the future though. [question on launchpad]: https://answers.launchpad.net/mosquitto/+question/164154 [downloads directory]: http://mosquitto.org/files/binary/qnx/ ================================================ FILE: www/posts/2011/07/version-0-11-3-released.md ================================================ This is a bugfix release. * 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) Thanks to Neil Bothwick, Yuvraaj Kelkar, Craig Hollabaugh, Karl Palsson and Andy Piper. ================================================ FILE: www/posts/2011/07/version-0-12-released.md ================================================ This is an update with some features and bug fixes. The most significant change is configuration reloading support. This will be improved to include bridge reloading in the future. * 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. ================================================ FILE: www/posts/2011/07/wireshark-mqtt-decoder.md ================================================ If you're trying to debug your MQTT connection, you may be interested in something Karl P has written - an MQTT decoder/dissector for Wireshark. It doesn't have complete protocol support yet, but is a good start. * ================================================ FILE: www/posts/2011/08/arch-linux-package.md ================================================ Gordon Pearce has packaged Mosquitto on Arch Linux through an Arch User Repository. The package details are at Thanks Gordon! ================================================ FILE: www/posts/2011/08/facebook-using-mqtt.attachments.json ================================================ {"165": {"wordpress_user_name": "roger", "title": "iphone-app", "date_utc": "2011-08-17 15:40:22", "files_meta": [{"height": 768, "width": 1024}, {"height": 225, "size": "medium", "width": 300}, {"height": 150, "size": "thumbnail", "width": 150}], "files": ["/wp-content/uploads/2011/08/image.png", "/wp-content/uploads/2011/08/image-300x225.png", "/wp-content/uploads/2011/08/image-150x150.png"]}} ================================================ FILE: www/posts/2011/08/facebook-using-mqtt.md ================================================ Something else that has happened recently is the announcement by Facebook that they're using MQTT in their new [Facebook Messenger app] They've posted some details in a [facebook-engineering blogpost] and cite the low bandwidth and battery usage as important considerations. This is very exciting as an application that is potentially huge and very user oriented (rather than "internet of things" oriented), but the really exciting bit is if you use an iPhone under Settings and Licenses (apparently it's quite hard to find): Thanks to Michael Rowe for getting me the screenshot and Andy Piper for pestering Michael on my behalf. You should note that if you're in the UK, the Facebook Messenger app isn't currently available. [Facebook Messenger app]: https://www.facebook.com/mobile/messenger [facebook-engineering blogpost]: http://www.facebook.com/notes/facebook-engineering/building-facebook-messenger/10150259350998920 ================================================ FILE: www/posts/2011/08/mosquitto-on-openwrt.md ================================================ Thanks to work done by Karl Palsson, Mosquitto is now available on [OpenWrt], the embedded Linux distribution frequently used on wireless routers. This is exciting if you want a really low power way of running an MQTT broker. It also includes the mosquitto clients and development libraries. It's only in the source tree at the moment, so if you want to install it I believe you'll have to download everything and compile it yourself. Update: Karl tells me that if you're running a binary snapshot from trunk then you can do: ``` opkg update opkg install mosquitto mosquitto-client libmosquitto ``` You only need to build it yourself if you're running a stable binary. [OpenWrt]: https://openwrt.org/ ================================================ FILE: www/posts/2011/08/mqtt-standardisation.md ================================================ IBM have announced that MQTT is to be formally standardised. If you're interested in taking part in the process, there are full details at ================================================ FILE: www/posts/2011/09/version-0-13-released.md ================================================ This release brings some new features and fixes. Although there are no real "killer features", this release does include some fairly significant updates. Of particular note are the fixes to subscription wildcard matching, which now meets the spec in all cases, the Python payload parameter being a Python string which should make life lots easier for Python developers, the non clean-session client fixes and related persistent database fixes. * 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. ================================================ FILE: www/posts/2011/10/mqtt-power-usage-on-android.md ================================================ Stephen Nicholas has carried out some power usage analysis of MQTT on Android. Details are at and the conclusion is that it doesn't use much power. ================================================ FILE: www/posts/2011/10/two.md ================================================ Today (just) marks the 2nd birthday of the mosquitto project. In the past year mosquitto has undergone pretty substantial changes and improvements. Some highlights from the year: * Move away from using sqlite to store data in memory and on disk, resulting in a much more compact, better performing and *more elegant* broker * Windows native port * MQTT 3.1 support * Greatly improved Python module * Getting really close to being feature complete with respect to RSMB * Being packaged in Debian... * ... and Ubuntu * The mosquitto client code being used by Facebook in their iphone app * The numerous bugs reported, bugfixes, suggestions and general interest displayed by people. Thanks everyone! Mosquitto has gone from version 0.8.3 to 0.13 - so what about next year? This will be the year when 1.0 is released. The bar I'm setting is complete RSMB features, with the exception of some of the more esoteric ones. At the moment this means there are still some of the bridge features to implement and complete configuration reloading. I'm also going to have a much improved Windows port so there will be no need for a separate Cygwin version. At the same time I'm making a Windows installer and allowing mosquitto to be installed as a proper Windows service. This work should all be in 0.14. Another point for improvement is the Python module - it could be more Pythonic than it is now. My current plan is to have it throw exceptions rather than return integer error values but I could do with the help of a Python expert really. All in all I think it should be a good year. ================================================ FILE: www/posts/2011/11/android-mqtt-example-project.md ================================================ To celebrate the news that the IBM Java MQTT client implementation will be released as open source, I've put together a simple Android example based on the [MQTT service code written by Dale Lane]. I'm a beginner at both Java and Android, so expect it to be a bit rough. The example displays incoming payload text on a text label. It's a complete project that you can build and install on your phone with only a few small changes - search for "CHANGE ME" in src/org/mosquitto/android/mqtt/MQTTDemo.java. To get the project working, assuming you've already installed the android sdk, first get the IBM Java library (see ) and put it in <project dir>/lib then do the following: ``` android update project -p <path to project> # If the update complains about build.xml - delete it and run again cd <path to project> ant debug sudo adb start-server ant installd ``` I'll not be at all surprised if there are problems in the project due to different sdk or tool versions. Please comment if you find a problem. The project is available from . Until the IBM Java implementation is open source please be aware of the licence attached to it. Thanks to Dale for the core Android MQTT service implementation. [MQTT service code written by Dale Lane]: http://dalelane.co.uk/blog/?p=1599 ================================================ FILE: www/posts/2011/11/ibm-java-and-c-clients-to-be-open-source.md ================================================ The web is currently buzzing with the announcement yesterday that IBM and Eurotech are donating MQTT to the Eclipse Foundation. One part of this is the new [Machine to Machine Working Group], again part of Eclipse. Another much more significant part has been released as part of a new Eclipse open source project [Paho], which is in the proposal stage. The exciting part is the "Initial contributions" section which states "The initial code contribution to Paho will include  Java and C client-side implementations the MQTT protocol, contributed by IBM. " It looks like the code will be licensed under the EPL (Eclipse Public License). This is particularly exciting because there is currently no solid freely available and usable implementation of MQTT in Java. Well done everyone at IBM for making this happen. Roll on the end of November! Update: This post on mqtt.org explains what the various announcements mean more clearly: Update 2: Andy Piper's blog post covers things even better, along with clearing up some of the confusions from the news releases: [Machine to Machine Working Group]: http://wiki.eclipse.org/M2MIWG_charter_draft [Paho]: http://www.eclipse.org/proposals/technology.paho/ ================================================ FILE: www/posts/2011/11/new-linux-repositories.md ================================================ I've just added some more Linux repositories to the download page for Fedora 16 and SLE 10, 11 and 11 SP1. Note that mosquitto-python isn't available on SLE 10. See the [download page](/download). ================================================ FILE: www/posts/2011/11/version-0-14-1-released.md ================================================ This is a bugfix release. * Fix Python syntax errors (bug #891673). ================================================ FILE: www/posts/2011/11/version-0-14-2-released.md ================================================ This is a bugfix release: * Add uninstall target for libs. * Don't try to write packet whilst in a callback. ================================================ FILE: www/posts/2011/11/version-0-14-released.md ================================================ This is a fairly minor feature release. The major changes are the pattern matching ACL support, the support for running directly as a Windows service and the change to the network code to attempt to send packets immediately. The Windows binary is now supplied as an installer rather than a zip file. * 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 / ================================================ FILE: www/posts/2011/12/mqtt-on-nanode.md ================================================ [Nanode], the popular arduino-with-ethernet board started early in 2011 is ideal for small MQTT based projects but has so far lacked an implementation of MQTT. Nick O'Leary, the author of the original Arduino MQTT client, [has created a Nanode implementation], but it [isn't quite ready for the public]. Nicholas Humfrey has made public some code at that he says [still needs some work] but supports publishing QoS 0 messages of up to 127 bytes long and subscribing to topics with QoS 0. [Nanode]: http://nanode.eu/ [has created a Nanode implementation]: https://twitter.com/#!/knolleary/status/151057575775965184 [isn't quite ready for the public]: https://twitter.com/#!/knolleary/status/151059089881960448 [still needs some work]: https://twitter.com/#!/njh/status/152913104446038018 ================================================ FILE: www/posts/2011/12/version-0-14-3-released.md ================================================ This is a bugfix release. * 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. ================================================ FILE: www/posts/2012/01/challenge-web-based-mqtt-graphing.md ================================================ Thanks to a data feed courtesy of an IBM broker, [test.mosquitto.org] now publishes information on energy generation and demand in the UK (in the energy/ topic tree). I think this could be used as a great demonstration for coupling MQTT and the web. # The challenge Create a web based report that takes energy data from the broker over MQTT and displays it in interesting and useful ways. Alternatively, an Android/iPhone app would be ok, but web based is the preferred option. # The rules There are no rules really. Having said that, I'd be most pleased if the end result was something that other people could learn from. There are bonus points for solutions that work where a web proxy is the only internet access. If you want to use new or unusual technologies that's fine. # The prize I'm afraid there is no tangible prize - I hope you'll be content with your work being shown here and the respect of your peers. # Some suggestions Google charts is definitely worth looking at for generating the actual graphs. Some examples of what you might show are: * Pie chart of generation source * Gauge of current mains frequency * Historical graph of electricity export amount I look forward to any and all responses! [test.mosquitto.org]: http://test.mosquitto.org/ ================================================ FILE: www/posts/2012/01/do-you-use-mqtt.md ================================================ I saw this in the nanode irc channel: > I've never seen any real world projects with MQTT... it looks good though. So I'm looking for real world projects that use MQTT. If you've got a project it'd be great if you could mention it in the comments. A short sentence on what it does and how many clients you run on it - really anything you can say. If it's a secret please still comment if you can, just be very very vague. If you've got a blog post describing it, link that instead. I'm interested in everything from a single temperature sensor reporting to a computer up to millions of mobile users. Thanks! ================================================ FILE: www/posts/2012/01/mosquitto-test-server.md ================================================ A publicly accessible Mosquitto server is now available to use. Details are at [test.mosquitto.org] [test.mosquitto.org]: http:/test.mosquitto.org/ ================================================ FILE: www/posts/2012/01/version-0-14-4-released.md ================================================ This is a bugfix release: * 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. ================================================ FILE: www/posts/2012/02/mqtt2pachube.md ================================================ I've written a tool to help get data from mqtt to [pachube]. Existing pachube libraries offer good support for updating feeds that have a single datastream or updating all feeds in a datastream, but seem to offer limited support for updating an arbitrary datastream on its own. This can make life difficult when your data is coming in from sensors as individual messages. [mqtt2pachube] allows you to choose what mqtt subscriptions to make and then match incoming messages by their topics to a pachube feed and datastream id. At the moment it is still experimental, but seems to work. It has highlighted a shortcoming in the mosquitto client library, so requires version 0.15.90 (ie. the in-progress work for the next release). There is no Windows support for the moment and no binary packages either. If you are interested in giving it a try, you will have to compile it yourself. If you need help, please get in touch. There are two examples of feeds created through mqtt2pachube using data from [test.mosquitto.org] * [test.mosquitto.org details] * [UK energy data - generation source percentage] [pachube]: http://pachube.com/ [mqtt2pachube]: http://bitbucket.org/oojah/mqtt2pachube [test.mosquitto.org details]: https://pachube.com/feeds/43810 [UK energy data - generation source percentage]: https://pachube.com/feeds/47080 [test.mosquitto.org]: http://test.mosquitto.org/ ================================================ FILE: www/posts/2012/02/version-0-15-released.md ================================================ This is a feature and bugfix release. * Implement "once" and "lazy" bridge start types. * 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. * 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. ================================================ FILE: www/posts/2012/03/quick-start-guide-for-mqtt-with-pachube.md ================================================ Pachube (now Cosm) has recently announced beta support for publishing and receiving data to their service using MQTT. This is great news and something I know that a lot of people have been hoping for. Well done Pachube! Their documentation is at and provides enough information to get going if you're already familiar with MQTT. If you aren't familiar with MQTT, here's a few examples of how you can use the new service. First off, I'm going to use the command line MQTT clients I've created to publish and receive data. You can get these clients as part of the [mosquitto download].   # Command Line Examples ## Publishing Data ``` mosquitto_pub -h api.xively.com -u <your xively api-key> -t /v2/feeds/504.csv -m "0,29" ``` In this example we're connecting to host api.xively.com, using our xively api-key as the username, publishing to feed /v2/feeds/504 using the csv format and are updating datastream 0 with the value 29. Another way to achieve the same thing would be to do: ``` mosquitto_pub -h api.xively.com -u <your xively api-key> -t /v2/feeds/504/datastreams/0.csv -m 29 ``` mosquitto_pub can read data from stdin and publish it, so on Unix type systems the following arrangement is possible: ``` sensor_read | mosquitto_pub -h api.xively.com -u <api-key> -t /v2/feeds/504/datastreams/0.csv -l ``` The `-l` option reads messages from stdin, sending a separate message for each line. This means that our imaginary executable sensor_read that is reading data from a sensor must be printing each reading as a text line. ## Retrieving Data In the MQTT world, retrieving data is done through subscriptions: ``` mosquitto_sub -h api.xively.com -u <api-key> -t /v2/feeds/504/datastreams/0.csv ``` In this example, mosquitto_sub will print a text line containing the csv data for datastream 0 of feed 504 every time it is updated. ## Last Will and Testament The last will and testament or just "will" is a very nice feature of MQTT. When your client connects to the MQTT broker/server, it can give the broker this will, which consists of a topic and a message. If the client is disconnected from the broker unexpectedly, that is to say without sending a disconnect message, then the broker publishes the will message on the will topic. This provides a very simple mechanism for client connection monitoring. When your client connects it could publish a message "1" to a topic. If it also set a will to send a message "0" to the same topic on unexpected disconnect, then it would be possible to determine whether that client was connected by monitoring the topic. In the context of Xively, the same approach is possible, but using a trigger to indicate that the client had disconnected. The mosquitto_sub client provides support for wills as shown in the example below: ``` mosquitto_sub -h api.xively.com -u <api-key> -t /v2/feeds/504/datastreams/0.csv --will-topic /v2/feeds/12345/datastreams/0.csv --will-payload "0" ``` In this example, the Xively broker would publish the value "0" to datastream 0 of feed 12345  if mosquitto_sub disconnects unexpectedly. This isn't the most useful example because of the limitations of what mosquitto_sub provides. # Writing Your Own Clients In practice, to get the full benefit of the advantages that MQTT provides you will probably want to write your own MQTT client to connect to Xively for your specific application. The page lists client implementations for lots of different programming languages including the mosquitto client libraries in C/C++, libraries in Java, Python and also device specific implementations for Arduino and other low power devices. # MQTT Beyond Xively The Xively offering is a slightly restricted MQTT offering. "Full" MQTT offers a bit more scope for doing fun things using topic wildcards for example, something that wouldn't really make sense for Xively. There is an overview of MQTT at [mqtt man page] and examples of some applications at . If you'd like to play on an MQTT broker, try looking at [test.mosquitto.org]. If you want some help there are mailing lists and irc channels listed on . [mosquitto download]: /download [mqtt man page]: /man/mqtt-7.html [test.mosquitto.org]: http://test.mosquitto.org/ ================================================ FILE: www/posts/2012/03/upcoming-incompatible-library-changes.md ================================================ Version 0.16 of the mosquitto client libraries will have some binary incompatible changes to their APIs. This means that it is a good time to make other changes that are incompatible. If you think any part of the interface (see ) is crazy or could be improved in any way, please get in touch or add a comment below. ================================================ FILE: www/posts/2012/05/python-client-module-available-for-testing.md ================================================ As part of the ongoing work on mosquitto 0.16, the libmosquitto C client library has been ported to Python. It provides complete MQTTv3.1 support and will eventually remove the need for the current Python wrapper around the C library and will allow it to be used more easily and in more situations. The interface is largely the same as the existing Python wrapper. The differences are that it uses the current development interface which differs slightly from that in 0.15 (see the [Python documentation]), not all of the new interface is implemented - there is no threading support and finally some datatypes may be more Python like (e.g. lists in `on_subscribe()` callback rather than an integer). The conversion from ~4000 lines C to ~1000 lines Python took just two evenings and is now ready for testing. It is available in the 0.16 branch in the [bitbucket repository], or as a single file at Please give it a try and report any bugs you find using any of the methods on the [Support page]. Please note that the new Python module does not currently support Python 3. [Python documentation]: /documentation/python [bitbucket repository]: https://bitbucket.org/oojah/mosquitto/src/b9e04ef2a762/lib/python/mosquitto.py [Support page]: /support ================================================ FILE: www/posts/2012/06/ipv6-on-test-server.md ================================================ The public Mosquitto test server, [test.mosquitto.org] has supported IPv6 since it was originally put online but the required DNS record was missing. This has now been fixed so once the record has propagated across the internet you should be able to test your IPv6 clients. [test.mosquitto.org]: http://test.msoquitto.org/ ================================================ FILE: www/posts/2012/06/ssl-support-on-test-server.md ================================================ The next version of Mosquitto will provide SSL support for network encryption and authentication. This work is still in development, but is sufficiently advanced to make available for testing on [test.mosquitto.org]. In addition to the existing unencrypted access via port 1883, connections are now possible on ports 8883 and 8884. Port 8883 provides simple encrypted access. Your client should verify the server certificate using the CA certificate available at Port 8884 uses the same server certificate, but requires that your client provide a valid certificate signed by the mosquitto.org CA key. If you wish to obtain a client certificate for testing purposes, please get in touch. The development Python module provides client SSL support. The latest version is available at [mosquitto.py] with a simple example at [ssub.py]. You will need to place the mosquitto.org CA certificate linked above in the same directory. All versions of Python from 2.7 upwards (including Python 3) are supported. Please get in touch if you have any problems. Update: All clients in the development version now support SSL. [test.mosquitto.org]: http://test.mosquitto.org/ [mosquitto.py]: http://test.mosquitto.org/ssl/mosquitto.py [ssub.py]: http://test.mosquitto.org/ssl/ssub.py ================================================ FILE: www/posts/2012/07/upcoming-release.md ================================================ The next release of mosquitto is approaching. There is currently only one feature left on the todo list to complete and I've pencilled in the end of the month as the release date. The date may slip a week or two after that depending on any bugs reported. Despite the development being carried out in the 0.16 branch and the current in-development version numbers being 0.15.90, this will be version 1.0 of mosquitto. There has been significant API changes (now a lot more sane hopefully) which means the client library interface version has been incremented, and the number of changes involved in this release far outreach any previous release, including SSL support, a pure Python client implementation, a healthy start on tests and an associated improvement in protocol compliance, and threaded client support. I think it is well worthy of the version number. I am, however, very keen that this be as bug free a release as possible. To this end, if you're a mosquitto user I'd be very appreciative if you'd download the current source code and give it a try. Maybe read through the documentation and check it makes sense The source for the current version is at either of these links (ignore the "0.16", that is just the branch name): * * If you want to test but with a minimum amount of effort, please download the source, run "make test" and report back any problems. This would be particularly  useful if you are using something other than a Debian/Ubuntu/openSUSE based Linux. If you have any problems, bugs can be reported at , by leaving a comment or by getting in touch directly. I'm interested in anything, but would be especially keen to hear from you if you think something to do with the client API needs changing. Thanks in advance! ================================================ FILE: www/posts/2012/08/baby.attachments.json ================================================ {"243": {"wordpress_user_name": "roger", "title": "IMAG0006", "date_utc": "2012-08-22 09:39:33", "files_meta": [{"height": 333, "width": 500, "meta": {"camera": "HTC Wildfire S A510e", "created_timestamp": 1345456796.0, "focal_length": 3.53, "iso": 165.0}}, {"height": 199, "size": "medium", "width": 300}, {"height": 150, "size": "thumbnail", "width": 150}], "files": ["/wp-content/uploads/2012/08/IMAG0006.jpg", "/wp-content/uploads/2012/08/IMAG0006-300x199.jpg", "/wp-content/uploads/2012/08/IMAG0006-150x150.jpg"]}} ================================================ FILE: www/posts/2012/08/baby.md ================================================ [![baby](/blog/uploads/2012/08/IMAG0006-300x199.jpg)](/blog/uploads/2012/08/IMAG0006.jpg) I've recently become a father, so please don't be offended if I take a while to respond to any mosquitto related queries. ================================================ FILE: www/posts/2012/08/bugfix-coming-soon.md ================================================ A few bugs have been identified with the 1.0 release; thanks to everyone who has got in touch about it. They're mostly documentation/build script mistakes (see [ChangeLog.txt]), but there is a Python bug that makes it worthwhile making a quick bugfix release. I intend to make the release this evening (in around 8 hours from this post), so if you have anything you think needs fixing please try and get in touch before then. [ChangeLog.txt]: /ChangeLog.txt ================================================ FILE: www/posts/2012/08/version-1-0-1-released.md ================================================ This is a bugfix release. The important changes are fixing the `on_log()` callback in the Python module and the `log_dest` option when running as a Windows service. The rest of the fixes are documentation and build script fixes. Downloads are available on the [download page] and include all supported binaries (except for Ubuntu packages which are still waiting to build due to Launchpad maintenance). The Python module has been uploaded to [Python Package Index]. # 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. [download page]: /download [Python Package Index]: http://pypi.python.org/pypi ================================================ FILE: www/posts/2012/08/version-1-0-2-released.md ================================================ This is a bugfix release. # 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. ================================================ FILE: www/posts/2012/08/version-1-0-released.md ================================================ This is a feature and bugfix release. This is the most significant release for the mosquitto project so far. It encompasses >20% of the total commits for the project and has an increase in source tarball size of 95%, mostly down to the new bundled tests and new man pages. It introduces lots of new features for the broker and improves the API of the client libraries, although this does mean that the libraries are incompatible with previous releases. I apologise for this and hope you'll agree that the changes are worth it. I've been overwhelmed with the amount of feedback that I've received recently, thanks to everyone that has got in touch to let me know where something could be improved. I'd particularly like to thank Nicholas Humfrey for setting me on the continuous integration path. On a slightly different note, my wife was expecting our first child two days ago so it's quite likely I'll be less responsive to support requests for a little while. # Significant changes These are what I think are the exciting changes for this release. * SSL/TLS support across the board - the broker, client libraries and pub/sub clients. This provides certificate based network encryption in a very similar manner to SSL in a web browser where the client verifies that the server is valid. It is also possible to use client certificates to authenticate the clients with the server. * TLS-PSK support (not on Python). This is "pre-shared-key" network encryption and represents a simpler encryption interface than certificate based encryption which makes it much more suitable for embedded/constrained devices. * The Python client library is now written in pure Python so is much easier to use. It supports Python 2.6, 2.7 and 3.\* (no SSL support for 2.6). * All client libraries have had their interface overhauled and should now be much saner and straightforward to use. * The client libraries have thread support. * Passwords files for the broker are stored hashed and salted and a utility for maintaining them has been provided. * It is now possible to write access and authentication plugins for the broker for providing custom support for authentication against e.g. a SQL database. * Implementation of a good test suite which has lead to improved protocol compliance amongst other bug fixes. * Masses of bug fixes. # Downloads Source is available on the [download page], the binary packages will follow as soon as possible. Windows and Ubuntu packages are currently available, more to follow. # Changes The complete list of changes is below: # The 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. ## The client libraries * 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. [download page]: /download ================================================ FILE: www/posts/2012/09/updating-password-files.md ================================================ Mosquitto 1.0 introduced the use of password files with hashed passwords but had no way to convert from the old plain text password files. This feature will be available in version 1.1 but if it is important to you then you can already get the updated code for the mosquitto_passwd utility at ================================================ FILE: www/posts/2012/09/version-1-0-3-released.md ================================================ This is a bugfix release. # 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. Source is available on the [download page], the binary packages for Windows are available now and Linux builds will be available as soon as the various build servers complete their tasks. [download page]: /download ================================================ FILE: www/posts/2012/10/version-1-0-4-released.md ================================================ This is a bugfix release. # 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. ================================================ FILE: www/posts/2012/11/making-mosquitto-packages-for-debian-yourself.md ================================================ As Debian has been in feature freeze since before Mosquitto 1.0 was released, it will be a long time until there is an updated version of Mosquitto in Debian. It is, however, fairly straightforward to do the packaging yourself. Here's how to do that from the command line. Download and unpack the mosquitto source tarball: ``` wget http://mosquitto.org/files/source/mosquitto-1.1.2.tar.gz tar -zxf mosquitto-1.1.2.tar.gz ``` Rename the tarball to match Debian requirements: ``` mv mosquitto-1.1.2.tar.gz mosquitto_1.1.2.orig.tar.gz ``` The current mosquitto packaging files are available at - you want the .debian.tar.xz. The next step is to build the package, but you may find that you need to install some packages first: ``` sudo apt-get install build-essential python quilt libwrap0-dev libssl-dev devscripts python-setuptools ``` To build the packages do ``` cd mosquitto-1.1.2/ debuild ``` You should now have a list of .deb files in the parent directory which you can install with: ``` sudo dpkg -i <deb file> ``` Please leave comments if you find this useful or have any problems. ================================================ FILE: www/posts/2012/11/version-1-0-5-released.md ================================================ This is a bugfix release. # 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. ================================================ FILE: www/posts/2012/12/libmosquitto-go-bindings.md ================================================ I just discovered that Shane Hanna has written a Go language binding for libmosquitto available at . Good work Shane! Note that the readme file states: > Doesn't expose all of libmosquitto, just what I've needed so far. so you shouldn't necessarily expect everything to work. ================================================ FILE: www/posts/2012/12/version-1-1-released.md ================================================ This is a feature and bugfix release. # 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. ================================================ FILE: www/posts/2013/01/mosquitto-debian-repository.md ================================================ On a previous post I described [how to make mosquitto debian packages]. This turned out to be a bit problematic, so I've now put up an experimental debian repository for mosquitto. It includes packages for the i386, amd64, armel and raspberry pi (raspbian armhf ) architectures. It's worth repeating that this is experimental - there are package changes that haven't been vetted by a Debian developer so it's possible something will break. I've tested myself and had no problems so far. To use the new repository you should first import the repository package signing key: ``` wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key sudo apt-key add mosquitto-repo.gpg.key ``` Then make the repository available to apt: ``` cd /etc/apt/sources.list.d/ ``` Then one of the following, depending on which version of debian you are using: ``` sudo wget http://repo.mosquitto.org/debian/mosquitto-jessie.list sudo wget http://repo.mosquitto.org/debian/mosquitto-stretch.list sudo wget http://repo.mosquitto.org/debian/mosquitto-buster.list ``` Then update apt information: ``` apt-get update ``` And discover what mosquitto packages are available: ``` apt-cache search mosquitto ``` Or just install: ``` apt-get install mosquitto ``` [how to make mosquitto debian packages]: /blog/2012/11/making-mosquitto-packages-for-debian-yourself/ ================================================ FILE: www/posts/2013/01/version-1-1-1-released.md ================================================ This is a bugfix release. # Broker * Fix crash on reload if using acl patterns. # Client library * Fix static C++ functions not being exported on Windows. Fixes bug #1098256. Binaries should be available shortly. ================================================ FILE: www/posts/2013/01/version-1-1-2-released.md ================================================ This is a bugfix release. # 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. Source and binaries are available on the [download page]. [download page]: /download ================================================ FILE: www/posts/2013/02/mqtt-standardisation-oasis-call-for-participation.md ================================================ The MQTT protocol is going for standardisation at OASIS. A technical committee is being formed and there is a call for participation for interested parties. There are details at the link below: The plan seems to be to take the 3.1 spec as it is for standardisation and see about changes in the future. If you are interested in taking part see the link above, but note that you need to be a paid up member of OASIS. ================================================ FILE: www/posts/2013/02/version-1-1-3-released.md ================================================ This is a minor bugfix release that addresses some problems identified during Debian packaging. # 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. ================================================ FILE: www/posts/2013/04/some-interesting-mqtt-things.md ================================================ It's been a while since there has been an update here, so in lieu of one here are some interesting links I've come across recently. Add a comment to the post if you've done something cool not mentioned here! Work progresses on mosquitto 1.2. Initial release of an MQTT-S gateway, written in ruby: * And some MQTT-S tools: * A Pinoccio/MQTT/sensor powered Theramin: * Voice controlled MQTT LED: * An MQTT notification plugin for Jenkins/Hudson: * ================================================ FILE: www/posts/2013/05/mosquitto-javascript-client-deprecated.md ================================================ The [Paho] project recently made a new Javascript client available: The mosquitto Javascript client, mosquitto.js, is neither as functional nor as well written as the Paho client, so is being deprecated. If you are using mosquitto.js I strongly recommend that you look to the Paho client for the future. I will be carrying out minor bug fixes but no other development will take place. There are no plans to remove the existing files. [Paho]: http://www.eclipse.org/paho/ ================================================ FILE: www/posts/2013/07/authentication-plugins.md ================================================ There has been some interest in authentication plugins for mosquitto recently. Some examples have appeared: Authentication based on md5 hashes: [mosquitto_auth_plugin_md5] Authentication based on md5 hashed passwords in postgresql: [mosquitto_auth_plugin_pg_md5] Authentication and topic ACL with redis and a PBKDF2 hash: [mosquitto-redis-auth] I particularly like the redis based plugin for the interesting additions like the "superuser" that is exempt from ACL checks. If you've written an auth plugin and think it might be useful to others, let me know. [mosquitto_auth_plugin_md5]: https://github.com/sskaje/mosquitto_auth_plugin_md5 [mosquitto_auth_plugin_pg_md5]: https://github.com/sebaroesch/mosquitto_auth_plugin_pg_md5 [mosquitto-redis-auth]: https://github.com/jpmens/mosquitto-redis-auth ================================================ FILE: www/posts/2013/07/version-1-2-near-complete.md ================================================ With the most recent commit, "Implement TLSv1.2 and TLSv1.1 support," everything that is planned for version 1.2 has been completed. If you haven't tried it out yet, now would be a good time to take a look. Before the release is finalised, there still needs to be more testing done, particularly on Windows. If you use another platform than Windows or Linux, I'd be interested to hear if you have any problems with the 1.2 code. I will also be updating the packaging for all of the binaries that I build or contribute to directly, so there is still time for bug reports. You can get a copy of the source at one of the links below, or through the mercurial repository directly on the 1.2 branch. * * ================================================ FILE: www/posts/2013/08/mosquitto-on-fedora.md ================================================ Mosquitto has been packaged for Fedora thanks to Rich Mattes. Fedora 19 users will be able to install with "yum install mosquitto". Thanks Rich! ================================================ FILE: www/posts/2013/08/mqtt-watchdir.md ================================================ Recursively watch a directory for modifications and publish file content to an MQTT broker `mqtt-watchdir` is a Python program by [Jan-Piet Mens] to watch a directory and publish new or modified files in that directory hierarchy to an MQTT broker, using a matching topic. Source and instructions are available at and it is also available via pypi. It is a similar idea to my [mqttfs] fuse filesystem, but ultimately implemented in a better (and portable) manner. [Jan-Piet Mens]: https://twitter.com/jpmens [mqttfs]: https://bitbucket.org/oojah/mqttfs ================================================ FILE: www/posts/2013/08/version-1-2-released.md ================================================ This is a (long overdue) feature release. There is a potential gotcha when upgrading to this release because the default version of TLS used has changed from 1.0 to 1.2. Python does not yet have support for TLS>1.0 so Python clients will be unable to communicate with brokers using the default TLS settings. The source is available at the [download page] and binaries will become available in the near future. # 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 truly 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. [download page]: /download ================================================ FILE: www/posts/2013/09/version-1-2-1-released.md ================================================ This is a bugfix release. # 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. ================================================ FILE: www/posts/2013/10/version-1-2-2-released.md ================================================ This is a bugfix release: # 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. ================================================ FILE: www/posts/2013/12/paho-mqtt-python-client.md ================================================ The Mosquitto Python client was donated to the Eclipse Paho project in June of this year. As mosquitto.py has been very popular, I have been maintaining both code bases together. With the Mosquitto project also moving to Eclipse it is now even more redundant to keep maintaining mosquitto.py so I would like to recommend that everybody currently using mosquitto.py move over to using the Paho Python client. The current state of the Paho client is now available on [pypi] and can be installed using `pip install paho-mqtt`. To port code from mosquitto.py, you should change: ``` import mosquitto mqttc = mosquitto.Mosquitto() ``` to: ``` import paho.mqtt.client as paho mqttc = paho.Client() ``` All error codes e.g. `MOSQ_ERR_SUCCESS` change to `MQTT_ERR_SUCCESS`. The Paho module has a compatibility Mosquitto class that means a very simple (but not recommended for the long term) port can be achieved with the following line, assuming none of the error codes are used: ``` import paho.mqtt.client as mosquitto ``` I will keep applying updates to mosquitto.py until the Paho 1.0 release. [pypi]: https://pypi.python.org/pypi/paho-mqtt ================================================ FILE: www/posts/2013/12/version-1-2-3-released.md ================================================ In time for the second day of [Thingmonk], which I regret not being able to go to, version 1.2.3 of mosquitto is released. This is a bugfix release. # All components * Various fixes caught by [Coverity Scan]. # 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. [Thingmonk]: http://redmonk.com/thingmonk/ [Coverity Scan]: https://scan.coverity.com/ ================================================ FILE: www/posts/2014/03/version-1-3-1-released.md ================================================ This is a bugfix release: # 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`. # Clients * Fix keepalive value on mosquitto_pub. * Fix possibility of mosquitto_pub not exiting after sending messages when using -l. ================================================ FILE: www/posts/2014/03/version-1-3-released.md ================================================ # 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. ================================================ FILE: www/posts/2014/05/new-arrival.attachments.json ================================================ {"322": {"wordpress_user_name": "roger", "title": "14098345978_c15d12f19a_z", "date_utc": "2014-05-27 22:29:02", "files_meta": [{"height": 427, "width": 640}, {"height": 200, "size": "medium", "width": 300}, {"height": 150, "size": "thumbnail", "width": 150}], "files": ["/wp-content/uploads/2014/05/14098345978_c15d12f19a_z.jpg", "/wp-content/uploads/2014/05/14098345978_c15d12f19a_z-300x200.jpg", "/wp-content/uploads/2014/05/14098345978_c15d12f19a_z-150x150.jpg"]}} ================================================ FILE: www/posts/2014/05/new-arrival.md ================================================ I'm pleased to say that I'm a new father again. My 7lb 12 (3.57kg) boy arrived today and is quite happy, as is his mother. Apologies to anybody who has emailed me recently and I've not yet replied - this is the main reason! [![baby][baby]](/blog/uploads/2014/05/14098345978_c15d12f19a_z.jpg) [baby]:/blog/uploads/2014/05/14098345978_c15d12f19a_z-300x200.jpg ================================================ FILE: www/posts/2014/07/version-1-3-2-released.md ================================================ This is a security and bugfix release. # Security A bug in the way that mosquitto handles authentication plugins has been identified. When using a plugin for authentication purposes, if the plugin returns `MOSQ_ERR_UNKNOWN` when making an authentication check, as might happen if a database was unavailable for example, then mosquitto incorrectly treats this as a successful authentication. This has the potential for unauthorised clients to access the running mosquitto broker and gain access to information to which they are not authorised. This is an important update for users of authentication plugins in mosquitto. # 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. * Anonymous clients are no longer accidentally disconnected from the broker after a SIGHUP. * Fix bug [#1324411], which could have had unexpected consequences for delayed messages in rare circumstances. # 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. # General * Use $(STRIP) for stripping binaries when installing, to allow easier cross compilation. [#1313725]: https://bugs.launchpad.net/mosquitto/+bug/1313725 [#1324411]: https://bugs.launchpad.net/mosquitto/+bug/1324411 [#1340782]: https://bugs.launchpad.net/mosquitto/+bug/1340782 ================================================ FILE: www/posts/2014/08/version-1-3-3-released.md ================================================ This is a bugfix release. # Broker * Fix incorrect handling of anonymous bridges on the local broker. Binaries will follow shortly. ================================================ FILE: www/posts/2014/08/version-1-3-4-released.md ================================================ This is a bugfix release. The reason for the rapid release of the past two versions is down to a Debian developer reviewing the mosquitto package. This is a good opportunity to ensure that as bug free a version as possible is present in Debian. # Broker * Don't ask client for certificate when `require_certificate` is **false**. * Backout incomplete functionality that was incorrectly included in 1.3.2. Binaries will follow shortly. ================================================ FILE: www/posts/2014/10/mosquitto-and-poodle.md ================================================ Details of the POODLE attack that targets SSLv3 have been released recently. Mosquitto has never provided support for SSLv3 (or SSLv2) so should not be vulnerable to this attack and does not require any configuration changes. ================================================ FILE: www/posts/2014/10/unintended-change-of-behaviour-in-1-3-4.md ================================================ Version 1.3.4 introduced the change that when using TLS with `require_certificate` set to false, the client is no longer asked for a client certificate. This seemed to be causing problems in some situations, particularly with embedded devices. If `use_identity_as_username` is set to true when `require_certificate` is set to false, then the client will not be asked for a certificate, even if it has one configured. This means that the client will be refused access with connack code 4, "bad username or password", because if `use_identity_as_username` currently requires that a certificate is present, even if `allow_anonymous` is set to true. This change may cause unexpected results, but does not represent a security flaw because the change results in more clients being rejected than would otherwise have been. ================================================ FILE: www/posts/2014/10/version-1-3-5-released.md ================================================ This is a bugfix release. # 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. ================================================ FILE: www/posts/2015/01/seeking-sponsorship.md ================================================ The mosquitto project has, or can get, access to a wide variety of different systems to help with development. One important platform for which this is not true is Mac OS X. There are sufficient differences between Macs and other systems that this makes life difficult. To this end, I would like to reach out to the mosquitto community to ask for help with obtaining either * A remote login on a Mac system * Donation of hardware * Donation of money to buy some hardware I have been offered a remote account by a few individuals in the past, for which I'm very grateful, but only on a short term basis and, understandably, with limited control. Something on a longer term, with the ability to install packages would be much more useful. Unfortunately I realise this is relatively difficult to offer. On the hardware side of things, there isn't a need for a modern, powerful computer. A second hand Mac Mini of Core2Duo vintage with 1GB RAM and a reasonably modern version of Mac OS X would be quite sufficient, and ideal for me in terms of the space it takes up. Regrettably I feel I would have to turn down offers of an old iMac or Mac Pro. 2007-era Mac Minis go on Ebay UK for around £100. I'm hopeful that there is a company out there using mosquitto, likes Macs and for whom £100 would be a drop in the ocean. If so, or any individuals want to help out with a small donation towards this, please get in touch directly to roger@atchoo.org or head over to the downloads page to see the paypal donation link, and thanks very much in advance.
Update: I have now awaiting delivery of a Mac mini. Thanks very much to all of you that have contributed, it is very much appreciated. If you would still like to support mosquitto development please don't let this put you off... ================================================ FILE: www/posts/2015/02/version-1-4-released.md ================================================ This is a feature release and is also the first release of the mosquitto project from the Eclipse Foundation umbrella. The code is now dual licenced under the [EPL]. The EDL and BSD 3 clause license are essentially identical so if you were happy with the BSD license then you should be happy with the EDL. Files distributed will remain in the same place but will in some cases also be available on the Eclipse download servers. # 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 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. # Dependencies This release introduces two new dependencies, libwebsockets and libuuid. Both are optional. libuuid comes from the e2fsprogs project and allows the broker to generate random client ids for MQTT v.3.1.1. The libwebsockets dependency can use either libwebsockets 1.3 or 1.2.x, with 1.3 being the preferred choice. [EPL]: https://www.eclipse.org/legal/epl-v10.html [EDL]: https://eclipse.org/org/documents/edl-v10.php ================================================ FILE: www/posts/2015/04/version-1-4-1-released.md ================================================ This is a bugfix and security release. Users of mosquitto 1.4 are strongly advised to upgrade. Upgrading from earlier versions is recommended but not as important. # Broker * Fix possible crash under heavy network load. Closes [#463241]. This bug only affects version 1.4. * 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]. [#463241]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=463241 [#462154]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=462154 [#461619]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=461619 [#461620]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=461620 [#463000]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=463000 [#461705]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=461705 [#462780]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=462780 [#462781]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=462781 [#463479]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=463479 ================================================ FILE: www/posts/2015/05/mosquitto-and-current-unreleased-libwebsockets-branch.md ================================================ The current unreleased libwebsockets master branch defines the VERSION macro in its header files. I believe this to be a bug in libwebsockets. This bug causes compilation of mosquitto with websockets support to fail. Please use a released version of libwebsockets, either 1.2, 1.3 or 1.4. Mosquitto will compile with all of these versions. I do not recommend using an unreleased version of libwebsockets, the project is not shy about making ABI/API incompatible changes between releases so it is impractical to provide support for. ================================================ FILE: www/posts/2015/05/version-1-4-2-released.md ================================================ This is a bugfix release. # 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]. * Fix calls to `mosquitto_connect*_async()` not completing. [#464437]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=464437 [#464779]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=464779 [#465384]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=465384 [#463884]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=463884 [#464436]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=464436 [#464632]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=464632 ================================================ FILE: www/posts/2015/08/version-1-4-3-released.md ================================================ This is a bugfix release. # Broker * Fix incorrect bridge notification on initial connection. Closes [#467096]. * Build fixes for OpenBSD. * Fix incorrect behaviour for `autosave_interval`, most noticeable 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. [#467096]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=467096 [#465438]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=465438 [#468987]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=468987 [#470253]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=470253 [#470660]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=470660 [#471334]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=471334 [#474935]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=474935 ================================================ FILE: www/posts/2015/09/version-1-4-4-released.md ================================================ This is a bugfix release. * 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 and FreeBSD. Closes [#475707]. * Fix excessive calls to message retry check. [#477571]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=477571 [#475707]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=475707 [#475807]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=475807 ================================================ FILE: www/posts/2015/11/version-1-4-5-released.md ================================================ This is a bugfix release: # 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]. [#468987]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=468987 [#478917]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=478917 ================================================ FILE: www/posts/2015/12/using-lets-encrypt-certificates-with-mosquitto.md ================================================ If you want to use TLS certificates you've generated using the [Let's Encrypt] service, this is how you should configure your listener (replace "example.com" with your own domain of course): Then use the following for your mosquitto.conf: ``` listener 8883 cafile /etc/ssl/certs/ISRG_Root_X1.pem certfile /etc/letsencrypt/live/example.com/fullchain.pem keyfile /etc/letsencrypt/live/example.com/privkey.pem ``` Since version 2.0 of Mosquitto, you can send a SIGHUP to the broker to cause it to reload certificates. Prior to this version, mosquitto would never update listener settings when running, so you will need to completely restart the broker. [Let's Encrypt]: https://letsencrypt.org/ ================================================ FILE: www/posts/2015/12/version-1-4-7-released.md ================================================ This is a bugfix release. The changes below include the changes for 1.4.6, which wasn't announced. # 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]. [#483979]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=483979 [#483981]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=483981 ================================================ FILE: www/posts/2016/01/test6-mosquitto-org.md ================================================ Thanks to a short discussion on irc, test6.mosquitto.org now exists. This is a DNS entry that points to the same address as test.mosquitto.org, but only with an AAAA record. This means that test6.mosquitto.org can be used to test clients using IPv6 and to be sure that IPv6 is actually being used. ================================================ FILE: www/posts/2016/02/version-1-4-8-released.md ================================================ This is a security bugfix release. Any users of the `mount_point` feature are strongly advised to upgrade because versions prior to 1.4.8 allow clients to inject messages outside of their `mount_point` through the use of a Will. # 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. [#487178]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=487178 [#485143]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=485143 [#485589]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=485589 [#485131]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=485131 ================================================ FILE: www/posts/2016/03/logo-contest-results-for-shortlisting.md ================================================ The first round of the logo contest has closed and we now need to shortlist 6 designers. A selection of 20 logos have been chosen out of the 100 entrants and you are invited to vote on them and make comments. If you like a particular logo but not the colour, or like an idea behind the logo but not another element then please say so. The links for voting (please do look at them all) are: ================================================ FILE: www/posts/2016/03/logo-contest.md ================================================ We have initiated a paid contest to create a new logo for the Mosquitto project. If you have graphics design skills or know someone who has,  please head over to the link below to see the design brief and submit your idea. ================================================ FILE: www/posts/2016/03/repository-moved-to-github.md ================================================ The mosquitto repository is now hosted on github: This is now the canonical location for mosquitto development work. Bug reports should also be made on github and the existing bug reports will be migrated over shortly. The documentation still needs updating with the new location and processes, so please do be patient with regards that. Contributions can now be made through a github pull request. If you want to contribute a bug fix, please base your work off the "fixes" branch, if you are developing a new feature please use the "develop" branch. Here's to a new stage in the mosquitto project! ================================================ FILE: www/posts/2016/05/stickers.attachments.json ================================================ {"385": {"wordpress_user_name": "roger", "title": "stickers", "date_utc": "2016-05-10 14:43:38", "files_meta": [{"height": 253, "width": 338, "meta": {"created_timestamp": 1462563610.0, "shutter_speed": 0.5, "focal_length": 48.0, "camera": "NIKON D3200", "aperture": 5.3, "iso": 800.0}}, {"height": 225, "size": "medium", "width": 300}, {"height": 150, "size": "thumbnail", "width": 150}], "files": ["/wp-content/uploads/2016/05/stickers.jpg", "/wp-content/uploads/2016/05/stickers-300x225.jpg", "/wp-content/uploads/2016/05/stickers-150x150.jpg"]}} ================================================ FILE: www/posts/2016/05/stickers.md ================================================ To celebrate the new mosquitto logo, stickers are now available: [![stickers](/blog/uploads/2016/05/stickers-300x225.jpg)](/blog/uploads/2016/05/stickers.jpg) If you would like to obtain some stickers for yourself you have two options. The first is to get in touch and I'll send you some for a small contribution. This contribution is to cover the cost of the stickers plus postage: (cost of postage)+N\*£0.45, where N is the number of sheets of 6 stickers that you want. Cost of postage for a letter can be calculated using the [Royal Mail price finder], but should be £1.05 for destinations outside of the UK. Please also consider Paypal fees using a [fees calculator] to calculate the final sum. So for a single sheet of stickers posted internationally, the cost would be £1.76 including paypal fees. Two sheets would be £2.23. The second option is to buy a full sticker book through moo.com. This can be done very easily by navigating to This allows you to easily order a sticker book of 90 stickers with either the colour or blue monochrome stickers, or a mix of both. There is a third option - get in touch to say why you deserve some stickers and maybe we'll send you some. We're looking for things that make us say "wow!" If you will be sending your sticker to space, getting mosquitto on television or using MQTT in your Formula 1 technology, these are all things that would exciting to see with a mosquitto sticker in place. If you want to give out stickers at a local IoT related event or similar that's great, but we'd ask that you make a small donation. It's only a small cost for you, but there are many people in your situation and it becomes a noticeable cost for the project. Please do post links of your kit sporting any stickers you use! [Royal Mail price finder]: http://www.royalmail.com/price-finder [fees calculator]: http://www.clothnappytree.com/ppcalculator/ ================================================ FILE: www/posts/2016/06/version-1-4-9-released.md ================================================ This is a bugfix release. # Broker * Ensure websockets clients that previously connected with clean session set to false have their queued messages delivered immediately on reconnecting. Closes [#5]. * 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]: https://github.com/eclipse/mosquitto/issues/1 [#4]: https://github.com/eclipse/mosquitto/issues/4 [#5]: https://github.com/eclipse/mosquitto/issues/5 [#57]: https://github.com/eclipse/mosquitto/issues/57 [#136]: https://github.com/eclipse/mosquitto/issues/136 [#150]: https://github.com/eclipse/mosquitto/issues/150 [#151]: https://github.com/eclipse/mosquitto/issues/151 [#154]: https://github.com/eclipse/mosquitto/issues/154 [#166]: https://github.com/eclipse/mosquitto/issues/166 [#169]: https://github.com/eclipse/mosquitto/issues/169 [#170]: https://github.com/eclipse/mosquitto/issues/170 [#180]: https://github.com/eclipse/mosquitto/issues/180 ================================================ FILE: www/posts/2016/08/mqtt-v5-draft-features.md ================================================ The [MQTT Technical Committee] at OASIS continue to work on improvements to MQTT. The next version looks set to be MQTT version 5 and has reached the "working draft" stage. This post lists some of the changes that are in the working draft 02 and so gives at least a flavour of the improvements coming up. Take this with a pinch of salt, I may have missed some changes and there is no commitment that any of these features will remain in the final specification as they are described here. # Session management In MQTT v3.1.1 and earlier, a client could control how the server treats its session with the clean session flag. If set to 1, the server would delete any existing session for that client and would not persist the session after disconnecting. If set to 0, the server would restore any existing session for a client when it reconnected, and persist the session when the client disconnected. A session here means the subscriptions for a client and any queued messages. The new spec changes this behaviour. The clean session flag has been renamed to clean start (this was actually the name of the flag in the old MQTT v3 spec) and now only affects how the broker handles a client session when the client connects. If set to 1, the server discards any previous session information, otherwise session information is kept. To deal with removing of sessions at any other time, a new identifier/value pair has been introduced. These identifier/value pairs are an addition to the variable header part of some MQTT packets and allow configuring of different behaviour. In the case of the CONNECT packet, a Session Expiry interval can be specified which is a 4 byte integer that gives the number of seconds after a client has disconnected that the server should remove session information for that client. If the Session Expiry interval is absent from the CONNECT packet, then the session will never expire. If it is set to 0, then the session is removed as soon as the client disconnects. The new clean start flag and session expiry interval allow the existing clean session behaviour to be duplicated but also allow client sessions to be expired based on time. # Updated Connect Return codes The return codes passed to the client in a CONNACK packet have been expanded to include: * 6: Connection Refused, reason unspecified * 7: Connection Refused, implementation specific * 8: Connection Refused, CONNECT packet was malformed # Repeated topics when publishing When publishing data to a single topic, a new feature will help reduce bandwidth use. A client or server can set the topic in a PUBLISH message to be a zero length string. This tells the client/server being published to, to use the previous topic instead. This goes some way to reducing the current overhead associated with publishing - a shame it isn't quite as good as the registered topics available in MQTT-SN. # Payload Format Indicator Another identifier/value pair is available for use when sending a PUBLISH message. This is the Payload Format indicator. If present and set to 1, this indicates that the PUBLISH payload is UTF-8 encoded data. If set to 0, or if the indicator is not present then the payload is an unspecified byte format, exactly as with MQTT v3.1.1. # Publication Expiry interval This is an identifier/value pair for use when publishing. If present, this value is a 4 byte integer which gives the number of seconds for which the server will attempt to deliver this message to a subscriber. This means that an offline client with messages being queued may not receive all of the messages when it reconnects, due to some of them expiring. Interestingly, when the server does deliver a message that had a Publication Expiry set, it sets the Publication Expiry on the outgoing message to the client but with the amount of time that there is left until the message expires. This means that the true time to expiry will propagate through bridges or similar. # Publish Return Codes The PUBACK and PUBREC packets have a new entry in their variable header which is the Publish Return Code. This can be used to tell the client a message has been refused for various reasons, accepted, or accepted with no matching subscribers.  For the PUBREC packet, if the message is refused or accepted with no matching subscribers then there is no expectation for the PUBREL/PUBCOMP messages to be sent for that message. The PUBCOMP packet also has a similar entry which has the same set of return codes and an additional one for the case when a message had expired. This is for the case when a client reconnects with clean start set to 0 and it has a QoS 2 message part way through its handshake, but the server has already expired the message. There is still no way to tell a client that its QoS 0 message was refused. # Disconnect notification In MQTT v3.1.1 and before, only the client sends a DISCONNECT packet. In the draft spec, either the client or the server can send DISCONNECT and it is used to indicate a reason for disconnection. The disconnect return codes are: * 0: Connection disconnected by application (sent by client) * 1: Server temporarily unavailable (server) * 2: Server unavailable (server) * 3: Malformed UNSUBSCRIBE packet received (server) * 4: Session taken over (server - for when another client connects with the same ID) * 5: Malformed packet received It is clear that there is some duplication there, so I think this is a likely place that changes will be made. # Disconnect expiry notification The DISCONNECT packet can also include a Session Expiry interval value, as with CONNECT. This allows a client to clean up when it disconnects, or to set a long expiry time, even if these were not specified at the initial connect. [MQTT Technical Committee]: https://www.oasis-open.org/committees/tc_home.php?wg_abbrev=mqtt ================================================ FILE: www/posts/2016/08/version-1-4-10-released.md ================================================ This is a bugfix release. # Broker * Fix TLS operation with websockets listeners and libwebsockets 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]. [#7]: https://github.com/eclipse/mosquitto/issues/7 [#184]: https://github.com/eclipse/mosquitto/issues/184 [#186]: https://github.com/eclipse/mosquitto/issues/186 [#189]: https://github.com/eclipse/mosquitto/issues/189 [#191]: https://github.com/eclipse/mosquitto/issues/191 [#198]: https://github.com/eclipse/mosquitto/issues/198 [#222]: https://github.com/eclipse/mosquitto/issues/222 [#234]: https://github.com/eclipse/mosquitto/issues/234 [#237]: https://github.com/eclipse/mosquitto/issues/237 ================================================ FILE: www/posts/2016/12/pre-christmas-update.md ================================================ I have taken a bit of a break from Mosquitto for the past few months, partly because I needed a break but also to work on another unrelated project. I'm now back and working on Mosquitto again, primarily implementing support for the upcoming MQTT v5 spec which has added even more features since I mentioned last wrote about it. Once that is in a state that is reasonably compliant if incomplete, I will be looking for testers. There are a few fixes in the repository waiting for release, I anticipate releasing 1.4.11 before the end of the year. There have been some changes to test.mosquitto.org. On its original host I was seeing lots of bandwidth being used by lots of clients, but in particular lots and lots of tiny connections being made which not showing up on my bandwidth monitoring, but were consuming bandwidth and causing problems at my provider. My provider got in touch to say that at times approximately half of the network flows for their network were related to test.mosquitto.org, and could would I please have a chat with the transit provider to discuss how best to manage this service. In the face of that and the risk of exceeding 2TB bandwidth usage per month, test.mosquitto.org has been moved to a lower spec host with smaller pipes and "automatic DDOS protection". This means I now get half a dozen emails per day to say that test.mosquitto.org is under attack. If you find you can't connect to test.mosquitto.org, it might be because you have been blocked by this DDOS protection - if so, maybe think about how you are using the service. The final thought for this post - if you are part of a company that uses mosquitto and it adds value to your company, please consider making a [donation] to the project that reflects that value. If it is difficult for your company to make donations but you would still like to contribute back, please get in touch and maybe we can arrange something. [donation]: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=J66JWQ3N76L5A ================================================ FILE: www/posts/2017/02/version-1-4-11-released.md ================================================ This is a bugfix release. # 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]. * Bridges can use asynchronous DNS lookups on systems with glibc. This can be enabled at compile time using `WITH_ADNS=yes`. # 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]. [#259]: https://github.com/eclipse/mosquitto/issues/259 [#271]: https://github.com/eclipse/mosquitto/issues/271 [#304]: https://github.com/eclipse/mosquitto/issues/304 [#316]: https://github.com/eclipse/mosquitto/issues/316 [#329]: https://github.com/eclipse/mosquitto/issues/329 [#354]: https://github.com/eclipse/mosquitto/issues/354 [#379]: https://github.com/eclipse/mosquitto/issues/379 [#380]: https://github.com/eclipse/mosquitto/issues/380 ================================================ FILE: www/posts/2017/03/for-the-final-time.attachments.json ================================================ {"410": {"wordpress_user_name": "roger", "title": "img_20170308_155049248_33196894011_o", "date_utc": "2017-03-09 19:08:45", "files_meta": [{"height": 720, "width": 1280, "meta": {"created_timestamp": 1488988249.0, "shutter_speed": 0.02999, "focal_length": 2.471, "camera": "MotoE2(4G-LTE)", "aperture": 2.2, "iso": 125.0}}, {"height": 432, "size": "medium_large", "width": 768}, {"height": 169, "size": "medium", "width": 300}, {"height": 150, "size": "thumbnail", "width": 150}, {"height": 576, "size": "large", "width": 1024}], "files": ["/wp-content/uploads/2017/03/img_20170308_155049248_33196894011_o.jpg", "/wp-content/uploads/2017/03/img_20170308_155049248_33196894011_o-768x432.jpg", "/wp-content/uploads/2017/03/img_20170308_155049248_33196894011_o-300x169.jpg", "/wp-content/uploads/2017/03/img_20170308_155049248_33196894011_o-150x150.jpg", "/wp-content/uploads/2017/03/img_20170308_155049248_33196894011_o-1024x576.jpg"]}} ================================================ FILE: www/posts/2017/03/for-the-final-time.md ================================================ This guy arrived on Tuesday, two weeks early and weighing 9lb 6oz / 4.26kg. Apologies if I'm a bit out of touch for a while. [![baby picture](/blog/uploads/2017/03/img_20170308_155049248_33196894011_o-300x169.jpg "baby picture")](/blog/uploads/2017/03/img_20170308_155049248_33196894011_o.jpg) ================================================ FILE: www/posts/2017/05/security-advisory-cve-2017-7650.md ================================================ A vulnerability exists in Mosquitto versions 0.15 to 1.4.11 inclusive known as [CVE-2017-7650]. Pattern based ACLs can be bypassed by clients that set their username/client id to '#' or '+'. This allows locally or remotely connected clients to access MQTT topics that they do have the rights to. The same issue may be present in third party authentication/access control plugins for Mosquitto. The vulnerability only comes into effect where pattern based ACLs are in use, or potentially where third party plugins are in use. The issue is fixed in Mosquitto 1.4.12, which has just been released. Patches for older versions are available at The fix addresses the problem by restricting access for clients with a '#', '+', or '/' in their username or client id. '/' has been included in the list of characters disallowed because it also has a special meaning in a topic and may represent an additional risk. The restriction placed on clients is that they may not receive or send messages that are subject to a pattern based ACL check, nor any message that is subject to a plugin check. Thanks to Artem Zinenko from HackerDom CTF team for finding this vulnerability and responsibly reporting it. Complete list of fixes addressed in version 1.4.12: # 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 uninitialised 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]. [CVE-2017-7650]: http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-7650 [#415]: https://github.com/eclipse/mosquitto/issues/415 [#416]: https://github.com/eclipse/mosquitto/issues/416 [#424]: https://github.com/eclipse/mosquitto/issues/424 [#428]: https://github.com/eclipse/mosquitto/issues/428 [#426]: https://github.com/eclipse/mosquitto/issues/426 [#446]: https://github.com/eclipse/mosquitto/issues/446 ================================================ FILE: www/posts/2017/06/citing-eclipse-mosquitto.md ================================================ A short paper has been published on Mosquitto in [The Journal of Open Source Software] If you use Mosquitto in your academic work, please now use this paper as your citation. > R. A. Light, "Mosquitto: server and client implementation of the MQTT > protocol," *The Journal of Open Source Software*, vol. 2, no. 13, May 2017, > DOI: [10.21105/joss.00265] The paper link is A [bibtex] entry is available. [The Journal of Open Source Software]: http://joss.theoj.org [10.21105/joss.00265]: http://dx.doi.org/10.21105/joss.00265 [bibtek]: http://www.doi2bib.org/#/doi/10.21105/joss.00265 ================================================ FILE: www/posts/2017/06/security-advisory-cve-2017-9868.md ================================================ A vulnerability exists in Mosquitto versions 0.15 to 1.4.12 inclusive known as [CVE-2017-9868]. If persistence is enabled, then the persistence file is created world readable, which has the potential to make sensitive information available to any local user. Patches are available to fix this for Unix like operating systems (i.e. not Windows): This will be fixed in version 1.4.13, due to be released shortly. This can also be fixed administratively by removing world read permissions for the directory that the persistence file is stored in. In many systems this can be achieved with: ``` chmod 700 /var/lib/mosquitto ``` [CVE-2017-9868]: http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-9868 ================================================ FILE: www/posts/2017/07/version-1-4-13-released.md ================================================ This is a bugfix and security release. # 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. [CVE-2017-7650]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-7650 [CVE-2017-9868]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-9868 [#417]: https://github.com/eclipse/mosquitto/issues/417 [#427]: https://github.com/eclipse/mosquitto/issues/427 [#462]: https://github.com/eclipse/mosquitto/issues/462 [#468]: https://github.com/eclipse/mosquitto/issues/468 [#477]: https://github.com/eclipse/mosquitto/issues/477 ================================================ FILE: www/posts/2017/07/version-1-4-14-released.md ================================================ This is a bugfix release. Version 1.4.13 contained a regression that meant persistence data was only being saved after client information had been freed. This release fixes that. If you use persistence then it is strongly recommended to avoid 1.4.13 so you do not suffer data loss. ================================================ FILE: www/posts/2018/01/mosquitto-debian-repo-key-updated.md ================================================ If you are using the [debian repository] at repo.mosquitto.org you may have noticed that the repository signing key expired at the end of 2017. To get the updated key use the following commands: ``` wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key sudo apt-key add mosquitto-repo.gpg.key ``` [debian repository]:/blog/2013/01/mosquitto-debian-repository ================================================ FILE: www/posts/2018/02/security-advisory-cve-2017-7651-cve-2017-7652.md ================================================ Mosquitto 1.4.15 has been released to address two security vulnerabilities. # CVE-2017-7651 A vulnerability exists in all Mosquitto versions up to and including 1.4.14 known as [CVE-2017-7651]. Unauthenticated clients can send a crafted CONNECT packet which causes large amounts of memory use in the broker. If multiple clients do this, an out of memory situation can occur and the system may become unresponsive or the broker will be killed by the operating system. The issue is fixed in Mosquitto 1.4.15. Patches for older versions are available at The fix addresses the problem by limiting the permissible size for CONNECT packet, and by adding a `memory_limit` configuration option that allows the broker to self limit the amount of memory it uses. Thanks to Felipe Balabanian for finding this vulnerability and responsibly reporting it. # CVE-2017-7652 A vulnerability exists in Mosquitto versions 1.0 to 1.4.14 inclusive known as [CVE-2017-7652]. If the broker has exhausted all of its free sockets/file descriptors and then a SIGHUP signal is received to trigger reloading of the configuration, then the reloading will fail. This results in many of the configuration options, including security options, being set to their default value. This means that authorisation and access control may no longer be in place. The issue is fixed in Mosquitto 1.4.15. Patches for older versions are available at The fix addresses the problem by only copying the new configuration options to the in use configuration after a successful reload has taken place. # Version 1.4.15 Changes The complete list of fixes addressed in version 1.4.15 is: ## 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]. [CVE-2017-7651]: http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-7651 [CVE-2017-7652]: http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-7652 [#8]: https://github.com/eclipse/mosquitto/issues/8 [#250]: https://github.com/eclipse/mosquitto/issues/250 [#490]: https://github.com/eclipse/mosquitto/issues/490 [#507]: https://github.com/eclipse/mosquitto/issues/507 [#534]: https://github.com/eclipse/mosquitto/issues/534 [#636]: https://github.com/eclipse/mosquitto/issues/636 [#649]: https://github.com/eclipse/mosquitto/issues/649 [#652]: https://github.com/eclipse/mosquitto/issues/652 [#654]: https://github.com/eclipse/mosquitto/issues/654 [#670]: https://github.com/eclipse/mosquitto/issues/670 [#676]: https://github.com/eclipse/mosquitto/issues/676 ================================================ FILE: www/posts/2018/05/press-release.md ================================================ I am pleased to announce that I am being paid to work on Mosquitto by Cedalo AG. I will be leaving my current job at the end of June this year, but have already started work for Cedalo on a limited basis. The press release for this change is below: # New 1.5 release, MQTT 5.0 roadmap and commercial sponsor for Open-Source Eclipse Mosquitto MQTT Broker Open-Source MQTT Broker Version 1.5 released – Estimate for availability of MQTT 5.0 compliant version – German based Cedalo AG becomes commercial sponsor for future Mosquitto Open Source development A new version of the open source Eclipse Mosquitto MQTT broker is available on the Mosquitto website at [mosquitto.org](https://mosquitto.org). Mosquitto version 1.5 brings a host of changes to the broker, including performance improvements and more flexible authentication and access control, as well as numerous bug fixes. The client library has added some helper functions to allow the creation of extremely simple MQTT clients. The initiator and core developer of the Mosquitto project is now employed by the German based company Cedalo AG ([www.cedalo.com](https://www.cedalo.com)). Cedalo has hired Roger Light to sponsor the further development of Mosquitto and to accelerate the public availability of a powerful MQTT broker. Cedalo is the creator of the end-user oriented IoT modelling tool “Streamsheets”. With the new sponsorship the project is now able to accelerate the path towards new releases. The next version of Mosquitto will add support for MQTT version 5, which is the most substantial revision of the protocol since the first public specification was released. MQTT v5 adds error reporting, enhancements for scalability at the server side, features to help resource constrained clients, and extensible metadata - which is used amongst other things to introduce support for a request/response capability. The MQTT v5 compliant release is planned for the end of August 2018. Press Contact: Cedalo AG 79098 Freiburg, Schnewlinstr. 6 Kristian Raue Mail: presse@cedalo.com ================================================ FILE: www/posts/2018/05/version-1-5-released.md ================================================ 1.5 - 20180502 ============== This is a features release. Updated binaries will be available shortly. # 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. Closes #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`. ================================================ FILE: www/posts/2018/08/updated-debian-repository-backend.md ================================================ The backend software for administering the Debian repository at https://repo.mosquitto.org/ has been migrated from `reprepro` to `aptly`. This has the benefit of allowing multiple versions of a package to remain in the repository. For mosquitto, this now means that old versions of the Debian packages will remain available even after newer versions are published, and so you can depend on a particular version. The recommendation is always to use the latest version of course. This change should be transparent to all current users, but there is the possibility that something is different between the two repository tools. If you do find a problem, please let us know. The repository now has builds for versions 1.4.15 and 1.5. ================================================ FILE: www/posts/2018/08/version-151-released.md ================================================ This is a bugfix release. # Packaging changes * The snap package now has support for websockets included. * The Windows packages have changed. - Support for Windows XP was dropped in Mosquitto 1.5, so the need for the Cygwin build has gone, and this has been dropped. - There are now 64-bit and 32-bit native packages. - Websockets support is included. - Threading support is not included in libmosquitto to simplify installation, alternative solutions are being looked into for the future. - The only external dependency is now OpenSSL. # Version 1.5.1 changes ## 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. [#209]: https://github.com/eclipse/mosquitto/issues/209 [#240]: https://github.com/eclipse/mosquitto/issues/240 [#258]: https://github.com/eclipse/mosquitto/issues/258 [#813]: https://github.com/eclipse/mosquitto/issues/813 [#833]: https://github.com/eclipse/mosquitto/issues/833 [#848]: https://github.com/eclipse/mosquitto/issues/848 [#849]: https://github.com/eclipse/mosquitto/issues/849 [#851]: https://github.com/eclipse/mosquitto/issues/851 [#860]: https://github.com/eclipse/mosquitto/issues/860 [#863]: https://github.com/eclipse/mosquitto/issues/863 [#869]: https://github.com/eclipse/mosquitto/issues/869 [#886]: https://github.com/eclipse/mosquitto/issues/886 [#900]: https://github.com/eclipse/mosquitto/issues/900 [#901]: https://github.com/eclipse/mosquitto/issues/901 [#903]: https://github.com/eclipse/mosquitto/issues/903 ================================================ FILE: www/posts/2018/09/security-advisory-cve-2018-12543.md ================================================ Mosquitto 1.5.3 has been released to address a security vulnerability. It also includes other bug fixes. # CVE-2018-12543 A vulnerability exists in Mosquitto versions 1.5 to 1.5.2 inclusive, known as [CVE-2018-12543]. If a message received by the broker has a topic that begins with `$`, but that does not begin `$SYS`, an assert is triggered that should otherwise not be accessible, causing Mosquitto to exit. The issue is fixed in Mosquitto 1.5.3. Patches for older versions are available at The fix addresses the problem by reverting a commit that intended to remove some unused checks, but also stopped part of the topic hierarchy being created. # Version 1.5.3 Changes The complete list of fixes addressed in version 1.5.3 is: ## 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]. ## Build * Various fixes to ease building. [CVE-2018-12543]: http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-12543 [#520]: https://github.com/eclipse/mosquitto/issues/520 [#566]: https://github.com/eclipse/mosquitto/issues/566 [#600]: https://github.com/eclipse/mosquitto/issues/600 [#645]: https://github.com/eclipse/mosquitto/issues/645 [#701]: https://github.com/eclipse/mosquitto/issues/701 ================================================ FILE: www/posts/2018/09/version-152-released.md ================================================ This is a bugfix release. # Version 1.5.2 changes ## 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]. [#481]: https://github.com/eclipse/mosquitto/issues/481 [#927]: https://github.com/eclipse/mosquitto/issues/927 [#932]: https://github.com/eclipse/mosquitto/issues/932 [#941]: https://github.com/eclipse/mosquitto/issues/941 [#948]: https://github.com/eclipse/mosquitto/issues/948 [#965]: https://github.com/eclipse/mosquitto/issues/965 ================================================ FILE: www/posts/2018/11/mqtt5-progress.md ================================================ Development of support for MQTT 5 is ongoing and making good progress, but has been substantially delayed due to other non-Mosquitto work having to take priority. It is possible to test the current state of MQTT 5 support by using the `mqtt5` branch of the [repository]. Please note that this is very much a work in progress, so parts are incomplete and interfaces may yet change. The client library in particular has had to have an increase in functions available in order to provide the features needed whilst providing backwards compatibility. Part of the plan for the 2.0 release, which will follow after 1.6, is to consolidate the libmosquitto API with breaking changes. There are more details on the [roadmap]. Current features include: * Support for all incoming and outgoing packets, although not everything is processed. * Support for sending and receiving all properties, with not all properties processed. * Client support for setting properties * Request/response support (client cannot process incoming correlation data) * Retain availability * Message expiry interval support * Server support for assigned client identifiers * Payload format indicator support * Content-type support * Basic topic alias support from client to broker * Lots of new tests Both `mosquitto_pub` and `mosquitto_sub` support setting properties on the command line, for example: ``` mosquitto_sub -t topic -v -D connect session-expiry-interval 60 -D connect user-property key value -D subscribe user-property sub-key sub-value ``` ``` mosquitto_pub -t topic -m '{"key":"value"}' -D publish content-type "application/json" ``` ``` ./sensor_read.sh | mosquitto_pub -t topic -l -D publish topic-alias 1 ``` Further updates will be posted when more features are available. [repository]: https://github.com/eclipse/mosquitto/tree/mqtt5 [roadmap]: https://mosquitto.org/roadmap/ ================================================ FILE: www/posts/2018/11/version-154-released.md ================================================ This is a bugfix and security release. # Version 1.5.4 changes ## 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]. [#7]: https://github.com/eclipse/mosquitto/issues/7 [#287]: https://github.com/eclipse/mosquitto/issues/287 [#592]: https://github.com/eclipse/mosquitto/issues/592 [#933]: https://github.com/eclipse/mosquitto/issues/933 [#977]: https://github.com/eclipse/mosquitto/issues/977 [#983]: https://github.com/eclipse/mosquitto/issues/983 [#990]: https://github.com/eclipse/mosquitto/issues/990 [#996]: https://github.com/eclipse/mosquitto/issues/996 [#1015]: https://github.com/eclipse/mosquitto/issues/1015 [#1016]: https://github.com/eclipse/mosquitto/issues/1016 [#1018]: https://github.com/eclipse/mosquitto/issues/1018 [#1019]: https://github.com/eclipse/mosquitto/issues/1019 ================================================ FILE: www/posts/2018/12/version-155-released.md ================================================ This is a bugfix and security release. # Version 1.5.5 changes ## 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]. [CVE-2018-20145]: https://nvd.nist.gov/vuln/detail/CVE-2018-20145 [#68]: https://github.com/eclipse/mosquitto/issues/68 [#537]: https://github.com/eclipse/mosquitto/issues/537 [#613]: https://github.com/eclipse/mosquitto/issues/613 [#772]: https://github.com/eclipse/mosquitto/issues/772 [#1004]: https://github.com/eclipse/mosquitto/issues/1004 [#1027]: https://github.com/eclipse/mosquitto/issues/1027 [#1040]: https://github.com/eclipse/mosquitto/issues/1040 [#1062]: https://github.com/eclipse/mosquitto/issues/1062 [#1066]: https://github.com/eclipse/mosquitto/issues/1066 [#1067]: https://github.com/eclipse/mosquitto/issues/1067 [#1068]: https://github.com/eclipse/mosquitto/issues/1068 [#1073]: https://github.com/eclipse/mosquitto/issues/1073 ================================================ FILE: www/posts/2019/02/mqtt5-test-release.md ================================================ The work on MQTT v5 support in Mosquitto has reached a point where it may be of interest to a range of people. It is not yet complete, but wider testing and feedback would be appreciated. The source is available at [mosquitto-mqtt5-test1.tar.gz] and can be compiled as normal. ## Supported features * Session expiry * Message expiry * Reason code on all ACKs (not all reason codes are used) * Reason string on all ACKs (no reason strings are provided by the broker however) * Payload format and content type * Request / response pattern * Subscription ID * Topic alias * Flow control * User properties * Optional server feature availability * Subscription options * Server keep alive * Assigned Client ID ## Unsupported features * Shared subscriptions * Extended authentication * Server reference * Not all reason codes are used by the broker * Bridges do not use MQTT v5 * On disk persistence does not include MQTT 5 property support * The broker will not create topic aliases [mosquitto-mqtt5-test1.tar.gz]: https://mosquitto.org/files/source/test/mosquitto-mqtt5-test1.tar.gz ================================================ FILE: www/posts/2019/02/version-1-5-6-released.md ================================================ Mosquitto 1.5.6 has been released to address three potential security vulnerabilities. # 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. Patches for older versions are available at # 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. Affects versions 1.0 to 1.5.5 inclusive. Patches for older versions are available at # 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. Patches for older versions are available at # Version 1.5.6 Changes The list of other fixes addressed in version 1.5.6 is: ## 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]. [#1080]: https://github.com/eclipse/mosquitto/issues/1080 [#1081]: https://github.com/eclipse/mosquitto/issues/1081 [#1094]: https://github.com/eclipse/mosquitto/issues/1094 [#1101]: https://github.com/eclipse/mosquitto/issues/1101 [#1131]: https://github.com/eclipse/mosquitto/issues/1131 [#1137]: https://github.com/eclipse/mosquitto/issues/1137 [#1139]: https://github.com/eclipse/mosquitto/issues/1139 [#1143]: https://github.com/eclipse/mosquitto/issues/1143 [#1144]: https://github.com/eclipse/mosquitto/issues/1144 ================================================ FILE: www/posts/2019/02/version-1-5-7-released.md ================================================ This is a bugfix release. ## 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. [#389]: https://github.com/eclipse/mosquitto/issues/389 [#1149]: https://github.com/eclipse/mosquitto/issues/1149 [#1154]: https://github.com/eclipse/mosquitto/issues/1154 ================================================ FILE: www/posts/2019/02/version-1-5-8-released.md ================================================ This is a bugfix release. ## 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. [#1032]: https://github.com/eclipse/mosquitto/issues/1032 [#1162]: https://github.com/eclipse/mosquitto/issues/1162 [#1174]: https://github.com/eclipse/mosquitto/issues/1174 [#1177]: https://github.com/eclipse/mosquitto/issues/1177 ================================================ FILE: www/posts/2019/04/version-1-6-1-released.md ================================================ This is a minor service release. The fixes are only related to documentation and the build process, and so is primarily of interest for people building Mosquitto. ## 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]. [#1048]: https://github.com/eclipse/mosquitto/issues/1048 [#1049]: https://github.com/eclipse/mosquitto/issues/1049 [#1230]: https://github.com/eclipse/mosquitto/issues/1230 [#1231]: https://github.com/eclipse/mosquitto/issues/1231 [#1232]: https://github.com/eclipse/mosquitto/issues/1232 ================================================ FILE: www/posts/2019/04/version-1-6-2-released.md ================================================ This is a security and bugfix release. ## Security If a client connects using MQTT v5, will a Will message that has MQTT v5 properties attached, and the very first Will property is one of `content-type`, `correlation-data`, `payload-format-indicator`, or `response-topic`, then at the point the client disconnects, the broker will attempt to read from freed memory, resulting in a possible crash. ## 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]. [#1244]: https://github.com/eclipse/mosquitto/issues/1244 [#1245]: https://github.com/eclipse/mosquitto/issues/1245 [#1246]: https://github.com/eclipse/mosquitto/issues/1246 [#1250]: https://github.com/eclipse/mosquitto/issues/1250 ================================================ FILE: www/posts/2019/04/version-1-6-released.md ================================================ This is a feature release and represents a substantial amount of change in the project. Since version 1.5, the overall code line count for the broker, library and clients has increased by 37% to 28k. Testing has been an important focus for this release. The number of tests has increased from 102 to 412. The test coverage, whilst still needing further improvement, has increased from 56% to 61%. A summary of the notable features is given below. # MQTT v5 support The big addition for this release is support for MQTT v5. This covers the broker, client library and client, and gives full support for the new specification, although not all features are accessible as they will be. You can quickly test out a v5 client by using `-V 5` and adding properties with the `-D` option, for example: ``` mosquitto_sub -V 5 -D connect receive-maximum 3 -D subscribe subscription-identifier 1 ... ``` The authentication plugin interface has been extended to allow use of the v5 extended authentication feature. # Performance improvements A number of performance improvements have been implemented in the broker, including the message routing logic, topic matching, and persistence file reading/writing. More improvements are planned for the next release. # New client - mosquitto_rr `mosquitto_rr` is the "request-response" client, intended for the situation where you want to publish a request message and await a response. It works best with the MQTT v5 request-response features, but can be used with v3.1.1 servers if the client it is talking to knows how to respond. This tool is almost certainly not going to see as much use as `mosquitto_sub` or `mosquitto_pub`, but is a useful utility to have available. # Contributed features Some notable features have been contributed by the community. On the TLS front, support for ALPN allows bridges and clients to connect to servers that have multiple protocols on a single port. The new OCSP stapling support allows the status of TLS certificates to be validated. Finally, TLS Engine support has been added. Away from TLS, support for Automotive DLT logging has been added, disabled by default. # Deprecations The C++ wrapper library, libmosquittopp is now deprecated and will be removed in version 2.0. It remains largely unchanged since v1.5. The C library, libmosquitto, is having its interface changed for version 2.0, so any current function should be considered at risk. The rationale for this is to consolidate the changes introduced since version 1.0, in particular the large number of functions required to support MQTT v5, but that otherwise closely match existing functions. Support for TLS v1.0 has been dropped. Support for TLS v1.1 will be dropped in version 2.0. # Changelog The more detailed changelog is below, but does not include many of the fixes and improvements that have been made: ## 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. - 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 `mosquitto_passwd` crashing on corrupt password file. Closes [#1207]. - 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]. [#924]: https://github.com/eclipse/mosquitto/issues/924 [#1208]: https://github.com/eclipse/mosquitto/issues/1208 [#1212]: https://github.com/eclipse/mosquitto/issues/1212 [#1220]: https://github.com/eclipse/mosquitto/issues/1220 ================================================ FILE: www/posts/2019/06/version-1-6-3-released.md ================================================ This is a bugfix release. ## 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. ## 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]. [#1152]: https://github.com/eclipse/mosquitto/issues/1152 [#1227]: https://github.com/eclipse/mosquitto/issues/1227 [#1257]: https://github.com/eclipse/mosquitto/issues/1257 [#1263]: https://github.com/eclipse/mosquitto/issues/1263 [#1264]: https://github.com/eclipse/mosquitto/issues/1264 [#1266]: https://github.com/eclipse/mosquitto/issues/1266 [#1273]: https://github.com/eclipse/mosquitto/issues/1273 [#1273]: https://github.com/eclipse/mosquitto/issues/1273 [#1273]: https://github.com/eclipse/mosquitto/issues/1273 [#1274]: https://github.com/eclipse/mosquitto/issues/1274 [#1276]: https://github.com/eclipse/mosquitto/issues/1276 [#1280]: https://github.com/eclipse/mosquitto/issues/1280 [#1284]: https://github.com/eclipse/mosquitto/issues/1284 [#1285]: https://github.com/eclipse/mosquitto/issues/1285 [#1290]: https://github.com/eclipse/mosquitto/issues/1290 [#1294]: https://github.com/eclipse/mosquitto/issues/1294 [#1302]: https://github.com/eclipse/mosquitto/issues/1302 ================================================ FILE: www/posts/2019/08/version-1-6-4-released.md ================================================ This is a bugfix release. ## 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. [#515]: https://github.com/eclipse/mosquitto/issues/515 [#1272]: https://github.com/eclipse/mosquitto/issues/1272 [#1322]: https://github.com/eclipse/mosquitto/issues/1322 [#1332]: https://github.com/eclipse/mosquitto/issues/1332 [#1344]: https://github.com/eclipse/mosquitto/issues/1344 [#1345]: https://github.com/eclipse/mosquitto/issues/1345 [#1353]: https://github.com/eclipse/mosquitto/issues/1353 [#1354]: https://github.com/eclipse/mosquitto/issues/1354 [#1360]: https://github.com/eclipse/mosquitto/issues/1360 ================================================ FILE: www/posts/2019/09/version-1-6-5-released.md ================================================ This is a bugfix release. # Compatibility - The most recent version of libwebsockets (3.2.0) changed its behaviour and is not compatible with Mosquitto. This has been fixed for the next libwebsockets release. The 1.6.5 release refuses to compile with libwebsockets 3.2.0. All previous versions of Mosquitto that use websockets are affected by the change in behaviour. # Broker - Fix v5 DISCONNECT packets with remaining length == 2 being treated as a protocol error. Closes [#1367]. - Fix support for libwebsockets 3.x (excluding 3.2.0) - 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]. [#35]: https://github.com/eclipse/mosquitto/issues/35 [#274]: https://github.com/eclipse/mosquitto/issues/274 [#448]: https://github.com/eclipse/mosquitto/issues/448 [#478]: https://github.com/eclipse/mosquitto/issues/478 [#522]: https://github.com/eclipse/mosquitto/issues/522 [#737]: https://github.com/eclipse/mosquitto/issues/737 [#1367]: https://github.com/eclipse/mosquitto/issues/1367 [#1369]: https://github.com/eclipse/mosquitto/issues/1369 [#1374]: https://github.com/eclipse/mosquitto/issues/1374 [#1390]: https://github.com/eclipse/mosquitto/issues/1390 [#1391]: https://github.com/eclipse/mosquitto/issues/1391 [#1401]: https://github.com/eclipse/mosquitto/issues/1401 [#1402]: https://github.com/eclipse/mosquitto/issues/1402 ================================================ FILE: www/posts/2019/09/version-1-6-6-released.md ================================================ Mosquitto 1.6.6 and 1.5.9 have been released to address two security vulnerabilities. Titles and links will be updated once the CVE numbers are assigned. # CVE-2019-11779 A vulnerability exists in Mosquitto versions 1.5 to 1.6.5 inclusive, known as [CVE-2019-11779]. If a client sends a SUBSCRIBE packet containing a topic that consists of approximately 65400 or more '/' characters, i.e. the topic hierarchy separator, then a stack overflow will occur. The issue is fixed in Mosquitto 1.6.6 and 1.5.9. Patches for older versions are available at The fix addresses the problem by restricting the allowed number of topic hierarchy levels to 200. An alternative fix is to increase the size of the stack by a small amount. # CVE-2019-11778 A vulnerability exists in Mosquitto version 1.6 to 1.6.4 inclusive, known as [CVE-2019-11778] If an MQTT v5 client connects to Mosquitto, sets a last will and testament, sets a will delay interval, sets a session expiry interval, and the will delay interval is set longer than the session expiry interval, then a use after free error occurs, which has the potential to cause a crash in some situations. The issue is fixed in Mosquitto 1.6.5. Patches for older versions are available at # Version 1.6.6 Changes The complete list of fixes addressed in version 1.6.6 is: ## 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]. [CVE-2019-11778]: http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-11778 [CVE-2019-11779]: http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-11779 [#1412]: https://github.com/eclipse/mosquitto/issues/1412 [#1414]: https://github.com/eclipse/mosquitto/issues/1414 ================================================ FILE: www/posts/2019/09/version-1-6-7-released.md ================================================ Mosquitto 1.6.7 has been released, this is a bugfix release. # 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. [#1415]: https://github.com/eclipse/mosquitto/issues/1415 [#1417]: https://github.com/eclipse/mosquitto/issues/1417 [#1418]: https://github.com/eclipse/mosquitto/issues/1418 [#1422]: https://github.com/eclipse/mosquitto/issues/1422 [#1424]: https://github.com/eclipse/mosquitto/issues/1424 [#1425]: https://github.com/eclipse/mosquitto/issues/1425 ================================================ FILE: www/posts/2019/11/version-1-6-8-released.md ================================================ Mosquitto 1.6.8 has been released, this is a bugfix release. # 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 quitting 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]. [#1429]: https://github.com/eclipse/mosquitto/issues/1429 [#1432]: https://github.com/eclipse/mosquitto/issues/1432 [#1437]: https://github.com/eclipse/mosquitto/issues/1437 [#1441]: https://github.com/eclipse/mosquitto/issues/1441 [#1442]: https://github.com/eclipse/mosquitto/issues/1442 [#1448]: https://github.com/eclipse/mosquitto/issues/1448 [#1453]: https://github.com/eclipse/mosquitto/issues/1453 [#1459]: https://github.com/eclipse/mosquitto/issues/1459 [#1463]: https://github.com/eclipse/mosquitto/issues/1463 [#1464]: https://github.com/eclipse/mosquitto/issues/1464 [#1473]: https://github.com/eclipse/mosquitto/issues/1473 [#1474]: https://github.com/eclipse/mosquitto/issues/1474 [#1478]: https://github.com/eclipse/mosquitto/issues/1478 [#1489]: https://github.com/eclipse/mosquitto/issues/1489 [#1494]: https://github.com/eclipse/mosquitto/issues/1494 [#1499]: https://github.com/eclipse/mosquitto/issues/1499 [#1513]: https://github.com/eclipse/mosquitto/issues/1513 ================================================ FILE: www/posts/2020/02/version-1-6-9-released.md ================================================ Mosquitto 1.6.9 has been released, this is a bugfix release. # Broker - Fix session expiry with very large expiry intervals. Closes [#1525]. - Check ACL patterns for validity when loading. Closes [#1539]. - Use presence of password file as indicator for whether username checks should take place, not whether usernames are defined in the password file. Closes [#1545]. - Strip whitespace from end of config file string options. Closes [#1566]. - Satisfy valgrind when exiting on error due to not being able to open a listening socket, by calling freeaddrinfo. Closes [#1565]. - Fix `config->user` not being freed on exit. Closes [#1564]. - Fix trailing whitespace not being trimmed on acl users. Closes [#1539]. - Fix `bind_interface` not working for the default listener. Closes [#1533]. - Improve password file parsing in the broker and `mosquitto_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]. [#1525]: https://github.com/eclipse/mosquitto/issues/1525 [#1533]: https://github.com/eclipse/mosquitto/issues/1533 [#1539]: https://github.com/eclipse/mosquitto/issues/1539 [#1539]: https://github.com/eclipse/mosquitto/issues/1539 [#1545]: https://github.com/eclipse/mosquitto/issues/1545 [#1546]: https://github.com/eclipse/mosquitto/issues/1546 [#1550]: https://github.com/eclipse/mosquitto/issues/1550 [#1552]: https://github.com/eclipse/mosquitto/issues/1552 [#1564]: https://github.com/eclipse/mosquitto/issues/1564 [#1565]: https://github.com/eclipse/mosquitto/issues/1565 [#1566]: https://github.com/eclipse/mosquitto/issues/1566 [#1584]: https://github.com/eclipse/mosquitto/issues/1584 [#1585]: https://github.com/eclipse/mosquitto/issues/1585 [#1589]: https://github.com/eclipse/mosquitto/issues/1589 ================================================ FILE: www/posts/2020/05/version-1-6-10-released.md ================================================ Mosquitto 1.6.10 has been released, this is a bugfix release. # 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 below C99 support. Closes [#1622]. - Fix use of sed on BSD. Closes [#1614]. [#1521]: https://github.com/eclipse/mosquitto/issues/1521 [#1614]: https://github.com/eclipse/mosquitto/issues/1614 [#1622]: https://github.com/eclipse/mosquitto/issues/1622 [#1629]: https://github.com/eclipse/mosquitto/issues/1629 [#1635]: https://github.com/eclipse/mosquitto/issues/1635 [#1664]: https://github.com/eclipse/mosquitto/issues/1664 [#1674]: https://github.com/eclipse/mosquitto/issues/1674 [#1684]: https://github.com/eclipse/mosquitto/issues/1684 [#1690]: https://github.com/eclipse/mosquitto/issues/1690 [#1691]: https://github.com/eclipse/mosquitto/issues/1691 [#1700]: https://github.com/eclipse/mosquitto/issues/1700 ================================================ FILE: www/posts/2020/06/mosquitto-ubuntu-appliance.md ================================================ Ubuntu has just announced their new [Ubuntu Appliance] initiative, which provides self contained images for a number of different applications, for use on a Raspberry Pi or PC. These are full Ubuntu derivatives that use snap packages, so will keep up to date with the latest releases. There are five different applications in the first set of appliances, and Mosquitto is one of them. Read more at the [Ubuntu blog]. [Ubuntu Appliance]: http://ubuntu.com/appliance [Ubuntu blog]: https://ubuntu.com/blog/the-ubuntu-appliance-portfolio ================================================ FILE: www/posts/2020/06/test-mosquitto-org-cert-updated.md ================================================ The CA certificate and server certificate for the broker running at [test.mosquitto.org] has been updated to use a stronger key. This means that if you have downloaded the CA certificate, you will need to do so again. Likewise, if you have used the [client certificate generator] then your certificate will no longer be accepted and you must generate a new one. [test.mosquitto.org]: https://test.mosquitto.org [client certificate generator]: https://test.mosquitto.org/ssl/ ================================================ FILE: www/posts/2020/08/version-1-6-11-released.md ================================================ Mosquitto 1.6.11 has been released, this is a bugfix release. # Security - On Windows the Mosquitto service was being installed without appropriate path quoting, this has been fixed. Closes [#565671]. # 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]. [#117]: https://github.com/eclipse/mosquitto/issues/117 [#821]: https://github.com/eclipse/mosquitto/issues/821 [#1547]: https://github.com/eclipse/mosquitto/issues/1547 [#1689]: https://github.com/eclipse/mosquitto/issues/1689 [#1713]: https://github.com/eclipse/mosquitto/issues/1713 [#1718]: https://github.com/eclipse/mosquitto/issues/1718 [#1725]: https://github.com/eclipse/mosquitto/issues/1725 [#1726]: https://github.com/eclipse/mosquitto/issues/1726 [#1729]: https://github.com/eclipse/mosquitto/issues/1729 [#1730]: https://github.com/eclipse/mosquitto/issues/1730 [#1735]: https://github.com/eclipse/mosquitto/issues/1735 [#1740]: https://github.com/eclipse/mosquitto/issues/1740 [#1741]: https://github.com/eclipse/mosquitto/issues/1741 [#1748]: https://github.com/eclipse/mosquitto/issues/1748 [#1749]: https://github.com/eclipse/mosquitto/issues/1749 [#1752]: https://github.com/eclipse/mosquitto/issues/1752 [#1773]: https://github.com/eclipse/mosquitto/issues/1773 [#1774]: https://github.com/eclipse/mosquitto/issues/1774 [#1777]: https://github.com/eclipse/mosquitto/issues/1777 [#565671]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=565671 ================================================ FILE: www/posts/2020/08/version-1-6-12-released.md ================================================ Mosquitto 1.6.12 and 1.5.10 have been released. # 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]. The following fixes apply to 1.6.12 only. # 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. [#1778]: https://github.com/eclipse/mosquitto/issues/1778 [#1793]: https://github.com/eclipse/mosquitto/issues/1793 ================================================ FILE: www/posts/2020/12/version-2-0-0-released.md ================================================ The Mosquitto project is happy to announce the release of version 2.0! This is a big change with breaking behaviour changes in the broker. Users, packages and plugin authors should read [migrating from 1.x to 2.0] to help with the changes. # Noteworthy changes Mosquitto is now more secure by default and requires users to take an active decision in how they configure security on their broker, instead of possibly relying on the older very permissive behaviour, as well as dropping privileged access more quickly. More details are in [migrating from 1.x to 2.0]. A new plugin interface has been introduced which goes beyond the existing authentication and access control plugin interface to offer more plugin capabilities, whilst being easier to develop for and easier to extend. More details will follow. Existing plugins are still supported, although plugin authors should look at [migrating from 1.x to 2.0] to ensure their plugins remain compatible when compiled against Mosquitto 2.0 headers. A new plugin has been introduced to provide client, group, and role based authentication and access control. The plugin configuration is managed over special topics and can be updated on the fly. It provides a flexible and straightforward means of configuring access to your broker. For more information, see [Dynamic Security plugin]. The broker performance has been improved, particularly for higher numbers of clients. We plan to run show some benchmarks to show the improvement. A new utility, `mosquitto_ctrl` has been added for controlling aspects of a running broker. At the present this is limited to controlling the dynamic security plugin, but will be extended to other features in later releases. Bridges now support MQTT v5. The mosquitto command line clients have received a variety of small improvements. mosquitto_sub can now format its output in fixed column widths, for example, and filter its output randomly so you can keep an eye on the overall behaviour of a topic without having to see every message, for example. # 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 # 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_plugin_publish()` function, 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 incorrectly 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]. [migrating from 1.x to 2.0]:/documentation/migrating-to-2-0/ [#265]: https://github.com/eclipse/mosquitto/issues/265 [#275]: https://github.com/eclipse/mosquitto/issues/275 [#291]: https://github.com/eclipse/mosquitto/issues/291 [#1222]: https://github.com/eclipse/mosquitto/issues/1222 [#1258]: https://github.com/eclipse/mosquitto/issues/1258 [#1311]: https://github.com/eclipse/mosquitto/issues/1311 [#1416]: https://github.com/eclipse/mosquitto/issues/1416 [#1526]: https://github.com/eclipse/mosquitto/issues/1526 [#1611]: https://github.com/eclipse/mosquitto/issues/1611 [#1735]: https://github.com/eclipse/mosquitto/issues/1735 [#1814]: https://github.com/eclipse/mosquitto/issues/1814 [#1819]: https://github.com/eclipse/mosquitto/issues/1819 [#1822]: https://github.com/eclipse/mosquitto/issues/1822 [#1824]: https://github.com/eclipse/mosquitto/issues/1824 [#1825]: https://github.com/eclipse/mosquitto/issues/1825 [#1831]: https://github.com/eclipse/mosquitto/issues/1831 [#1833]: https://github.com/eclipse/mosquitto/issues/1833 [#1842]: https://github.com/eclipse/mosquitto/issues/1842 [#1846]: https://github.com/eclipse/mosquitto/issues/1846 [#1862]: https://github.com/eclipse/mosquitto/issues/1862 [#1866]: https://github.com/eclipse/mosquitto/issues/1866 [#1880]: https://github.com/eclipse/mosquitto/issues/1880 [#1881]: https://github.com/eclipse/mosquitto/issues/1881 [#1891]: https://github.com/eclipse/mosquitto/issues/1891 [#1897]: https://github.com/eclipse/mosquitto/issues/1897 [#1902]: https://github.com/eclipse/mosquitto/issues/1902 [#1908]: https://github.com/eclipse/mosquitto/issues/1908 [#1911]: https://github.com/eclipse/mosquitto/issues/1911 ================================================ FILE: www/posts/2020/12/version-2-0-2-released.md ================================================ Version 2.0.2 and 2.0.1 of Mosquitto has been released. These are bugfix releases. Version 2.0.2 fixes a build regression introduced in 2.0.1 when websockets support was enabled on non-Linux systems. The 2.0.1 changes are below. # 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. [#1476]: https://github.com/eclipse/mosquitto/issues/1476 [#1925]: https://github.com/eclipse/mosquitto/issues/1925 [#1934]: https://github.com/eclipse/mosquitto/issues/1934 [#1936]: https://github.com/eclipse/mosquitto/issues/1936 ================================================ FILE: www/posts/2020/12/version-2-0-3-released.md ================================================ Version 2.0.3 of Mosquitto has been released. This is a bugfix release. # 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. # 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]. [#1938]: https://github.com/eclipse/mosquitto/issues/1938 [#1942]: https://github.com/eclipse/mosquitto/issues/1942 [#1945]: https://github.com/eclipse/mosquitto/issues/1945 [#1946]: https://github.com/eclipse/mosquitto/issues/1946 [#1947]: https://github.com/eclipse/mosquitto/issues/1947 [#1949]: https://github.com/eclipse/mosquitto/issues/1949 [#1956]: https://github.com/eclipse/mosquitto/issues/1956 [#1957]: https://github.com/eclipse/mosquitto/issues/1957 [#1960]: https://github.com/eclipse/mosquitto/issues/1960 ================================================ FILE: www/posts/2020/12/version-2-0-4-released.md ================================================ Version 2.0.4 of Mosquitto has been released. This is a bugfix release. # 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]. [#1934]: https://github.com/eclipse/mosquitto/issues/1934 [#1962]: https://github.com/eclipse/mosquitto/issues/1962 [#1968]: https://github.com/eclipse/mosquitto/issues/1968 [#1969]: https://github.com/eclipse/mosquitto/issues/1969 ================================================ FILE: www/posts/2021/01/version-2-0-5-released.md ================================================ Version 2.0.5 of Mosquitto has been released. This is a bugfix release. # 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]. [#1975]: https://github.com/eclipse/mosquitto/issues/1975 [#1977]: https://github.com/eclipse/mosquitto/issues/1977 [#1978]: https://github.com/eclipse/mosquitto/issues/1978 [#1979]: https://github.com/eclipse/mosquitto/issues/1979 [#1989]: https://github.com/eclipse/mosquitto/issues/1989 [#1995]: https://github.com/eclipse/mosquitto/issues/1995 [#1997]: https://github.com/eclipse/mosquitto/issues/1997 [#1998]: https://github.com/eclipse/mosquitto/issues/1998 [#1999]: https://github.com/eclipse/mosquitto/issues/1999 [#2005]: https://github.com/eclipse/mosquitto/issues/2005 [#2008]: https://github.com/eclipse/mosquitto/issues/2008 ================================================ FILE: www/posts/2021/01/version-2-0-6-released.md ================================================ Version 2.0.6 of Mosquitto has been released. This is a bugfix release. # Broker - Fix calculation of remaining length parameter for websockets clients that send fragmented packets. Closes [#1974]. - 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. [#1974]: https://github.com/eclipse/mosquitto/issues/1974 [#2010]: https://github.com/eclipse/mosquitto/issues/2010 [#2011]: https://github.com/eclipse/mosquitto/issues/2011 [#2017]: https://github.com/eclipse/mosquitto/issues/2017 [#2019]: https://github.com/eclipse/mosquitto/issues/2019 [#2020]: https://github.com/eclipse/mosquitto/issues/2020 [#2022]: https://github.com/eclipse/mosquitto/issues/2022 [#2026]: https://github.com/eclipse/mosquitto/issues/2026 [#2029]: https://github.com/eclipse/mosquitto/issues/2029 [#2037]: https://github.com/eclipse/mosquitto/issues/2037 [#2043]: https://github.com/eclipse/mosquitto/issues/2043 ================================================ FILE: www/posts/2021/02/version-2-0-7-released.md ================================================ Version 2.0.7 and 1.6.13 of Mosquitto have been released. These are bugfix releases. # 2.0.7 ## 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 ## 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. [#1476]: https://github.com/eclipse/mosquitto/issues/1476 [#1866]: https://github.com/eclipse/mosquitto/issues/1866 [#1880]: https://github.com/eclipse/mosquitto/issues/1880 [#1891]: https://github.com/eclipse/mosquitto/issues/1891 [#1897]: https://github.com/eclipse/mosquitto/issues/1897 [#1905]: https://github.com/eclipse/mosquitto/issues/1905 [#1908]: https://github.com/eclipse/mosquitto/issues/1908 [#1925]: https://github.com/eclipse/mosquitto/issues/1925 [#1942]: https://github.com/eclipse/mosquitto/issues/1942 [#1968]: https://github.com/eclipse/mosquitto/issues/1968 [#2057]: https://github.com/eclipse/mosquitto/issues/2057 [#2059]: https://github.com/eclipse/mosquitto/issues/2059 [#2066]: https://github.com/eclipse/mosquitto/issues/2066 [#570126]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=570126 ================================================ FILE: www/posts/2021/02/version-2-0-8-released.md ================================================ Version 2.0.8 of Mosquitto has been released. This is a bugfix release. # 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]. [#2040]: https://github.com/eclipse/mosquitto/issues/2040 [#2060]: https://github.com/eclipse/mosquitto/issues/2060 [#2078]: https://github.com/eclipse/mosquitto/issues/2078 [#2096]: https://github.com/eclipse/mosquitto/issues/2096 ================================================ FILE: www/posts/2021/03/version-2-0-9-released.md ================================================ Versions 2.0.9, 1.6.14, and 1.5.11 of Mosquitto have been released. These are bugfix releases and include a minor security fix. # 2.0.9 ## 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 minimum 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. # 1.6.14 ## 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]. ## 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. ## Clients - Fix possible loss of data in `mosquitto_pub -l` when sending multiple long lines. Closes [#2078]. # 1.5.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]. ## Client library - Fix encrypted connections incorrectly connecting when the CA file passed to `mosquitto_tls_set()` is empty or invalid. Closes [#2130]. [#2040]: https://github.com/eclipse/mosquitto/issues/2040 [#2078]: https://github.com/eclipse/mosquitto/issues/2078 [#2081]: https://github.com/eclipse/mosquitto/issues/2081 [#2110]: https://github.com/eclipse/mosquitto/issues/2110 [#2111]: https://github.com/eclipse/mosquitto/issues/2111 [#2117]: https://github.com/eclipse/mosquitto/issues/2117 [#2123]: https://github.com/eclipse/mosquitto/issues/2123 [#2130]: https://github.com/eclipse/mosquitto/issues/2130 ================================================ FILE: www/posts/2021/04/version-2-0-10-released.md ================================================ Versions 2.0.10 of Mosquitto has been released. This is a security and bugfix release. # 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. This will be updated with the CVE number when it is assigned. Affects versions 2.0.0 to 2.0.9 inclusive. # Broker - Don't overwrite 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]. [CVE-2021-23980]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28166 [#2134]: https://github.com/eclipse/mosquitto/issues/2134 [#2136]: https://github.com/eclipse/mosquitto/issues/2136 [#2152]: https://github.com/eclipse/mosquitto/issues/2152 [#2160]: https://github.com/eclipse/mosquitto/issues/2160 [#2163]: https://github.com/eclipse/mosquitto/issues/2163 ================================================ FILE: www/posts/2021/06/version-2-0-11-released.md ================================================ Versions 2.0.11 and 1.6.15 of Mosquitto has been released. These are a security and bugfix releases. # 2.0.11 ## Security - If an authenticated client connected with MQTT v5 sent a crafted CONNECT message to the broker a memory leak would occur. Affects versions 1.6 to 2.0.10 inclusive. ## 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]. # 1.6.15 ## Security - If an authenticated client connected with MQTT v5 sent a crafted CONNECT message to the broker a memory leak would occur. Affects versions 1.6 to 2.0.10 inclusive. [#2164]: https://github.com/eclipse/mosquitto/issues/2164 [#2167]: https://github.com/eclipse/mosquitto/issues/2167 [#2172]: https://github.com/eclipse/mosquitto/issues/2172 [#2173]: https://github.com/eclipse/mosquitto/issues/2173 [#2187]: https://github.com/eclipse/mosquitto/issues/2187 [#2207]: https://github.com/eclipse/mosquitto/issues/2207 [#2224]: https://github.com/eclipse/mosquitto/issues/2224 ================================================ FILE: www/posts/2021/08/version-2-0-12-released.md ================================================ Versions 2.0.12 of Mosquitto has been released. This is a security and bugfix release. # Security - An MQTT v5 client connecting with a large number of user-property properties could cause excessive CPU usage, leading to a loss of performance and possible denial of service. This has been fixed. - Fix `max_keepalive` not applying to MQTT v3.1.1 and v3.1 connections. These clients are now rejected if their keepalive value exceeds max_keepalive. This option allows [CVE-2020-13849], which is for the MQTT v3.1.1 protocol itself rather than an implementation, to be addressed. - Using certain listener related configuration options e.g. `cafile`, that apply to the default listener without defining any listener would cause a remotely accessible listener to be opened that was not confined to the local machine but did have anonymous access enabled, contrary to the documentation. This has been fixed. Closes [#2283]. - [CVE-2021-34434]: If a plugin had granted ACL subscription access to a durable/non-clean-session client, then removed that access, the client would keep its existing subscription. This has been fixed. - Incoming QoS 2 messages that had not completed the QoS flow were not being checked for ACL access when a clean session=False client was reconnecting. This has been fixed. # Broker - Fix possible out of bounds memory reads when reading a corrupt/crafted configuration file. Unless your configuration file is writable by untrusted users this is not a risk. Closes [#567213]. - Fix `max_connections` option not being correctly counted. - Fix TLS certificates and TLS-PSK not being able to be configured at the same time. - Disable TLS v1.3 when using TLS-PSK, because it isn't correctly configured. - Fix `max_keepalive` not applying to MQTT v3.1.1 and v3.1 connections. These clients are now rejected if their keepalive value exceeds `max_keepalive`. This option allows CVE-2020-13849, which is for the MQTT v3.1.1 protocol itself rather than an implementation, to be addressed. - Fix broker not quitting if e.g. the `password_file` is specified as a directory. Closes [#2241]. - Fix listener `mount_point` not being removed on outgoing messages. Closes [#2244]. - Strict protocol compliance fixes, plus test suite. - Fix $share subscriptions not being recovered for durable clients that reconnect. - Update plugin configuration documentation. Closes [#2286]. # Client library - If a client uses TLS-PSK then force the default cipher list to use "PSK" ciphers only. This means that a client connecting to a broker configured with x509 certificates only will now fail. Prior to this, the client would connect successfully without verifying certificates, because they were not configured. - Disable TLS v1.3 when using TLS-PSK, because it isn't correctly configured. - Threaded mode is deconfigured when the `mosquitto_loop_start()` thread ends, which allows `mosquitto_loop_start()` to be called again. Closes [#2242]. - Fix `MOSQ_OPT_SSL_CTX` not being able to be set to NULL. Closes [#2289]. - Fix reconnecting failing when `MOSQ_OPT_TLS_USE_OS_CERTS` was in use, but none of `capath`, `cafile`, `psk`, nor `MOSQ_OPT_SSL_CTX` were set, and `MOSQ_OPT_SSL_CTX_WITH_DEFAULTS` was set to the default value of true. Closes [#2288]. # Apps - Fix `mosquitto_ctrl dynsec setDefaultACLAccess` command not working. # Clients - `mosquitto_sub` and `mosquitto_rr` now open stdout in binary mode on Windows so binary payloads are not modified when printing. - Document TLS certificate behaviour when using `-p 8883`. # Build - Fix installation using `WITH_TLS=no`. Closes [#2281]. - Fix builds with libressl 3.4.0. Closes [#2198]. - Remove some unnecessary code guards related to libressl. - Fix printf format build warning on MIPS. Closes [#2271]. [#2198]: https://github.com/eclipse/mosquitto/issues/2198 [#2241]: https://github.com/eclipse/mosquitto/issues/2241 [#2242]: https://github.com/eclipse/mosquitto/issues/2242 [#2244]: https://github.com/eclipse/mosquitto/issues/2244 [#2271]: https://github.com/eclipse/mosquitto/issues/2271 [#2281]: https://github.com/eclipse/mosquitto/issues/2281 [#2286]: https://github.com/eclipse/mosquitto/issues/2286 [#2288]: https://github.com/eclipse/mosquitto/issues/2288 [#2289]: https://github.com/eclipse/mosquitto/issues/2289 [#567213]: https://bugs.eclipse.org/bugs/show_bug.cgi?id=567213 [CVE-2020-13849]: https://nvd.nist.gov/vuln/detail/CVE-2020-13849 [CVE-2021-34434]: https://nvd.nist.gov/vuln/detail/CVE-2021-34434 ================================================ FILE: www/posts/2021/10/version-2-0-13-released.md ================================================ Version 2.0.13 of Mosquitto has been released. This is a bugfix release. # Broker - Fix `max_keepalive` option not being able to be set to 0. - Fix LWT messages not being delivered if `per_listener_settings` was set to true. Closes [#2314]. - Various fixes around inflight quota management. Closes [#2306]. - Fix problem parsing config files with Windows line endings. Closes [#2297]. - Don't send retained messages when a shared subscription is made. - Fix log being truncated in Windows. - Fix client id not showing in log on failed connections, where possible. - Fix broker sending duplicate CONNACK on failed MQTT v5 reauthentication. Closes [#2339]. - Fix mosquitto_plugin.h not including mosquitto_broker.h. Closes [#2350]. # Client library - Initialise sockpairR/W to invalid in `mosquitto_reinitialise()` to avoid closing invalid sockets in `mosquitto_destroy()` on error. Closes [#2326]. # Clients - Fix date format in mosquitto_sub output. Closes [#2353]. [#2297]: https://github.com/eclipse/mosquitto/issues/2297 [#2306]: https://github.com/eclipse/mosquitto/issues/2306 [#2314]: https://github.com/eclipse/mosquitto/issues/2314 [#2326]: https://github.com/eclipse/mosquitto/issues/2326 [#2339]: https://github.com/eclipse/mosquitto/issues/2339 [#2350]: https://github.com/eclipse/mosquitto/issues/2350 [#2353]: https://github.com/eclipse/mosquitto/issues/2353 ================================================ FILE: www/posts/2021/11/version-2-0-14-released.md ================================================ Versions 2.0.14 of Mosquitto has been released. This is a bugfix release. # Broker - Fix bridge not respecting receive-maximum when reconnecting with MQTT v5. # Client library - Fix `mosquitto_topic_matches_sub2()` not using the length parameters. Closes [#2364]. - Fix incorrect `subscribe_callback` in mosquittopp.h. Closes [#2367]. [#2364]: https://github.com/eclipse/mosquitto/issues/2364 [#2367]: https://github.com/eclipse/mosquitto/issues/2367 ================================================ FILE: www/posts/2022/08/version-2-0-15-released.md ================================================ Versions 2.0.15 of Mosquitto has been released. This is a security and bugfix release. # Security - Deleting the group configured as the anonymous group in the Dynamic Security plugin, would leave a dangling pointer that could lead to a single crash. This is considered a minor issue - only administrative users should have access to dynsec, the impact on availability is one-off, and there is no associated loss of data. It is now forbidden to delete the group configured as the anonymous group. # Broker - Fix memory leak when a plugin modifies the topic of a message in `MOSQ_EVT_MESSAGE`. - Fix bridge `restart_timeout` not being honoured. - Fix potential memory leaks if a plugin modifies the message in the `MOSQ_EVT_MESSAGE` event. - Fix unused flags in CONNECT command being forced to be 0, which is not required for MQTT v3.1. Closes [#2522]. - Improve documentation of `persistent_client_expiration` option. Closes [#2404]. - Add clients to session expiry check list when restarting and reloading from persistence. Closes [#2546]. - Fix bridges not sending failure notification messages to the local broker if the remote bridge connection fails. Closes [#2467]. Closes [#1488]. - Fix some PUBLISH messages not being counted in $SYS stats. Closes [#2448]. - Fix incorrect return code being sent in DISCONNECT when a client session is taken over. Closes [#2607]. - Fix confusing "out of memory" error when a client is kicked in the dynamic security plugin. Closes [#2525]. - Fix confusing error message when dynamic security config file was a directory. Closes [#2520]. - Fix bridge queued messages not being persisted when local_cleansession is set to false and cleansession is set to true. Closes [#2604]. - Dynamic security: Fix modifyClient and modifyGroup commands to not modify the client/group if a new group/client being added is not valid. Closes [#2598]. - Dynamic security: Fix the plugin being able to be loaded twice. Currently only a single plugin can interact with a unique $CONTROL topic. Using multiple instances of the plugin would produce duplicate entries in the config file. Closes [#2601]. Closes [#2470]. - Fix case where expired messages were causing queued messages not to be delivered. Closes [#2609]. - Fix websockets not passing on the X-Forwarded-For header. # Client library - Fix threads library detection on Windows under cmake. Bumps the minimum cmake version to 3.1, which is still ancient. - Fix use of `MOSQ_OPT_TLS_ENGINE` being unable to be used due to the openssl ctx not being initialised until starting to connect. Closes [#2537]. - Fix incorrect use of SSL_connect. Closes [#2594]. - Don't set SIGPIPE to ignore, use MSG_NOSIGNAL instead. Closes [#2564]. - Add documentation of struct mosquitto_message to header. Closes [#2561]. - Fix documentation omission around mosquitto_reinitialise. Closes [#2489]. - Fix use of MOSQ_OPT_SSL_CTX when used in conjunction with MOSQ_OPT_SSL_CTX_DEFAULTS. Closes [#2463]. - Fix failure to close thread in some situations. Closes [#2545]. # Clients - Fix mosquitto_pub incorrectly reusing topic aliases when reconnecting. Closes [#2494]. # Apps - Fix `-o` not working in `mosquitto_ctrl`, and typo in related documentation. Closes [#2471]. [#1488]: https://github.com/eclipse/mosquitto/issues/1488 [#2404]: https://github.com/eclipse/mosquitto/issues/2404 [#2448]: https://github.com/eclipse/mosquitto/issues/2448 [#2463]: https://github.com/eclipse/mosquitto/issues/2463 [#2467]: https://github.com/eclipse/mosquitto/issues/2467 [#2470]: https://github.com/eclipse/mosquitto/issues/2470 [#2471]: https://github.com/eclipse/mosquitto/issues/2471 [#2489]: https://github.com/eclipse/mosquitto/issues/2489 [#2494]: https://github.com/eclipse/mosquitto/issues/2494 [#2520]: https://github.com/eclipse/mosquitto/issues/2520 [#2522]: https://github.com/eclipse/mosquitto/issues/2522 [#2525]: https://github.com/eclipse/mosquitto/issues/2525 [#2537]: https://github.com/eclipse/mosquitto/issues/2537 [#2545]: https://github.com/eclipse/mosquitto/issues/2545 [#2546]: https://github.com/eclipse/mosquitto/issues/2546 [#2561]: https://github.com/eclipse/mosquitto/issues/2561 [#2564]: https://github.com/eclipse/mosquitto/issues/2564 [#2594]: https://github.com/eclipse/mosquitto/issues/2594 [#2598]: https://github.com/eclipse/mosquitto/issues/2598 [#2601]: https://github.com/eclipse/mosquitto/issues/2601 [#2604]: https://github.com/eclipse/mosquitto/issues/2604 [#2607]: https://github.com/eclipse/mosquitto/issues/2607 [#2609]: https://github.com/eclipse/mosquitto/issues/2609 ================================================ FILE: www/posts/2023/08/version-2-0-16-released.md ================================================ Version 2.0.16 of Mosquitto has been released. This is a security and bugfix release. # Security - [CVE-2023-28366]: Fix memory leak in broker when clients send multiple QoS 2 messages with the same message ID, but then never respond to the PUBREC commands. - [CVE-2023-0809]: Fix excessive memory being allocated based on malicious initial packets that are not CONNECT packets. - [CVE-2023-3592]: Fix memory leak when clients send v5 CONNECT packets with a will message that contains invalid property types. - Broker will now reject Will messages that attempt to publish to $CONTROL/. - Broker now validates usernames provided in a TLS certificate or TLS-PSK identity are valid UTF-8. - Fix potential crash when loading invalid persistence file. - Library will no longer allow single level wildcard certificates, e.g. *.com # Broker - Fix $SYS messages being expired after 60 seconds and hence unchanged values disappearing. - Fix some retained topic memory not being cleared immediately after used. - Fix error handling related to the `bind_interface` option. - Fix std* files not being redirected when daemonising, when built with assertions removed. Closes [#2708]. - Fix default settings incorrectly allowing TLS v1.1. Closes [#2722]. - Use line buffered mode for stdout. Closes #2354. Closes [#2749]. - Fix bridges with non-matching cleansession/local_cleansession being expired on start after restoring from persistence. Closes [#2634]. - Fix connections being limited to 2048 on Windows. The limit is now 8192, where supported. Closes [#2732]. - Broker will log warnings if sensitive files are world readable/writable, or if the owner/group is not the same as the user/group the broker is running as. In future versions the broker will refuse to open these files. - mosquitto_memcmp_const is now more constant time. - Only register with DLT if DLT logging is enabled. - Fix any possible case where a json string might be incorrectly loaded. This could have caused a crash if a textname or textdescription field of a role was not a string, when loading the dynsec config from file only. - Dynsec plugin will not allow duplicate clients/groups/roles when loading config from file, which matches the behaviour for when creating them. - Fix heap overflow when reading corrupt config with "log_dest file". # Client library - Use CLOCK_BOOTTIME when available, to keep track of time. This solves the problem of the client OS sleeping and the client hence not being able to calculate the actual time for keepalive purposes. Closes [#2760]. - Fix default settings incorrectly allowing TLS v1.1. Closes [#2722]. - Fix high CPU use on slow TLS connect. Closes [#2794]. # Clients - Fix incorrect topic-alias property value in mosquitto_sub json output. - Fix confusing message on TLS certificate verification. Closes [#2746]. # Apps - mosquitto_passwd uses mkstemp() for backup files. - `mosquitto_ctrl dynsec init` will refuse to overwrite an existing file, without a race-condition. [CVE-2023-0809]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-0809 [CVE-2023-28366]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-27366 [CVE-2023-3592]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-3592 [#2354]: https://github.com/eclipse/mosquitto/issues/2354 [#2634]: https://github.com/eclipse/mosquitto/issues/2634 [#2708]: https://github.com/eclipse/mosquitto/issues/2708 [#2722]: https://github.com/eclipse/mosquitto/issues/2722 [#2722]: https://github.com/eclipse/mosquitto/issues/2722 [#2732]: https://github.com/eclipse/mosquitto/issues/2732 [#2746]: https://github.com/eclipse/mosquitto/issues/2746 [#2749]: https://github.com/eclipse/mosquitto/issues/2749 [#2760]: https://github.com/eclipse/mosquitto/issues/2760 [#2794]: https://github.com/eclipse/mosquitto/issues/2794 [#1488]: https://github.com/eclipse/mosquitto/issues/1488 ================================================ FILE: www/posts/2023/08/version-2-0-17-released.md ================================================ Version 2.0.17 of Mosquitto has been released. This is a bugfix release. Broker: - Fix `max_queued_messages 0` stopping clients from receiving messages. Closes [#2879]. - Fix `max_inflight_messages` not being set correctly. Closes [#2876]. Apps: - Fix `mosquitto_passwd -U` backup file creation. Closes [#2873]. [#2873]: https://github.com/eclipse/mosquitto/issues/2873 [#2876]: https://github.com/eclipse/mosquitto/issues/2876 [#2879]: https://github.com/eclipse/mosquitto/issues/2879 ================================================ FILE: www/posts/2023/09/version-2-0-18-released.md ================================================ Version 2.0.18 of Mosquitto has been released. This is a bugfix release. Broker: - Fix crash on subscribe under certain unlikely conditions. Closes [#2885]. Closes [#2881]. Clients: - Fix mosquitto_rr not honouring `-R`. Closes [#2893]. [#2881]: https://github.com/eclipse/mosquitto/issues/2881 [#2885]: https://github.com/eclipse/mosquitto/issues/2885 [#2893]: https://github.com/eclipse/mosquitto/issues/2893 ================================================ FILE: www/posts/2024/10/version-2-0-19-released.md ================================================ Version 2.0.19 of Mosquitto has been released. This is a security and bugfix release. # Security - Fix mismatched subscribe/unsubscribe with normal/shared topics. - Fix crash on bridge using remapped topic being sent a crafted packet. - Don't allow SUBACK with missing reason codes in client library. # Broker - Fix assert failure when loading a persistence file that contains subscriptions with no client id. - Fix local bridges being incorrectly expired when `persistent_client_expiration` is in use. - Fix use of CLOCK_BOOTTIME for getting time. Closes [#3089]. - Fix mismatched subscribe/unsubscribe with normal/shared topics. - Fix crash on bridge using remapped topic being sent a crafted packet. # Client library - Fix some error codes being converted to string as "unknown". Closes [#2579]. - Clear SSL error state to avoid spurious error reporting. Closes [#3054]. - Fix "payload format invalid" not being allowed as a PUBREC reason code. - Don't allow SUBACK with missing reason codes. # Build - Thread support is re-enabled on Windows. [#2579]: https://github.com/eclipse/mosquitto/issues/2579 [#3054]: https://github.com/eclipse/mosquitto/issues/3054 [#3089]: https://github.com/eclipse/mosquitto/issues/3089 ================================================ FILE: www/posts/2024/10/version-2-0-20-released.md ================================================ Version 2.0.20 of Mosquitto has been released. This is a bugfix release. # Broker - Fix QoS 1 / QoS 2 publish incorrectly returning "no subscribers". Closes #3128. - Open files with appropriate access on Windows. Closes #3119. - Don't allow invalid response topic values. - Fix some strict protocol compliance issues. Closes #3052. # Client library - Fix cmake build on OS X. Closes #3125. # Build - Fix build on NetBSD [#3052]: https://github.com/eclipse/mosquitto/issues/3052 [#3119]: https://github.com/eclipse/mosquitto/issues/3119 [#3125]: https://github.com/eclipse/mosquitto/issues/3125 [#3128]: https://github.com/eclipse/mosquitto/issues/3128 ================================================ FILE: www/posts/2025/03/version-2-0-21-released.md ================================================ Version 2.0.21 of Mosquitto has been released. This is a security and bugfix release. Security: - Fix leak on malicious SUBSCRIBE by authenticated client. Closes [eclipse #248]. - Further fix for CVE-2023-28366. # Broker - Fix clients sending a RESERVED packet not being quickly disconnected. Closes [#2325]. - Fix `bind_interface` producing an error when used with an interface that has an IPv6 link-local address and no other IPv6 addresses. Closes [#2696]. - Fix mismatched wrapped/unwrapped memory alloc/free in properties. Closes [#3192]. - Fix `allow_anonymous false` not being applied in local only mode. Closes [#3198]. - Add `retain_expiry_interval` option to fix expired retained message not being removed from memory if they are not subscribed to. Closes [#3221]. - Produce an error if invalid combinations of cafile/capath/certfile/keyfile are used. Closes [#1836]. Closes [#3130]. - Backport keepalive checking from develop to fix problems in current implementation. Closes [#3138]. # Client library - Fix potential deadlock in mosquitto_sub if `-W` is used. Closes [#3175]. # Apps - mosquitto_ctrl dynsec now also allows `-i` to specify a clientid as well as `-c`. This matches the documentation which states `-i`. Closes [#3219]. Client library: - Fix threads linking on Windows for static libmosquitto library Closes [#3143] # Build - Fix Windows builds not having websockets enabled. - Add tzdata to docker images # Tests - Fix 08-ssl-connect-cert-auth-expired and 08-ssl-connect-cert-auth-revoked tests when under load. Closes [#3208]. [#eclipse 248]: https://gitlab.eclipse.org/security/vulnerability-reports/-/issues/248 [#1836]: https://github.com/eclipse/mosquitto/issues/1836 [#2325]: https://github.com/eclipse/mosquitto/issues/2325 [#2696]: https://github.com/eclipse/mosquitto/issues/2696 [#3130]: https://github.com/eclipse/mosquitto/issues/3130 [#3138]: https://github.com/eclipse/mosquitto/issues/3138 [#3143]: https://github.com/eclipse/mosquitto/issues/3143 [#3175]: https://github.com/eclipse/mosquitto/issues/3175 [#3192]: https://github.com/eclipse/mosquitto/issues/3192 [#3198]: https://github.com/eclipse/mosquitto/issues/3198 [#3208]: https://github.com/eclipse/mosquitto/issues/3208 [#3219]: https://github.com/eclipse/mosquitto/issues/3219 [#3221]: https://github.com/eclipse/mosquitto/issues/3221 ================================================ FILE: www/posts/2025/07/version-2-0-22-released.md ================================================ Version 2.0.22 of Mosquitto has been released. This is a bugfix release. # Broker - Windows: Fix broker crash on startup if using `log_dest stdout` - Bridge: Fix `idle_timeout` never occurring for lazy bridges. - Fix case where `max_queued_messages = 0` was not treated as unlimited. Closes [#3244]. - Fix `--version` exit code and output. Closes [#3267]. - Fix crash on receiving a $CONTROL message over a bridge, if `per_listener_settings` is set true and the bridge is carrying out topic remapping. Closes [#3261]. - Fix incorrect reference clock being selected on startup on Linux. Closes [#3238]. - Fix reporting of client disconnections being incorrectly attributed to "out of memory". Closes [#3253]. - Fix compilation when using `WITH_OLD_KEEPALIVE`. Closes [#3250]. - Add Windows linker file for the broker to the installer. Closes [#3269]. - Fix Websockets PING not being sent on Windows. Closes [#3272]. - Fix problems with secure websockets. Closes [#1211]. - Fix crash on exit when using `WITH_EPOLL=no`. Closes [#3302]. - Fix clients being incorrectly expired when they have keepalive == `max_keepalive`. Closes [#3226], [#3286]. # Dynamic security plugin - Fix mismatch memory free when saving config which caused memory tracking to be incorrect. # Client library - Fix C++ symbols being removed when compiled with link time optimisation. Closes [#3259]. - TLS error handling was incorrectly setting a protocol error for non-TLS errors. This would cause the `mosquitto_loop_start()` thread to exit if no broker was available on the first connection attempt. This has been fixed. Closes [#3258]. - Fix linker errors on some architectures using cmake. Closes [#3167]. Tests: - Fix 08-ssl-connect-cert-auth-expired and 08-ssl-connect-cert-auth-revoked tests when running on a single CPU system. Closes [#3230]. [#1211]: https://github.com/eclipse/mosquitto/issues/1211 [#3167]: https://github.com/eclipse/mosquitto/issues/3167 [#3226]: https://github.com/eclipse/mosquitto/issues/3226 [#3230]: https://github.com/eclipse/mosquitto/issues/3230 [#3238]: https://github.com/eclipse/mosquitto/issues/3238 [#3244]: https://github.com/eclipse/mosquitto/issues/3244 [#3250]: https://github.com/eclipse/mosquitto/issues/3250 [#3253]: https://github.com/eclipse/mosquitto/issues/3253 [#3258]: https://github.com/eclipse/mosquitto/issues/3258 [#3259]: https://github.com/eclipse/mosquitto/issues/3259 [#3261]: https://github.com/eclipse/mosquitto/issues/3261 [#3267]: https://github.com/eclipse/mosquitto/issues/3267 [#3269]: https://github.com/eclipse/mosquitto/issues/3269 [#3272]: https://github.com/eclipse/mosquitto/issues/3272 [#3286]: https://github.com/eclipse/mosquitto/issues/3286 [#3302]: https://github.com/eclipse/mosquitto/issues/3302 ================================================ FILE: www/posts/2026/01/rc-2.1.0rc1-available.md ================================================ The first release candidate for Mosquitto 2.1.0 is now available for testing. If no release critical issues are reported, this will become 2.1.0 on 2026-01-26. The source and binary packages are available: * [Source](https://mosquitto.org/files/source/mosquitto-2.1.0rc1.tar.gz) * [Windows 64-bit](https://mosquitto.org/files/binary/win64/mosquitto-2.1.0rc1-install-windows-x64.exe) * [Windows 32-bit](https://mosquitto.org/files/binary/win32/mosquitto-2.1.0rc1-install-windows-x86.exe) * [Debian (amd64, armhf)](https://mosquitto.org/files/binary/debian) (note: the final release version will be available in the normal repository) * [Ubuntu (amd64)](https://mosquitto.org/files/binary/ubuntu) (note: the final release version will be available in the normal repository) * Snap (amd64): `snap refresh --edge mosquitto` or `snap install --edge mosquitto` ================================================ FILE: www/posts/2026/01/version-2-1-0-released.md ================================================ Version 2.1.0 of Mosquitto has been released. This is a feature release. # Broker ## Deprecations - The `acl_file` option is deprecated in favour of the acl-file plugin, which is the same code but moved into a plugin. The `acl_file` option will be removed in 3.0. - The `password_file` option is deprecated in favour of the password-file plugin, which is the same code but moved into a plugin. The `password_file` option will be removed in 3.0. - The `per_listener_settings` option is deprecated in favour of the new listener specific options. The `per_listener_settings` option will be removed in 3.0. ## Behaviour changes - `max_packet_size` now defaults to 2,000,000 bytes instead of the 256MB MQTT limit. If you are using payloads that will result in a packet larger than this, you need to manually set the option to a value that suits your application. - `acl_file` and `password_file` will produce an error on invalid input when reloading the config, causing the broker to quit. ## Protocol related - Add support for broker created topic aliases. Topics are allocated on a first come first serve basis. - Add support for bridges to allow remote brokers to create topic aliases when running in MQTT v5 mode. - Enforce receive maximum on MQTT v5. - Return protocol error if a client attemps to subscribe to a shared subscription and also sets no-local. - Protocol version numbers reported in the log when a client connects now match the MQTT protocol version numbers, not internal Mosquitto values. - Send DISCONNECT With session-takeover return code to MQTT v5 clients when a client connects with the same client id. Closes [#2340]. - The `allow_duplicate_messages` now defaults to `true`. - Add `accept_protocol_versions` option to allow limiting which MQTT protocol versions are allowed for a particular listener. ## TLS related - Add `--tls-keylog` option which can be used to generate a file that can be used by wireshark to decrypt TLS traffic for debugging purposes. Closes [#1818]. - Add `disable_client_cert_date_checks` option to allow expired client certificate to be considered valid. - Add `bridge_tls_use_os_certs` option to allow bridges to be easily configured to trust default CA certificates. Closes [#2473]. - Remove support for TLS v1.1 (clients only - it remains available in the broker but is now undocumented) - Use openssl provided function for x509 certificate hostname verification, rather than own function. ## Bridge related - Add `bridge_receive_maximum` option for MQTT v5.0 bridges. - Add `bridge_session_expiry_interval` option for MQTT v5.0 bridges. - Bridge reconnection backoff improvements. ## Transport related - Add the `websockets_origin` option to allow optional enforcement of origin when a connection attempts an upgrade to WebSockets. - Add built-in websockets support that doesn't use libwebsockets. This is the preferred websockets implementation. - Add support for X-Forwarded-For header for built in websockets. - Add suport for PROXY protocol v1 and v2. ## Platform specific - Increase maximum connection count on Windows from 2048 to 8192 where supported. Closes [#2122]. - Allow multiple instances of mosquitto to run as services on Windows. See README-windows.txt. - Add kqueue support. - Add support for systemd watchdog. ## General - Report on what compile time options are enabled. Closes [#2193]. - Performance: reduce memory allocations when sending packets. - Log protocol version and ciphers that a client negotiates when connecting. - Password salts are now 64 bytes long. - Add the `global_plugin` option, which gives global plugin loaded regardless of `per_listener_settings`. - Add `global_max_clients` option to allow limiting client sessions globally on the broker. - Add `global_max_connections` option to allow limiting client connections globally on the broker. - Improve idle performance. The broker now calculates when the next event of interest is, and uses that as the timeout for e.g. `epoll_wait()`. This can reduce the number of process wakeups by 100x on an idle broker. - Add more efficient keepalive check. - Add support for sending the SIGRTMIN signal to trigger log rotation. Closes [#2337]. - Add `--test-config` option which can be used to test a configuration file before trying to use it in a live broker. Closes [#2521]. - Add support for PUID/PGID environment variables for setting the user/group to drop privileges to. Closes [#2441]. - Report persistence stats when starting. - $SYS updates are now aligned to `sys_interval` seconds, meaning that if set to 10, for example, updates will be sent at times matching x0 seconds. Previously update intervals were aligned to the time the broker was started. - Add `log_dest android` for logging to the Android logd daemon. - Fix some retained topic memory not being cleared immediately after used. - Add -q option to allow logging to be disabled at the command line. - Log message if a client attempts to connect with TLS to a non-TLS listener. - Add `listener_allow_anonymous` option. - Add `listener_auto_id_prefix` option. - Allow seconds when defining `persistent_client_expiration`. ## Plugin interface - Add `mosquitto_topic_matches_sub_with_pattern()`, which can match against subscriptions with `%c` and `%u` patterns for client id / username substitution. - Add support for modifying outgoing messages using `MOSQ_EVT_MESSAGE_OUT`. - Add `mosquitto_client()` function for retrieving a client struct if that client is connected. - Add `MOSQ_ERR_PLUGIN_IGNORE` to allow plugins to register basic auth or acl check callbacks, but still act as though they are not registered. A plugin that wanted to act as a blocklist for certain usernames, but wasn't carrying out authentication could return `MOSQ_ERR_PLUGIN_IGNORE` for usernames not on its blocklist. If no other plugins were configured, the client would be authenticated. Using `MOSQ_ERR_PLUGIN_DEFER` instead would mean the clients would be denied if no other plugins were configured. - Add `mosquitto_client_port()` function for plugins. - Add `MOSQ_EVT_CONNECT`, to allow plugins to know when a client has successfully authenticated to the broker. - Add connection-state example plugin to demonstrate `MOSQ_EVT_CONNECT`. - Add `MOSQ_EVT_CLIENT_OFFLINE`, to allow plugins to know when a client with a non-zero session expiry interval has gone offline. - Plugins on non-Windows platforms now no longer make their symbols globally available, which means they are self contained. - Add support for delayed basic authentication in plugins. - Plugins using the `MOSQ_EVT_MESSAGE_WRITE` callback can now return `MOSQ_ERR_QUOTA_EXCEEDED` to have the message be rejected. MQTT v5 clients using QoS 1 or 2 will receive the quota-exceeded reason code in the corresponding PUBACK/PUBREC. - `MOSQ_EVT_TICK` is now passed to plugins when `per_listener_settings` is true. - Add `mosquitto_sub_matches_acl()`, which can match one topic filter (a subscription) against another topic filter (an ACL). - Registration of the `MOSQ_EVT_CONTROL` plugin event is now handled globally across the broker, so only a single plugin can register for a given $CONTROL topic. - Add `mosquitto_plugin_set_info()` to allow plugins to tell the broker their name and version. - Add builtin $CONTROL/broker/v1 control topic with the `listPlugins` command. This is disabled by default, but can be enabled with the `enable_control_api` option. - Plugins no longer need to define `mosquitto_plugin_cleanup()` if they do not need to do any of their own cleanup. Callbacks will be unregistered automatically. - Add `mosquitto_set_clientid()` to allow plugins to force a client id for a client. - Add `MOSQ_EVT_SUBSCRIBE` and `MOSQ_EVT_UNSUBSCRIBE` events that are called when subscribe/unsubscribes actually succeed. Allow modifying topic and qos. - Add `mosquitto_persistence_location()` for plugins to use to find a valid location for storing persistent data. - Plugins can now use the `next_s` and `next_ms` members of the tick event data struct to set a minimum interval that the broker will wait before calling the tick callback again. - MOSQ_EVT_ACL_CHECK event is now passed message properties where possible. # Plugins - Add acl-file plugin. - Add password-file plugin. - Add persist-sqlite plugin. - Add sparkplug-aware plugin. # Dynamic security plugin - Add ability to deny wildcard subscriptions for a role to the dynsec plugin. - The dynamic security plugin now only kicks clients at the start of the next network loop, to give chance for PUBACK/PUBREC to be sent. Closes [#2474]. - The dynamic security plugin now reports client connections in getClient and listClients. - The dynamic security plugin now generates an initial configuration if none is present, including a set of default roles. - The dynamic security plugin now supports `%c` and `%u` patterns for substituting client id and username respectively, in all ACLs except for subscribeLiteral and unsubscribeLiteral. - The dynamic security plugin now supports multiple ways to initialise the first configuration file. # Client library - Add `MOSQ_OPT_DISABLE_SOCKETPAIR` to allow the disabling of the socketpair feature that allows the network thread to be woken from select() by another thread when e.g. `mosquitto_publish()` is called. This reduces the number of sockets used by each client by two. - Add `on_pre_connect()` callback to allow clients to update username/password/TLS parameters before an automatic reconnection. - Callbacks no longer block other callbacks, and can be set from within a callback. Closes [#2127]. - Add support for MQTT v5 broker to client topic aliases. - Add `mosquitto_topic_matches_sub_with_pattern()`, which can match against subscriptions with `%c` and `%u` patterns for client id / username substitution. - Add `mosquitto_sub_matches_acl()`, which can match one topic filter (a subscription) against another topic filter (an ACL). - Add `mosquitto_sub_matches_acl_with_pattern()`, which can match one topic filter (a subscription) against another topic filter (an ACL), with `%c` and `%u` patterns for client id / username substitution. - Performance: reduce memory allocations when sending packets. - Reintroduce threading support for Windows. Closes [#1509]. - `mosquitto_subscribe*()` now returns `MOSQ_ERR_INVAL` if an empty string is passed as a topic filter. - `mosquitto_unsubscribe*()` now returns `MOSQ_ERR_INVAL` if an empty string is passed as a topic filter. - Add websockets support. - `mosquitto_property_read_binary/string/string_pair` will now set the name/value parameter to NULL if the binary/string is empty. This aligns the behaviour with other property functions. Closes [#2648]. - Add `mosquitto_unsubscribe2_v5_callback_set`, which provides a callback that gives access to reason codes for each of the unsubscription requests. - Add `mosquitto_property_remove`, for removing properties from property lists. - Add `on_ext_auth()` callback to allow handling MQTT v5 extended authentication. - Add `mosquitto_ext_auth_continue()` function to continue an MQTT v5 extended authentication. - Remove support for TLS v1.1. - Use openssl provided function for x509 certificate hostname verification, rather than own function. # Clients ## General - Add `-W` timeout support to Windows. - The `--insecure` option now disables all server certificate verification. - Add websockets support. - Using `-x` now sets the clients to use MQTT v5.0. - Fix parsing of IPv6 addresses in socks proxy urls. - Add `--tls-keylog` option which can be used to generate a file that can be used by wireshark to decrypt TLS traffic for debugging purposes. - Remove support for TLS v1.1. ## mosquitto_rr - Fix `-f` and `-s` options in mosquitto_rr. - Add `--latency` option to mosquitto_rr, for printing the request/response latency. - Add `--retain-handling` option. ## mosquitto_sub - Fix incorrect output formatting in mosquitto_sub when using field widths with `%x` and `%X` for printing the payload in hex. - Add float printing option to mosquitto_sub. - mosquitto_sub payload hex output can now be split by fixed field length. - Add `--message-rate` option to mosquitto_sub, for printing the count of messages received each second. - Add `--retain-handling` option. # Apps ## mosquitto_signal - Add `mosquitto_signal` for helping send signals to mosquitto on Windows. ## mosquitto_ctrl - Add interactive shell mode to mosquitto_ctrl. - Add support for `listPlugins` to mosquitto_ctrl. - Allow mosquitto_ctrl dynsec module to update passwords in files rather than having to connect to a broker. ## mosquitto_passwd - Print messages in mosquitto_passwd when adding/updating passwords. Closes [#2544]. - When creating a new file with `-c`, setting the output filename to a dash `-` will output the result to stdout. ## mosquitto_db_dump - Add `--json` output mode do mosquitto_db_dump. # Build - Increased CMake minimal required version to 3.14, which is required for the preinstalled SQLite3 find module. - Add an CMake option `WITH_LTO` to enable/disable link time optimization. - Set C99 as the explicit, rather than implicit, build standard. - cJSON is now a required dependency. - Refactored headers for easier discovery. - Support for openssl < 3.0 removed. [#1509]: https://github.com/eclipse-mosquitto/mosquitto/issues/1509 [#1818]: https://github.com/eclipse-mosquitto/mosquitto/issues/1818 [#2122]: https://github.com/eclipse-mosquitto/mosquitto/issues/2122 [#2172]: https://github.com/eclipse-mosquitto/mosquitto/issues/2172 [#2193]: https://github.com/eclipse-mosquitto/mosquitto/issues/2193 [#2337]: https://github.com/eclipse-mosquitto/mosquitto/issues/2337 [#2340]: https://github.com/eclipse-mosquitto/mosquitto/issues/2340 [#2441]: https://github.com/eclipse-mosquitto/mosquitto/issues/2441 [#2473]: https://github.com/eclipse-mosquitto/mosquitto/issues/2473 [#2474]: https://github.com/eclipse-mosquitto/mosquitto/issues/2474 [#2521]: https://github.com/eclipse-mosquitto/mosquitto/issues/2521 [#2544]: https://github.com/eclipse-mosquitto/mosquitto/issues/2544 [#2648]: https://github.com/eclipse-mosquitto/mosquitto/issues/2648 ================================================ FILE: www/posts/2026/02/version-2-1-1-released.md ================================================ Version 2.1.1 of Mosquitto has been released. This is a bugfix release. # Broker - Fix PUID/PGID checking for docker - Add `MOSQUITTO_UNSAFE_ALLOW_SYMLINKS` environment variable to allow the restrictions on reading files through symlinks to be lifted in safe environments like kubernetes. Closes [#3461]. - Fix inconsistent disconnect log message format, and add address:port. - Fix `plugin`/`global_plugin` option not allowing space characters. - Fix $SYS load values not being published initially. Closes [#3459]. - Fix `max_connections not being honoured on libwebsockets listeners. This does not affect the built-in websockets support. Closes [#3455]. - Don't enforce receive-maximum, just log a warning. This allows badly behaving clients to be fixed. Closes [#3471]. # Plugins - Fix incorrect linking of libmosquitto_common.so for the acl and password file plugins. Closes [#3460]. # Build - Fix building with WITH_TLS=no [#3455]: https://github.com/eclipse-mosquitto/mosquitto/issues/3455 [#3459]: https://github.com/eclipse-mosquitto/mosquitto/issues/3459 [#3460]: https://github.com/eclipse-mosquitto/mosquitto/issues/3460 [#3461]: https://github.com/eclipse-mosquitto/mosquitto/issues/3461 [#3471]: https://github.com/eclipse-mosquitto/mosquitto/issues/3471 ================================================ FILE: www/posts/2026/02/version-2-1-2-released.md ================================================ Version 2.1.2 of Mosquitto has been released. This is a bugfix release. # Broker: - Forbid running with `persistence true` and with a persistence plugin at the same time. Closes [#3480]. # Build: - Build fixes for OpenBSD. Closes [#3474]. - Add missing libedit to docker builds. Closes [#3476]. - Fix static/shared linking of libwebsockets under cmake. [#3474]: https://github.com/eclipse-mosquitto/mosquitto/issues/3474 [#3476]: https://github.com/eclipse-mosquitto/mosquitto/issues/3476 [#3480]: https://github.com/eclipse-mosquitto/mosquitto/issues/3480 ================================================ FILE: www/templates/book.tmpl ================================================ ## -*- coding: utf-8 -*- <%namespace name="helper" file="post_helper.tmpl"/> <%namespace name="pheader" file="post_header.tmpl"/> <%namespace name="comments" file="comments_helper.tmpl"/> <%inherit file="post.tmpl"/> <%block name="extra_head"> ${parent.extra_head()} <%block name="content">

${post.title()}

${post.text()}
<%block name="extra_js"> ================================================ FILE: www/themes/mosquitto/assets/css/bulma.css ================================================ /*! bulma.io v0.6.1 | MIT License | github.com/jgthms/bulma */ @-webkit-keyframes spinAround { from { -webkit-transform: rotate(0deg); transform: rotate(0deg); } to { -webkit-transform: rotate(359deg); transform: rotate(359deg); } } @keyframes spinAround { from { -webkit-transform: rotate(0deg); transform: rotate(0deg); } to { -webkit-transform: rotate(359deg); transform: rotate(359deg); } } /*! minireset.css v0.0.2 | MIT License | github.com/jgthms/minireset.css */ html, body, p, ol, ul, li, dl, dt, dd, blockquote, figure, fieldset, legend, textarea, pre, iframe, hr, h1, h2, h3, h4, h5, h6 { margin: 0; padding: 0; } h1, h2, h3, h4, h5, h6 { font-size: 100%; font-weight: normal; } ul { list-style: none; } button, input, select, textarea { margin: 0; } html { -webkit-box-sizing: border-box; box-sizing: border-box; } * { -webkit-box-sizing: inherit; box-sizing: inherit; } *:before, *:after { -webkit-box-sizing: inherit; box-sizing: inherit; } img, embed, object, audio, video { max-width: 100%; } iframe { border: 0; } table { border-collapse: collapse; border-spacing: 0; } td, th { padding: 0; text-align: left; } html { background-color: white; font-size: 16px; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; min-width: 300px; overflow-x: hidden; overflow-y: scroll; text-rendering: optimizeLegibility; -webkit-text-size-adjust: 100%; -moz-text-size-adjust: 100%; -ms-text-size-adjust: 100%; text-size-adjust: 100%; } article, aside, figure, footer, header, hgroup, section { display: block; } body, button, input, select, textarea { font-family: BlinkMacSystemFont, -apple-system, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", "Helvetica", "Arial", sans-serif; } code, pre { -moz-osx-font-smoothing: auto; -webkit-font-smoothing: auto; font-family: monospace; } body { color: #4a4a4a; font-size: 1rem; font-weight: 400; line-height: 1.5; } a { color: #7a91c1; cursor: pointer; text-decoration: none; } a strong { color: currentColor; } a:hover { color: #363636; } code { background-color: whitesmoke; color: #ff3860; font-size: 0.875em; font-weight: normal; padding: 0.25em 0.5em 0.25em; } hr { background-color: #dbdbdb; border: none; display: block; height: 1px; margin: 1.5rem 0; } img { height: auto; max-width: 100%; } input[type="checkbox"], input[type="radio"] { vertical-align: baseline; } small { font-size: 0.875em; } span { font-style: inherit; font-weight: inherit; } strong { color: #363636; font-weight: 700; } pre { -webkit-overflow-scrolling: touch; background-color: whitesmoke; color: #4a4a4a; font-size: 0.875em; overflow-x: auto; padding: 1.25rem 1.5rem; white-space: pre; word-wrap: normal; } pre code { background-color: transparent; color: currentColor; font-size: 1em; padding: 0; } table td, table th { text-align: left; vertical-align: top; } table th { color: #363636; } .is-clearfix:after { clear: both; content: " "; display: table; } .is-pulled-left { float: left !important; } .is-pulled-right { float: right !important; } .is-clipped { overflow: hidden !important; } .is-overlay { bottom: 0; left: 0; position: absolute; right: 0; top: 0; } .is-size-1 { font-size: 3rem !important; } .is-size-2 { font-size: 2.5rem !important; } .is-size-3 { font-size: 2rem !important; } .is-size-4 { font-size: 1.5rem !important; } .is-size-5 { font-size: 1.25rem !important; } .is-size-6 { font-size: 1rem !important; } .is-size-7 { font-size: 0.75rem !important; } @media screen and (max-width: 768px) { .is-size-1-mobile { font-size: 3rem !important; } .is-size-2-mobile { font-size: 2.5rem !important; } .is-size-3-mobile { font-size: 2rem !important; } .is-size-4-mobile { font-size: 1.5rem !important; } .is-size-5-mobile { font-size: 1.25rem !important; } .is-size-6-mobile { font-size: 1rem !important; } .is-size-7-mobile { font-size: 0.75rem !important; } } @media screen and (min-width: 769px), print { .is-size-1-tablet { font-size: 3rem !important; } .is-size-2-tablet { font-size: 2.5rem !important; } .is-size-3-tablet { font-size: 2rem !important; } .is-size-4-tablet { font-size: 1.5rem !important; } .is-size-5-tablet { font-size: 1.25rem !important; } .is-size-6-tablet { font-size: 1rem !important; } .is-size-7-tablet { font-size: 0.75rem !important; } } @media screen and (max-width: 1023px) { .is-size-1-touch { font-size: 3rem !important; } .is-size-2-touch { font-size: 2.5rem !important; } .is-size-3-touch { font-size: 2rem !important; } .is-size-4-touch { font-size: 1.5rem !important; } .is-size-5-touch { font-size: 1.25rem !important; } .is-size-6-touch { font-size: 1rem !important; } .is-size-7-touch { font-size: 0.75rem !important; } } @media screen and (min-width: 1024px) { .is-size-1-desktop { font-size: 3rem !important; } .is-size-2-desktop { font-size: 2.5rem !important; } .is-size-3-desktop { font-size: 2rem !important; } .is-size-4-desktop { font-size: 1.5rem !important; } .is-size-5-desktop { font-size: 1.25rem !important; } .is-size-6-desktop { font-size: 1rem !important; } .is-size-7-desktop { font-size: 0.75rem !important; } } @media screen and (min-width: 1216px) { .is-size-1-widescreen { font-size: 3rem !important; } .is-size-2-widescreen { font-size: 2.5rem !important; } .is-size-3-widescreen { font-size: 2rem !important; } .is-size-4-widescreen { font-size: 1.5rem !important; } .is-size-5-widescreen { font-size: 1.25rem !important; } .is-size-6-widescreen { font-size: 1rem !important; } .is-size-7-widescreen { font-size: 0.75rem !important; } } @media screen and (min-width: 1408px) { .is-size-1-fullhd { font-size: 3rem !important; } .is-size-2-fullhd { font-size: 2.5rem !important; } .is-size-3-fullhd { font-size: 2rem !important; } .is-size-4-fullhd { font-size: 1.5rem !important; } .is-size-5-fullhd { font-size: 1.25rem !important; } .is-size-6-fullhd { font-size: 1rem !important; } .is-size-7-fullhd { font-size: 0.75rem !important; } } .has-text-centered { text-align: center !important; } @media screen and (max-width: 768px) { .has-text-centered-mobile { text-align: center !important; } } @media screen and (min-width: 769px), print { .has-text-centered-tablet { text-align: center !important; } } @media screen and (min-width: 769px) and (max-width: 1023px) { .has-text-centered-tablet-only { text-align: center !important; } } @media screen and (max-width: 1023px) { .has-text-centered-touch { text-align: center !important; } } @media screen and (min-width: 1024px) { .has-text-centered-desktop { text-align: center !important; } } @media screen and (min-width: 1024px) and (max-width: 1215px) { .has-text-centered-desktop-only { text-align: center !important; } } @media screen and (min-width: 1216px) { .has-text-centered-widescreen { text-align: center !important; } } @media screen and (min-width: 1216px) and (max-width: 1407px) { .has-text-centered-widescreen-only { text-align: center !important; } } @media screen and (min-width: 1408px) { .has-text-centered-fullhd { text-align: center !important; } } .has-text-justified { text-align: justify !important; } @media screen and (max-width: 768px) { .has-text-justified-mobile { text-align: justify !important; } } @media screen and (min-width: 769px), print { .has-text-justified-tablet { text-align: justify !important; } } @media screen and (min-width: 769px) and (max-width: 1023px) { .has-text-justified-tablet-only { text-align: justify !important; } } @media screen and (max-width: 1023px) { .has-text-justified-touch { text-align: justify !important; } } @media screen and (min-width: 1024px) { .has-text-justified-desktop { text-align: justify !important; } } @media screen and (min-width: 1024px) and (max-width: 1215px) { .has-text-justified-desktop-only { text-align: justify !important; } } @media screen and (min-width: 1216px) { .has-text-justified-widescreen { text-align: justify !important; } } @media screen and (min-width: 1216px) and (max-width: 1407px) { .has-text-justified-widescreen-only { text-align: justify !important; } } @media screen and (min-width: 1408px) { .has-text-justified-fullhd { text-align: justify !important; } } .has-text-left { text-align: left !important; } @media screen and (max-width: 768px) { .has-text-left-mobile { text-align: left !important; } } @media screen and (min-width: 769px), print { .has-text-left-tablet { text-align: left !important; } } @media screen and (min-width: 769px) and (max-width: 1023px) { .has-text-left-tablet-only { text-align: left !important; } } @media screen and (max-width: 1023px) { .has-text-left-touch { text-align: left !important; } } @media screen and (min-width: 1024px) { .has-text-left-desktop { text-align: left !important; } } @media screen and (min-width: 1024px) and (max-width: 1215px) { .has-text-left-desktop-only { text-align: left !important; } } @media screen and (min-width: 1216px) { .has-text-left-widescreen { text-align: left !important; } } @media screen and (min-width: 1216px) and (max-width: 1407px) { .has-text-left-widescreen-only { text-align: left !important; } } @media screen and (min-width: 1408px) { .has-text-left-fullhd { text-align: left !important; } } .has-text-right { text-align: right !important; } @media screen and (max-width: 768px) { .has-text-right-mobile { text-align: right !important; } } @media screen and (min-width: 769px), print { .has-text-right-tablet { text-align: right !important; } } @media screen and (min-width: 769px) and (max-width: 1023px) { .has-text-right-tablet-only { text-align: right !important; } } @media screen and (max-width: 1023px) { .has-text-right-touch { text-align: right !important; } } @media screen and (min-width: 1024px) { .has-text-right-desktop { text-align: right !important; } } @media screen and (min-width: 1024px) and (max-width: 1215px) { .has-text-right-desktop-only { text-align: right !important; } } @media screen and (min-width: 1216px) { .has-text-right-widescreen { text-align: right !important; } } @media screen and (min-width: 1216px) and (max-width: 1407px) { .has-text-right-widescreen-only { text-align: right !important; } } @media screen and (min-width: 1408px) { .has-text-right-fullhd { text-align: right !important; } } .is-capitalized { text-transform: capitalize !important; } .is-lowercase { text-transform: lowercase !important; } .is-uppercase { text-transform: uppercase !important; } .has-text-white { color: white !important; } a.has-text-white:hover, a.has-text-white:focus { color: #e6e6e6 !important; } .has-text-black { color: #0a0a0a !important; } a.has-text-black:hover, a.has-text-black:focus { color: black !important; } .has-text-light { color: whitesmoke !important; } a.has-text-light:hover, a.has-text-light:focus { color: #dbdbdb !important; } .has-text-dark { color: #363636 !important; } a.has-text-dark:hover, a.has-text-dark:focus { color: #1c1c1c !important; } .has-text-primary { color: #00d1b2 !important; } a.has-text-primary:hover, a.has-text-primary:focus { color: #009e86 !important; } .has-text-link { color: #7a91c1 !important; } a.has-text-link:hover, a.has-text-link:focus { color: #205bbc !important; } .has-text-info { color: #209cee !important; } a.has-text-info:hover, a.has-text-info:focus { color: #0f81cc !important; } .has-text-success { color: #23d160 !important; } a.has-text-success:hover, a.has-text-success:focus { color: #1ca64c !important; } .has-text-warning { color: #ffdd57 !important; } a.has-text-warning:hover, a.has-text-warning:focus { color: #ffd324 !important; } .has-text-danger { color: #ff3860 !important; } a.has-text-danger:hover, a.has-text-danger:focus { color: #ff0537 !important; } .has-text-black-bis { color: #121212 !important; } .has-text-black-ter { color: #242424 !important; } .has-text-grey-darker { color: #363636 !important; } .has-text-grey-dark { color: #4a4a4a !important; } .has-text-grey { color: #7a7a7a !important; } .has-text-grey-light { color: #b5b5b5 !important; } .has-text-grey-lighter { color: #dbdbdb !important; } .has-text-white-ter { color: whitesmoke !important; } .has-text-white-bis { color: #fafafa !important; } .has-text-weight-light { font-weight: 300 !important; } .has-text-weight-normal { font-weight: 400 !important; } .has-text-weight-semibold { font-weight: 600 !important; } .has-text-weight-bold { font-weight: 700 !important; } .is-block { display: block !important; } @media screen and (max-width: 768px) { .is-block-mobile { display: block !important; } } @media screen and (min-width: 769px), print { .is-block-tablet { display: block !important; } } @media screen and (min-width: 769px) and (max-width: 1023px) { .is-block-tablet-only { display: block !important; } } @media screen and (max-width: 1023px) { .is-block-touch { display: block !important; } } @media screen and (min-width: 1024px) { .is-block-desktop { display: block !important; } } @media screen and (min-width: 1024px) and (max-width: 1215px) { .is-block-desktop-only { display: block !important; } } @media screen and (min-width: 1216px) { .is-block-widescreen { display: block !important; } } @media screen and (min-width: 1216px) and (max-width: 1407px) { .is-block-widescreen-only { display: block !important; } } @media screen and (min-width: 1408px) { .is-block-fullhd { display: block !important; } } .is-flex { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; } @media screen and (max-width: 768px) { .is-flex-mobile { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; } } @media screen and (min-width: 769px), print { .is-flex-tablet { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; } } @media screen and (min-width: 769px) and (max-width: 1023px) { .is-flex-tablet-only { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; } } @media screen and (max-width: 1023px) { .is-flex-touch { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; } } @media screen and (min-width: 1024px) { .is-flex-desktop { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; } } @media screen and (min-width: 1024px) and (max-width: 1215px) { .is-flex-desktop-only { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; } } @media screen and (min-width: 1216px) { .is-flex-widescreen { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; } } @media screen and (min-width: 1216px) and (max-width: 1407px) { .is-flex-widescreen-only { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; } } @media screen and (min-width: 1408px) { .is-flex-fullhd { display: -webkit-box !important; display: -ms-flexbox !important; display: flex !important; } } .is-inline { display: inline !important; } @media screen and (max-width: 768px) { .is-inline-mobile { display: inline !important; } } @media screen and (min-width: 769px), print { .is-inline-tablet { display: inline !important; } } @media screen and (min-width: 769px) and (max-width: 1023px) { .is-inline-tablet-only { display: inline !important; } } @media screen and (max-width: 1023px) { .is-inline-touch { display: inline !important; } } @media screen and (min-width: 1024px) { .is-inline-desktop { display: inline !important; } } @media screen and (min-width: 1024px) and (max-width: 1215px) { .is-inline-desktop-only { display: inline !important; } } @media screen and (min-width: 1216px) { .is-inline-widescreen { display: inline !important; } } @media screen and (min-width: 1216px) and (max-width: 1407px) { .is-inline-widescreen-only { display: inline !important; } } @media screen and (min-width: 1408px) { .is-inline-fullhd { display: inline !important; } } .is-inline-block { display: inline-block !important; } @media screen and (max-width: 768px) { .is-inline-block-mobile { display: inline-block !important; } } @media screen and (min-width: 769px), print { .is-inline-block-tablet { display: inline-block !important; } } @media screen and (min-width: 769px) and (max-width: 1023px) { .is-inline-block-tablet-only { display: inline-block !important; } } @media screen and (max-width: 1023px) { .is-inline-block-touch { display: inline-block !important; } } @media screen and (min-width: 1024px) { .is-inline-block-desktop { display: inline-block !important; } } @media screen and (min-width: 1024px) and (max-width: 1215px) { .is-inline-block-desktop-only { display: inline-block !important; } } @media screen and (min-width: 1216px) { .is-inline-block-widescreen { display: inline-block !important; } } @media screen and (min-width: 1216px) and (max-width: 1407px) { .is-inline-block-widescreen-only { display: inline-block !important; } } @media screen and (min-width: 1408px) { .is-inline-block-fullhd { display: inline-block !important; } } .is-inline-flex { display: -webkit-inline-box !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } @media screen and (max-width: 768px) { .is-inline-flex-mobile { display: -webkit-inline-box !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media screen and (min-width: 769px), print { .is-inline-flex-tablet { display: -webkit-inline-box !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media screen and (min-width: 769px) and (max-width: 1023px) { .is-inline-flex-tablet-only { display: -webkit-inline-box !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media screen and (max-width: 1023px) { .is-inline-flex-touch { display: -webkit-inline-box !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media screen and (min-width: 1024px) { .is-inline-flex-desktop { display: -webkit-inline-box !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media screen and (min-width: 1024px) and (max-width: 1215px) { .is-inline-flex-desktop-only { display: -webkit-inline-box !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media screen and (min-width: 1216px) { .is-inline-flex-widescreen { display: -webkit-inline-box !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media screen and (min-width: 1216px) and (max-width: 1407px) { .is-inline-flex-widescreen-only { display: -webkit-inline-box !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } @media screen and (min-width: 1408px) { .is-inline-flex-fullhd { display: -webkit-inline-box !important; display: -ms-inline-flexbox !important; display: inline-flex !important; } } .is-hidden { display: none !important; } @media screen and (max-width: 768px) { .is-hidden-mobile { display: none !important; } } @media screen and (min-width: 769px), print { .is-hidden-tablet { display: none !important; } } @media screen and (min-width: 769px) and (max-width: 1023px) { .is-hidden-tablet-only { display: none !important; } } @media screen and (max-width: 1023px) { .is-hidden-touch { display: none !important; } } @media screen and (min-width: 1024px) { .is-hidden-desktop { display: none !important; } } @media screen and (min-width: 1024px) and (max-width: 1215px) { .is-hidden-desktop-only { display: none !important; } } @media screen and (min-width: 1216px) { .is-hidden-widescreen { display: none !important; } } @media screen and (min-width: 1216px) and (max-width: 1407px) { .is-hidden-widescreen-only { display: none !important; } } @media screen and (min-width: 1408px) { .is-hidden-fullhd { display: none !important; } } .is-invisible { visibility: hidden !important; } @media screen and (max-width: 768px) { .is-invisible-mobile { visibility: hidden !important; } } @media screen and (min-width: 769px), print { .is-invisible-tablet { visibility: hidden !important; } } @media screen and (min-width: 769px) and (max-width: 1023px) { .is-invisible-tablet-only { visibility: hidden !important; } } @media screen and (max-width: 1023px) { .is-invisible-touch { visibility: hidden !important; } } @media screen and (min-width: 1024px) { .is-invisible-desktop { visibility: hidden !important; } } @media screen and (min-width: 1024px) and (max-width: 1215px) { .is-invisible-desktop-only { visibility: hidden !important; } } @media screen and (min-width: 1216px) { .is-invisible-widescreen { visibility: hidden !important; } } @media screen and (min-width: 1216px) and (max-width: 1407px) { .is-invisible-widescreen-only { visibility: hidden !important; } } @media screen and (min-width: 1408px) { .is-invisible-fullhd { visibility: hidden !important; } } .is-marginless { margin: 0 !important; } .is-paddingless { padding: 0 !important; } .is-radiusless { border-radius: 0 !important; } .is-shadowless { -webkit-box-shadow: none !important; box-shadow: none !important; } .is-unselectable { -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .box { background-color: white; border-radius: 5px; -webkit-box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); color: #4a4a4a; display: block; padding: 1.25rem; } .box:not(:last-child) { margin-bottom: 1.5rem; } a.box:hover, a.box:focus { -webkit-box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px #7a91c1; box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px #7a91c1; } a.box:active { -webkit-box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.2), 0 0 0 1px #7a91c1; box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.2), 0 0 0 1px #7a91c1; } .button { -moz-appearance: none; -webkit-appearance: none; -webkit-box-align: center; -ms-flex-align: center; align-items: center; border: 1px solid transparent; border-radius: 3px; -webkit-box-shadow: none; box-shadow: none; display: -webkit-inline-box; display: -ms-inline-flexbox; display: inline-flex; font-size: 1rem; height: 2.25em; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; line-height: 1.5; padding-bottom: calc(0.375em - 1px); padding-left: calc(0.625em - 1px); padding-right: calc(0.625em - 1px); padding-top: calc(0.375em - 1px); position: relative; vertical-align: top; -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-color: white; border-color: #dbdbdb; color: #363636; cursor: pointer; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; padding-left: 0.75em; padding-right: 0.75em; text-align: center; white-space: nowrap; } .button:focus, .button.is-focused, .button:active, .button.is-active { outline: none; } .button[disabled] { cursor: not-allowed; } .button strong { color: inherit; } .button .icon, .button .icon.is-small, .button .icon.is-medium, .button .icon.is-large { height: 1.5em; width: 1.5em; } .button .icon:first-child:not(:last-child) { margin-left: calc(-0.375em - 1px); margin-right: 0.1875em; } .button .icon:last-child:not(:first-child) { margin-left: 0.1875em; margin-right: calc(-0.375em - 1px); } .button .icon:first-child:last-child { margin-left: calc(-0.375em - 1px); margin-right: calc(-0.375em - 1px); } .button:hover, .button.is-hovered { border-color: #b5b5b5; color: #363636; } .button:focus, .button.is-focused { border-color: #7a91c1; color: #363636; } .button:focus:not(:active), .button.is-focused:not(:active) { -webkit-box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); } .button:active, .button.is-active { border-color: #4a4a4a; color: #363636; } .button.is-text { background-color: transparent; border-color: transparent; color: #4a4a4a; text-decoration: underline; } .button.is-text:hover, .button.is-text.is-hovered, .button.is-text:focus, .button.is-text.is-focused { background-color: whitesmoke; color: #363636; } .button.is-text:active, .button.is-text.is-active { background-color: #e8e8e8; color: #363636; } .button.is-text[disabled] { background-color: transparent; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .button.is-white { background-color: white; border-color: transparent; color: #0a0a0a; } .button.is-white:hover, .button.is-white.is-hovered { background-color: #f9f9f9; border-color: transparent; color: #0a0a0a; } .button.is-white:focus, .button.is-white.is-focused { border-color: transparent; color: #0a0a0a; } .button.is-white:focus:not(:active), .button.is-white.is-focused:not(:active) { -webkit-box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); } .button.is-white:active, .button.is-white.is-active { background-color: #f2f2f2; border-color: transparent; color: #0a0a0a; } .button.is-white[disabled] { background-color: white; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .button.is-white.is-inverted { background-color: #0a0a0a; color: white; } .button.is-white.is-inverted:hover { background-color: black; } .button.is-white.is-inverted[disabled] { background-color: #0a0a0a; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; color: white; } .button.is-white.is-loading:after { border-color: transparent transparent #0a0a0a #0a0a0a !important; } .button.is-white.is-outlined { background-color: transparent; border-color: white; color: white; } .button.is-white.is-outlined:hover, .button.is-white.is-outlined:focus { background-color: white; border-color: white; color: #0a0a0a; } .button.is-white.is-outlined.is-loading:after { border-color: transparent transparent white white !important; } .button.is-white.is-outlined[disabled] { background-color: transparent; border-color: white; -webkit-box-shadow: none; box-shadow: none; color: white; } .button.is-white.is-inverted.is-outlined { background-color: transparent; border-color: #0a0a0a; color: #0a0a0a; } .button.is-white.is-inverted.is-outlined:hover, .button.is-white.is-inverted.is-outlined:focus { background-color: #0a0a0a; color: white; } .button.is-white.is-inverted.is-outlined[disabled] { background-color: transparent; border-color: #0a0a0a; -webkit-box-shadow: none; box-shadow: none; color: #0a0a0a; } .button.is-black { background-color: #0a0a0a; border-color: transparent; color: white; } .button.is-black:hover, .button.is-black.is-hovered { background-color: #040404; border-color: transparent; color: white; } .button.is-black:focus, .button.is-black.is-focused { border-color: transparent; color: white; } .button.is-black:focus:not(:active), .button.is-black.is-focused:not(:active) { -webkit-box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); } .button.is-black:active, .button.is-black.is-active { background-color: black; border-color: transparent; color: white; } .button.is-black[disabled] { background-color: #0a0a0a; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .button.is-black.is-inverted { background-color: white; color: #0a0a0a; } .button.is-black.is-inverted:hover { background-color: #f2f2f2; } .button.is-black.is-inverted[disabled] { background-color: white; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; color: #0a0a0a; } .button.is-black.is-loading:after { border-color: transparent transparent white white !important; } .button.is-black.is-outlined { background-color: transparent; border-color: #0a0a0a; color: #0a0a0a; } .button.is-black.is-outlined:hover, .button.is-black.is-outlined:focus { background-color: #0a0a0a; border-color: #0a0a0a; color: white; } .button.is-black.is-outlined.is-loading:after { border-color: transparent transparent #0a0a0a #0a0a0a !important; } .button.is-black.is-outlined[disabled] { background-color: transparent; border-color: #0a0a0a; -webkit-box-shadow: none; box-shadow: none; color: #0a0a0a; } .button.is-black.is-inverted.is-outlined { background-color: transparent; border-color: white; color: white; } .button.is-black.is-inverted.is-outlined:hover, .button.is-black.is-inverted.is-outlined:focus { background-color: white; color: #0a0a0a; } .button.is-black.is-inverted.is-outlined[disabled] { background-color: transparent; border-color: white; -webkit-box-shadow: none; box-shadow: none; color: white; } .button.is-light { background-color: whitesmoke; border-color: transparent; color: #363636; } .button.is-light:hover, .button.is-light.is-hovered { background-color: #eeeeee; border-color: transparent; color: #363636; } .button.is-light:focus, .button.is-light.is-focused { border-color: transparent; color: #363636; } .button.is-light:focus:not(:active), .button.is-light.is-focused:not(:active) { -webkit-box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); } .button.is-light:active, .button.is-light.is-active { background-color: #e8e8e8; border-color: transparent; color: #363636; } .button.is-light[disabled] { background-color: whitesmoke; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .button.is-light.is-inverted { background-color: #363636; color: whitesmoke; } .button.is-light.is-inverted:hover { background-color: #292929; } .button.is-light.is-inverted[disabled] { background-color: #363636; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; color: whitesmoke; } .button.is-light.is-loading:after { border-color: transparent transparent #363636 #363636 !important; } .button.is-light.is-outlined { background-color: transparent; border-color: whitesmoke; color: whitesmoke; } .button.is-light.is-outlined:hover, .button.is-light.is-outlined:focus { background-color: whitesmoke; border-color: whitesmoke; color: #363636; } .button.is-light.is-outlined.is-loading:after { border-color: transparent transparent whitesmoke whitesmoke !important; } .button.is-light.is-outlined[disabled] { background-color: transparent; border-color: whitesmoke; -webkit-box-shadow: none; box-shadow: none; color: whitesmoke; } .button.is-light.is-inverted.is-outlined { background-color: transparent; border-color: #363636; color: #363636; } .button.is-light.is-inverted.is-outlined:hover, .button.is-light.is-inverted.is-outlined:focus { background-color: #363636; color: whitesmoke; } .button.is-light.is-inverted.is-outlined[disabled] { background-color: transparent; border-color: #363636; -webkit-box-shadow: none; box-shadow: none; color: #363636; } .button.is-dark { background-color: #363636; border-color: transparent; color: whitesmoke; } .button.is-dark:hover, .button.is-dark.is-hovered { background-color: #2f2f2f; border-color: transparent; color: whitesmoke; } .button.is-dark:focus, .button.is-dark.is-focused { border-color: transparent; color: whitesmoke; } .button.is-dark:focus:not(:active), .button.is-dark.is-focused:not(:active) { -webkit-box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); } .button.is-dark:active, .button.is-dark.is-active { background-color: #292929; border-color: transparent; color: whitesmoke; } .button.is-dark[disabled] { background-color: #363636; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .button.is-dark.is-inverted { background-color: whitesmoke; color: #363636; } .button.is-dark.is-inverted:hover { background-color: #e8e8e8; } .button.is-dark.is-inverted[disabled] { background-color: whitesmoke; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; color: #363636; } .button.is-dark.is-loading:after { border-color: transparent transparent whitesmoke whitesmoke !important; } .button.is-dark.is-outlined { background-color: transparent; border-color: #363636; color: #363636; } .button.is-dark.is-outlined:hover, .button.is-dark.is-outlined:focus { background-color: #363636; border-color: #363636; color: whitesmoke; } .button.is-dark.is-outlined.is-loading:after { border-color: transparent transparent #363636 #363636 !important; } .button.is-dark.is-outlined[disabled] { background-color: transparent; border-color: #363636; -webkit-box-shadow: none; box-shadow: none; color: #363636; } .button.is-dark.is-inverted.is-outlined { background-color: transparent; border-color: whitesmoke; color: whitesmoke; } .button.is-dark.is-inverted.is-outlined:hover, .button.is-dark.is-inverted.is-outlined:focus { background-color: whitesmoke; color: #363636; } .button.is-dark.is-inverted.is-outlined[disabled] { background-color: transparent; border-color: whitesmoke; -webkit-box-shadow: none; box-shadow: none; color: whitesmoke; } .button.is-primary { background-color: #00d1b2; border-color: transparent; color: #fff; } .button.is-primary:hover, .button.is-primary.is-hovered { background-color: #00c4a7; border-color: transparent; color: #fff; } .button.is-primary:focus, .button.is-primary.is-focused { border-color: transparent; color: #fff; } .button.is-primary:focus:not(:active), .button.is-primary.is-focused:not(:active) { -webkit-box-shadow: 0 0 0 0.125em rgba(0, 209, 178, 0.25); box-shadow: 0 0 0 0.125em rgba(0, 209, 178, 0.25); } .button.is-primary:active, .button.is-primary.is-active { background-color: #00b89c; border-color: transparent; color: #fff; } .button.is-primary[disabled] { background-color: #00d1b2; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .button.is-primary.is-inverted { background-color: #fff; color: #00d1b2; } .button.is-primary.is-inverted:hover { background-color: #f2f2f2; } .button.is-primary.is-inverted[disabled] { background-color: #fff; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; color: #00d1b2; } .button.is-primary.is-loading:after { border-color: transparent transparent #fff #fff !important; } .button.is-primary.is-outlined { background-color: transparent; border-color: #00d1b2; color: #00d1b2; } .button.is-primary.is-outlined:hover, .button.is-primary.is-outlined:focus { background-color: #00d1b2; border-color: #00d1b2; color: #fff; } .button.is-primary.is-outlined.is-loading:after { border-color: transparent transparent #00d1b2 #00d1b2 !important; } .button.is-primary.is-outlined[disabled] { background-color: transparent; border-color: #00d1b2; -webkit-box-shadow: none; box-shadow: none; color: #00d1b2; } .button.is-primary.is-inverted.is-outlined { background-color: transparent; border-color: #fff; color: #fff; } .button.is-primary.is-inverted.is-outlined:hover, .button.is-primary.is-inverted.is-outlined:focus { background-color: #fff; color: #00d1b2; } .button.is-primary.is-inverted.is-outlined[disabled] { background-color: transparent; border-color: #fff; -webkit-box-shadow: none; box-shadow: none; color: #fff; } .button.is-link { background-color: #7a91c1; border-color: transparent; color: #fff; } .button.is-link:hover, .button.is-link.is-hovered { background-color: #276cda; border-color: transparent; color: #fff; } .button.is-link:focus, .button.is-link.is-focused { border-color: transparent; color: #fff; } .button.is-link:focus:not(:active), .button.is-link.is-focused:not(:active) { -webkit-box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); } .button.is-link:active, .button.is-link.is-active { background-color: #2366d1; border-color: transparent; color: #fff; } .button.is-link[disabled] { background-color: #7a91c1; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .button.is-link.is-inverted { background-color: #fff; color: #7a91c1; } .button.is-link.is-inverted:hover { background-color: #f2f2f2; } .button.is-link.is-inverted[disabled] { background-color: #fff; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; color: #7a91c1; } .button.is-link.is-loading:after { border-color: transparent transparent #fff #fff !important; } .button.is-link.is-outlined { background-color: transparent; border-color: #7a91c1; color: #7a91c1; } .button.is-link.is-outlined:hover, .button.is-link.is-outlined:focus { background-color: #7a91c1; border-color: #7a91c1; color: #fff; } .button.is-link.is-outlined.is-loading:after { border-color: transparent transparent #7a91c1 #7a91c1 !important; } .button.is-link.is-outlined[disabled] { background-color: transparent; border-color: #7a91c1; -webkit-box-shadow: none; box-shadow: none; color: #7a91c1; } .button.is-link.is-inverted.is-outlined { background-color: transparent; border-color: #fff; color: #fff; } .button.is-link.is-inverted.is-outlined:hover, .button.is-link.is-inverted.is-outlined:focus { background-color: #fff; color: #7a91c1; } .button.is-link.is-inverted.is-outlined[disabled] { background-color: transparent; border-color: #fff; -webkit-box-shadow: none; box-shadow: none; color: #fff; } .button.is-info { background-color: #209cee; border-color: transparent; color: #fff; } .button.is-info:hover, .button.is-info.is-hovered { background-color: #1496ed; border-color: transparent; color: #fff; } .button.is-info:focus, .button.is-info.is-focused { border-color: transparent; color: #fff; } .button.is-info:focus:not(:active), .button.is-info.is-focused:not(:active) { -webkit-box-shadow: 0 0 0 0.125em rgba(32, 156, 238, 0.25); box-shadow: 0 0 0 0.125em rgba(32, 156, 238, 0.25); } .button.is-info:active, .button.is-info.is-active { background-color: #118fe4; border-color: transparent; color: #fff; } .button.is-info[disabled] { background-color: #209cee; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .button.is-info.is-inverted { background-color: #fff; color: #209cee; } .button.is-info.is-inverted:hover { background-color: #f2f2f2; } .button.is-info.is-inverted[disabled] { background-color: #fff; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; color: #209cee; } .button.is-info.is-loading:after { border-color: transparent transparent #fff #fff !important; } .button.is-info.is-outlined { background-color: transparent; border-color: #209cee; color: #209cee; } .button.is-info.is-outlined:hover, .button.is-info.is-outlined:focus { background-color: #209cee; border-color: #209cee; color: #fff; } .button.is-info.is-outlined.is-loading:after { border-color: transparent transparent #209cee #209cee !important; } .button.is-info.is-outlined[disabled] { background-color: transparent; border-color: #209cee; -webkit-box-shadow: none; box-shadow: none; color: #209cee; } .button.is-info.is-inverted.is-outlined { background-color: transparent; border-color: #fff; color: #fff; } .button.is-info.is-inverted.is-outlined:hover, .button.is-info.is-inverted.is-outlined:focus { background-color: #fff; color: #209cee; } .button.is-info.is-inverted.is-outlined[disabled] { background-color: transparent; border-color: #fff; -webkit-box-shadow: none; box-shadow: none; color: #fff; } .button.is-success { background-color: #23d160; border-color: transparent; color: #fff; } .button.is-success:hover, .button.is-success.is-hovered { background-color: #22c65b; border-color: transparent; color: #fff; } .button.is-success:focus, .button.is-success.is-focused { border-color: transparent; color: #fff; } .button.is-success:focus:not(:active), .button.is-success.is-focused:not(:active) { -webkit-box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); } .button.is-success:active, .button.is-success.is-active { background-color: #20bc56; border-color: transparent; color: #fff; } .button.is-success[disabled] { background-color: #23d160; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .button.is-success.is-inverted { background-color: #fff; color: #23d160; } .button.is-success.is-inverted:hover { background-color: #f2f2f2; } .button.is-success.is-inverted[disabled] { background-color: #fff; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; color: #23d160; } .button.is-success.is-loading:after { border-color: transparent transparent #fff #fff !important; } .button.is-success.is-outlined { background-color: transparent; border-color: #23d160; color: #23d160; } .button.is-success.is-outlined:hover, .button.is-success.is-outlined:focus { background-color: #23d160; border-color: #23d160; color: #fff; } .button.is-success.is-outlined.is-loading:after { border-color: transparent transparent #23d160 #23d160 !important; } .button.is-success.is-outlined[disabled] { background-color: transparent; border-color: #23d160; -webkit-box-shadow: none; box-shadow: none; color: #23d160; } .button.is-success.is-inverted.is-outlined { background-color: transparent; border-color: #fff; color: #fff; } .button.is-success.is-inverted.is-outlined:hover, .button.is-success.is-inverted.is-outlined:focus { background-color: #fff; color: #23d160; } .button.is-success.is-inverted.is-outlined[disabled] { background-color: transparent; border-color: #fff; -webkit-box-shadow: none; box-shadow: none; color: #fff; } .button.is-warning { background-color: #ffdd57; border-color: transparent; color: rgba(0, 0, 0, 0.7); } .button.is-warning:hover, .button.is-warning.is-hovered { background-color: #ffdb4a; border-color: transparent; color: rgba(0, 0, 0, 0.7); } .button.is-warning:focus, .button.is-warning.is-focused { border-color: transparent; color: rgba(0, 0, 0, 0.7); } .button.is-warning:focus:not(:active), .button.is-warning.is-focused:not(:active) { -webkit-box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); } .button.is-warning:active, .button.is-warning.is-active { background-color: #ffd83d; border-color: transparent; color: rgba(0, 0, 0, 0.7); } .button.is-warning[disabled] { background-color: #ffdd57; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .button.is-warning.is-inverted { background-color: rgba(0, 0, 0, 0.7); color: #ffdd57; } .button.is-warning.is-inverted:hover { background-color: rgba(0, 0, 0, 0.7); } .button.is-warning.is-inverted[disabled] { background-color: rgba(0, 0, 0, 0.7); border-color: transparent; -webkit-box-shadow: none; box-shadow: none; color: #ffdd57; } .button.is-warning.is-loading:after { border-color: transparent transparent rgba(0, 0, 0, 0.7) rgba(0, 0, 0, 0.7) !important; } .button.is-warning.is-outlined { background-color: transparent; border-color: #ffdd57; color: #ffdd57; } .button.is-warning.is-outlined:hover, .button.is-warning.is-outlined:focus { background-color: #ffdd57; border-color: #ffdd57; color: rgba(0, 0, 0, 0.7); } .button.is-warning.is-outlined.is-loading:after { border-color: transparent transparent #ffdd57 #ffdd57 !important; } .button.is-warning.is-outlined[disabled] { background-color: transparent; border-color: #ffdd57; -webkit-box-shadow: none; box-shadow: none; color: #ffdd57; } .button.is-warning.is-inverted.is-outlined { background-color: transparent; border-color: rgba(0, 0, 0, 0.7); color: rgba(0, 0, 0, 0.7); } .button.is-warning.is-inverted.is-outlined:hover, .button.is-warning.is-inverted.is-outlined:focus { background-color: rgba(0, 0, 0, 0.7); color: #ffdd57; } .button.is-warning.is-inverted.is-outlined[disabled] { background-color: transparent; border-color: rgba(0, 0, 0, 0.7); -webkit-box-shadow: none; box-shadow: none; color: rgba(0, 0, 0, 0.7); } .button.is-danger { background-color: #ff3860; border-color: transparent; color: #fff; } .button.is-danger:hover, .button.is-danger.is-hovered { background-color: #ff2b56; border-color: transparent; color: #fff; } .button.is-danger:focus, .button.is-danger.is-focused { border-color: transparent; color: #fff; } .button.is-danger:focus:not(:active), .button.is-danger.is-focused:not(:active) { -webkit-box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); } .button.is-danger:active, .button.is-danger.is-active { background-color: #ff1f4b; border-color: transparent; color: #fff; } .button.is-danger[disabled] { background-color: #ff3860; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; } .button.is-danger.is-inverted { background-color: #fff; color: #ff3860; } .button.is-danger.is-inverted:hover { background-color: #f2f2f2; } .button.is-danger.is-inverted[disabled] { background-color: #fff; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; color: #ff3860; } .button.is-danger.is-loading:after { border-color: transparent transparent #fff #fff !important; } .button.is-danger.is-outlined { background-color: transparent; border-color: #ff3860; color: #ff3860; } .button.is-danger.is-outlined:hover, .button.is-danger.is-outlined:focus { background-color: #ff3860; border-color: #ff3860; color: #fff; } .button.is-danger.is-outlined.is-loading:after { border-color: transparent transparent #ff3860 #ff3860 !important; } .button.is-danger.is-outlined[disabled] { background-color: transparent; border-color: #ff3860; -webkit-box-shadow: none; box-shadow: none; color: #ff3860; } .button.is-danger.is-inverted.is-outlined { background-color: transparent; border-color: #fff; color: #fff; } .button.is-danger.is-inverted.is-outlined:hover, .button.is-danger.is-inverted.is-outlined:focus { background-color: #fff; color: #ff3860; } .button.is-danger.is-inverted.is-outlined[disabled] { background-color: transparent; border-color: #fff; -webkit-box-shadow: none; box-shadow: none; color: #fff; } .button.is-small { border-radius: 2px; font-size: 0.75rem; } .button.is-medium { font-size: 1.25rem; } .button.is-large { font-size: 1.5rem; } .button[disabled] { background-color: white; border-color: #dbdbdb; -webkit-box-shadow: none; box-shadow: none; opacity: 0.5; } .button.is-fullwidth { display: -webkit-box; display: -ms-flexbox; display: flex; width: 100%; } .button.is-loading { color: transparent !important; pointer-events: none; } .button.is-loading:after { -webkit-animation: spinAround 500ms infinite linear; animation: spinAround 500ms infinite linear; border: 2px solid #dbdbdb; border-radius: 290486px; border-right-color: transparent; border-top-color: transparent; content: ""; display: block; height: 1em; position: relative; width: 1em; position: absolute; left: calc(50% - (1em / 2)); top: calc(50% - (1em / 2)); position: absolute !important; } .button.is-static { background-color: whitesmoke; border-color: #dbdbdb; color: #7a7a7a; -webkit-box-shadow: none; box-shadow: none; pointer-events: none; } .buttons { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; } .buttons .button { margin-bottom: 0.5rem; } .buttons .button:not(:last-child) { margin-right: 0.5rem; } .buttons:last-child { margin-bottom: -0.5rem; } .buttons:not(:last-child) { margin-bottom: 1rem; } .buttons.has-addons .button:not(:first-child) { border-bottom-left-radius: 0; border-top-left-radius: 0; } .buttons.has-addons .button:not(:last-child) { border-bottom-right-radius: 0; border-top-right-radius: 0; margin-right: -1px; } .buttons.has-addons .button:last-child { margin-right: 0; } .buttons.has-addons .button:hover, .buttons.has-addons .button.is-hovered { z-index: 2; } .buttons.has-addons .button:focus, .buttons.has-addons .button.is-focused, .buttons.has-addons .button:active, .buttons.has-addons .button.is-active, .buttons.has-addons .button.is-selected { z-index: 3; } .buttons.has-addons .button:focus:hover, .buttons.has-addons .button.is-focused:hover, .buttons.has-addons .button:active:hover, .buttons.has-addons .button.is-active:hover, .buttons.has-addons .button.is-selected:hover { z-index: 4; } .buttons.is-centered { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .buttons.is-right { -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } .container { margin: 0 auto; position: relative; } @media screen and (min-width: 1024px) { .container { max-width: 960px; width: 960px; } .container.is-fluid { margin-left: 32px; margin-right: 32px; max-width: none; width: auto; } } @media screen and (max-width: 1215px) { .container.is-widescreen { max-width: 1152px; width: auto; } } @media screen and (max-width: 1407px) { .container.is-fullhd { max-width: 1344px; width: auto; } } @media screen and (min-width: 1216px) { .container { max-width: 1152px; width: 1152px; } } @media screen and (min-width: 1408px) { .container { max-width: 1344px; width: 1344px; } } .content:not(:last-child) { margin-bottom: 1.5rem; } .content li + li { margin-top: 0.25em; } .content p:not(:last-child), .content dl:not(:last-child), .content ol:not(:last-child), .content ul:not(:last-child), .content blockquote:not(:last-child), .content pre:not(:last-child), .content table:not(:last-child) { margin-bottom: 1em; } .content h1, .content h2, .content h3, .content h4, .content h5, .content h6 { color: #363636; font-weight: 400; line-height: 1.125; } .content h1 { font-size: 2em; margin-bottom: 0.5em; } .content h1:not(:first-child) { margin-top: 1em; } .content h2 { font-size: 1.75em; margin-bottom: 0.5714em; } .content h2:not(:first-child) { margin-top: 1.1428em; } .content h3 { font-size: 1.5em; margin-bottom: 0.6666em; } .content h3:not(:first-child) { margin-top: 1.3333em; } .content h4 { font-size: 1.25em; margin-bottom: 0.8em; } .content h5 { font-size: 1.125em; margin-bottom: 0.8888em; } .content h6 { font-size: 1em; margin-bottom: 1em; } .content blockquote { background-color: whitesmoke; border-left: 5px solid #dbdbdb; padding: 1.25em 1.5em; } .content ol { list-style: decimal outside; margin-left: 2em; margin-top: 1em; } .content ul { list-style: disc outside; margin-left: 2em; margin-top: 1em; } .content ul ul { list-style-type: circle; margin-top: 0.5em; } .content ul ul ul { list-style-type: square; } .content dd { margin-left: 2em; } .content figure { margin-left: 2em; margin-right: 2em; text-align: center; } .content figure:not(:first-child) { margin-top: 2em; } .content figure:not(:last-child) { margin-bottom: 2em; } .content figure img { display: inline-block; } .content figure figcaption { font-style: italic; } .content pre { -webkit-overflow-scrolling: touch; overflow-x: auto; padding: 1.25em 1.5em; white-space: pre; word-wrap: normal; } .content sup, .content sub { font-size: 75%; } .content table { width: 100%; } .content table td, .content table th { border: 1px solid #dbdbdb; border-width: 0 0 1px; padding: 0.5em 0.75em; vertical-align: top; } .content table th { color: #363636; text-align: left; } .content table tr:hover { background-color: whitesmoke; } .content table thead td, .content table thead th { border-width: 0 0 2px; color: #363636; } .content table tfoot td, .content table tfoot th { border-width: 2px 0 0; color: #363636; } .content table tbody tr:last-child td, .content table tbody tr:last-child th { border-bottom-width: 0; } .content.is-small { font-size: 0.75rem; } .content.is-medium { font-size: 1.25rem; } .content.is-large { font-size: 1.5rem; } .input, .textarea { -moz-appearance: none; -webkit-appearance: none; -webkit-box-align: center; -ms-flex-align: center; align-items: center; border: 1px solid transparent; border-radius: 3px; -webkit-box-shadow: none; box-shadow: none; display: -webkit-inline-box; display: -ms-inline-flexbox; display: inline-flex; font-size: 1rem; height: 2.25em; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; line-height: 1.5; padding-bottom: calc(0.375em - 1px); padding-left: calc(0.625em - 1px); padding-right: calc(0.625em - 1px); padding-top: calc(0.375em - 1px); position: relative; vertical-align: top; background-color: white; border-color: #dbdbdb; color: #363636; -webkit-box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.1); box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.1); max-width: 100%; width: 100%; } .input:focus, .input.is-focused, .input:active, .input.is-active, .textarea:focus, .textarea.is-focused, .textarea:active, .textarea.is-active { outline: none; } .input[disabled], .textarea[disabled] { cursor: not-allowed; } .input::-moz-placeholder, .textarea::-moz-placeholder { color: rgba(54, 54, 54, 0.3); } .input::-webkit-input-placeholder, .textarea::-webkit-input-placeholder { color: rgba(54, 54, 54, 0.3); } .input:-moz-placeholder, .textarea:-moz-placeholder { color: rgba(54, 54, 54, 0.3); } .input:-ms-input-placeholder, .textarea:-ms-input-placeholder { color: rgba(54, 54, 54, 0.3); } .input:hover, .input.is-hovered, .textarea:hover, .textarea.is-hovered { border-color: #b5b5b5; } .input:focus, .input.is-focused, .input:active, .input.is-active, .textarea:focus, .textarea.is-focused, .textarea:active, .textarea.is-active { border-color: #7a91c1; -webkit-box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); } .input[disabled], .textarea[disabled] { background-color: whitesmoke; border-color: whitesmoke; -webkit-box-shadow: none; box-shadow: none; color: #7a7a7a; } .input[disabled]::-moz-placeholder, .textarea[disabled]::-moz-placeholder { color: rgba(122, 122, 122, 0.3); } .input[disabled]::-webkit-input-placeholder, .textarea[disabled]::-webkit-input-placeholder { color: rgba(122, 122, 122, 0.3); } .input[disabled]:-moz-placeholder, .textarea[disabled]:-moz-placeholder { color: rgba(122, 122, 122, 0.3); } .input[disabled]:-ms-input-placeholder, .textarea[disabled]:-ms-input-placeholder { color: rgba(122, 122, 122, 0.3); } .input[type="search"], .textarea[type="search"] { border-radius: 290486px; } .input[readonly], .textarea[readonly] { -webkit-box-shadow: none; box-shadow: none; } .input.is-white, .textarea.is-white { border-color: white; } .input.is-white:focus, .input.is-white.is-focused, .input.is-white:active, .input.is-white.is-active, .textarea.is-white:focus, .textarea.is-white.is-focused, .textarea.is-white:active, .textarea.is-white.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); } .input.is-black, .textarea.is-black { border-color: #0a0a0a; } .input.is-black:focus, .input.is-black.is-focused, .input.is-black:active, .input.is-black.is-active, .textarea.is-black:focus, .textarea.is-black.is-focused, .textarea.is-black:active, .textarea.is-black.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); } .input.is-light, .textarea.is-light { border-color: whitesmoke; } .input.is-light:focus, .input.is-light.is-focused, .input.is-light:active, .input.is-light.is-active, .textarea.is-light:focus, .textarea.is-light.is-focused, .textarea.is-light:active, .textarea.is-light.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); } .input.is-dark, .textarea.is-dark { border-color: #363636; } .input.is-dark:focus, .input.is-dark.is-focused, .input.is-dark:active, .input.is-dark.is-active, .textarea.is-dark:focus, .textarea.is-dark.is-focused, .textarea.is-dark:active, .textarea.is-dark.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); } .input.is-primary, .textarea.is-primary { border-color: #00d1b2; } .input.is-primary:focus, .input.is-primary.is-focused, .input.is-primary:active, .input.is-primary.is-active, .textarea.is-primary:focus, .textarea.is-primary.is-focused, .textarea.is-primary:active, .textarea.is-primary.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(0, 209, 178, 0.25); box-shadow: 0 0 0 0.125em rgba(0, 209, 178, 0.25); } .input.is-link, .textarea.is-link { border-color: #7a91c1; } .input.is-link:focus, .input.is-link.is-focused, .input.is-link:active, .input.is-link.is-active, .textarea.is-link:focus, .textarea.is-link.is-focused, .textarea.is-link:active, .textarea.is-link.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); } .input.is-info, .textarea.is-info { border-color: #209cee; } .input.is-info:focus, .input.is-info.is-focused, .input.is-info:active, .input.is-info.is-active, .textarea.is-info:focus, .textarea.is-info.is-focused, .textarea.is-info:active, .textarea.is-info.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(32, 156, 238, 0.25); box-shadow: 0 0 0 0.125em rgba(32, 156, 238, 0.25); } .input.is-success, .textarea.is-success { border-color: #23d160; } .input.is-success:focus, .input.is-success.is-focused, .input.is-success:active, .input.is-success.is-active, .textarea.is-success:focus, .textarea.is-success.is-focused, .textarea.is-success:active, .textarea.is-success.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); } .input.is-warning, .textarea.is-warning { border-color: #ffdd57; } .input.is-warning:focus, .input.is-warning.is-focused, .input.is-warning:active, .input.is-warning.is-active, .textarea.is-warning:focus, .textarea.is-warning.is-focused, .textarea.is-warning:active, .textarea.is-warning.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); } .input.is-danger, .textarea.is-danger { border-color: #ff3860; } .input.is-danger:focus, .input.is-danger.is-focused, .input.is-danger:active, .input.is-danger.is-active, .textarea.is-danger:focus, .textarea.is-danger.is-focused, .textarea.is-danger:active, .textarea.is-danger.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); } .input.is-small, .textarea.is-small { border-radius: 2px; font-size: 0.75rem; } .input.is-medium, .textarea.is-medium { font-size: 1.25rem; } .input.is-large, .textarea.is-large { font-size: 1.5rem; } .input.is-fullwidth, .textarea.is-fullwidth { display: block; width: 100%; } .input.is-inline, .textarea.is-inline { display: inline; width: auto; } .input.is-static { background-color: transparent; border-color: transparent; -webkit-box-shadow: none; box-shadow: none; padding-left: 0; padding-right: 0; } .textarea { display: block; max-width: 100%; min-width: 100%; padding: 0.625em; resize: vertical; } .textarea:not([rows]) { max-height: 600px; min-height: 120px; } .textarea[rows] { height: unset; } .textarea.has-fixed-size { resize: none; } .checkbox, .radio { cursor: pointer; display: inline-block; line-height: 1.25; position: relative; } .checkbox input, .radio input { cursor: pointer; } .checkbox:hover, .radio:hover { color: #363636; } .checkbox[disabled], .radio[disabled] { color: #7a7a7a; cursor: not-allowed; } .radio + .radio { margin-left: 0.5em; } .select { display: inline-block; max-width: 100%; position: relative; vertical-align: top; } .select:not(.is-multiple) { height: 2.25em; } .select:not(.is-multiple)::after { border: 1px solid #7a91c1; border-right: 0; border-top: 0; content: " "; display: block; height: 0.5em; pointer-events: none; position: absolute; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: center; transform-origin: center; width: 0.5em; margin-top: -0.375em; right: 1.125em; top: 50%; z-index: 4; } .select select { -moz-appearance: none; -webkit-appearance: none; -webkit-box-align: center; -ms-flex-align: center; align-items: center; border: 1px solid transparent; border-radius: 3px; -webkit-box-shadow: none; box-shadow: none; display: -webkit-inline-box; display: -ms-inline-flexbox; display: inline-flex; font-size: 1rem; height: 2.25em; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; line-height: 1.5; padding-bottom: calc(0.375em - 1px); padding-left: calc(0.625em - 1px); padding-right: calc(0.625em - 1px); padding-top: calc(0.375em - 1px); position: relative; vertical-align: top; background-color: white; border-color: #dbdbdb; color: #363636; cursor: pointer; display: block; font-size: 1em; max-width: 100%; outline: none; } .select select:focus, .select select.is-focused, .select select:active, .select select.is-active { outline: none; } .select select[disabled] { cursor: not-allowed; } .select select::-moz-placeholder { color: rgba(54, 54, 54, 0.3); } .select select::-webkit-input-placeholder { color: rgba(54, 54, 54, 0.3); } .select select:-moz-placeholder { color: rgba(54, 54, 54, 0.3); } .select select:-ms-input-placeholder { color: rgba(54, 54, 54, 0.3); } .select select:hover, .select select.is-hovered { border-color: #b5b5b5; } .select select:focus, .select select.is-focused, .select select:active, .select select.is-active { border-color: #7a91c1; -webkit-box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); } .select select[disabled] { background-color: whitesmoke; border-color: whitesmoke; -webkit-box-shadow: none; box-shadow: none; color: #7a7a7a; } .select select[disabled]::-moz-placeholder { color: rgba(122, 122, 122, 0.3); } .select select[disabled]::-webkit-input-placeholder { color: rgba(122, 122, 122, 0.3); } .select select[disabled]:-moz-placeholder { color: rgba(122, 122, 122, 0.3); } .select select[disabled]:-ms-input-placeholder { color: rgba(122, 122, 122, 0.3); } .select select::-ms-expand { display: none; } .select select[disabled]:hover { border-color: whitesmoke; } .select select:not([multiple]) { padding-right: 2.5em; } .select select[multiple] { height: unset; padding: 0; } .select select[multiple] option { padding: 0.5em 1em; } .select:hover::after { border-color: #363636; } .select.is-white select { border-color: white; } .select.is-white select:focus, .select.is-white select.is-focused, .select.is-white select:active, .select.is-white select.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); box-shadow: 0 0 0 0.125em rgba(255, 255, 255, 0.25); } .select.is-black select { border-color: #0a0a0a; } .select.is-black select:focus, .select.is-black select.is-focused, .select.is-black select:active, .select.is-black select.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); box-shadow: 0 0 0 0.125em rgba(10, 10, 10, 0.25); } .select.is-light select { border-color: whitesmoke; } .select.is-light select:focus, .select.is-light select.is-focused, .select.is-light select:active, .select.is-light select.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); box-shadow: 0 0 0 0.125em rgba(245, 245, 245, 0.25); } .select.is-dark select { border-color: #363636; } .select.is-dark select:focus, .select.is-dark select.is-focused, .select.is-dark select:active, .select.is-dark select.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); box-shadow: 0 0 0 0.125em rgba(54, 54, 54, 0.25); } .select.is-primary select { border-color: #00d1b2; } .select.is-primary select:focus, .select.is-primary select.is-focused, .select.is-primary select:active, .select.is-primary select.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(0, 209, 178, 0.25); box-shadow: 0 0 0 0.125em rgba(0, 209, 178, 0.25); } .select.is-link select { border-color: #7a91c1; } .select.is-link select:focus, .select.is-link select.is-focused, .select.is-link select:active, .select.is-link select.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); box-shadow: 0 0 0 0.125em rgba(50, 115, 220, 0.25); } .select.is-info select { border-color: #209cee; } .select.is-info select:focus, .select.is-info select.is-focused, .select.is-info select:active, .select.is-info select.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(32, 156, 238, 0.25); box-shadow: 0 0 0 0.125em rgba(32, 156, 238, 0.25); } .select.is-success select { border-color: #23d160; } .select.is-success select:focus, .select.is-success select.is-focused, .select.is-success select:active, .select.is-success select.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); box-shadow: 0 0 0 0.125em rgba(35, 209, 96, 0.25); } .select.is-warning select { border-color: #ffdd57; } .select.is-warning select:focus, .select.is-warning select.is-focused, .select.is-warning select:active, .select.is-warning select.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); box-shadow: 0 0 0 0.125em rgba(255, 221, 87, 0.25); } .select.is-danger select { border-color: #ff3860; } .select.is-danger select:focus, .select.is-danger select.is-focused, .select.is-danger select:active, .select.is-danger select.is-active { -webkit-box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); box-shadow: 0 0 0 0.125em rgba(255, 56, 96, 0.25); } .select.is-small { border-radius: 2px; font-size: 0.75rem; } .select.is-medium { font-size: 1.25rem; } .select.is-large { font-size: 1.5rem; } .select.is-disabled::after { border-color: #7a7a7a; } .select.is-fullwidth { width: 100%; } .select.is-fullwidth select { width: 100%; } .select.is-loading::after { -webkit-animation: spinAround 500ms infinite linear; animation: spinAround 500ms infinite linear; border: 2px solid #dbdbdb; border-radius: 290486px; border-right-color: transparent; border-top-color: transparent; content: ""; display: block; height: 1em; position: relative; width: 1em; margin-top: 0; position: absolute; right: 0.625em; top: 0.625em; -webkit-transform: none; transform: none; } .select.is-loading.is-small:after { font-size: 0.75rem; } .select.is-loading.is-medium:after { font-size: 1.25rem; } .select.is-loading.is-large:after { font-size: 1.5rem; } .file { -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; position: relative; } .file.is-white .file-cta { background-color: white; border-color: transparent; color: #0a0a0a; } .file.is-white:hover .file-cta, .file.is-white.is-hovered .file-cta { background-color: #f9f9f9; border-color: transparent; color: #0a0a0a; } .file.is-white:focus .file-cta, .file.is-white.is-focused .file-cta { border-color: transparent; -webkit-box-shadow: 0 0 0.5em rgba(255, 255, 255, 0.25); box-shadow: 0 0 0.5em rgba(255, 255, 255, 0.25); color: #0a0a0a; } .file.is-white:active .file-cta, .file.is-white.is-active .file-cta { background-color: #f2f2f2; border-color: transparent; color: #0a0a0a; } .file.is-black .file-cta { background-color: #0a0a0a; border-color: transparent; color: white; } .file.is-black:hover .file-cta, .file.is-black.is-hovered .file-cta { background-color: #040404; border-color: transparent; color: white; } .file.is-black:focus .file-cta, .file.is-black.is-focused .file-cta { border-color: transparent; -webkit-box-shadow: 0 0 0.5em rgba(10, 10, 10, 0.25); box-shadow: 0 0 0.5em rgba(10, 10, 10, 0.25); color: white; } .file.is-black:active .file-cta, .file.is-black.is-active .file-cta { background-color: black; border-color: transparent; color: white; } .file.is-light .file-cta { background-color: whitesmoke; border-color: transparent; color: #363636; } .file.is-light:hover .file-cta, .file.is-light.is-hovered .file-cta { background-color: #eeeeee; border-color: transparent; color: #363636; } .file.is-light:focus .file-cta, .file.is-light.is-focused .file-cta { border-color: transparent; -webkit-box-shadow: 0 0 0.5em rgba(245, 245, 245, 0.25); box-shadow: 0 0 0.5em rgba(245, 245, 245, 0.25); color: #363636; } .file.is-light:active .file-cta, .file.is-light.is-active .file-cta { background-color: #e8e8e8; border-color: transparent; color: #363636; } .file.is-dark .file-cta { background-color: #363636; border-color: transparent; color: whitesmoke; } .file.is-dark:hover .file-cta, .file.is-dark.is-hovered .file-cta { background-color: #2f2f2f; border-color: transparent; color: whitesmoke; } .file.is-dark:focus .file-cta, .file.is-dark.is-focused .file-cta { border-color: transparent; -webkit-box-shadow: 0 0 0.5em rgba(54, 54, 54, 0.25); box-shadow: 0 0 0.5em rgba(54, 54, 54, 0.25); color: whitesmoke; } .file.is-dark:active .file-cta, .file.is-dark.is-active .file-cta { background-color: #292929; border-color: transparent; color: whitesmoke; } .file.is-primary .file-cta { background-color: #00d1b2; border-color: transparent; color: #fff; } .file.is-primary:hover .file-cta, .file.is-primary.is-hovered .file-cta { background-color: #00c4a7; border-color: transparent; color: #fff; } .file.is-primary:focus .file-cta, .file.is-primary.is-focused .file-cta { border-color: transparent; -webkit-box-shadow: 0 0 0.5em rgba(0, 209, 178, 0.25); box-shadow: 0 0 0.5em rgba(0, 209, 178, 0.25); color: #fff; } .file.is-primary:active .file-cta, .file.is-primary.is-active .file-cta { background-color: #00b89c; border-color: transparent; color: #fff; } .file.is-link .file-cta { background-color: #7a91c1; border-color: transparent; color: #fff; } .file.is-link:hover .file-cta, .file.is-link.is-hovered .file-cta { background-color: #276cda; border-color: transparent; color: #fff; } .file.is-link:focus .file-cta, .file.is-link.is-focused .file-cta { border-color: transparent; -webkit-box-shadow: 0 0 0.5em rgba(50, 115, 220, 0.25); box-shadow: 0 0 0.5em rgba(50, 115, 220, 0.25); color: #fff; } .file.is-link:active .file-cta, .file.is-link.is-active .file-cta { background-color: #2366d1; border-color: transparent; color: #fff; } .file.is-info .file-cta { background-color: #209cee; border-color: transparent; color: #fff; } .file.is-info:hover .file-cta, .file.is-info.is-hovered .file-cta { background-color: #1496ed; border-color: transparent; color: #fff; } .file.is-info:focus .file-cta, .file.is-info.is-focused .file-cta { border-color: transparent; -webkit-box-shadow: 0 0 0.5em rgba(32, 156, 238, 0.25); box-shadow: 0 0 0.5em rgba(32, 156, 238, 0.25); color: #fff; } .file.is-info:active .file-cta, .file.is-info.is-active .file-cta { background-color: #118fe4; border-color: transparent; color: #fff; } .file.is-success .file-cta { background-color: #23d160; border-color: transparent; color: #fff; } .file.is-success:hover .file-cta, .file.is-success.is-hovered .file-cta { background-color: #22c65b; border-color: transparent; color: #fff; } .file.is-success:focus .file-cta, .file.is-success.is-focused .file-cta { border-color: transparent; -webkit-box-shadow: 0 0 0.5em rgba(35, 209, 96, 0.25); box-shadow: 0 0 0.5em rgba(35, 209, 96, 0.25); color: #fff; } .file.is-success:active .file-cta, .file.is-success.is-active .file-cta { background-color: #20bc56; border-color: transparent; color: #fff; } .file.is-warning .file-cta { background-color: #ffdd57; border-color: transparent; color: rgba(0, 0, 0, 0.7); } .file.is-warning:hover .file-cta, .file.is-warning.is-hovered .file-cta { background-color: #ffdb4a; border-color: transparent; color: rgba(0, 0, 0, 0.7); } .file.is-warning:focus .file-cta, .file.is-warning.is-focused .file-cta { border-color: transparent; -webkit-box-shadow: 0 0 0.5em rgba(255, 221, 87, 0.25); box-shadow: 0 0 0.5em rgba(255, 221, 87, 0.25); color: rgba(0, 0, 0, 0.7); } .file.is-warning:active .file-cta, .file.is-warning.is-active .file-cta { background-color: #ffd83d; border-color: transparent; color: rgba(0, 0, 0, 0.7); } .file.is-danger .file-cta { background-color: #ff3860; border-color: transparent; color: #fff; } .file.is-danger:hover .file-cta, .file.is-danger.is-hovered .file-cta { background-color: #ff2b56; border-color: transparent; color: #fff; } .file.is-danger:focus .file-cta, .file.is-danger.is-focused .file-cta { border-color: transparent; -webkit-box-shadow: 0 0 0.5em rgba(255, 56, 96, 0.25); box-shadow: 0 0 0.5em rgba(255, 56, 96, 0.25); color: #fff; } .file.is-danger:active .file-cta, .file.is-danger.is-active .file-cta { background-color: #ff1f4b; border-color: transparent; color: #fff; } .file.is-small { font-size: 0.75rem; } .file.is-medium { font-size: 1.25rem; } .file.is-medium .file-icon .fa { font-size: 21px; } .file.is-large { font-size: 1.5rem; } .file.is-large .file-icon .fa { font-size: 28px; } .file.has-name .file-cta { border-bottom-right-radius: 0; border-top-right-radius: 0; } .file.has-name .file-name { border-bottom-left-radius: 0; border-top-left-radius: 0; } .file.has-name.is-empty .file-cta { border-radius: 3px; } .file.has-name.is-empty .file-name { display: none; } .file.is-centered { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .file.is-right { -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } .file.is-boxed .file-label { -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; } .file.is-boxed .file-cta { -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; height: auto; padding: 1em 3em; } .file.is-boxed .file-name { border-width: 0 1px 1px; } .file.is-boxed .file-icon { height: 1.5em; width: 1.5em; } .file.is-boxed .file-icon .fa { font-size: 21px; } .file.is-boxed.is-small .file-icon .fa { font-size: 14px; } .file.is-boxed.is-medium .file-icon .fa { font-size: 28px; } .file.is-boxed.is-large .file-icon .fa { font-size: 35px; } .file.is-boxed.has-name .file-cta { border-radius: 3px 3px 0 0; } .file.is-boxed.has-name .file-name { border-radius: 0 0 3px 3px; border-width: 0 1px 1px; } .file.is-right .file-cta { border-radius: 0 3px 3px 0; } .file.is-right .file-name { border-radius: 3px 0 0 3px; border-width: 1px 0 1px 1px; -webkit-box-ordinal-group: 0; -ms-flex-order: -1; order: -1; } .file.is-fullwidth .file-label { width: 100%; } .file.is-fullwidth .file-name { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; max-width: none; } .file-label { -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -ms-flexbox; display: flex; cursor: pointer; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; overflow: hidden; position: relative; } .file-label:hover .file-cta { background-color: #eeeeee; color: #363636; } .file-label:hover .file-name { border-color: #d5d5d5; } .file-label:active .file-cta { background-color: #e8e8e8; color: #363636; } .file-label:active .file-name { border-color: #cfcfcf; } .file-input { height: 0.01em; left: 0; outline: none; position: absolute; top: 0; width: 0.01em; } .file-cta, .file-name { -moz-appearance: none; -webkit-appearance: none; -webkit-box-align: center; -ms-flex-align: center; align-items: center; border: 1px solid transparent; border-radius: 3px; -webkit-box-shadow: none; box-shadow: none; display: -webkit-inline-box; display: -ms-inline-flexbox; display: inline-flex; font-size: 1rem; height: 2.25em; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; line-height: 1.5; padding-bottom: calc(0.375em - 1px); padding-left: calc(0.625em - 1px); padding-right: calc(0.625em - 1px); padding-top: calc(0.375em - 1px); position: relative; vertical-align: top; border-color: #dbdbdb; border-radius: 3px; font-size: 1em; padding-left: 1em; padding-right: 1em; white-space: nowrap; } .file-cta:focus, .file-cta.is-focused, .file-cta:active, .file-cta.is-active, .file-name:focus, .file-name.is-focused, .file-name:active, .file-name.is-active { outline: none; } .file-cta[disabled], .file-name[disabled] { cursor: not-allowed; } .file-cta { background-color: whitesmoke; color: #4a4a4a; } .file-name { border-color: #dbdbdb; border-style: solid; border-width: 1px 1px 1px 0; display: block; max-width: 16em; overflow: hidden; text-align: left; text-overflow: ellipsis; } .file-icon { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -ms-flexbox; display: flex; height: 1em; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; margin-right: 0.5em; width: 1em; } .file-icon .fa { font-size: 14px; } .label { color: #363636; display: block; font-size: 1rem; font-weight: 700; } .label:not(:last-child) { margin-bottom: 0.5em; } .label.is-small { font-size: 0.75rem; } .label.is-medium { font-size: 1.25rem; } .label.is-large { font-size: 1.5rem; } .help { display: block; font-size: 0.75rem; margin-top: 0.25rem; } .help.is-white { color: white; } .help.is-black { color: #0a0a0a; } .help.is-light { color: whitesmoke; } .help.is-dark { color: #363636; } .help.is-primary { color: #00d1b2; } .help.is-link { color: #7a91c1; } .help.is-info { color: #209cee; } .help.is-success { color: #23d160; } .help.is-warning { color: #ffdd57; } .help.is-danger { color: #ff3860; } .field:not(:last-child) { margin-bottom: 0.75rem; } .field.has-addons { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; } .field.has-addons .control:not(:last-child) { margin-right: -1px; } .field.has-addons .control:first-child .button, .field.has-addons .control:first-child .input, .field.has-addons .control:first-child .select select { border-bottom-left-radius: 3px; border-top-left-radius: 3px; } .field.has-addons .control:last-child .button, .field.has-addons .control:last-child .input, .field.has-addons .control:last-child .select select { border-bottom-right-radius: 3px; border-top-right-radius: 3px; } .field.has-addons .control .button, .field.has-addons .control .input, .field.has-addons .control .select select { border-radius: 0; } .field.has-addons .control .button:hover, .field.has-addons .control .button.is-hovered, .field.has-addons .control .input:hover, .field.has-addons .control .input.is-hovered, .field.has-addons .control .select select:hover, .field.has-addons .control .select select.is-hovered { z-index: 2; } .field.has-addons .control .button:focus, .field.has-addons .control .button.is-focused, .field.has-addons .control .button:active, .field.has-addons .control .button.is-active, .field.has-addons .control .input:focus, .field.has-addons .control .input.is-focused, .field.has-addons .control .input:active, .field.has-addons .control .input.is-active, .field.has-addons .control .select select:focus, .field.has-addons .control .select select.is-focused, .field.has-addons .control .select select:active, .field.has-addons .control .select select.is-active { z-index: 3; } .field.has-addons .control .button:focus:hover, .field.has-addons .control .button.is-focused:hover, .field.has-addons .control .button:active:hover, .field.has-addons .control .button.is-active:hover, .field.has-addons .control .input:focus:hover, .field.has-addons .control .input.is-focused:hover, .field.has-addons .control .input:active:hover, .field.has-addons .control .input.is-active:hover, .field.has-addons .control .select select:focus:hover, .field.has-addons .control .select select.is-focused:hover, .field.has-addons .control .select select:active:hover, .field.has-addons .control .select select.is-active:hover { z-index: 4; } .field.has-addons .control.is-expanded { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; } .field.has-addons.has-addons-centered { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .field.has-addons.has-addons-right { -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } .field.has-addons.has-addons-fullwidth .control { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 0; flex-shrink: 0; } .field.is-grouped { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; } .field.is-grouped > .control { -ms-flex-negative: 0; flex-shrink: 0; } .field.is-grouped > .control:not(:last-child) { margin-bottom: 0; margin-right: 0.75rem; } .field.is-grouped > .control.is-expanded { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; } .field.is-grouped.is-grouped-centered { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .field.is-grouped.is-grouped-right { -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } .field.is-grouped.is-grouped-multiline { -ms-flex-wrap: wrap; flex-wrap: wrap; } .field.is-grouped.is-grouped-multiline > .control:last-child, .field.is-grouped.is-grouped-multiline > .control:not(:last-child) { margin-bottom: 0.75rem; } .field.is-grouped.is-grouped-multiline:last-child { margin-bottom: -0.75rem; } .field.is-grouped.is-grouped-multiline:not(:last-child) { margin-bottom: 0; } @media screen and (min-width: 769px), print { .field.is-horizontal { display: -webkit-box; display: -ms-flexbox; display: flex; } } .field-label .label { font-size: inherit; } @media screen and (max-width: 768px) { .field-label { margin-bottom: 0.5rem; } } @media screen and (min-width: 769px), print { .field-label { -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 0; flex-shrink: 0; margin-right: 1.5rem; text-align: right; } .field-label.is-small { font-size: 0.75rem; padding-top: 0.375em; } .field-label.is-normal { padding-top: 0.375em; } .field-label.is-medium { font-size: 1.25rem; padding-top: 0.375em; } .field-label.is-large { font-size: 1.5rem; padding-top: 0.375em; } } .field-body .field .field { margin-bottom: 0; } @media screen and (min-width: 769px), print { .field-body { display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 5; -ms-flex-positive: 5; flex-grow: 5; -ms-flex-negative: 1; flex-shrink: 1; } .field-body .field { margin-bottom: 0; } .field-body > .field { -ms-flex-negative: 1; flex-shrink: 1; } .field-body > .field:not(.is-narrow) { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; } .field-body > .field:not(:last-child) { margin-right: 0.75rem; } } .control { font-size: 1rem; position: relative; text-align: left; } .control.has-icon .icon { color: #dbdbdb; height: 2.25em; pointer-events: none; position: absolute; top: 0; width: 2.25em; z-index: 4; } .control.has-icon .input:focus + .icon { color: #7a7a7a; } .control.has-icon .input.is-small + .icon { font-size: 0.75rem; } .control.has-icon .input.is-medium + .icon { font-size: 1.25rem; } .control.has-icon .input.is-large + .icon { font-size: 1.5rem; } .control.has-icon:not(.has-icon-right) .icon { left: 0; } .control.has-icon:not(.has-icon-right) .input { padding-left: 2.25em; } .control.has-icon.has-icon-right .icon { right: 0; } .control.has-icon.has-icon-right .input { padding-right: 2.25em; } .control.has-icons-left .input:focus ~ .icon, .control.has-icons-left .select:focus ~ .icon, .control.has-icons-right .input:focus ~ .icon, .control.has-icons-right .select:focus ~ .icon { color: #7a7a7a; } .control.has-icons-left .input.is-small ~ .icon, .control.has-icons-left .select.is-small ~ .icon, .control.has-icons-right .input.is-small ~ .icon, .control.has-icons-right .select.is-small ~ .icon { font-size: 0.75rem; } .control.has-icons-left .input.is-medium ~ .icon, .control.has-icons-left .select.is-medium ~ .icon, .control.has-icons-right .input.is-medium ~ .icon, .control.has-icons-right .select.is-medium ~ .icon { font-size: 1.25rem; } .control.has-icons-left .input.is-large ~ .icon, .control.has-icons-left .select.is-large ~ .icon, .control.has-icons-right .input.is-large ~ .icon, .control.has-icons-right .select.is-large ~ .icon { font-size: 1.5rem; } .control.has-icons-left .icon, .control.has-icons-right .icon { color: #dbdbdb; height: 2.25em; pointer-events: none; position: absolute; top: 0; width: 2.25em; z-index: 4; } .control.has-icons-left .input, .control.has-icons-left .select select { padding-left: 2.25em; } .control.has-icons-left .icon.is-left { left: 0; } .control.has-icons-right .input, .control.has-icons-right .select select { padding-right: 2.25em; } .control.has-icons-right .icon.is-right { right: 0; } .control.is-loading::after { -webkit-animation: spinAround 500ms infinite linear; animation: spinAround 500ms infinite linear; border: 2px solid #dbdbdb; border-radius: 290486px; border-right-color: transparent; border-top-color: transparent; content: ""; display: block; height: 1em; position: relative; width: 1em; position: absolute !important; right: 0.625em; top: 0.625em; } .control.is-loading.is-small:after { font-size: 0.75rem; } .control.is-loading.is-medium:after { font-size: 1.25rem; } .control.is-loading.is-large:after { font-size: 1.5rem; } .icon { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-inline-box; display: -ms-inline-flexbox; display: inline-flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; height: 1.5rem; width: 1.5rem; } .icon.is-small { height: 1rem; width: 1rem; } .icon.is-medium { height: 2rem; width: 2rem; } .icon.is-large { height: 3rem; width: 3rem; } .image { display: block; position: relative; } .image img { display: block; height: auto; width: 100%; } .image.is-square img, .image.is-1by1 img, .image.is-4by3 img, .image.is-3by2 img, .image.is-16by9 img, .image.is-2by1 img { bottom: 0; left: 0; position: absolute; right: 0; top: 0; height: 100%; width: 100%; } .image.is-square, .image.is-1by1 { padding-top: 100%; } .image.is-4by3 { padding-top: 75%; } .image.is-3by2 { padding-top: 66.6666%; } .image.is-16by9 { padding-top: 56.25%; } .image.is-2by1 { padding-top: 50%; } .image.is-16x16 { height: 16px; width: 16px; } .image.is-24x24 { height: 24px; width: 24px; } .image.is-32x32 { height: 32px; width: 32px; } .image.is-48x48 { height: 48px; width: 48px; } .image.is-64x64 { height: 64px; width: 64px; } .image.is-96x96 { height: 96px; width: 96px; } .image.is-128x128 { height: 128px; width: 128px; } .notification { background-color: whitesmoke; border-radius: 3px; padding: 1.25rem 2.5rem 1.25rem 1.5rem; position: relative; } .notification:not(:last-child) { margin-bottom: 1.5rem; } .notification a:not(.button) { color: currentColor; text-decoration: underline; } .notification strong { color: currentColor; } .notification code, .notification pre { background: white; } .notification pre code { background: transparent; } .notification > .delete { position: absolute; right: 0.5em; top: 0.5em; } .notification .title, .notification .subtitle, .notification .content { color: currentColor; } .notification.is-white { background-color: white; color: #0a0a0a; } .notification.is-black { background-color: #0a0a0a; color: white; } .notification.is-light { background-color: whitesmoke; color: #363636; } .notification.is-dark { background-color: #363636; color: whitesmoke; } .notification.is-primary { background-color: #00d1b2; color: #fff; } .notification.is-link { background-color: #7a91c1; color: #fff; } .notification.is-info { background-color: #209cee; color: #fff; } .notification.is-success { background-color: #23d160; color: #fff; } .notification.is-warning { background-color: #ffdd57; color: rgba(0, 0, 0, 0.7); } .notification.is-danger { background-color: #ff3860; color: #fff; } .progress { -moz-appearance: none; -webkit-appearance: none; border: none; border-radius: 290486px; display: block; height: 1rem; overflow: hidden; padding: 0; width: 100%; } .progress:not(:last-child) { margin-bottom: 1.5rem; } .progress::-webkit-progress-bar { background-color: #dbdbdb; } .progress::-webkit-progress-value { background-color: #4a4a4a; } .progress::-moz-progress-bar { background-color: #4a4a4a; } .progress::-ms-fill { background-color: #4a4a4a; border: none; } .progress.is-white::-webkit-progress-value { background-color: white; } .progress.is-white::-moz-progress-bar { background-color: white; } .progress.is-white::-ms-fill { background-color: white; } .progress.is-black::-webkit-progress-value { background-color: #0a0a0a; } .progress.is-black::-moz-progress-bar { background-color: #0a0a0a; } .progress.is-black::-ms-fill { background-color: #0a0a0a; } .progress.is-light::-webkit-progress-value { background-color: whitesmoke; } .progress.is-light::-moz-progress-bar { background-color: whitesmoke; } .progress.is-light::-ms-fill { background-color: whitesmoke; } .progress.is-dark::-webkit-progress-value { background-color: #363636; } .progress.is-dark::-moz-progress-bar { background-color: #363636; } .progress.is-dark::-ms-fill { background-color: #363636; } .progress.is-primary::-webkit-progress-value { background-color: #00d1b2; } .progress.is-primary::-moz-progress-bar { background-color: #00d1b2; } .progress.is-primary::-ms-fill { background-color: #00d1b2; } .progress.is-link::-webkit-progress-value { background-color: #7a91c1; } .progress.is-link::-moz-progress-bar { background-color: #7a91c1; } .progress.is-link::-ms-fill { background-color: #7a91c1; } .progress.is-info::-webkit-progress-value { background-color: #209cee; } .progress.is-info::-moz-progress-bar { background-color: #209cee; } .progress.is-info::-ms-fill { background-color: #209cee; } .progress.is-success::-webkit-progress-value { background-color: #23d160; } .progress.is-success::-moz-progress-bar { background-color: #23d160; } .progress.is-success::-ms-fill { background-color: #23d160; } .progress.is-warning::-webkit-progress-value { background-color: #ffdd57; } .progress.is-warning::-moz-progress-bar { background-color: #ffdd57; } .progress.is-warning::-ms-fill { background-color: #ffdd57; } .progress.is-danger::-webkit-progress-value { background-color: #ff3860; } .progress.is-danger::-moz-progress-bar { background-color: #ff3860; } .progress.is-danger::-ms-fill { background-color: #ff3860; } .progress.is-small { height: 0.75rem; } .progress.is-medium { height: 1.25rem; } .progress.is-large { height: 1.5rem; } .table { background-color: white; color: #363636; margin-bottom: 1.5rem; } .table td, .table th { border: 1px solid #dbdbdb; border-width: 0 0 1px; padding: 0.5em 0.75em; vertical-align: top; } .table td.is-white, .table th.is-white { background-color: white; border-color: white; color: #0a0a0a; } .table td.is-black, .table th.is-black { background-color: #0a0a0a; border-color: #0a0a0a; color: white; } .table td.is-light, .table th.is-light { background-color: whitesmoke; border-color: whitesmoke; color: #363636; } .table td.is-dark, .table th.is-dark { background-color: #363636; border-color: #363636; color: whitesmoke; } .table td.is-primary, .table th.is-primary { background-color: #00d1b2; border-color: #00d1b2; color: #fff; } .table td.is-link, .table th.is-link { background-color: #7a91c1; border-color: #7a91c1; color: #fff; } .table td.is-info, .table th.is-info { background-color: #209cee; border-color: #209cee; color: #fff; } .table td.is-success, .table th.is-success { background-color: #23d160; border-color: #23d160; color: #fff; } .table td.is-warning, .table th.is-warning { background-color: #ffdd57; border-color: #ffdd57; color: rgba(0, 0, 0, 0.7); } .table td.is-danger, .table th.is-danger { background-color: #ff3860; border-color: #ff3860; color: #fff; } .table td.is-narrow, .table th.is-narrow { white-space: nowrap; width: 1%; } .table td.is-selected, .table th.is-selected { background-color: #00d1b2; color: #fff; } .table td.is-selected a, .table td.is-selected strong, .table th.is-selected a, .table th.is-selected strong { color: currentColor; } .table th { color: #363636; text-align: left; } .table tr.is-selected { background-color: #00d1b2; color: #fff; } .table tr.is-selected a, .table tr.is-selected strong { color: currentColor; } .table tr.is-selected td, .table tr.is-selected th { border-color: #fff; color: currentColor; } .table thead td, .table thead th { border-width: 0 0 2px; color: #363636; } .table tfoot td, .table tfoot th { border-width: 2px 0 0; color: #363636; } .table tbody tr:last-child td, .table tbody tr:last-child th { border-bottom-width: 0; } .table.is-bordered td, .table.is-bordered th { border-width: 1px; } .table.is-bordered tr:last-child td, .table.is-bordered tr:last-child th { border-bottom-width: 1px; } .table.is-fullwidth { width: 100%; } .table.is-hoverable tbody tr:not(.is-selected):hover { background-color: #fafafa; } .table.is-hoverable.is-striped tbody tr:not(.is-selected):hover { background-color: whitesmoke; } .table.is-narrow td, .table.is-narrow th { padding: 0.25em 0.5em; } .table.is-striped tbody tr:not(.is-selected):nth-child(even) { background-color: #fafafa; } .tags { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; } .tags .tag { margin-bottom: 0.5rem; } .tags .tag:not(:last-child) { margin-right: 0.5rem; } .tags:last-child { margin-bottom: -0.5rem; } .tags:not(:last-child) { margin-bottom: 1rem; } .tags.has-addons .tag { margin-right: 0; } .tags.has-addons .tag:not(:first-child) { border-bottom-left-radius: 0; border-top-left-radius: 0; } .tags.has-addons .tag:not(:last-child) { border-bottom-right-radius: 0; border-top-right-radius: 0; } .tags.is-centered { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .tags.is-centered .tag { margin-right: 0.25rem; margin-left: 0.25rem; } .tags.is-right { -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } .tags.is-right .tag:not(:first-child) { margin-left: 0.5rem; } .tags.is-right .tag:not(:last-child) { margin-right: 0; } .tag:not(body) { -webkit-box-align: center; -ms-flex-align: center; align-items: center; background-color: whitesmoke; border-radius: 3px; color: #4a4a4a; display: -webkit-inline-box; display: -ms-inline-flexbox; display: inline-flex; font-size: 0.75rem; height: 2em; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; line-height: 1.5; padding-left: 0.75em; padding-right: 0.75em; white-space: nowrap; } .tag:not(body) .delete { margin-left: 0.25em; margin-right: -0.375em; } .tag:not(body).is-white { background-color: white; color: #0a0a0a; } .tag:not(body).is-black { background-color: #0a0a0a; color: white; } .tag:not(body).is-light { background-color: whitesmoke; color: #363636; } .tag:not(body).is-dark { background-color: #363636; color: whitesmoke; } .tag:not(body).is-primary { background-color: #00d1b2; color: #fff; } .tag:not(body).is-link { background-color: #7a91c1; color: #fff; } .tag:not(body).is-info { background-color: #209cee; color: #fff; } .tag:not(body).is-success { background-color: #23d160; color: #fff; } .tag:not(body).is-warning { background-color: #ffdd57; color: rgba(0, 0, 0, 0.7); } .tag:not(body).is-danger { background-color: #ff3860; color: #fff; } .tag:not(body).is-medium { font-size: 1rem; } .tag:not(body).is-large { font-size: 1.25rem; } .tag:not(body) .icon:first-child:not(:last-child) { margin-left: -0.375em; margin-right: 0.1875em; } .tag:not(body) .icon:last-child:not(:first-child) { margin-left: 0.1875em; margin-right: -0.375em; } .tag:not(body) .icon:first-child:last-child { margin-left: -0.375em; margin-right: -0.375em; } .tag:not(body).is-delete { margin-left: 1px; padding: 0; position: relative; width: 2em; } .tag:not(body).is-delete:before, .tag:not(body).is-delete:after { background-color: currentColor; content: ""; display: block; left: 50%; position: absolute; top: 50%; -webkit-transform: translateX(-50%) translateY(-50%) rotate(45deg); transform: translateX(-50%) translateY(-50%) rotate(45deg); -webkit-transform-origin: center center; transform-origin: center center; } .tag:not(body).is-delete:before { height: 1px; width: 50%; } .tag:not(body).is-delete:after { height: 50%; width: 1px; } .tag:not(body).is-delete:hover, .tag:not(body).is-delete:focus { background-color: #e8e8e8; } .tag:not(body).is-delete:active { background-color: #dbdbdb; } .tag:not(body).is-rounded { border-radius: 290486px; } a.tag:hover { text-decoration: underline; } .title, .subtitle { word-break: break-word; } .title:not(:last-child), .subtitle:not(:last-child) { margin-bottom: 1.5rem; } .title em, .title span, .subtitle em, .subtitle span { font-weight: inherit; } .title .tag, .subtitle .tag { vertical-align: middle; } .title { color: #363636; font-size: 2rem; font-weight: 600; line-height: 1.125; } .title strong { color: inherit; font-weight: inherit; } .title + .highlight { margin-top: -0.75rem; } .title:not(.is-spaced) + .subtitle { margin-top: -1.5rem; } .title.is-1 { font-size: 3rem; } .title.is-2 { font-size: 2.5rem; } .title.is-3 { font-size: 2rem; } .title.is-4 { font-size: 1.5rem; } .title.is-5 { font-size: 1.25rem; } .title.is-6 { font-size: 1rem; } .title.is-7 { font-size: 0.75rem; } .subtitle { color: #4a4a4a; font-size: 1.25rem; font-weight: 400; line-height: 1.25; } .subtitle strong { color: #363636; font-weight: 600; } .subtitle:not(.is-spaced) + .title { margin-top: -1.5rem; } .subtitle.is-1 { font-size: 3rem; } .subtitle.is-2 { font-size: 2.5rem; } .subtitle.is-3 { font-size: 2rem; } .subtitle.is-4 { font-size: 1.5rem; } .subtitle.is-5 { font-size: 1.25rem; } .subtitle.is-6 { font-size: 1rem; } .subtitle.is-7 { font-size: 0.75rem; } .block:not(:last-child) { margin-bottom: 1.5rem; } .delete { -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -moz-appearance: none; -webkit-appearance: none; background-color: rgba(10, 10, 10, 0.2); border: none; border-radius: 290486px; cursor: pointer; display: inline-block; -webkit-box-flex: 0; -ms-flex-positive: 0; flex-grow: 0; -ms-flex-negative: 0; flex-shrink: 0; font-size: 0; height: 20px; max-height: 20px; max-width: 20px; min-height: 20px; min-width: 20px; outline: none; position: relative; vertical-align: top; width: 20px; } .delete:before, .delete:after { background-color: white; content: ""; display: block; left: 50%; position: absolute; top: 50%; -webkit-transform: translateX(-50%) translateY(-50%) rotate(45deg); transform: translateX(-50%) translateY(-50%) rotate(45deg); -webkit-transform-origin: center center; transform-origin: center center; } .delete:before { height: 2px; width: 50%; } .delete:after { height: 50%; width: 2px; } .delete:hover, .delete:focus { background-color: rgba(10, 10, 10, 0.3); } .delete:active { background-color: rgba(10, 10, 10, 0.4); } .delete.is-small { height: 16px; max-height: 16px; max-width: 16px; min-height: 16px; min-width: 16px; width: 16px; } .delete.is-medium { height: 24px; max-height: 24px; max-width: 24px; min-height: 24px; min-width: 24px; width: 24px; } .delete.is-large { height: 32px; max-height: 32px; max-width: 32px; min-height: 32px; min-width: 32px; width: 32px; } .heading { display: block; font-size: 11px; letter-spacing: 1px; margin-bottom: 5px; text-transform: uppercase; } .highlight { font-weight: 400; max-width: 100%; overflow: hidden; padding: 0; } .highlight:not(:last-child) { margin-bottom: 1.5rem; } .highlight pre { overflow: auto; max-width: 100%; } .loader { -webkit-animation: spinAround 500ms infinite linear; animation: spinAround 500ms infinite linear; border: 2px solid #dbdbdb; border-radius: 290486px; border-right-color: transparent; border-top-color: transparent; content: ""; display: block; height: 1em; position: relative; width: 1em; } .number { -webkit-box-align: center; -ms-flex-align: center; align-items: center; background-color: whitesmoke; border-radius: 290486px; display: -webkit-inline-box; display: -ms-inline-flexbox; display: inline-flex; font-size: 1.25rem; height: 2em; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; margin-right: 1.5rem; min-width: 2.5em; padding: 0.25rem 0.5rem; text-align: center; vertical-align: top; } .breadcrumb { -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -ms-flexbox; display: flex; font-size: 1rem; overflow: hidden; overflow-x: auto; white-space: nowrap; } .breadcrumb:not(:last-child) { margin-bottom: 1.5rem; } .breadcrumb a { -webkit-box-align: center; -ms-flex-align: center; align-items: center; color: #7a91c1; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; padding: 0.5em 0.75em; } .breadcrumb a:hover { color: #363636; } .breadcrumb li { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -ms-flexbox; display: flex; } .breadcrumb li:first-child a { padding-left: 0; } .breadcrumb li.is-active a { color: #363636; cursor: default; pointer-events: none; } .breadcrumb li + li::before { color: #4a4a4a; content: "\0002f"; } .breadcrumb ul, .breadcrumb ol { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 0; flex-shrink: 0; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; } .breadcrumb .icon:first-child { margin-right: 0.5em; } .breadcrumb .icon:last-child { margin-left: 0.5em; } .breadcrumb.is-centered ol, .breadcrumb.is-centered ul { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .breadcrumb.is-right ol, .breadcrumb.is-right ul { -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } .breadcrumb.is-small { font-size: 0.75rem; } .breadcrumb.is-medium { font-size: 1.25rem; } .breadcrumb.is-large { font-size: 1.5rem; } .breadcrumb.has-arrow-separator li + li::before { content: "\02192"; } .breadcrumb.has-bullet-separator li + li::before { content: "\02022"; } .breadcrumb.has-dot-separator li + li::before { content: "\000b7"; } .breadcrumb.has-succeeds-separator li + li::before { content: "\0227B"; } .card { background-color: white; -webkit-box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); color: #4a4a4a; max-width: 100%; position: relative; } .card-header { -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; -webkit-box-shadow: 0 1px 2px rgba(10, 10, 10, 0.1); box-shadow: 0 1px 2px rgba(10, 10, 10, 0.1); display: -webkit-box; display: -ms-flexbox; display: flex; } .card-header-title { -webkit-box-align: center; -ms-flex-align: center; align-items: center; color: #363636; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; font-weight: 700; padding: 0.75rem; } .card-header-title.is-centered { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .card-header-icon { -webkit-box-align: center; -ms-flex-align: center; align-items: center; cursor: pointer; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; padding: 0.75rem; } .card-image { display: block; position: relative; } .card-content { padding: 1.5rem; } .card-footer { border-top: 1px solid #dbdbdb; -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -ms-flexbox; display: flex; } .card-footer-item { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 0; flex-shrink: 0; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; padding: 0.75rem; } .card-footer-item:not(:last-child) { border-right: 1px solid #dbdbdb; } .card .media:not(:last-child) { margin-bottom: 0.75rem; } .dropdown { display: -webkit-inline-box; display: -ms-inline-flexbox; display: inline-flex; position: relative; vertical-align: top; } .dropdown.is-active .dropdown-menu, .dropdown.is-hoverable:hover .dropdown-menu { display: block; } .dropdown.is-right .dropdown-menu { left: auto; right: 0; } .dropdown.is-up .dropdown-menu { bottom: 100%; padding-bottom: 4px; padding-top: unset; top: auto; } .dropdown-menu { display: none; left: 0; min-width: 12rem; padding-top: 4px; position: absolute; top: 100%; z-index: 20; } .dropdown-content { background-color: white; border-radius: 3px; -webkit-box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); padding-bottom: 0.5rem; padding-top: 0.5rem; } .dropdown-item { color: #4a4a4a; display: block; font-size: 0.875rem; line-height: 1.5; padding: 0.375rem 1rem; position: relative; } a.dropdown-item { padding-right: 3rem; white-space: nowrap; } a.dropdown-item:hover { background-color: whitesmoke; color: #0a0a0a; } a.dropdown-item.is-active { background-color: #7a91c1; color: #fff; } .dropdown-divider { background-color: #dbdbdb; border: none; display: block; height: 1px; margin: 0.5rem 0; } .level { -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; } .level:not(:last-child) { margin-bottom: 1.5rem; } .level code { border-radius: 3px; } .level img { display: inline-block; vertical-align: top; } .level.is-mobile { display: -webkit-box; display: -ms-flexbox; display: flex; } .level.is-mobile .level-left, .level.is-mobile .level-right { display: -webkit-box; display: -ms-flexbox; display: flex; } .level.is-mobile .level-left + .level-right { margin-top: 0; } .level.is-mobile .level-item { margin-right: 0.75rem; } .level.is-mobile .level-item:not(:last-child) { margin-bottom: 0; } .level.is-mobile .level-item:not(.is-narrow) { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; } @media screen and (min-width: 769px), print { .level { display: -webkit-box; display: -ms-flexbox; display: flex; } .level > .level-item:not(.is-narrow) { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; } } .level-item { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-preferred-size: auto; flex-basis: auto; -webkit-box-flex: 0; -ms-flex-positive: 0; flex-grow: 0; -ms-flex-negative: 0; flex-shrink: 0; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .level-item .title, .level-item .subtitle { margin-bottom: 0; } @media screen and (max-width: 768px) { .level-item:not(:last-child) { margin-bottom: 0.75rem; } } .level-left, .level-right { -ms-flex-preferred-size: auto; flex-basis: auto; -webkit-box-flex: 0; -ms-flex-positive: 0; flex-grow: 0; -ms-flex-negative: 0; flex-shrink: 0; } .level-left .level-item.is-flexible, .level-right .level-item.is-flexible { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; } @media screen and (min-width: 769px), print { .level-left .level-item:not(:last-child), .level-right .level-item:not(:last-child) { margin-right: 0.75rem; } } .level-left { -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; } @media screen and (max-width: 768px) { .level-left + .level-right { margin-top: 1.5rem; } } @media screen and (min-width: 769px), print { .level-left { display: -webkit-box; display: -ms-flexbox; display: flex; } } .level-right { -webkit-box-align: center; -ms-flex-align: center; align-items: center; -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } @media screen and (min-width: 769px), print { .level-right { display: -webkit-box; display: -ms-flexbox; display: flex; } } .media { -webkit-box-align: start; -ms-flex-align: start; align-items: flex-start; display: -webkit-box; display: -ms-flexbox; display: flex; text-align: left; } .media .content:not(:last-child) { margin-bottom: 0.75rem; } .media .media { border-top: 1px solid rgba(219, 219, 219, 0.5); display: -webkit-box; display: -ms-flexbox; display: flex; padding-top: 0.75rem; } .media .media .content:not(:last-child), .media .media .control:not(:last-child) { margin-bottom: 0.5rem; } .media .media .media { padding-top: 0.5rem; } .media .media .media + .media { margin-top: 0.5rem; } .media + .media { border-top: 1px solid rgba(219, 219, 219, 0.5); margin-top: 1rem; padding-top: 1rem; } .media.is-large + .media { margin-top: 1.5rem; padding-top: 1.5rem; } .media-left, .media-right { -ms-flex-preferred-size: auto; flex-basis: auto; -webkit-box-flex: 0; -ms-flex-positive: 0; flex-grow: 0; -ms-flex-negative: 0; flex-shrink: 0; } .media-left { margin-right: 1rem; } .media-right { margin-left: 1rem; } .media-content { -ms-flex-preferred-size: auto; flex-basis: auto; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; text-align: left; } .menu { font-size: 1rem; } .menu.is-small { font-size: 0.75rem; } .menu.is-medium { font-size: 1.25rem; } .menu.is-large { font-size: 1.5rem; } .menu-list { line-height: 1.25; } .menu-list a { border-radius: 2px; color: #4a4a4a; display: block; padding: 0.5em 0.75em; } .menu-list a:hover { background-color: whitesmoke; color: #363636; } .menu-list a.is-active { background-color: #7a91c1; color: #fff; } .menu-list li ul { border-left: 1px solid #dbdbdb; margin: 0.75em; padding-left: 0.75em; } .menu-label { color: #7a7a7a; font-size: 0.75em; letter-spacing: 0.1em; text-transform: uppercase; } .menu-label:not(:first-child) { margin-top: 1em; } .menu-label:not(:last-child) { margin-bottom: 1em; } .message { background-color: whitesmoke; border-radius: 3px; font-size: 1rem; } .message:not(:last-child) { margin-bottom: 1.5rem; } .message strong { color: currentColor; } .message a:not(.button):not(.tag) { color: currentColor; text-decoration: underline; } .message.is-small { font-size: 0.75rem; } .message.is-medium { font-size: 1.25rem; } .message.is-large { font-size: 1.5rem; } .message.is-white { background-color: white; } .message.is-white .message-header { background-color: white; color: #0a0a0a; } .message.is-white .message-body { border-color: white; color: #4d4d4d; } .message.is-black { background-color: #fafafa; } .message.is-black .message-header { background-color: #0a0a0a; color: white; } .message.is-black .message-body { border-color: #0a0a0a; color: #090909; } .message.is-light { background-color: #fafafa; } .message.is-light .message-header { background-color: whitesmoke; color: #363636; } .message.is-light .message-body { border-color: whitesmoke; color: #505050; } .message.is-dark { background-color: #fafafa; } .message.is-dark .message-header { background-color: #363636; color: whitesmoke; } .message.is-dark .message-body { border-color: #363636; color: #2a2a2a; } .message.is-primary { background-color: #f5fffd; } .message.is-primary .message-header { background-color: #00d1b2; color: #fff; } .message.is-primary .message-body { border-color: #00d1b2; color: #021310; } .message.is-link { background-color: #f6f9fe; } .message.is-link .message-header { background-color: #7a91c1; color: #fff; } .message.is-link .message-body { border-color: #7a91c1; color: #22509a; } .message.is-info { background-color: #f6fbfe; } .message.is-info .message-header { background-color: #209cee; color: #fff; } .message.is-info .message-body { border-color: #209cee; color: #12537e; } .message.is-success { background-color: #f6fef9; } .message.is-success .message-header { background-color: #23d160; color: #fff; } .message.is-success .message-body { border-color: #23d160; color: #0e301a; } .message.is-warning { background-color: #fffdf5; } .message.is-warning .message-header { background-color: #ffdd57; color: rgba(0, 0, 0, 0.7); } .message.is-warning .message-body { border-color: #ffdd57; color: #3b3108; } .message.is-danger { background-color: #fff5f7; } .message.is-danger .message-header { background-color: #ff3860; color: #fff; } .message.is-danger .message-body { border-color: #ff3860; color: #cd0930; } .message-header { -webkit-box-align: center; -ms-flex-align: center; align-items: center; background-color: #4a4a4a; border-radius: 3px 3px 0 0; color: #fff; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; line-height: 1.25; padding: 0.5em 0.75em; position: relative; } .message-header .delete { -webkit-box-flex: 0; -ms-flex-positive: 0; flex-grow: 0; -ms-flex-negative: 0; flex-shrink: 0; margin-left: 0.75em; } .message-header + .message-body { border-top-left-radius: 0; border-top-right-radius: 0; border-top: none; } .message-body { border: 1px solid #dbdbdb; border-radius: 3px; color: #4a4a4a; padding: 1em 1.25em; } .message-body code, .message-body pre { background-color: white; } .message-body pre code { background-color: transparent; } .modal { bottom: 0; left: 0; position: absolute; right: 0; top: 0; -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: none; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; overflow: hidden; position: fixed; z-index: 20; } .modal.is-active { display: -webkit-box; display: -ms-flexbox; display: flex; } .modal-background { bottom: 0; left: 0; position: absolute; right: 0; top: 0; background-color: rgba(10, 10, 10, 0.86); } .modal-content, .modal-card { margin: 0 20px; max-height: calc(100vh - 160px); overflow: auto; position: relative; width: 100%; } @media screen and (min-width: 769px), print { .modal-content, .modal-card { margin: 0 auto; max-height: calc(100vh - 40px); width: 640px; } } .modal-close { -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -moz-appearance: none; -webkit-appearance: none; background-color: rgba(10, 10, 10, 0.2); border: none; border-radius: 290486px; cursor: pointer; display: inline-block; -webkit-box-flex: 0; -ms-flex-positive: 0; flex-grow: 0; -ms-flex-negative: 0; flex-shrink: 0; font-size: 0; height: 20px; max-height: 20px; max-width: 20px; min-height: 20px; min-width: 20px; outline: none; position: relative; vertical-align: top; width: 20px; background: none; height: 40px; position: fixed; right: 20px; top: 20px; width: 40px; } .modal-close:before, .modal-close:after { background-color: white; content: ""; display: block; left: 50%; position: absolute; top: 50%; -webkit-transform: translateX(-50%) translateY(-50%) rotate(45deg); transform: translateX(-50%) translateY(-50%) rotate(45deg); -webkit-transform-origin: center center; transform-origin: center center; } .modal-close:before { height: 2px; width: 50%; } .modal-close:after { height: 50%; width: 2px; } .modal-close:hover, .modal-close:focus { background-color: rgba(10, 10, 10, 0.3); } .modal-close:active { background-color: rgba(10, 10, 10, 0.4); } .modal-close.is-small { height: 16px; max-height: 16px; max-width: 16px; min-height: 16px; min-width: 16px; width: 16px; } .modal-close.is-medium { height: 24px; max-height: 24px; max-width: 24px; min-height: 24px; min-width: 24px; width: 24px; } .modal-close.is-large { height: 32px; max-height: 32px; max-width: 32px; min-height: 32px; min-width: 32px; width: 32px; } .modal-card { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; max-height: calc(100vh - 40px); overflow: hidden; } .modal-card-head, .modal-card-foot { -webkit-box-align: center; -ms-flex-align: center; align-items: center; background-color: whitesmoke; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-negative: 0; flex-shrink: 0; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; padding: 20px; position: relative; } .modal-card-head { border-bottom: 1px solid #dbdbdb; border-top-left-radius: 5px; border-top-right-radius: 5px; } .modal-card-title { color: #363636; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 0; flex-shrink: 0; font-size: 1.5rem; line-height: 1; } .modal-card-foot { border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; border-top: 1px solid #dbdbdb; } .modal-card-foot .button:not(:last-child) { margin-right: 10px; } .modal-card-body { -webkit-overflow-scrolling: touch; background-color: white; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; overflow: auto; padding: 20px; } .navbar { background-color: white; min-height: 3.25rem; position: relative; } .navbar.is-white { background-color: white; color: #0a0a0a; } .navbar.is-white .navbar-brand > .navbar-item, .navbar.is-white .navbar-brand .navbar-link { color: #0a0a0a; } .navbar.is-white .navbar-brand > a.navbar-item:hover, .navbar.is-white .navbar-brand > a.navbar-item.is-active, .navbar.is-white .navbar-brand .navbar-link:hover, .navbar.is-white .navbar-brand .navbar-link.is-active { background-color: #f2f2f2; color: #0a0a0a; } .navbar.is-white .navbar-brand .navbar-link::after { border-color: #0a0a0a; } @media screen and (min-width: 1024px) { .navbar.is-white .navbar-start > .navbar-item, .navbar.is-white .navbar-start .navbar-link, .navbar.is-white .navbar-end > .navbar-item, .navbar.is-white .navbar-end .navbar-link { color: #0a0a0a; } .navbar.is-white .navbar-start > a.navbar-item:hover, .navbar.is-white .navbar-start > a.navbar-item.is-active, .navbar.is-white .navbar-start .navbar-link:hover, .navbar.is-white .navbar-start .navbar-link.is-active, .navbar.is-white .navbar-end > a.navbar-item:hover, .navbar.is-white .navbar-end > a.navbar-item.is-active, .navbar.is-white .navbar-end .navbar-link:hover, .navbar.is-white .navbar-end .navbar-link.is-active { background-color: #f2f2f2; color: #0a0a0a; } .navbar.is-white .navbar-start .navbar-link::after, .navbar.is-white .navbar-end .navbar-link::after { border-color: #0a0a0a; } .navbar.is-white .navbar-item.has-dropdown:hover .navbar-link, .navbar.is-white .navbar-item.has-dropdown.is-active .navbar-link { background-color: #f2f2f2; color: #0a0a0a; } .navbar.is-white .navbar-dropdown a.navbar-item.is-active { background-color: white; color: #0a0a0a; } } .navbar.is-black { background-color: #0a0a0a; color: white; } .navbar.is-black .navbar-brand > .navbar-item, .navbar.is-black .navbar-brand .navbar-link { color: white; } .navbar.is-black .navbar-brand > a.navbar-item:hover, .navbar.is-black .navbar-brand > a.navbar-item.is-active, .navbar.is-black .navbar-brand .navbar-link:hover, .navbar.is-black .navbar-brand .navbar-link.is-active { background-color: black; color: white; } .navbar.is-black .navbar-brand .navbar-link::after { border-color: white; } @media screen and (min-width: 1024px) { .navbar.is-black .navbar-start > .navbar-item, .navbar.is-black .navbar-start .navbar-link, .navbar.is-black .navbar-end > .navbar-item, .navbar.is-black .navbar-end .navbar-link { color: white; } .navbar.is-black .navbar-start > a.navbar-item:hover, .navbar.is-black .navbar-start > a.navbar-item.is-active, .navbar.is-black .navbar-start .navbar-link:hover, .navbar.is-black .navbar-start .navbar-link.is-active, .navbar.is-black .navbar-end > a.navbar-item:hover, .navbar.is-black .navbar-end > a.navbar-item.is-active, .navbar.is-black .navbar-end .navbar-link:hover, .navbar.is-black .navbar-end .navbar-link.is-active { background-color: black; color: white; } .navbar.is-black .navbar-start .navbar-link::after, .navbar.is-black .navbar-end .navbar-link::after { border-color: white; } .navbar.is-black .navbar-item.has-dropdown:hover .navbar-link, .navbar.is-black .navbar-item.has-dropdown.is-active .navbar-link { background-color: black; color: white; } .navbar.is-black .navbar-dropdown a.navbar-item.is-active { background-color: #0a0a0a; color: white; } } .navbar.is-light { background-color: whitesmoke; color: #363636; } .navbar.is-light .navbar-brand > .navbar-item, .navbar.is-light .navbar-brand .navbar-link { color: #363636; } .navbar.is-light .navbar-brand > a.navbar-item:hover, .navbar.is-light .navbar-brand > a.navbar-item.is-active, .navbar.is-light .navbar-brand .navbar-link:hover, .navbar.is-light .navbar-brand .navbar-link.is-active { background-color: #e8e8e8; color: #363636; } .navbar.is-light .navbar-brand .navbar-link::after { border-color: #363636; } @media screen and (min-width: 1024px) { .navbar.is-light .navbar-start > .navbar-item, .navbar.is-light .navbar-start .navbar-link, .navbar.is-light .navbar-end > .navbar-item, .navbar.is-light .navbar-end .navbar-link { color: #363636; } .navbar.is-light .navbar-start > a.navbar-item:hover, .navbar.is-light .navbar-start > a.navbar-item.is-active, .navbar.is-light .navbar-start .navbar-link:hover, .navbar.is-light .navbar-start .navbar-link.is-active, .navbar.is-light .navbar-end > a.navbar-item:hover, .navbar.is-light .navbar-end > a.navbar-item.is-active, .navbar.is-light .navbar-end .navbar-link:hover, .navbar.is-light .navbar-end .navbar-link.is-active { background-color: #e8e8e8; color: #363636; } .navbar.is-light .navbar-start .navbar-link::after, .navbar.is-light .navbar-end .navbar-link::after { border-color: #363636; } .navbar.is-light .navbar-item.has-dropdown:hover .navbar-link, .navbar.is-light .navbar-item.has-dropdown.is-active .navbar-link { background-color: #e8e8e8; color: #363636; } .navbar.is-light .navbar-dropdown a.navbar-item.is-active { background-color: whitesmoke; color: #363636; } } .navbar.is-dark { background-color: #363636; color: whitesmoke; } .navbar.is-dark .navbar-brand > .navbar-item, .navbar.is-dark .navbar-brand .navbar-link { color: whitesmoke; } .navbar.is-dark .navbar-brand > a.navbar-item:hover, .navbar.is-dark .navbar-brand > a.navbar-item.is-active, .navbar.is-dark .navbar-brand .navbar-link:hover, .navbar.is-dark .navbar-brand .navbar-link.is-active { background-color: #292929; color: whitesmoke; } .navbar.is-dark .navbar-brand .navbar-link::after { border-color: whitesmoke; } @media screen and (min-width: 1024px) { .navbar.is-dark .navbar-start > .navbar-item, .navbar.is-dark .navbar-start .navbar-link, .navbar.is-dark .navbar-end > .navbar-item, .navbar.is-dark .navbar-end .navbar-link { color: whitesmoke; } .navbar.is-dark .navbar-start > a.navbar-item:hover, .navbar.is-dark .navbar-start > a.navbar-item.is-active, .navbar.is-dark .navbar-start .navbar-link:hover, .navbar.is-dark .navbar-start .navbar-link.is-active, .navbar.is-dark .navbar-end > a.navbar-item:hover, .navbar.is-dark .navbar-end > a.navbar-item.is-active, .navbar.is-dark .navbar-end .navbar-link:hover, .navbar.is-dark .navbar-end .navbar-link.is-active { background-color: #292929; color: whitesmoke; } .navbar.is-dark .navbar-start .navbar-link::after, .navbar.is-dark .navbar-end .navbar-link::after { border-color: whitesmoke; } .navbar.is-dark .navbar-item.has-dropdown:hover .navbar-link, .navbar.is-dark .navbar-item.has-dropdown.is-active .navbar-link { background-color: #292929; color: whitesmoke; } .navbar.is-dark .navbar-dropdown a.navbar-item.is-active { background-color: #363636; color: whitesmoke; } } .navbar.is-primary { background-color: #00d1b2; color: #fff; } .navbar.is-primary .navbar-brand > .navbar-item, .navbar.is-primary .navbar-brand .navbar-link { color: #fff; } .navbar.is-primary .navbar-brand > a.navbar-item:hover, .navbar.is-primary .navbar-brand > a.navbar-item.is-active, .navbar.is-primary .navbar-brand .navbar-link:hover, .navbar.is-primary .navbar-brand .navbar-link.is-active { background-color: #00b89c; color: #fff; } .navbar.is-primary .navbar-brand .navbar-link::after { border-color: #fff; } @media screen and (min-width: 1024px) { .navbar.is-primary .navbar-start > .navbar-item, .navbar.is-primary .navbar-start .navbar-link, .navbar.is-primary .navbar-end > .navbar-item, .navbar.is-primary .navbar-end .navbar-link { color: #fff; } .navbar.is-primary .navbar-start > a.navbar-item:hover, .navbar.is-primary .navbar-start > a.navbar-item.is-active, .navbar.is-primary .navbar-start .navbar-link:hover, .navbar.is-primary .navbar-start .navbar-link.is-active, .navbar.is-primary .navbar-end > a.navbar-item:hover, .navbar.is-primary .navbar-end > a.navbar-item.is-active, .navbar.is-primary .navbar-end .navbar-link:hover, .navbar.is-primary .navbar-end .navbar-link.is-active { background-color: #00b89c; color: #fff; } .navbar.is-primary .navbar-start .navbar-link::after, .navbar.is-primary .navbar-end .navbar-link::after { border-color: #fff; } .navbar.is-primary .navbar-item.has-dropdown:hover .navbar-link, .navbar.is-primary .navbar-item.has-dropdown.is-active .navbar-link { background-color: #00b89c; color: #fff; } .navbar.is-primary .navbar-dropdown a.navbar-item.is-active { background-color: #00d1b2; color: #fff; } } .navbar.is-link { background-color: #7a91c1; color: #fff; } .navbar.is-link .navbar-brand > .navbar-item, .navbar.is-link .navbar-brand .navbar-link { color: #fff; } .navbar.is-link .navbar-brand > a.navbar-item:hover, .navbar.is-link .navbar-brand > a.navbar-item.is-active, .navbar.is-link .navbar-brand .navbar-link:hover, .navbar.is-link .navbar-brand .navbar-link.is-active { background-color: #2366d1; color: #fff; } .navbar.is-link .navbar-brand .navbar-link::after { border-color: #fff; } @media screen and (min-width: 1024px) { .navbar.is-link .navbar-start > .navbar-item, .navbar.is-link .navbar-start .navbar-link, .navbar.is-link .navbar-end > .navbar-item, .navbar.is-link .navbar-end .navbar-link { color: #fff; } .navbar.is-link .navbar-start > a.navbar-item:hover, .navbar.is-link .navbar-start > a.navbar-item.is-active, .navbar.is-link .navbar-start .navbar-link:hover, .navbar.is-link .navbar-start .navbar-link.is-active, .navbar.is-link .navbar-end > a.navbar-item:hover, .navbar.is-link .navbar-end > a.navbar-item.is-active, .navbar.is-link .navbar-end .navbar-link:hover, .navbar.is-link .navbar-end .navbar-link.is-active { background-color: #2366d1; color: #fff; } .navbar.is-link .navbar-start .navbar-link::after, .navbar.is-link .navbar-end .navbar-link::after { border-color: #fff; } .navbar.is-link .navbar-item.has-dropdown:hover .navbar-link, .navbar.is-link .navbar-item.has-dropdown.is-active .navbar-link { background-color: #2366d1; color: #fff; } .navbar.is-link .navbar-dropdown a.navbar-item.is-active { background-color: #7a91c1; color: #fff; } } .navbar.is-info { background-color: #209cee; color: #fff; } .navbar.is-info .navbar-brand > .navbar-item, .navbar.is-info .navbar-brand .navbar-link { color: #fff; } .navbar.is-info .navbar-brand > a.navbar-item:hover, .navbar.is-info .navbar-brand > a.navbar-item.is-active, .navbar.is-info .navbar-brand .navbar-link:hover, .navbar.is-info .navbar-brand .navbar-link.is-active { background-color: #118fe4; color: #fff; } .navbar.is-info .navbar-brand .navbar-link::after { border-color: #fff; } @media screen and (min-width: 1024px) { .navbar.is-info .navbar-start > .navbar-item, .navbar.is-info .navbar-start .navbar-link, .navbar.is-info .navbar-end > .navbar-item, .navbar.is-info .navbar-end .navbar-link { color: #fff; } .navbar.is-info .navbar-start > a.navbar-item:hover, .navbar.is-info .navbar-start > a.navbar-item.is-active, .navbar.is-info .navbar-start .navbar-link:hover, .navbar.is-info .navbar-start .navbar-link.is-active, .navbar.is-info .navbar-end > a.navbar-item:hover, .navbar.is-info .navbar-end > a.navbar-item.is-active, .navbar.is-info .navbar-end .navbar-link:hover, .navbar.is-info .navbar-end .navbar-link.is-active { background-color: #118fe4; color: #fff; } .navbar.is-info .navbar-start .navbar-link::after, .navbar.is-info .navbar-end .navbar-link::after { border-color: #fff; } .navbar.is-info .navbar-item.has-dropdown:hover .navbar-link, .navbar.is-info .navbar-item.has-dropdown.is-active .navbar-link { background-color: #118fe4; color: #fff; } .navbar.is-info .navbar-dropdown a.navbar-item.is-active { background-color: #209cee; color: #fff; } } .navbar.is-success { background-color: #23d160; color: #fff; } .navbar.is-success .navbar-brand > .navbar-item, .navbar.is-success .navbar-brand .navbar-link { color: #fff; } .navbar.is-success .navbar-brand > a.navbar-item:hover, .navbar.is-success .navbar-brand > a.navbar-item.is-active, .navbar.is-success .navbar-brand .navbar-link:hover, .navbar.is-success .navbar-brand .navbar-link.is-active { background-color: #20bc56; color: #fff; } .navbar.is-success .navbar-brand .navbar-link::after { border-color: #fff; } @media screen and (min-width: 1024px) { .navbar.is-success .navbar-start > .navbar-item, .navbar.is-success .navbar-start .navbar-link, .navbar.is-success .navbar-end > .navbar-item, .navbar.is-success .navbar-end .navbar-link { color: #fff; } .navbar.is-success .navbar-start > a.navbar-item:hover, .navbar.is-success .navbar-start > a.navbar-item.is-active, .navbar.is-success .navbar-start .navbar-link:hover, .navbar.is-success .navbar-start .navbar-link.is-active, .navbar.is-success .navbar-end > a.navbar-item:hover, .navbar.is-success .navbar-end > a.navbar-item.is-active, .navbar.is-success .navbar-end .navbar-link:hover, .navbar.is-success .navbar-end .navbar-link.is-active { background-color: #20bc56; color: #fff; } .navbar.is-success .navbar-start .navbar-link::after, .navbar.is-success .navbar-end .navbar-link::after { border-color: #fff; } .navbar.is-success .navbar-item.has-dropdown:hover .navbar-link, .navbar.is-success .navbar-item.has-dropdown.is-active .navbar-link { background-color: #20bc56; color: #fff; } .navbar.is-success .navbar-dropdown a.navbar-item.is-active { background-color: #23d160; color: #fff; } } .navbar.is-warning { background-color: #ffdd57; color: rgba(0, 0, 0, 0.7); } .navbar.is-warning .navbar-brand > .navbar-item, .navbar.is-warning .navbar-brand .navbar-link { color: rgba(0, 0, 0, 0.7); } .navbar.is-warning .navbar-brand > a.navbar-item:hover, .navbar.is-warning .navbar-brand > a.navbar-item.is-active, .navbar.is-warning .navbar-brand .navbar-link:hover, .navbar.is-warning .navbar-brand .navbar-link.is-active { background-color: #ffd83d; color: rgba(0, 0, 0, 0.7); } .navbar.is-warning .navbar-brand .navbar-link::after { border-color: rgba(0, 0, 0, 0.7); } @media screen and (min-width: 1024px) { .navbar.is-warning .navbar-start > .navbar-item, .navbar.is-warning .navbar-start .navbar-link, .navbar.is-warning .navbar-end > .navbar-item, .navbar.is-warning .navbar-end .navbar-link { color: rgba(0, 0, 0, 0.7); } .navbar.is-warning .navbar-start > a.navbar-item:hover, .navbar.is-warning .navbar-start > a.navbar-item.is-active, .navbar.is-warning .navbar-start .navbar-link:hover, .navbar.is-warning .navbar-start .navbar-link.is-active, .navbar.is-warning .navbar-end > a.navbar-item:hover, .navbar.is-warning .navbar-end > a.navbar-item.is-active, .navbar.is-warning .navbar-end .navbar-link:hover, .navbar.is-warning .navbar-end .navbar-link.is-active { background-color: #ffd83d; color: rgba(0, 0, 0, 0.7); } .navbar.is-warning .navbar-start .navbar-link::after, .navbar.is-warning .navbar-end .navbar-link::after { border-color: rgba(0, 0, 0, 0.7); } .navbar.is-warning .navbar-item.has-dropdown:hover .navbar-link, .navbar.is-warning .navbar-item.has-dropdown.is-active .navbar-link { background-color: #ffd83d; color: rgba(0, 0, 0, 0.7); } .navbar.is-warning .navbar-dropdown a.navbar-item.is-active { background-color: #ffdd57; color: rgba(0, 0, 0, 0.7); } } .navbar.is-danger { background-color: #ff3860; color: #fff; } .navbar.is-danger .navbar-brand > .navbar-item, .navbar.is-danger .navbar-brand .navbar-link { color: #fff; } .navbar.is-danger .navbar-brand > a.navbar-item:hover, .navbar.is-danger .navbar-brand > a.navbar-item.is-active, .navbar.is-danger .navbar-brand .navbar-link:hover, .navbar.is-danger .navbar-brand .navbar-link.is-active { background-color: #ff1f4b; color: #fff; } .navbar.is-danger .navbar-brand .navbar-link::after { border-color: #fff; } @media screen and (min-width: 1024px) { .navbar.is-danger .navbar-start > .navbar-item, .navbar.is-danger .navbar-start .navbar-link, .navbar.is-danger .navbar-end > .navbar-item, .navbar.is-danger .navbar-end .navbar-link { color: #fff; } .navbar.is-danger .navbar-start > a.navbar-item:hover, .navbar.is-danger .navbar-start > a.navbar-item.is-active, .navbar.is-danger .navbar-start .navbar-link:hover, .navbar.is-danger .navbar-start .navbar-link.is-active, .navbar.is-danger .navbar-end > a.navbar-item:hover, .navbar.is-danger .navbar-end > a.navbar-item.is-active, .navbar.is-danger .navbar-end .navbar-link:hover, .navbar.is-danger .navbar-end .navbar-link.is-active { background-color: #ff1f4b; color: #fff; } .navbar.is-danger .navbar-start .navbar-link::after, .navbar.is-danger .navbar-end .navbar-link::after { border-color: #fff; } .navbar.is-danger .navbar-item.has-dropdown:hover .navbar-link, .navbar.is-danger .navbar-item.has-dropdown.is-active .navbar-link { background-color: #ff1f4b; color: #fff; } .navbar.is-danger .navbar-dropdown a.navbar-item.is-active { background-color: #ff3860; color: #fff; } } .navbar > .container { -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -ms-flexbox; display: flex; min-height: 3.25rem; width: 100%; } .navbar.has-shadow { -webkit-box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1); box-shadow: 0 2px 3px rgba(10, 10, 10, 0.1); } .navbar.is-fixed-bottom, .navbar.is-fixed-top { left: 0; position: fixed; right: 0; z-index: 30; } .navbar.is-fixed-bottom { bottom: 0; } .navbar.is-fixed-bottom.has-shadow { -webkit-box-shadow: 0 -2px 3px rgba(10, 10, 10, 0.1); box-shadow: 0 -2px 3px rgba(10, 10, 10, 0.1); } .navbar.is-fixed-top { top: 0; } html.has-navbar-fixed-top { padding-top: 3.25rem; } html.has-navbar-fixed-bottom { padding-bottom: 3.25rem; } .navbar-brand, .navbar-tabs { -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-negative: 0; flex-shrink: 0; min-height: 3.25rem; } .navbar-tabs { -webkit-overflow-scrolling: touch; max-width: 100vw; overflow-x: auto; overflow-y: hidden; } .navbar-burger { cursor: pointer; display: block; height: 3.25rem; position: relative; width: 3.25rem; margin-left: auto; } .navbar-burger span { background-color: currentColor; display: block; height: 1px; left: calc(50% - 8px); position: absolute; -webkit-transform-origin: center; transform-origin: center; -webkit-transition-duration: 86ms; transition-duration: 86ms; -webkit-transition-property: background-color, opacity, -webkit-transform; transition-property: background-color, opacity, -webkit-transform; transition-property: background-color, opacity, transform; transition-property: background-color, opacity, transform, -webkit-transform; -webkit-transition-timing-function: ease-out; transition-timing-function: ease-out; width: 16px; } .navbar-burger span:nth-child(1) { top: calc(50% - 6px); } .navbar-burger span:nth-child(2) { top: calc(50% - 1px); } .navbar-burger span:nth-child(3) { top: calc(50% + 4px); } .navbar-burger:hover { background-color: rgba(0, 0, 0, 0.05); } .navbar-burger.is-active span:nth-child(1) { -webkit-transform: translateY(5px) rotate(45deg); transform: translateY(5px) rotate(45deg); } .navbar-burger.is-active span:nth-child(2) { opacity: 0; } .navbar-burger.is-active span:nth-child(3) { -webkit-transform: translateY(-5px) rotate(-45deg); transform: translateY(-5px) rotate(-45deg); } .navbar-menu { display: none; } .navbar-item, .navbar-link { color: #4a4a4a; display: block; line-height: 1.5; padding: 0.5rem 1rem; position: relative; } a.navbar-item:hover, a.navbar-item.is-active, a.navbar-link:hover, a.navbar-link.is-active { background-color: whitesmoke; color: #7a91c1; } .navbar-item { -webkit-box-flex: 0; -ms-flex-positive: 0; flex-grow: 0; -ms-flex-negative: 0; flex-shrink: 0; } .navbar-item img { max-height: 1.75rem; } .navbar-item.has-dropdown { padding: 0; } .navbar-item.is-expanded { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; } .navbar-item.is-tab { border-bottom: 1px solid transparent; min-height: 3.25rem; padding-bottom: calc(0.5rem - 1px); } .navbar-item.is-tab:hover { background-color: transparent; border-bottom-color: #7a91c1; } .navbar-item.is-tab.is-active { background-color: transparent; border-bottom-color: #7a91c1; border-bottom-style: solid; border-bottom-width: 3px; color: #7a91c1; padding-bottom: calc(0.5rem - 3px); } .navbar-content { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; } .navbar-link { padding-right: 2.5em; } .navbar-dropdown { font-size: 0.875rem; padding-bottom: 0.5rem; padding-top: 0.5rem; } .navbar-dropdown .navbar-item { padding-left: 1.5rem; padding-right: 1.5rem; } .navbar-divider { background-color: #dbdbdb; border: none; display: none; height: 1px; margin: 0.5rem 0; } @media screen and (max-width: 1023px) { .navbar > .container { display: block; } .navbar-brand .navbar-item, .navbar-tabs .navbar-item { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -ms-flexbox; display: flex; } .navbar-menu { background-color: white; -webkit-box-shadow: 0 8px 16px rgba(10, 10, 10, 0.1); box-shadow: 0 8px 16px rgba(10, 10, 10, 0.1); padding: 0.5rem 0; } .navbar-menu.is-active { display: block; } .navbar.is-fixed-bottom-touch, .navbar.is-fixed-top-touch { left: 0; position: fixed; right: 0; z-index: 30; } .navbar.is-fixed-bottom-touch { bottom: 0; } .navbar.is-fixed-bottom-touch.has-shadow { -webkit-box-shadow: 0 -2px 3px rgba(10, 10, 10, 0.1); box-shadow: 0 -2px 3px rgba(10, 10, 10, 0.1); } .navbar.is-fixed-top-touch { top: 0; } .navbar.is-fixed-top .navbar-menu, .navbar.is-fixed-top-touch .navbar-menu { -webkit-overflow-scrolling: touch; max-height: calc(100vh - 3.25rem); overflow: auto; } html.has-navbar-fixed-top-touch { padding-top: 3.25rem; } html.has-navbar-fixed-bottom-touch { padding-bottom: 3.25rem; } } @media screen and (min-width: 1024px) { .navbar, .navbar-menu, .navbar-start, .navbar-end { -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -ms-flexbox; display: flex; } .navbar { min-height: 3.25rem; } .navbar.is-transparent a.navbar-item:hover, .navbar.is-transparent a.navbar-item.is-active, .navbar.is-transparent a.navbar-link:hover, .navbar.is-transparent a.navbar-link.is-active { background-color: transparent !important; } .navbar.is-transparent .navbar-item.has-dropdown.is-active .navbar-link, .navbar.is-transparent .navbar-item.has-dropdown.is-hoverable:hover .navbar-link { background-color: transparent !important; } .navbar.is-transparent .navbar-dropdown a.navbar-item:hover { background-color: whitesmoke; color: #0a0a0a; } .navbar.is-transparent .navbar-dropdown a.navbar-item.is-active { background-color: whitesmoke; color: #7a91c1; } .navbar-burger { display: none; } .navbar-item, .navbar-link { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -ms-flexbox; display: flex; } .navbar-item.has-dropdown { -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; } .navbar-item.has-dropdown-up .navbar-link::after { -webkit-transform: rotate(135deg) translate(0.25em, -0.25em); transform: rotate(135deg) translate(0.25em, -0.25em); } .navbar-item.has-dropdown-up .navbar-dropdown { border-bottom: 1px solid #dbdbdb; border-radius: 5px 5px 0 0; border-top: none; bottom: 100%; -webkit-box-shadow: 0 -8px 8px rgba(10, 10, 10, 0.1); box-shadow: 0 -8px 8px rgba(10, 10, 10, 0.1); top: auto; } .navbar-item.is-active .navbar-dropdown, .navbar-item.is-hoverable:hover .navbar-dropdown { display: block; } .navbar-item.is-active .navbar-dropdown.is-boxed, .navbar-item.is-hoverable:hover .navbar-dropdown.is-boxed { opacity: 1; pointer-events: auto; -webkit-transform: translateY(0); transform: translateY(0); } .navbar-link::after { border: 1px solid #7a91c1; border-right: 0; border-top: 0; content: " "; display: block; height: 0.5em; pointer-events: none; position: absolute; -webkit-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: center; transform-origin: center; width: 0.5em; margin-top: -0.375em; right: 1.125em; top: 50%; } .navbar-menu { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 0; flex-shrink: 0; } .navbar-start { -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; margin-right: auto; } .navbar-end { -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; margin-left: auto; } .navbar-dropdown { background-color: white; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; border-top: 1px solid #dbdbdb; -webkit-box-shadow: 0 8px 8px rgba(10, 10, 10, 0.1); box-shadow: 0 8px 8px rgba(10, 10, 10, 0.1); display: none; font-size: 0.875rem; left: 0; min-width: 100%; position: absolute; top: 100%; z-index: 20; } .navbar-dropdown .navbar-item { padding: 0.375rem 1rem; white-space: nowrap; } .navbar-dropdown a.navbar-item { padding-right: 3rem; } .navbar-dropdown a.navbar-item:hover { background-color: whitesmoke; color: #0a0a0a; } .navbar-dropdown a.navbar-item.is-active { background-color: whitesmoke; color: #7a91c1; } .navbar-dropdown.is-boxed { border-radius: 5px; border-top: none; -webkit-box-shadow: 0 8px 8px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); box-shadow: 0 8px 8px rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.1); display: block; opacity: 0; pointer-events: none; top: calc(100% + (-4px)); -webkit-transform: translateY(-5px); transform: translateY(-5px); -webkit-transition-duration: 86ms; transition-duration: 86ms; -webkit-transition-property: opacity, -webkit-transform; transition-property: opacity, -webkit-transform; transition-property: opacity, transform; transition-property: opacity, transform, -webkit-transform; } .navbar-dropdown.is-right { left: auto; right: 0; } .navbar-divider { display: block; } .navbar > .container .navbar-brand, .container > .navbar .navbar-brand { margin-left: -1rem; } .navbar > .container .navbar-menu, .container > .navbar .navbar-menu { margin-right: -1rem; } .navbar.is-fixed-bottom-desktop, .navbar.is-fixed-top-desktop { left: 0; position: fixed; right: 0; z-index: 30; } .navbar.is-fixed-bottom-desktop { bottom: 0; } .navbar.is-fixed-bottom-desktop.has-shadow { -webkit-box-shadow: 0 -2px 3px rgba(10, 10, 10, 0.1); box-shadow: 0 -2px 3px rgba(10, 10, 10, 0.1); } .navbar.is-fixed-top-desktop { top: 0; } html.has-navbar-fixed-top-desktop { padding-top: 3.25rem; } html.has-navbar-fixed-bottom-desktop { padding-bottom: 3.25rem; } a.navbar-item.is-active, a.navbar-link.is-active { color: #0a0a0a; } a.navbar-item.is-active:not(:hover), a.navbar-link.is-active:not(:hover) { background-color: transparent; } .navbar-item.has-dropdown:hover .navbar-link, .navbar-item.has-dropdown.is-active .navbar-link { background-color: whitesmoke; } } .pagination { font-size: 1rem; margin: -0.25rem; } .pagination.is-small { font-size: 0.75rem; } .pagination.is-medium { font-size: 1.25rem; } .pagination.is-large { font-size: 1.5rem; } .pagination, .pagination-list { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; text-align: center; } .pagination-previous, .pagination-next, .pagination-link, .pagination-ellipsis { -moz-appearance: none; -webkit-appearance: none; -webkit-box-align: center; -ms-flex-align: center; align-items: center; border: 1px solid transparent; border-radius: 3px; -webkit-box-shadow: none; box-shadow: none; display: -webkit-inline-box; display: -ms-inline-flexbox; display: inline-flex; font-size: 1rem; height: 2.25em; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; line-height: 1.5; padding-bottom: calc(0.375em - 1px); padding-left: calc(0.625em - 1px); padding-right: calc(0.625em - 1px); padding-top: calc(0.375em - 1px); position: relative; vertical-align: top; -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; font-size: 1em; padding-left: 0.5em; padding-right: 0.5em; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; margin: 0.25rem; text-align: center; } .pagination-previous:focus, .pagination-previous.is-focused, .pagination-previous:active, .pagination-previous.is-active, .pagination-next:focus, .pagination-next.is-focused, .pagination-next:active, .pagination-next.is-active, .pagination-link:focus, .pagination-link.is-focused, .pagination-link:active, .pagination-link.is-active, .pagination-ellipsis:focus, .pagination-ellipsis.is-focused, .pagination-ellipsis:active, .pagination-ellipsis.is-active { outline: none; } .pagination-previous[disabled], .pagination-next[disabled], .pagination-link[disabled], .pagination-ellipsis[disabled] { cursor: not-allowed; } .pagination-previous, .pagination-next, .pagination-link { border-color: #dbdbdb; min-width: 2.25em; } .pagination-previous:hover, .pagination-next:hover, .pagination-link:hover { border-color: #b5b5b5; color: #363636; } .pagination-previous:focus, .pagination-next:focus, .pagination-link:focus { border-color: #7a91c1; } .pagination-previous:active, .pagination-next:active, .pagination-link:active { -webkit-box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.2); box-shadow: inset 0 1px 2px rgba(10, 10, 10, 0.2); } .pagination-previous[disabled], .pagination-next[disabled], .pagination-link[disabled] { background-color: #dbdbdb; border-color: #dbdbdb; -webkit-box-shadow: none; box-shadow: none; color: #7a7a7a; opacity: 0.5; } .pagination-previous, .pagination-next { padding-left: 0.75em; padding-right: 0.75em; white-space: nowrap; } .pagination-link.is-current { background-color: #7a91c1; border-color: #7a91c1; color: #fff; } .pagination-ellipsis { color: #b5b5b5; pointer-events: none; } .pagination-list { -ms-flex-wrap: wrap; flex-wrap: wrap; } @media screen and (max-width: 768px) { .pagination { -ms-flex-wrap: wrap; flex-wrap: wrap; } .pagination-previous, .pagination-next { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; } .pagination-list li { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; } } @media screen and (min-width: 769px), print { .pagination-list { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; -webkit-box-ordinal-group: 2; -ms-flex-order: 1; order: 1; } .pagination-previous { -webkit-box-ordinal-group: 3; -ms-flex-order: 2; order: 2; } .pagination-next { -webkit-box-ordinal-group: 4; -ms-flex-order: 3; order: 3; } .pagination { -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; } .pagination.is-centered .pagination-previous { -webkit-box-ordinal-group: 2; -ms-flex-order: 1; order: 1; } .pagination.is-centered .pagination-list { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-box-ordinal-group: 3; -ms-flex-order: 2; order: 2; } .pagination.is-centered .pagination-next { -webkit-box-ordinal-group: 4; -ms-flex-order: 3; order: 3; } .pagination.is-right .pagination-previous { -webkit-box-ordinal-group: 2; -ms-flex-order: 1; order: 1; } .pagination.is-right .pagination-next { -webkit-box-ordinal-group: 3; -ms-flex-order: 2; order: 2; } .pagination.is-right .pagination-list { -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; -webkit-box-ordinal-group: 4; -ms-flex-order: 3; order: 3; } } .panel { font-size: 1rem; } .panel:not(:last-child) { margin-bottom: 1.5rem; } .panel-heading, .panel-tabs, .panel-block { border-bottom: 1px solid #dbdbdb; border-left: 1px solid #dbdbdb; border-right: 1px solid #dbdbdb; } .panel-heading:first-child, .panel-tabs:first-child, .panel-block:first-child { border-top: 1px solid #dbdbdb; } .panel-heading { background-color: whitesmoke; border-radius: 3px 3px 0 0; color: #363636; font-size: 1.25em; font-weight: 300; line-height: 1.25; padding: 0.5em 0.75em; } .panel-tabs { -webkit-box-align: end; -ms-flex-align: end; align-items: flex-end; display: -webkit-box; display: -ms-flexbox; display: flex; font-size: 0.875em; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .panel-tabs a { border-bottom: 1px solid #dbdbdb; margin-bottom: -1px; padding: 0.5em; } .panel-tabs a.is-active { border-bottom-color: #4a4a4a; color: #363636; } .panel-list a { color: #4a4a4a; } .panel-list a:hover { color: #7a91c1; } .panel-block { -webkit-box-align: center; -ms-flex-align: center; align-items: center; color: #363636; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; padding: 0.5em 0.75em; } .panel-block input[type="checkbox"] { margin-right: 0.75em; } .panel-block > .control { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; width: 100%; } .panel-block.is-wrapped { -ms-flex-wrap: wrap; flex-wrap: wrap; } .panel-block.is-active { border-left-color: #7a91c1; color: #363636; } .panel-block.is-active .panel-icon { color: #7a91c1; } a.panel-block, label.panel-block { cursor: pointer; } a.panel-block:hover, label.panel-block:hover { background-color: whitesmoke; } .panel-icon { display: inline-block; font-size: 14px; height: 1em; line-height: 1em; text-align: center; vertical-align: top; width: 1em; color: #7a7a7a; margin-right: 0.75em; } .panel-icon .fa { font-size: inherit; line-height: inherit; } .tabs { -webkit-overflow-scrolling: touch; -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -ms-flexbox; display: flex; font-size: 1rem; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; overflow: hidden; overflow-x: auto; white-space: nowrap; } .tabs:not(:last-child) { margin-bottom: 1.5rem; } .tabs a { -webkit-box-align: center; -ms-flex-align: center; align-items: center; border-bottom-color: #dbdbdb; border-bottom-style: solid; border-bottom-width: 1px; color: #4a4a4a; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; margin-bottom: -1px; padding: 0.5em 1em; vertical-align: top; } .tabs a:hover { border-bottom-color: #363636; color: #363636; } .tabs li { display: block; } .tabs li.is-active a { border-bottom-color: #7a91c1; color: #7a91c1; } .tabs ul { -webkit-box-align: center; -ms-flex-align: center; align-items: center; border-bottom-color: #dbdbdb; border-bottom-style: solid; border-bottom-width: 1px; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 0; flex-shrink: 0; -webkit-box-pack: start; -ms-flex-pack: start; justify-content: flex-start; } .tabs ul.is-left { padding-right: 0.75em; } .tabs ul.is-center { -webkit-box-flex: 0; -ms-flex: none; flex: none; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; padding-left: 0.75em; padding-right: 0.75em; } .tabs ul.is-right { -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; padding-left: 0.75em; } .tabs .icon:first-child { margin-right: 0.5em; } .tabs .icon:last-child { margin-left: 0.5em; } .tabs.is-centered ul { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .tabs.is-right ul { -webkit-box-pack: end; -ms-flex-pack: end; justify-content: flex-end; } .tabs.is-boxed a { border: 1px solid transparent; border-radius: 3px 3px 0 0; } .tabs.is-boxed a:hover { background-color: whitesmoke; border-bottom-color: #dbdbdb; } .tabs.is-boxed li.is-active a { background-color: white; border-color: #dbdbdb; border-bottom-color: transparent !important; } .tabs.is-fullwidth li { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 0; flex-shrink: 0; } .tabs.is-toggle a { border-color: #dbdbdb; border-style: solid; border-width: 1px; margin-bottom: 0; position: relative; } .tabs.is-toggle a:hover { background-color: whitesmoke; border-color: #b5b5b5; z-index: 2; } .tabs.is-toggle li + li { margin-left: -1px; } .tabs.is-toggle li:first-child a { border-radius: 3px 0 0 3px; } .tabs.is-toggle li:last-child a { border-radius: 0 3px 3px 0; } .tabs.is-toggle li.is-active a { background-color: #7a91c1; border-color: #7a91c1; color: #fff; z-index: 1; } .tabs.is-toggle ul { border-bottom: none; } .tabs.is-small { font-size: 0.75rem; } .tabs.is-medium { font-size: 1.25rem; } .tabs.is-large { font-size: 1.5rem; } .column { display: block; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; padding: 0.75rem; } .columns.is-mobile > .column.is-narrow { -webkit-box-flex: 0; -ms-flex: none; flex: none; } .columns.is-mobile > .column.is-full { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .columns.is-mobile > .column.is-three-quarters { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .columns.is-mobile > .column.is-two-thirds { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.6666%; } .columns.is-mobile > .column.is-half { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .columns.is-mobile > .column.is-one-third { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.3333%; } .columns.is-mobile > .column.is-one-quarter { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .columns.is-mobile > .column.is-one-fifth { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 20%; } .columns.is-mobile > .column.is-two-fifths { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 40%; } .columns.is-mobile > .column.is-three-fifths { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 60%; } .columns.is-mobile > .column.is-four-fifths { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 80%; } .columns.is-mobile > .column.is-offset-three-quarters { margin-left: 75%; } .columns.is-mobile > .column.is-offset-two-thirds { margin-left: 66.6666%; } .columns.is-mobile > .column.is-offset-half { margin-left: 50%; } .columns.is-mobile > .column.is-offset-one-third { margin-left: 33.3333%; } .columns.is-mobile > .column.is-offset-one-quarter { margin-left: 25%; } .columns.is-mobile > .column.is-offset-one-fifth { margin-left: 20%; } .columns.is-mobile > .column.is-offset-two-fifths { margin-left: 40%; } .columns.is-mobile > .column.is-offset-three-fifths { margin-left: 60%; } .columns.is-mobile > .column.is-offset-four-fifths { margin-left: 80%; } .columns.is-mobile > .column.is-1 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 8.33333%; } .columns.is-mobile > .column.is-offset-1 { margin-left: 8.33333%; } .columns.is-mobile > .column.is-2 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 16.66667%; } .columns.is-mobile > .column.is-offset-2 { margin-left: 16.66667%; } .columns.is-mobile > .column.is-3 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .columns.is-mobile > .column.is-offset-3 { margin-left: 25%; } .columns.is-mobile > .column.is-4 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.33333%; } .columns.is-mobile > .column.is-offset-4 { margin-left: 33.33333%; } .columns.is-mobile > .column.is-5 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 41.66667%; } .columns.is-mobile > .column.is-offset-5 { margin-left: 41.66667%; } .columns.is-mobile > .column.is-6 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .columns.is-mobile > .column.is-offset-6 { margin-left: 50%; } .columns.is-mobile > .column.is-7 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 58.33333%; } .columns.is-mobile > .column.is-offset-7 { margin-left: 58.33333%; } .columns.is-mobile > .column.is-8 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.66667%; } .columns.is-mobile > .column.is-offset-8 { margin-left: 66.66667%; } .columns.is-mobile > .column.is-9 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .columns.is-mobile > .column.is-offset-9 { margin-left: 75%; } .columns.is-mobile > .column.is-10 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 83.33333%; } .columns.is-mobile > .column.is-offset-10 { margin-left: 83.33333%; } .columns.is-mobile > .column.is-11 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 91.66667%; } .columns.is-mobile > .column.is-offset-11 { margin-left: 91.66667%; } .columns.is-mobile > .column.is-12 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .columns.is-mobile > .column.is-offset-12 { margin-left: 100%; } @media screen and (max-width: 768px) { .column.is-narrow-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; } .column.is-full-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-three-quarters-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-two-thirds-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.6666%; } .column.is-half-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-one-third-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.3333%; } .column.is-one-quarter-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-one-fifth-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 20%; } .column.is-two-fifths-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 40%; } .column.is-three-fifths-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 60%; } .column.is-four-fifths-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 80%; } .column.is-offset-three-quarters-mobile { margin-left: 75%; } .column.is-offset-two-thirds-mobile { margin-left: 66.6666%; } .column.is-offset-half-mobile { margin-left: 50%; } .column.is-offset-one-third-mobile { margin-left: 33.3333%; } .column.is-offset-one-quarter-mobile { margin-left: 25%; } .column.is-offset-one-fifth-mobile { margin-left: 20%; } .column.is-offset-two-fifths-mobile { margin-left: 40%; } .column.is-offset-three-fifths-mobile { margin-left: 60%; } .column.is-offset-four-fifths-mobile { margin-left: 80%; } .column.is-1-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 8.33333%; } .column.is-offset-1-mobile { margin-left: 8.33333%; } .column.is-2-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 16.66667%; } .column.is-offset-2-mobile { margin-left: 16.66667%; } .column.is-3-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-offset-3-mobile { margin-left: 25%; } .column.is-4-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.33333%; } .column.is-offset-4-mobile { margin-left: 33.33333%; } .column.is-5-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 41.66667%; } .column.is-offset-5-mobile { margin-left: 41.66667%; } .column.is-6-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-offset-6-mobile { margin-left: 50%; } .column.is-7-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 58.33333%; } .column.is-offset-7-mobile { margin-left: 58.33333%; } .column.is-8-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.66667%; } .column.is-offset-8-mobile { margin-left: 66.66667%; } .column.is-9-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-offset-9-mobile { margin-left: 75%; } .column.is-10-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 83.33333%; } .column.is-offset-10-mobile { margin-left: 83.33333%; } .column.is-11-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 91.66667%; } .column.is-offset-11-mobile { margin-left: 91.66667%; } .column.is-12-mobile { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-offset-12-mobile { margin-left: 100%; } } @media screen and (min-width: 769px), print { .column.is-narrow, .column.is-narrow-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; } .column.is-full, .column.is-full-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-three-quarters, .column.is-three-quarters-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-two-thirds, .column.is-two-thirds-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.6666%; } .column.is-half, .column.is-half-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-one-third, .column.is-one-third-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.3333%; } .column.is-one-quarter, .column.is-one-quarter-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-one-fifth, .column.is-one-fifth-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 20%; } .column.is-two-fifths, .column.is-two-fifths-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 40%; } .column.is-three-fifths, .column.is-three-fifths-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 60%; } .column.is-four-fifths, .column.is-four-fifths-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 80%; } .column.is-offset-three-quarters, .column.is-offset-three-quarters-tablet { margin-left: 75%; } .column.is-offset-two-thirds, .column.is-offset-two-thirds-tablet { margin-left: 66.6666%; } .column.is-offset-half, .column.is-offset-half-tablet { margin-left: 50%; } .column.is-offset-one-third, .column.is-offset-one-third-tablet { margin-left: 33.3333%; } .column.is-offset-one-quarter, .column.is-offset-one-quarter-tablet { margin-left: 25%; } .column.is-offset-one-fifth, .column.is-offset-one-fifth-tablet { margin-left: 20%; } .column.is-offset-two-fifths, .column.is-offset-two-fifths-tablet { margin-left: 40%; } .column.is-offset-three-fifths, .column.is-offset-three-fifths-tablet { margin-left: 60%; } .column.is-offset-four-fifths, .column.is-offset-four-fifths-tablet { margin-left: 80%; } .column.is-1, .column.is-1-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 8.33333%; } .column.is-offset-1, .column.is-offset-1-tablet { margin-left: 8.33333%; } .column.is-2, .column.is-2-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 16.66667%; } .column.is-offset-2, .column.is-offset-2-tablet { margin-left: 16.66667%; } .column.is-3, .column.is-3-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-offset-3, .column.is-offset-3-tablet { margin-left: 25%; } .column.is-4, .column.is-4-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.33333%; } .column.is-offset-4, .column.is-offset-4-tablet { margin-left: 33.33333%; } .column.is-5, .column.is-5-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 41.66667%; } .column.is-offset-5, .column.is-offset-5-tablet { margin-left: 41.66667%; } .column.is-6, .column.is-6-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-offset-6, .column.is-offset-6-tablet { margin-left: 50%; } .column.is-7, .column.is-7-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 58.33333%; } .column.is-offset-7, .column.is-offset-7-tablet { margin-left: 58.33333%; } .column.is-8, .column.is-8-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.66667%; } .column.is-offset-8, .column.is-offset-8-tablet { margin-left: 66.66667%; } .column.is-9, .column.is-9-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-offset-9, .column.is-offset-9-tablet { margin-left: 75%; } .column.is-10, .column.is-10-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 83.33333%; } .column.is-offset-10, .column.is-offset-10-tablet { margin-left: 83.33333%; } .column.is-11, .column.is-11-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 91.66667%; } .column.is-offset-11, .column.is-offset-11-tablet { margin-left: 91.66667%; } .column.is-12, .column.is-12-tablet { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-offset-12, .column.is-offset-12-tablet { margin-left: 100%; } } @media screen and (max-width: 1023px) { .column.is-narrow-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; } .column.is-full-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-three-quarters-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-two-thirds-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.6666%; } .column.is-half-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-one-third-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.3333%; } .column.is-one-quarter-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-one-fifth-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 20%; } .column.is-two-fifths-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 40%; } .column.is-three-fifths-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 60%; } .column.is-four-fifths-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 80%; } .column.is-offset-three-quarters-touch { margin-left: 75%; } .column.is-offset-two-thirds-touch { margin-left: 66.6666%; } .column.is-offset-half-touch { margin-left: 50%; } .column.is-offset-one-third-touch { margin-left: 33.3333%; } .column.is-offset-one-quarter-touch { margin-left: 25%; } .column.is-offset-one-fifth-touch { margin-left: 20%; } .column.is-offset-two-fifths-touch { margin-left: 40%; } .column.is-offset-three-fifths-touch { margin-left: 60%; } .column.is-offset-four-fifths-touch { margin-left: 80%; } .column.is-1-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 8.33333%; } .column.is-offset-1-touch { margin-left: 8.33333%; } .column.is-2-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 16.66667%; } .column.is-offset-2-touch { margin-left: 16.66667%; } .column.is-3-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-offset-3-touch { margin-left: 25%; } .column.is-4-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.33333%; } .column.is-offset-4-touch { margin-left: 33.33333%; } .column.is-5-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 41.66667%; } .column.is-offset-5-touch { margin-left: 41.66667%; } .column.is-6-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-offset-6-touch { margin-left: 50%; } .column.is-7-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 58.33333%; } .column.is-offset-7-touch { margin-left: 58.33333%; } .column.is-8-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.66667%; } .column.is-offset-8-touch { margin-left: 66.66667%; } .column.is-9-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-offset-9-touch { margin-left: 75%; } .column.is-10-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 83.33333%; } .column.is-offset-10-touch { margin-left: 83.33333%; } .column.is-11-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 91.66667%; } .column.is-offset-11-touch { margin-left: 91.66667%; } .column.is-12-touch { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-offset-12-touch { margin-left: 100%; } } @media screen and (min-width: 1024px) { .column.is-narrow-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; } .column.is-full-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-three-quarters-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-two-thirds-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.6666%; } .column.is-half-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-one-third-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.3333%; } .column.is-one-quarter-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-one-fifth-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 20%; } .column.is-two-fifths-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 40%; } .column.is-three-fifths-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 60%; } .column.is-four-fifths-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 80%; } .column.is-offset-three-quarters-desktop { margin-left: 75%; } .column.is-offset-two-thirds-desktop { margin-left: 66.6666%; } .column.is-offset-half-desktop { margin-left: 50%; } .column.is-offset-one-third-desktop { margin-left: 33.3333%; } .column.is-offset-one-quarter-desktop { margin-left: 25%; } .column.is-offset-one-fifth-desktop { margin-left: 20%; } .column.is-offset-two-fifths-desktop { margin-left: 40%; } .column.is-offset-three-fifths-desktop { margin-left: 60%; } .column.is-offset-four-fifths-desktop { margin-left: 80%; } .column.is-1-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 8.33333%; } .column.is-offset-1-desktop { margin-left: 8.33333%; } .column.is-2-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 16.66667%; } .column.is-offset-2-desktop { margin-left: 16.66667%; } .column.is-3-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-offset-3-desktop { margin-left: 25%; } .column.is-4-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.33333%; } .column.is-offset-4-desktop { margin-left: 33.33333%; } .column.is-5-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 41.66667%; } .column.is-offset-5-desktop { margin-left: 41.66667%; } .column.is-6-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-offset-6-desktop { margin-left: 50%; } .column.is-7-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 58.33333%; } .column.is-offset-7-desktop { margin-left: 58.33333%; } .column.is-8-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.66667%; } .column.is-offset-8-desktop { margin-left: 66.66667%; } .column.is-9-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-offset-9-desktop { margin-left: 75%; } .column.is-10-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 83.33333%; } .column.is-offset-10-desktop { margin-left: 83.33333%; } .column.is-11-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 91.66667%; } .column.is-offset-11-desktop { margin-left: 91.66667%; } .column.is-12-desktop { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-offset-12-desktop { margin-left: 100%; } } @media screen and (min-width: 1216px) { .column.is-narrow-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; } .column.is-full-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-three-quarters-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-two-thirds-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.6666%; } .column.is-half-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-one-third-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.3333%; } .column.is-one-quarter-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-one-fifth-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 20%; } .column.is-two-fifths-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 40%; } .column.is-three-fifths-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 60%; } .column.is-four-fifths-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 80%; } .column.is-offset-three-quarters-widescreen { margin-left: 75%; } .column.is-offset-two-thirds-widescreen { margin-left: 66.6666%; } .column.is-offset-half-widescreen { margin-left: 50%; } .column.is-offset-one-third-widescreen { margin-left: 33.3333%; } .column.is-offset-one-quarter-widescreen { margin-left: 25%; } .column.is-offset-one-fifth-widescreen { margin-left: 20%; } .column.is-offset-two-fifths-widescreen { margin-left: 40%; } .column.is-offset-three-fifths-widescreen { margin-left: 60%; } .column.is-offset-four-fifths-widescreen { margin-left: 80%; } .column.is-1-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 8.33333%; } .column.is-offset-1-widescreen { margin-left: 8.33333%; } .column.is-2-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 16.66667%; } .column.is-offset-2-widescreen { margin-left: 16.66667%; } .column.is-3-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-offset-3-widescreen { margin-left: 25%; } .column.is-4-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.33333%; } .column.is-offset-4-widescreen { margin-left: 33.33333%; } .column.is-5-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 41.66667%; } .column.is-offset-5-widescreen { margin-left: 41.66667%; } .column.is-6-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-offset-6-widescreen { margin-left: 50%; } .column.is-7-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 58.33333%; } .column.is-offset-7-widescreen { margin-left: 58.33333%; } .column.is-8-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.66667%; } .column.is-offset-8-widescreen { margin-left: 66.66667%; } .column.is-9-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-offset-9-widescreen { margin-left: 75%; } .column.is-10-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 83.33333%; } .column.is-offset-10-widescreen { margin-left: 83.33333%; } .column.is-11-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 91.66667%; } .column.is-offset-11-widescreen { margin-left: 91.66667%; } .column.is-12-widescreen { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-offset-12-widescreen { margin-left: 100%; } } @media screen and (min-width: 1408px) { .column.is-narrow-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; } .column.is-full-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-three-quarters-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-two-thirds-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.6666%; } .column.is-half-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-one-third-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.3333%; } .column.is-one-quarter-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-one-fifth-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 20%; } .column.is-two-fifths-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 40%; } .column.is-three-fifths-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 60%; } .column.is-four-fifths-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 80%; } .column.is-offset-three-quarters-fullhd { margin-left: 75%; } .column.is-offset-two-thirds-fullhd { margin-left: 66.6666%; } .column.is-offset-half-fullhd { margin-left: 50%; } .column.is-offset-one-third-fullhd { margin-left: 33.3333%; } .column.is-offset-one-quarter-fullhd { margin-left: 25%; } .column.is-offset-one-fifth-fullhd { margin-left: 20%; } .column.is-offset-two-fifths-fullhd { margin-left: 40%; } .column.is-offset-three-fifths-fullhd { margin-left: 60%; } .column.is-offset-four-fifths-fullhd { margin-left: 80%; } .column.is-1-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 8.33333%; } .column.is-offset-1-fullhd { margin-left: 8.33333%; } .column.is-2-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 16.66667%; } .column.is-offset-2-fullhd { margin-left: 16.66667%; } .column.is-3-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .column.is-offset-3-fullhd { margin-left: 25%; } .column.is-4-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.33333%; } .column.is-offset-4-fullhd { margin-left: 33.33333%; } .column.is-5-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 41.66667%; } .column.is-offset-5-fullhd { margin-left: 41.66667%; } .column.is-6-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .column.is-offset-6-fullhd { margin-left: 50%; } .column.is-7-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 58.33333%; } .column.is-offset-7-fullhd { margin-left: 58.33333%; } .column.is-8-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.66667%; } .column.is-offset-8-fullhd { margin-left: 66.66667%; } .column.is-9-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .column.is-offset-9-fullhd { margin-left: 75%; } .column.is-10-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 83.33333%; } .column.is-offset-10-fullhd { margin-left: 83.33333%; } .column.is-11-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 91.66667%; } .column.is-offset-11-fullhd { margin-left: 91.66667%; } .column.is-12-fullhd { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } .column.is-offset-12-fullhd { margin-left: 100%; } } .columns { margin-left: -0.75rem; margin-right: -0.75rem; margin-top: -0.75rem; } .columns:last-child { margin-bottom: -0.75rem; } .columns:not(:last-child) { margin-bottom: calc(1.5rem - 0.75rem); } .columns.is-centered { -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .columns.is-gapless { margin-left: 0; margin-right: 0; margin-top: 0; } .columns.is-gapless > .column { margin: 0; padding: 0 !important; } .columns.is-gapless:not(:last-child) { margin-bottom: 1.5rem; } .columns.is-gapless:last-child { margin-bottom: 0; } .columns.is-mobile { display: -webkit-box; display: -ms-flexbox; display: flex; } .columns.is-multiline { -ms-flex-wrap: wrap; flex-wrap: wrap; } .columns.is-vcentered { -webkit-box-align: center; -ms-flex-align: center; align-items: center; } @media screen and (min-width: 769px), print { .columns:not(.is-desktop) { display: -webkit-box; display: -ms-flexbox; display: flex; } } @media screen and (min-width: 1024px) { .columns.is-desktop { display: -webkit-box; display: -ms-flexbox; display: flex; } } .columns.is-variable { --columnGap: 0.75rem; margin-left: calc(-1 * var(--columnGap)); margin-right: calc(-1 * var(--columnGap)); } .columns.is-variable .column { padding-left: var(--columnGap); padding-right: var(--columnGap); } .columns.is-variable.is-0 { --columnGap: 0rem; } .columns.is-variable.is-1 { --columnGap: 0.25rem; } .columns.is-variable.is-2 { --columnGap: 0.5rem; } .columns.is-variable.is-3 { --columnGap: 0.75rem; } .columns.is-variable.is-4 { --columnGap: 1rem; } .columns.is-variable.is-5 { --columnGap: 1.25rem; } .columns.is-variable.is-6 { --columnGap: 1.5rem; } .columns.is-variable.is-7 { --columnGap: 1.75rem; } .columns.is-variable.is-8 { --columnGap: 2rem; } .tile { -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: block; -ms-flex-preferred-size: 0; flex-basis: 0; -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; min-height: -webkit-min-content; min-height: -moz-min-content; min-height: min-content; } .tile.is-ancestor { margin-left: -0.75rem; margin-right: -0.75rem; margin-top: -0.75rem; } .tile.is-ancestor:last-child { margin-bottom: -0.75rem; } .tile.is-ancestor:not(:last-child) { margin-bottom: 0.75rem; } .tile.is-child { margin: 0 !important; } .tile.is-parent { padding: 0.75rem; } .tile.is-vertical { -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; } .tile.is-vertical > .tile.is-child:not(:last-child) { margin-bottom: 1.5rem !important; } @media screen and (min-width: 769px), print { .tile:not(.is-child) { display: -webkit-box; display: -ms-flexbox; display: flex; } .tile.is-1 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 8.33333%; } .tile.is-2 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 16.66667%; } .tile.is-3 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 25%; } .tile.is-4 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 33.33333%; } .tile.is-5 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 41.66667%; } .tile.is-6 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 50%; } .tile.is-7 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 58.33333%; } .tile.is-8 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 66.66667%; } .tile.is-9 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 75%; } .tile.is-10 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 83.33333%; } .tile.is-11 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 91.66667%; } .tile.is-12 { -webkit-box-flex: 0; -ms-flex: none; flex: none; width: 100%; } } .hero { -webkit-box-align: stretch; -ms-flex-align: stretch; align-items: stretch; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; } .hero .navbar { background: none; } .hero .tabs ul { border-bottom: none; } .hero.is-white { background-color: white; color: #0a0a0a; } .hero.is-white a:not(.button), .hero.is-white strong { color: inherit; } .hero.is-white .title { color: #0a0a0a; } .hero.is-white .subtitle { color: rgba(10, 10, 10, 0.9); } .hero.is-white .subtitle a:not(.button), .hero.is-white .subtitle strong { color: #0a0a0a; } @media screen and (max-width: 1023px) { .hero.is-white .navbar-menu { background-color: white; } } .hero.is-white .navbar-item, .hero.is-white .navbar-link { color: rgba(10, 10, 10, 0.7); } .hero.is-white a.navbar-item:hover, .hero.is-white a.navbar-item.is-active, .hero.is-white .navbar-link:hover, .hero.is-white .navbar-link.is-active { background-color: #f2f2f2; color: #0a0a0a; } .hero.is-white .tabs a { color: #0a0a0a; opacity: 0.9; } .hero.is-white .tabs a:hover { opacity: 1; } .hero.is-white .tabs li.is-active a { opacity: 1; } .hero.is-white .tabs.is-boxed a, .hero.is-white .tabs.is-toggle a { color: #0a0a0a; } .hero.is-white .tabs.is-boxed a:hover, .hero.is-white .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } .hero.is-white .tabs.is-boxed li.is-active a, .hero.is-white .tabs.is-boxed li.is-active a:hover, .hero.is-white .tabs.is-toggle li.is-active a, .hero.is-white .tabs.is-toggle li.is-active a:hover { background-color: #0a0a0a; border-color: #0a0a0a; color: white; } .hero.is-white.is-bold { background-image: linear-gradient(141deg, #e6e6e6 0%, white 71%, white 100%); } @media screen and (max-width: 768px) { .hero.is-white.is-bold .navbar-menu { background-image: linear-gradient(141deg, #e6e6e6 0%, white 71%, white 100%); } } .hero.is-black { background-color: #0a0a0a; color: white; } .hero.is-black a:not(.button), .hero.is-black strong { color: inherit; } .hero.is-black .title { color: white; } .hero.is-black .subtitle { color: rgba(255, 255, 255, 0.9); } .hero.is-black .subtitle a:not(.button), .hero.is-black .subtitle strong { color: white; } @media screen and (max-width: 1023px) { .hero.is-black .navbar-menu { background-color: #0a0a0a; } } .hero.is-black .navbar-item, .hero.is-black .navbar-link { color: rgba(255, 255, 255, 0.7); } .hero.is-black a.navbar-item:hover, .hero.is-black a.navbar-item.is-active, .hero.is-black .navbar-link:hover, .hero.is-black .navbar-link.is-active { background-color: black; color: white; } .hero.is-black .tabs a { color: white; opacity: 0.9; } .hero.is-black .tabs a:hover { opacity: 1; } .hero.is-black .tabs li.is-active a { opacity: 1; } .hero.is-black .tabs.is-boxed a, .hero.is-black .tabs.is-toggle a { color: white; } .hero.is-black .tabs.is-boxed a:hover, .hero.is-black .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } .hero.is-black .tabs.is-boxed li.is-active a, .hero.is-black .tabs.is-boxed li.is-active a:hover, .hero.is-black .tabs.is-toggle li.is-active a, .hero.is-black .tabs.is-toggle li.is-active a:hover { background-color: white; border-color: white; color: #0a0a0a; } .hero.is-black.is-bold { background-image: linear-gradient(141deg, black 0%, #0a0a0a 71%, #181616 100%); } @media screen and (max-width: 768px) { .hero.is-black.is-bold .navbar-menu { background-image: linear-gradient(141deg, black 0%, #0a0a0a 71%, #181616 100%); } } .hero.is-light { background-color: whitesmoke; color: #363636; } .hero.is-light a:not(.button), .hero.is-light strong { color: inherit; } .hero.is-light .title { color: #363636; } .hero.is-light .subtitle { color: rgba(54, 54, 54, 0.9); } .hero.is-light .subtitle a:not(.button), .hero.is-light .subtitle strong { color: #363636; } @media screen and (max-width: 1023px) { .hero.is-light .navbar-menu { background-color: whitesmoke; } } .hero.is-light .navbar-item, .hero.is-light .navbar-link { color: rgba(54, 54, 54, 0.7); } .hero.is-light a.navbar-item:hover, .hero.is-light a.navbar-item.is-active, .hero.is-light .navbar-link:hover, .hero.is-light .navbar-link.is-active { background-color: #e8e8e8; color: #363636; } .hero.is-light .tabs a { color: #363636; opacity: 0.9; } .hero.is-light .tabs a:hover { opacity: 1; } .hero.is-light .tabs li.is-active a { opacity: 1; } .hero.is-light .tabs.is-boxed a, .hero.is-light .tabs.is-toggle a { color: #363636; } .hero.is-light .tabs.is-boxed a:hover, .hero.is-light .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } .hero.is-light .tabs.is-boxed li.is-active a, .hero.is-light .tabs.is-boxed li.is-active a:hover, .hero.is-light .tabs.is-toggle li.is-active a, .hero.is-light .tabs.is-toggle li.is-active a:hover { background-color: #363636; border-color: #363636; color: whitesmoke; } .hero.is-light.is-bold { background-image: linear-gradient(141deg, #dfd8d9 0%, whitesmoke 71%, white 100%); } @media screen and (max-width: 768px) { .hero.is-light.is-bold .navbar-menu { background-image: linear-gradient(141deg, #dfd8d9 0%, whitesmoke 71%, white 100%); } } .hero.is-dark { background-color: #363636; color: whitesmoke; } .hero.is-dark a:not(.button), .hero.is-dark strong { color: inherit; } .hero.is-dark .title { color: whitesmoke; } .hero.is-dark .subtitle { color: rgba(245, 245, 245, 0.9); } .hero.is-dark .subtitle a:not(.button), .hero.is-dark .subtitle strong { color: whitesmoke; } @media screen and (max-width: 1023px) { .hero.is-dark .navbar-menu { background-color: #363636; } } .hero.is-dark .navbar-item, .hero.is-dark .navbar-link { color: rgba(245, 245, 245, 0.7); } .hero.is-dark a.navbar-item:hover, .hero.is-dark a.navbar-item.is-active, .hero.is-dark .navbar-link:hover, .hero.is-dark .navbar-link.is-active { background-color: #292929; color: whitesmoke; } .hero.is-dark .tabs a { color: whitesmoke; opacity: 0.9; } .hero.is-dark .tabs a:hover { opacity: 1; } .hero.is-dark .tabs li.is-active a { opacity: 1; } .hero.is-dark .tabs.is-boxed a, .hero.is-dark .tabs.is-toggle a { color: whitesmoke; } .hero.is-dark .tabs.is-boxed a:hover, .hero.is-dark .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } .hero.is-dark .tabs.is-boxed li.is-active a, .hero.is-dark .tabs.is-boxed li.is-active a:hover, .hero.is-dark .tabs.is-toggle li.is-active a, .hero.is-dark .tabs.is-toggle li.is-active a:hover { background-color: whitesmoke; border-color: whitesmoke; color: #363636; } .hero.is-dark.is-bold { background-image: linear-gradient(141deg, #1f191a 0%, #363636 71%, #46403f 100%); } @media screen and (max-width: 768px) { .hero.is-dark.is-bold .navbar-menu { background-image: linear-gradient(141deg, #1f191a 0%, #363636 71%, #46403f 100%); } } .hero.is-primary { background-color: #00d1b2; color: #fff; } .hero.is-primary a:not(.button), .hero.is-primary strong { color: inherit; } .hero.is-primary .title { color: #fff; } .hero.is-primary .subtitle { color: rgba(255, 255, 255, 0.9); } .hero.is-primary .subtitle a:not(.button), .hero.is-primary .subtitle strong { color: #fff; } @media screen and (max-width: 1023px) { .hero.is-primary .navbar-menu { background-color: #00d1b2; } } .hero.is-primary .navbar-item, .hero.is-primary .navbar-link { color: rgba(255, 255, 255, 0.7); } .hero.is-primary a.navbar-item:hover, .hero.is-primary a.navbar-item.is-active, .hero.is-primary .navbar-link:hover, .hero.is-primary .navbar-link.is-active { background-color: #00b89c; color: #fff; } .hero.is-primary .tabs a { color: #fff; opacity: 0.9; } .hero.is-primary .tabs a:hover { opacity: 1; } .hero.is-primary .tabs li.is-active a { opacity: 1; } .hero.is-primary .tabs.is-boxed a, .hero.is-primary .tabs.is-toggle a { color: #fff; } .hero.is-primary .tabs.is-boxed a:hover, .hero.is-primary .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } .hero.is-primary .tabs.is-boxed li.is-active a, .hero.is-primary .tabs.is-boxed li.is-active a:hover, .hero.is-primary .tabs.is-toggle li.is-active a, .hero.is-primary .tabs.is-toggle li.is-active a:hover { background-color: #fff; border-color: #fff; color: #00d1b2; } .hero.is-primary.is-bold { background-image: linear-gradient(141deg, #009e6c 0%, #00d1b2 71%, #00e7eb 100%); } @media screen and (max-width: 768px) { .hero.is-primary.is-bold .navbar-menu { background-image: linear-gradient(141deg, #009e6c 0%, #00d1b2 71%, #00e7eb 100%); } } .hero.is-link { background-color: #7a91c1; color: #fff; } .hero.is-link a:not(.button), .hero.is-link strong { color: inherit; } .hero.is-link .title { color: #fff; } .hero.is-link .subtitle { color: rgba(255, 255, 255, 0.9); } .hero.is-link .subtitle a:not(.button), .hero.is-link .subtitle strong { color: #fff; } @media screen and (max-width: 1023px) { .hero.is-link .navbar-menu { background-color: #7a91c1; } } .hero.is-link .navbar-item, .hero.is-link .navbar-link { color: rgba(255, 255, 255, 0.7); } .hero.is-link a.navbar-item:hover, .hero.is-link a.navbar-item.is-active, .hero.is-link .navbar-link:hover, .hero.is-link .navbar-link.is-active { background-color: #2366d1; color: #fff; } .hero.is-link .tabs a { color: #fff; opacity: 0.9; } .hero.is-link .tabs a:hover { opacity: 1; } .hero.is-link .tabs li.is-active a { opacity: 1; } .hero.is-link .tabs.is-boxed a, .hero.is-link .tabs.is-toggle a { color: #fff; } .hero.is-link .tabs.is-boxed a:hover, .hero.is-link .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } .hero.is-link .tabs.is-boxed li.is-active a, .hero.is-link .tabs.is-boxed li.is-active a:hover, .hero.is-link .tabs.is-toggle li.is-active a, .hero.is-link .tabs.is-toggle li.is-active a:hover { background-color: #fff; border-color: #fff; color: #7a91c1; } .hero.is-link.is-bold { background-image: linear-gradient(141deg, #1577c6 0%, #7a91c1 71%, #4366e5 100%); } @media screen and (max-width: 768px) { .hero.is-link.is-bold .navbar-menu { background-image: linear-gradient(141deg, #1577c6 0%, #7a91c1 71%, #4366e5 100%); } } .hero.is-info { background-color: #209cee; color: #fff; } .hero.is-info a:not(.button), .hero.is-info strong { color: inherit; } .hero.is-info .title { color: #fff; } .hero.is-info .subtitle { color: rgba(255, 255, 255, 0.9); } .hero.is-info .subtitle a:not(.button), .hero.is-info .subtitle strong { color: #fff; } @media screen and (max-width: 1023px) { .hero.is-info .navbar-menu { background-color: #209cee; } } .hero.is-info .navbar-item, .hero.is-info .navbar-link { color: rgba(255, 255, 255, 0.7); } .hero.is-info a.navbar-item:hover, .hero.is-info a.navbar-item.is-active, .hero.is-info .navbar-link:hover, .hero.is-info .navbar-link.is-active { background-color: #118fe4; color: #fff; } .hero.is-info .tabs a { color: #fff; opacity: 0.9; } .hero.is-info .tabs a:hover { opacity: 1; } .hero.is-info .tabs li.is-active a { opacity: 1; } .hero.is-info .tabs.is-boxed a, .hero.is-info .tabs.is-toggle a { color: #fff; } .hero.is-info .tabs.is-boxed a:hover, .hero.is-info .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } .hero.is-info .tabs.is-boxed li.is-active a, .hero.is-info .tabs.is-boxed li.is-active a:hover, .hero.is-info .tabs.is-toggle li.is-active a, .hero.is-info .tabs.is-toggle li.is-active a:hover { background-color: #fff; border-color: #fff; color: #209cee; } .hero.is-info.is-bold { background-image: linear-gradient(141deg, #04a6d7 0%, #209cee 71%, #3287f5 100%); } @media screen and (max-width: 768px) { .hero.is-info.is-bold .navbar-menu { background-image: linear-gradient(141deg, #04a6d7 0%, #209cee 71%, #3287f5 100%); } } .hero.is-success { background-color: #23d160; color: #fff; } .hero.is-success a:not(.button), .hero.is-success strong { color: inherit; } .hero.is-success .title { color: #fff; } .hero.is-success .subtitle { color: rgba(255, 255, 255, 0.9); } .hero.is-success .subtitle a:not(.button), .hero.is-success .subtitle strong { color: #fff; } @media screen and (max-width: 1023px) { .hero.is-success .navbar-menu { background-color: #23d160; } } .hero.is-success .navbar-item, .hero.is-success .navbar-link { color: rgba(255, 255, 255, 0.7); } .hero.is-success a.navbar-item:hover, .hero.is-success a.navbar-item.is-active, .hero.is-success .navbar-link:hover, .hero.is-success .navbar-link.is-active { background-color: #20bc56; color: #fff; } .hero.is-success .tabs a { color: #fff; opacity: 0.9; } .hero.is-success .tabs a:hover { opacity: 1; } .hero.is-success .tabs li.is-active a { opacity: 1; } .hero.is-success .tabs.is-boxed a, .hero.is-success .tabs.is-toggle a { color: #fff; } .hero.is-success .tabs.is-boxed a:hover, .hero.is-success .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } .hero.is-success .tabs.is-boxed li.is-active a, .hero.is-success .tabs.is-boxed li.is-active a:hover, .hero.is-success .tabs.is-toggle li.is-active a, .hero.is-success .tabs.is-toggle li.is-active a:hover { background-color: #fff; border-color: #fff; color: #23d160; } .hero.is-success.is-bold { background-image: linear-gradient(141deg, #12af2f 0%, #23d160 71%, #2ce28a 100%); } @media screen and (max-width: 768px) { .hero.is-success.is-bold .navbar-menu { background-image: linear-gradient(141deg, #12af2f 0%, #23d160 71%, #2ce28a 100%); } } .hero.is-warning { background-color: #ffdd57; color: rgba(0, 0, 0, 0.7); } .hero.is-warning a:not(.button), .hero.is-warning strong { color: inherit; } .hero.is-warning .title { color: rgba(0, 0, 0, 0.7); } .hero.is-warning .subtitle { color: rgba(0, 0, 0, 0.9); } .hero.is-warning .subtitle a:not(.button), .hero.is-warning .subtitle strong { color: rgba(0, 0, 0, 0.7); } @media screen and (max-width: 1023px) { .hero.is-warning .navbar-menu { background-color: #ffdd57; } } .hero.is-warning .navbar-item, .hero.is-warning .navbar-link { color: rgba(0, 0, 0, 0.7); } .hero.is-warning a.navbar-item:hover, .hero.is-warning a.navbar-item.is-active, .hero.is-warning .navbar-link:hover, .hero.is-warning .navbar-link.is-active { background-color: #ffd83d; color: rgba(0, 0, 0, 0.7); } .hero.is-warning .tabs a { color: rgba(0, 0, 0, 0.7); opacity: 0.9; } .hero.is-warning .tabs a:hover { opacity: 1; } .hero.is-warning .tabs li.is-active a { opacity: 1; } .hero.is-warning .tabs.is-boxed a, .hero.is-warning .tabs.is-toggle a { color: rgba(0, 0, 0, 0.7); } .hero.is-warning .tabs.is-boxed a:hover, .hero.is-warning .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } .hero.is-warning .tabs.is-boxed li.is-active a, .hero.is-warning .tabs.is-boxed li.is-active a:hover, .hero.is-warning .tabs.is-toggle li.is-active a, .hero.is-warning .tabs.is-toggle li.is-active a:hover { background-color: rgba(0, 0, 0, 0.7); border-color: rgba(0, 0, 0, 0.7); color: #ffdd57; } .hero.is-warning.is-bold { background-image: linear-gradient(141deg, #ffaf24 0%, #ffdd57 71%, #fffa70 100%); } @media screen and (max-width: 768px) { .hero.is-warning.is-bold .navbar-menu { background-image: linear-gradient(141deg, #ffaf24 0%, #ffdd57 71%, #fffa70 100%); } } .hero.is-danger { background-color: #ff3860; color: #fff; } .hero.is-danger a:not(.button), .hero.is-danger strong { color: inherit; } .hero.is-danger .title { color: #fff; } .hero.is-danger .subtitle { color: rgba(255, 255, 255, 0.9); } .hero.is-danger .subtitle a:not(.button), .hero.is-danger .subtitle strong { color: #fff; } @media screen and (max-width: 1023px) { .hero.is-danger .navbar-menu { background-color: #ff3860; } } .hero.is-danger .navbar-item, .hero.is-danger .navbar-link { color: rgba(255, 255, 255, 0.7); } .hero.is-danger a.navbar-item:hover, .hero.is-danger a.navbar-item.is-active, .hero.is-danger .navbar-link:hover, .hero.is-danger .navbar-link.is-active { background-color: #ff1f4b; color: #fff; } .hero.is-danger .tabs a { color: #fff; opacity: 0.9; } .hero.is-danger .tabs a:hover { opacity: 1; } .hero.is-danger .tabs li.is-active a { opacity: 1; } .hero.is-danger .tabs.is-boxed a, .hero.is-danger .tabs.is-toggle a { color: #fff; } .hero.is-danger .tabs.is-boxed a:hover, .hero.is-danger .tabs.is-toggle a:hover { background-color: rgba(10, 10, 10, 0.1); } .hero.is-danger .tabs.is-boxed li.is-active a, .hero.is-danger .tabs.is-boxed li.is-active a:hover, .hero.is-danger .tabs.is-toggle li.is-active a, .hero.is-danger .tabs.is-toggle li.is-active a:hover { background-color: #fff; border-color: #fff; color: #ff3860; } .hero.is-danger.is-bold { background-image: linear-gradient(141deg, #ff0561 0%, #ff3860 71%, #ff5257 100%); } @media screen and (max-width: 768px) { .hero.is-danger.is-bold .navbar-menu { background-image: linear-gradient(141deg, #ff0561 0%, #ff3860 71%, #ff5257 100%); } } .hero.is-small .hero-body { padding-bottom: 1.5rem; padding-top: 1.5rem; } @media screen and (min-width: 769px), print { .hero.is-medium .hero-body { padding-bottom: 9rem; padding-top: 9rem; } } @media screen and (min-width: 769px), print { .hero.is-large .hero-body { padding-bottom: 18rem; padding-top: 18rem; } } .hero.is-halfheight .hero-body, .hero.is-fullheight .hero-body { -webkit-box-align: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -ms-flexbox; display: flex; } .hero.is-halfheight .hero-body > .container, .hero.is-fullheight .hero-body > .container { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 1; flex-shrink: 1; } .hero.is-halfheight { min-height: 50vh; } .hero.is-fullheight { min-height: 100vh; } .hero-video { bottom: 0; left: 0; position: absolute; right: 0; top: 0; overflow: hidden; } .hero-video video { left: 50%; min-height: 100%; min-width: 100%; position: absolute; top: 50%; -webkit-transform: translate3d(-50%, -50%, 0); transform: translate3d(-50%, -50%, 0); } .hero-video.is-transparent { opacity: 0.3; } @media screen and (max-width: 768px) { .hero-video { display: none; } } .hero-buttons { margin-top: 1.5rem; } @media screen and (max-width: 768px) { .hero-buttons .button { display: -webkit-box; display: -ms-flexbox; display: flex; } .hero-buttons .button:not(:last-child) { margin-bottom: 0.75rem; } } @media screen and (min-width: 769px), print { .hero-buttons { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; } .hero-buttons .button:not(:last-child) { margin-right: 1.5rem; } } .hero-head, .hero-foot { -webkit-box-flex: 0; -ms-flex-positive: 0; flex-grow: 0; -ms-flex-negative: 0; flex-shrink: 0; } .hero-body { -webkit-box-flex: 1; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-negative: 0; flex-shrink: 0; padding: 3rem 1.5rem; } .section { padding: 1.5rem 1.5rem; } @media screen and (min-width: 1024px) { .section.is-small { padding: 1.5rem 1.5rem; } .section.is-medium { padding: 9rem 1.5rem; } .section.is-large { padding: 18rem 1.5rem; } } .footer { background-color: whitesmoke; padding: 3rem 1.5rem 6rem; } /*# sourceMappingURL=bulma.css.map */ ================================================ FILE: www/themes/mosquitto/assets/css/local.css ================================================ .title { color: #363636; font-size: 2rem; font-weight: 300; line-height: 1.125; } finalfooter { display: block; } .finalfooter { background-color: black; color: whitesmoke; padding: 1rem 1.5rem 1rem; margin-top: 1rem; } div.footerlink a { color: whitesmoke; cursor: pointer; text-decoration: none; -webkit-transition: none 86ms ease-out; transition: none 86ms ease-out; padding-right: 1.5rem; } div.footerlink a:hover { color: gray; } .footer { background-color: whitesmoke; padding: 2rem 1.5rem 1rem; } .column-justify { text-align: justify; } .column-justify h1 { text-align: center; } img.center { display: block; margin-left: auto; margin-right: auto; } /* Blog */ h1.p-name, .authorpage h1, .tagpage h1 /* Tag page */{ font-size: 36px; margin-top: 20px; margin-bottom: 10px; } .e-content.entry-content h2 { font-size: 150%; } div.e-content { margin-top: 14px; } div.e-content.entry-content p, div.e-content.entry-content div p, div.e-content.entry-content div { margin-bottom: 10px; } div.e-content.entry-content ul { padding-left: 40px; margin-bottom: 10px; } div.e-content.entry-content ul li { list-style-type: disc; } div.e-content.entry-content div blockquote { background-color: whitesmoke; padding: 1.5rem; margin: 0.5rem; } .pager::before, .pager::after { clear: both; display: table; content: " "; } .pager .previous a { float: left; } .pager .next a { float: right; } .pager li { display: inline; } .pager li a { display: inline-block; padding: 5px 14px; border: 1px solid #ddd; border-radius: 15px; } .dateline { margin-top: -1rem; } /* Tag Page */ .listdate { margin-right: 3rem; } ================================================ FILE: www/themes/mosquitto/assets/css/man.css ================================================ /* DocBook Man Page */ .refentry { } .refsynopsisdiv h3 { font-size: 1.5rem; font-weight: 350; line-height: 1.125; margin-top: 1rem; margin-bottom: 0.5rem; } .refnamediv h3 { font-size: 1.5rem; font-weight: 350; line-height: 1.125; } .refnamediv p { } .refsect1 { } .refsect1 h3 { margin-top: 1rem; margin-bottom: 0.5rem; font-weight: 350; font-size: 1.5rem; } .refsect1 p { margin-top: 1rem; } .refsect2 { } .refsect2 h4 { font-size: 1.25rem; line-height: 1.5; margin-top: 1rem; margin-bottom: 1rem; } .note h4 { font-size: 1.25rem; line-height: 1.5; margin-top: 1rem; margin-bottom: 0; } .note { margin-top: 1rem; } .funcsynopsis { } .funcprototype-table { } .funcdef { color: #d73a49; } .funcprototype-table tr td { font-size: 12px; color: #d73a49; background-color: whitesmoke; font-family: monospace; } .fsfunc { font-size: 12px; color: #6f42c1; font-weight: normal; } .pdparam { font-size: 12px; color: black; } .email { color: black; background-color: inherit; } .command { color: black; } .uri, .literal { background-color: inherit; color: inherit; } .filename { color: inherit; } .option { font-family: monospace; color: inherit; } .listitem { margin: 1rem 0 1rem 2rem; } dl.variablelist dt { margin-top: 1rem; } dl.variablelist dd { margin-left: 1rem; } .term { background-color: whitesmoke; font-size: 0.875rem; padding: 0.25em 0.5em 0.25em 0; } .term .option, dd p .code, .cmdsynopsis, .cmdsynopsis p .command, .cmdsynopsis p .option, .replaceable code { font-family: monospace; background-color: whitesmoke; color: black; font-size: 0.875rem; } .cmdsynopsis { padding-top: 0.25rem; padding-bottom: 0.25rem; text-indent: -2rem; padding-left: 2rem; } .informaltable { padding: 0.5rem; } .informaltable thead tr th, .informaltable tbody tr td{ padding: 0.5rem; } .itemizedlist .listitem p { display: inline-block; padding: 0.25rem; background-color: whitesmoke; font-family: monospace; font-size: 0.875rem; list-style-type: none; margin-top: 0; margin-bottom: 0.5rem; } .itemizedlist .listitem, li.listitem { margin-top: 0; margin-bottom: 0; list-style-type: none; } div.itemizedlist, ul.itemizedlist { margin-top: 0; margin-bottom: 1rem; } ================================================ FILE: www/themes/mosquitto/engine ================================================ mako ================================================ FILE: www/themes/mosquitto/parent ================================================ base ================================================ FILE: www/themes/mosquitto/templates/base.tmpl ================================================ ## -*- coding: utf-8 -*- <%namespace name="base" file="base_helper.tmpl" import="*"/> <%namespace name="header" file="base_header.tmpl" import="*"/> <%namespace name="footer" file="base_footer.tmpl" import="*"/> ${set_locale(lang)} ${base.html_headstart()} <%block name="extra_head"> ### Leave this block alone. ${template_hooks['extra_head']()} ${header.html_header()}
<%block name="content">
${footer.html_footer()} ${base.late_load_js()} <%block name="extra_js"> ${body_end} ${template_hooks['body_end']()} ================================================ FILE: www/themes/mosquitto/templates/base_footer.tmpl ================================================ ## -*- coding: utf-8 -*- <%namespace name="base" file="base_helper.tmpl" import="*"/> <%def name="html_footer()"> %if content_footer: %endif ================================================ FILE: www/themes/mosquitto/templates/base_header.tmpl ================================================ ## -*- coding: utf-8 -*- <%namespace name="base" file="base_helper.tmpl" import="*"/> <%def name="html_header()"> ${template_hooks['page_header']()} <%def name="html_site_title()"> % if (post and post.title):
% if title == blog_title:

Eclipse Mosquitto™

An open source MQTT broker

% elif post and post.title:

${post.title()|h}

% endif

% endif <%def name="html_navigation_links()">

<%def name="html_translation_header()"> %if len(translations) > 1:

${messages("Languages:")}

${base.html_translations()}
%endif ================================================ FILE: www/themes/mosquitto/templates/base_helper.tmpl ================================================ ## -*- coding: utf-8 -*- <%def name="html_headstart()"> % if use_base_tag: % endif %if description: %endif %if title == blog_title: ${blog_title|h} %else: ${title|h} | ${blog_title|h} %endif ${html_stylesheets()} % if meta_generator_tag: % endif ${html_feedlinks()} %if favicons: %for name, file, size in favicons: %endfor %endif % if comment_system == 'facebook': % endif %if prevlink: %endif %if nextlink: %endif %if use_cdn: %else: %endif ${extra_head_data} <%def name="late_load_js()"> ${social_buttons_code} <%def name="html_stylesheets()"> %if use_bundles: %if use_cdn: %else: %endif %else: %if has_custom_css: %endif %endif % if needs_ipython_css: % endif <%def name="html_feedlinks()"> %if rss_link: ${rss_link} %elif generate_rss: %if len(translations) > 1: %for language in sorted(translations): %endfor %else: %endif %endif %if generate_atom: %if len(translations) > 1: %for language in sorted(translations): %endfor %else: %endif %endif <%def name="html_translations()"> ================================================ FILE: www/themes/mosquitto/templates/index.tmpl ================================================ ## -*- coding: utf-8 -*- <%namespace name="helper" file="index_helper.tmpl"/> <%namespace name="math" file="math_helper.tmpl"/> <%namespace name="comments" file="comments_helper.tmpl"/> <%namespace name="pagination" file="pagination_helper.tmpl"/> <%inherit file="base.tmpl"/> <%block name="extra_head"> ${parent.extra_head()} % if posts and (permalink == '/' or permalink == '/' + index_file): % endif ${math.math_styles_ifposts(posts)} <%block name="content"> <%block name="content_header"> % if 'main_index' in pagekind: ${front_index_header} % endif % if page_links: ${pagination.page_navigation(current_page, page_links, prevlink, nextlink, prev_next_links_reversed)} % endif
% for post in posts:

${post.title()|h}

%if index_teasers:
${post.text(teaser_only=True)} %else:
${post.text(teaser_only=False)} %endif

% endfor
${helper.html_pager()} ${comments.comment_link_script()} ================================================ FILE: www/themes/mosquitto/templates/post.tmpl ================================================ ## -*- coding: utf-8 -*- <%namespace name="helper" file="post_helper.tmpl"/> <%namespace name="pheader" file="post_header.tmpl"/> <%namespace name="comments" file="comments_helper.tmpl"/> <%namespace name="math" file="math_helper.tmpl"/> <%inherit file="base.tmpl"/> <%block name="extra_head"> ${parent.extra_head()} % if post.meta('keywords'): % endif ## %if post.prev_post: %endif %if post.next_post: %endif % if post.is_draft: % endif ${helper.open_graph_metadata(post)} ${helper.twitter_card_information(post)} ${helper.meta_translations(post)} ${math.math_styles_ifpost(post)} <%block name="content">
${pheader.html_post_header()}
${post.text()}
% if not post.meta('nocomments') and site_has_comments:

${messages("Comments")}

${comments.comment_form(post.permalink(absolute=True), post.title(), post._base_path)}
% endif ${math.math_scripts_ifpost(post)}
${comments.comment_link_script()} ================================================ FILE: www/themes/mosquitto/templates/post_header.tmpl ================================================ ## -*- coding: utf-8 -*- <%namespace name="helper" file="post_helper.tmpl"/> <%namespace name="comments" file="comments_helper.tmpl"/> <%def name="html_title()"> %if title and not post.meta('hidetitle'):

${post.title()|h}

%endif <%def name="html_translations(post)"> % if len(post.translated_to) > 1: % endif <%def name="html_sourcelink()"> % if show_sourcelink:

${messages("Source")}

% endif <%def name="html_post_header()">
##${html_title()} ${html_translations(post)}
================================================ FILE: www/themes/mosquitto/templates/story.tmpl ================================================ ## -*- coding: utf-8 -*- <%namespace name="helper" file="post_helper.tmpl"/> <%namespace name="pheader" file="post_header.tmpl"/> <%namespace name="comments" file="comments_helper.tmpl"/> <%namespace name="math" file="math_helper.tmpl"/> <%inherit file="post.tmpl"/> <%block name="content">
###${pheader.html_title()} ${pheader.html_translations(post)}
${post.text()}
%if site_has_comments and enable_comments and not post.meta('nocomments'):

${messages("Comments")}

${comments.comment_form(post.permalink(absolute=True), post.title(), post.base_path)}
%endif ${math.math_scripts_ifpost(post)}