How to setup everything to run a lua function in command line

so I have been looking at this thread for a bit Get the list of rooms - #52 by tmaass and I want to be able to do what is done here but every time I follow this I am unable to produce anything from the curl command. I don’t really understand if there is something I am over looking or need to set up in addition on my end, but it would be appreciated if someone can guide me to which files and settings I should look into to do this properly

Have you checked for errors in the prosody log?

portmanager     error   Error binding encrypted port for https: No certificate present in SSL/TLS configuration for https port 5281

Nope, that you can ignore. Something while executing the curl or what is the response …

HTTP/1.1 404 Not Found
Content-Length: 453
Connection: Keep-Alive
Date: Fri, 30 Sep 2022 15:02:39 GMT
Content-Type: text/html; charset=utf-8

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>404 Not Found</title>
<style>
body{
        margin-top:14%;
        text-align:center;
        background-color:#F8F8F8;
        font-family:sans-serif;
}
h1{
        font-size:xx-large;
}
p{
        font-size:x-large;
}
p+p {
        font-size:large;
        font-family:courier;
}
</style>
</head>
<body>
<h1>404 Not Found</h1>
<p>Whatever you were looking for is not here. Where did you put it?</p>
<p>Unknown host: localhost</p>
</body>
</html>

this is what was produced when I ran

curl 'http://localhost:5280/all-rooms?domain=conference.mydomain.com' -i

How did you enable your plugin in prosody config?

I believe it will only work for curl http://localhost:5280/.... if you enable the module under VirtualHost "localhost" or globally.

Or you could specify the host header with curl to match the virtual host you installed the module under, e.g.

curl --header 'Host: meet.mydomain.com' http://localhost:5280/all-rooms?...
-- Prosody Example Configuration File
--
-- Information on configuring Prosody can be found on our
-- website at https://prosody.im/doc/configure
--
-- Tip: You can check that the syntax of this file is correct
-- when you have finished by running this command:
--     prosodyctl check config
-- If there are any errors, it will let you know what and where
-- they are, otherwise it will keep quiet.
--
-- The only thing left to do is rename this file to remove the .dist ending, and fill in the
-- blanks. Good luck, and happy Jabbering!


---------- Server-wide settings ----------
-- Settings in this section apply to the whole server and are the default settings
-- for any virtual hosts

-- This is a (by default, empty) list of accounts that are admins
-- for the server. Note that you must create the accounts separately
-- (see https://prosody.im/doc/creating_accounts for info)
-- Example: admins = { "user1@example.com", "user2@example.net" }
admins = { }

-- Enable use of libevent for better performance under high load
-- For more information see: https://prosody.im/doc/libevent
--use_libevent = true

-- Prosody will always look in its source directory for modules, but
-- this option allows you to specify additional locations where Prosody
-- will look for modules first. For community modules, see https://modules.prosody.im/
-- For a local administrator it's common to place local modifications
-- under /usr/local/ hierarchy:
-- plugin_paths = { "/var//jitsi-meet/resources/prosody-plugins/" }

-- This is the list of modules Prosody will load on startup.
-- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too.
-- Documentation for bundled modules can be found at: https://prosody.im/doc/modules
modules_enabled = {

        -- Generally required
                "roster"; -- Allow users to have a roster. Recommended ;)
                "saslauth"; -- Authentication for clients and servers. Recommended if you want to log in.
                "tls"; -- Add support for secure TLS on c2s/s2s connections
                "dialback"; -- s2s dialback support
                "disco"; -- Service discovery

        -- Not essential, but recommended
                "carbons"; -- Keep multiple clients in sync
                "pep"; -- Enables users to publish their avatar, mood, activity, playing music and more
                "private"; -- Private XML storage (for room bookmarks, etc.)
                "blocklist"; -- Allow users to block communications with other users
                "vcard4"; -- User profiles (stored in PEP)
                "vcard_legacy"; -- Conversion between legacy vCard and PEP Avatar, vcard
                "limits"; -- Enable bandwidth for XMPP connections

        -- Nice to have
                "version"; -- Replies to server version requests
                "uptime"; -- Report how long server has been running
                "time"; -- Let others know the time here on this server
                "ping"; -- Replies to XMPP pings with pongs
                "register"; -- Allow users to register on this server using a client and change passwords
                --"mam"; -- Store messages in an archive and allow users to access it
                --"csi_simple"; -- Simple Mobile optimizations

        -- Admin interfaces
                "admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands
                --"admin_telnet"; -- Opens telnet console interface on localhost port 5582

        -- HTTP modules
                --"bosh"; -- Enable BOSH clients, aka "Jabber over HTTP"
                --"websocket"; -- XMPP over WebSockets
                --"http_files"; -- Serve static files from a directory over HTTP

        -- Other specific functionality
                "posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
                --"limits"; -- Enable bandwidth limiting for XMPP connections
                --"groups"; -- Shared roster support
                --"server_contact_info"; -- Publish contact information for this service
                --"announce"; -- Send announcement to all online users
                --"welcome"; -- Welcome users who register accounts
                --"watchregistrations"; -- Alert admins of registrations
                --"motd"; -- Send a message to users when they log in
                --"legacyauth"; -- Legacy authentication. Only used by some old clients and bots.
                --"proxy65"; -- Enables a file transfer proxy service which clients behind NAT can use
}

-- These modules are auto-loaded, but should you want
-- to disable them then uncomment them here:
modules_disabled = {
        -- "offline"; -- Store offline messages
        -- "c2s"; -- Handle client connections
        -- "s2s"; -- Handle server-to-server connections
}

-- Disable account creation by default, for security
-- For more information see https://prosody.im/doc/creating_accounts
allow_registration = false

-- Debian:
--   Do not send the server to background, either systemd or start-stop-daemon take care of that.
--
daemonize = false;

-- Debian:
--   Please, don't change this option since /run/prosody/
--   is one of the few directories Prosody is allowed to write to
--
pidfile = "/run/prosody/prosody.pid";

-- Force clients to use encrypted connections? This option will
-- prevent clients from authenticating unless they are using encryption.

c2s_require_encryption = true

-- Force servers to use encrypted connections? This option will
-- prevent servers from authenticating unless they are using encryption.

s2s_require_encryption = true

-- Force certificate authentication for server-to-server connections?

s2s_secure_auth = false

-- Some servers have invalid or self-signed certificates. You can list
-- remote domains here that will not be required to authenticate using
-- certificates. They will be authenticated using DNS instead, even
-- when s2s_secure_auth is enabled.

--s2s_insecure_domains = { "insecure.example" }

-- Even if you disable s2s_secure_auth, you can still require valid
-- certificates for some domains by specifying a list here.

--s2s_secure_domains = { "jabber.org" }

-- Select the authentication backend to use. The 'internal' providers
-- use Prosody's configured data storage to store the authentication data.

authentication = "internal_hashed"

-- Select the storage backend to use. By default Prosody uses flat files
-- in its configured data directory, but it also supports more backends
-- through modules. An "sql" backend is included by default, but requires
-- additional dependencies. See https://prosody.im/doc/storage for more info.

--storage = "sql" -- Default is "internal" (Debian: "sql" requires one of the
-- lua-dbi-sqlite3, lua-dbi-mysql or lua-dbi-postgresql packages to work)

-- For the "sql" backend, you can uncomment *one* of the below to configure:
--sql = { driver = "SQLite3", database = "prosody.sqlite" } -- Default. 'database' is the filename.
--sql = { driver = "MySQL", database = "wordpress", username = "newuser", password = "password", host = "localhost" }
--sql = { driver = "PostgreSQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
--sql_manage_tables = true
--default_storage = "internal"
--storage = {
--      accounts = "sql";
--}

-- Archiving configuration
-- If mod_mam is enabled, Prosody will store a copy of every message. This
-- is used to synchronize conversations between multiple clients, even if
-- they are offline. This setting controls how long Prosody will keep
-- messages in the archive before removing them.

archive_expires_after = "1w" -- Remove archived messages after 1 week

-- You can also configure messages to be stored in-memory only. For more
-- archiving options, see https://prosody.im/doc/modules/mod_mam

-- Logging configuration
-- For advanced logging see https://prosody.im/doc/logging
--
-- Debian:
--  Logs info and higher to /var/log
--  Logs errors to syslog also
log = {
        -- Log files (change 'info' to 'debug' for debug logs):
        info = "/var/log/prosody/prosody.log";
        error = "/var/log/prosody/prosody.err";
        -- Syslog:
        { levels = { "error" }; to = "syslog";  };
}

-- Uncomment to enable statistics
-- For more info see https://prosody.im/doc/statistics
-- statistics = "internal"

-- Certificates
-- Every virtual host and component needs a certificate so that clients and
-- servers can securely verify its identity. Prosody will automatically load
-- certificates/keys from the directory specified here.
-- For more information, including how to use 'prosodyctl' to auto-import certificates
-- (from e.g. Let's Encrypt) see https://prosody.im/doc/certificates

-- Location of directory to find certificates in (relative to main config file):
certificates = "certs"

-- HTTPS currently only supports a single certificate, specify it here:
--https_certificate = "/etc/prosody/certs/localhost.crt"

----------- Virtual hosts -----------
-- You need to add a VirtualHost entry for each domain you wish Prosody to serve.
-- Settings under each VirtualHost entry apply *only* to that host.
-- It's customary to maintain VirtualHost entries in separate config files
-- under /etc/prosody/conf.d/ directory. Examples of such config files can
-- be found in /etc/prosody/conf.avail/ directory.

------ Additional config files ------
-- For organizational purposes you may prefer to add VirtualHost and
-- Component definitions in their own config files. This line includes
-- all config files in /etc/prosody/conf.d/

VirtualHost "localhost"

--VirtualHost "example.com"
--      certificate = "/path/to/example.crt"

------ Components ------
-- You can specify components to add hosts that provide special services,
-- like multi-user conferences, and transports.
-- For more information on components, see https://prosody.im/doc/components

---Set up a MUC (multi-user chat) room server on conference.example.com:
--Component "conference.example.com" "muc"
--- Store MUC messages in an archive and allow users to access it
--modules_enabled = { "muc_mam" }

---Set up an external component (default component port is 5347)
--
-- External components allow adding various services, such as gateways/
-- transports to other networks like ICQ, MSN and Yahoo. For more info
-- see: https://prosody.im/doc/components#adding_an_external_component
--
--Component "gateway.example.com"
--      component_secret = "password"
Include "conf.d/*.cfg.lua"

this is my prosody.cfg.lua file
so in the --modules_enabled = { "muc_mam" } part that needs to be uncommented?

Hmm… where did you store the prosody plugin that will serve your requests for /all-rooms? That sounds like a custom plugin.

No.

it is in mod_muc_size.lua

You modified mod_muc_size?

i modified it like this

-- Prosody IM
-- Copyright (C) 2017 Atlassian
--

local jid = require "util.jid";
local it = require "util.iterators";
local json = require "util.json";
local iterators = require "util.iterators";
local array = require"util.array";

local have_async = pcall(require, "util.async");
if not have_async then
    module:log("error", "requires a version of Prosody with util.async");
    return;
end

local async_handler_wrapper = module:require "util".async_handler_wrapper;

local tostring = tostring;
local neturl = require "net.url";
local parse = neturl.parseQuery;

-- option to enable/disable room API token verifications
local enableTokenVerification
    = module:get_option_boolean("enable_roomsize_token_verification", false);

local token_util = module:require "token/util".new(module);
local get_room_from_jid = module:require "util".get_room_from_jid;

-- no token configuration but required
if token_util == nil and enableTokenVerification then
    log("error", "no token configuration but it is required");
    return;
end

-- required parameter for custom muc component prefix,
-- defaults to "conference"
local muc_domain_prefix
    = module:get_option_string("muc_mapper_domain_prefix", "conference");

--- Verifies room name, domain name with the values in the token
-- @param token the token we received
-- @param room_address the full room address jid
-- @return true if values are ok or false otherwise
function verify_token(token, room_address)
    if not enableTokenVerification then
        return true;
    end

    -- if enableTokenVerification is enabled and we do not have token
    -- stop here, cause the main virtual host can have guest access enabled
    -- (allowEmptyToken = true) and we will allow access to rooms info without
    -- a token
    if token == nil then
        log("warn", "no token provided");
        return false;
    end

    local session = {};
    session.auth_token = token;
    local verified, reason = token_util:process_and_verify_token(session);
    if not verified then
        log("warn", "not a valid token %s", tostring(reason));
        return false;
    end

    if not token_util:verify_room(session, room_address) then
        log("warn", "Token %s not allowed to join: %s",
            tostring(token), tostring(room_address));
        return false;
    end

    return true;
end

--- Handles request for retrieving the room size
-- @param event the http event, holds the request query
-- @return GET response, containing a json with participants count,
--         tha value is without counting the focus.
function handle_get_room_size(event)
    if (not event.request.url.query) then
        return { status_code = 400; };
    end

	local params = parse(event.request.url.query);
	local room_name = params["room"];
	local domain_name = params["domain"];
    local subdomain = params["subdomain"];

    local room_address
        = jid.join(room_name, muc_domain_prefix.."."..domain_name);

    if subdomain and subdomain ~= "" then
        room_address = "["..subdomain.."]"..room_address;
    end

    if not verify_token(params["token"], room_address) then
        return { status_code = 403; };
    end

	local room = get_room_from_jid(room_address);
	local participant_count = 0;

	log("debug", "Querying room %s", tostring(room_address));

	if room then
		local occupants = room._occupants;
		if occupants then
			participant_count = iterators.count(room:each_occupant());
		end
		log("debug",
            "there are %s occupants in room", tostring(participant_count));
	else
		log("debug", "no such room exists");
		return { status_code = 404; };
	end

	if participant_count > 1 then
		participant_count = participant_count - 1;
	end

	return { status_code = 200; body = [[{"participants":]]..participant_count..[[}]] };
end

--- Handles request for retrieving the room participants details
-- @param event the http event, holds the request query
-- @return GET response, containing a json with participants details
function handle_get_room (event)
    if (not event.request.url.query) then
        return { status_code = 400; };
    end

	local params = parse(event.request.url.query);
	local room_name = params["room"];
	local domain_name = params["domain"];
    local subdomain = params["subdomain"];
    local room_address
        = jid.join(room_name, muc_domain_prefix.."."..domain_name);

    if subdomain and subdomain ~= "" then
        room_address = "["..subdomain.."]"..room_address;
    end

    if not verify_token(params["token"], room_address) then
        return { status_code = 403; };
    end

	local room = get_room_from_jid(room_address);
	local participant_count = 0;
	local occupants_json = array();

	log("debug", "Querying room %s", tostring(room_address));

	if room then
		local occupants = room._occupants;
		if occupants then
			participant_count = iterators.count(room:each_occupant());
			for _, occupant in room:each_occupant() do
			    -- filter focus as we keep it as hidden participant
			    if string.sub(occupant.nick,-string.len("/focus"))~="/focus" then
				    for _, pr in occupant:each_session() do
					local nick = pr:get_child_text("nick", "http://jabber.org/protocol/nick") or "";
					local email = pr:get_child_text("email") or "";
					occupants_json:push({
					    jid = tostring(occupant.nick),
					    email = tostring(email),
					    display_name = tostring(nick)});
				    end
			    end
			end
		end
		log("debug",
            "there are %s occupants in room", tostring(participant_count));
	else
		log("debug", "no such room exists");
		return { status_code = 404; };
	end

	if participant_count > 1 then
		participant_count = participant_count - 1;
	end

	return { status_code = 200; body = json.encode(occupants_json); };
end;

-- below added by Me
function get_raw_rooms(ahost)
	local component = hosts[ahost];
	if component then
		local muc = component.modules.muc
		if muc and rawget(muc,"all_rooms") then
			return muc.all_rooms();
		end
	end
end

function handle_get_all_rooms(event)
	if (not event.request.url.query) then
		return { status_code = 400; };
	end

	local params = parse(event.request.url.query);
	local domain_name = params["domain"];

	local raw_rooms = get_raw_rooms(domain_name);

	local rooms_json = array();

	for room in raw_rooms do

		local room_jid = room.jid;
		local participant_count = 0;
		local occupants_json = array();
		local occupants = room._occupants;
		if occupants then
			for _, occupant in room:each_occupant() do
				-- filter focus as we keep it as hidden participant
				if string.sub(occupant.nick,-string.len("/focus"))~="/focus" then
					for _, pr in occupant:each_session() do
						participant_count = participant_count + 1;
						local nick = pr:get_child_text("nick", "http://jabber.org/protocol/nick") or "";
						local email = pr:get_child_text("email") or "";
						occupants_json:push({
							jid = tostring(occupant.nick),
							email = tostring(email),
							display_name = tostring(nick)});
					end
				end
			end
		end

		rooms_json:push({
			jid = room_jid,
			participant_count = participant_count,
			participants = occupants_json
		});

	end

	local result_json={
		rooms = rooms_json;
	};
	-- create json response
	return { status_code = 200; body = json.encode(result_json); };
end
-- above added by Me

function module.load()
    module:depends("http");
	module:provides("http", {
		default_path = "/";
		route = {
			["GET room-size"] = function (event) return async_handler_wrapper(event,handle_get_room_size) end;
			["GET sessions"] = function () return tostring(it.count(it.keys(prosody.full_sessions))); end;
			["GET room"] = function (event) return async_handler_wrapper(event,handle_get_room) end;
			["GET all-rooms"] = function (event) return async_handler_wrapper(event,handle_get_all_rooms) end; --added by Me
		};
	});
end


Right, so in /etc/prosody/conf.d/mydomain.com.cfg.lua, enabled that module with something like:

Virtualhost "mydomain.com"
    modules_enabled = {
       -- ....
       "muc_size";
    }

then restart prosody.

It should now accept requests if host headers match mydomain.com, so try:

curl -H "Host: mydomain.com" "http://localhost:5280/all-rooms?domain=conference.mydomain.com"

Also monitor your prosody logs in case there are errors.

how do you determine which port to use here? http://localhost:5380

Sorry, should be 5280.

That’s the standard port Prosody listens to for HTTP. See Port and network configuration – Prosody IM

I still am producing this

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>404 Not Found</title>
<style>
body{
        margin-top:14%;
        text-align:center;
        background-color:#F8F8F8;
        font-family:sans-serif;
}
h1{
        font-size:xx-large;
}
p{
        font-size:x-large;
}
p+p {
        font-size:large;
        font-family:courier;
}
</style>
</head>
<body>
<h1>404 Not Found</h1>
<p>Whatever you were looking for is not here. Keep looking.</p>
<p>Unknown host: wirtualus.com</p>
</body>
</html>

How does your config look like in /etc/prosody/conf.d/YOURDOMAIN.cfg.lua? In particular, the Virtualhost block where you enabled “muc_size”?

VirtualHost "mydomain.com"
    -- enabled = false -- Remove this line to enable this host
    authentication = "anonymous"
    -- Properties below are modified by jitsi-meet-tokens package config
    -- and authentication above is switched to "token"
    -- app_id="mydomain"
    -- app_secret=""
    -- allow_empty_token = false;
    -- Assign this host a certificate for TLS, otherwise it would use the one
    -- set in the global section (if any).
    -- Note that old-style SSL on port 5223 only supports one certificate, and will always
    -- use the global one.
    ssl = {
        key = "/etc/prosody/certs/mydomain.com.key";
        certificate = "/etc/prosody/certs/mydomain.com.crt";
    }
    av_moderation_component = "avmoderation.mydomain.com"
    speakerstats_component = "speakerstats.mydomain.com"
    conference_duration_component = "conferenceduration.mydomain.com"
    -- we need bosh
    modules_enabled = {
        "bosh";
        "pubsub";
        "ping"; -- Enable mod_ping
        "speakerstats";
        "external_services";
        "conference_duration";
        "muc_lobby_rooms";
        "muc_breakout_rooms";
        "av_moderation";
        "muc_size";
    }

    c2s_require_encryption = false
    lobby_muc = "lobby.mydomain.com"
    breakout_rooms_muc = "breakout.mydomain.com"
    main_muc = "conference.mydomain.com"
    -- muc_lobby_whitelist = { "recorder.mydomain.com" } -- Here we can whitelist jibri to enter lobby enabled rooms


like this

And you are sure this domain name is what you specified in curl -H "Host: mydomain.com" ?

Your error message appears to imply the request you made does not match a known host.

Also check there are not errors for “muc_size” after you restart prosody.

is it possible it is a port issue, since I have 2 websites at different ports

Try stopping prosody and see if you still get the same error message when you run curl, or if it fails to connect.