aboutsummaryrefslogtreecommitdiff
path: root/src/jthread/pthread/jthread.cpp
blob: 414d8fde593b2976b9e2b6c22b731747e93d31c8 (plain)
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
163
164
165
166
167
168
/*

    This file is a part of the JThread package, which contains some object-
    oriented thread wrappers for different thread implementations.

    Copyright (c) 2000-2006  Jori Liesenborgs (jori.liesenborgs@gmail.com)

    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 "jthread/jthread.h"
#include <assert.h>
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>

#define UNUSED(expr) do { (void)(expr); } while (0)

JThread::JThread()
{
	retval = NULL;
	requeststop = false;
	running = false;
	started = false;
}

JThread::~JThread()
{
	Kill();
}

void JThread::Wait() {
	void* status;
	if (started) {
		int pthread_join_retval = pthread_join(threadid,&status);
		assert(pthread_join_retval == 0);
		UNUSED(pthread_join_retval);
		started = false;
	}
}

int JThread::Start()
{
	int status;

	if (running)
	{
		return ERR_JTHREAD_ALREADYRUNNING;
	}
	requeststop = false;

	pthread_attr_t attr;
	pthread_attr_init(&attr);
	//pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);

	continuemutex.Lock();
	status = pthread_create(&threadid,&attr,TheThread,this);
	pthread_attr_destroy(&attr);
	if (status != 0)
	{
		continuemutex.Unlock();
		return ERR_JTHREAD_CANTSTARTTHREAD;
	}

	/* Wait until 'running' is set */

	while (!running)
	{
		struct timespec req,rem;

		req.tv_sec = 0;
		req.tv_nsec = 1000000;
		nanosleep(&req,&rem);
	}
	started = true;

	continuemutex.Unlock();

	continuemutex2.Lock();
	continuemutex2.Unlock();
	return 0;
}

int JThread::Kill()
{
	void* status;
	if (!running)
	{
		if (started) {
			int pthread_join_retval = pthread_join(threadid,&status);
			assert(pthread_join_retval == 0);
			UNUSED(pthread_join_retval);
			started = false;
		}
		return ERR_JTHREAD_NOTRUNNING;
	}
#ifdef __ANDROID__
	pthread_kill(threadid, SIGKILL);
#else
	pthread_cancel(threadid);
#endif
	if (started) {
		int pthread_join_retval = pthread_join(threadid,&status);
		assert(pthread_join_retval == 0);
		UNUSED(pthread_join_retval);
		started = false;
	}
	running = false;
	return 0;
}

void *JThread::GetReturnValue()
{
	void *val;

	if (running) {
		val = NULL;
	} else {
		val = retval;
	}

	return val;
}

bool JThread::IsSameThread()
{
	return pthread_equal(pthread_self(), threadid);
}

void *JThread::TheThread(void *param)
{
	JThread *jthread = (JThread *)param;

	jthread->continuemutex2.Lock();
	jthread->running = true;

	jthread->continuemutex.Lock();
	jthread->continuemutex.Unlock();

	jthread->Thread();

	jthread->running = false;

	return NULL;
}

void JThread::ThreadStarted()
{
	continuemutex2.Unlock();
}

574'>574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
-- Minetest: builtin/game/chat.lua

-- Helper function that implements search and replace without pattern matching
-- Returns the string and a boolean indicating whether or not the string was modified
local function safe_gsub(s, replace, with)
	local i1, i2 = s:find(replace, 1, true)
	if not i1 then
		return s, false
	end

	return s:sub(1, i1 - 1) .. with .. s:sub(i2 + 1), true
end

--
-- Chat message formatter
--

-- Implemented in Lua to allow redefinition
function core.format_chat_message(name, message)
	local error_str = "Invalid chat message format - missing %s"
	local str = core.settings:get("chat_message_format")
	local replaced

	-- Name
	str, replaced = safe_gsub(str, "@name", name)
	if not replaced then
		error(error_str:format("@name"), 2)
	end

	-- Timestamp
	str = safe_gsub(str, "@timestamp", os.date("%H:%M:%S", os.time()))

	-- Insert the message into the string only after finishing all other processing
	str, replaced = safe_gsub(str, "@message", message)
	if not replaced then
		error(error_str:format("@message"), 2)
	end

	return str
end

--
-- Chat command handler
--

core.chatcommands = core.registered_chatcommands -- BACKWARDS COMPATIBILITY

core.register_on_chat_message(function(name, message)
	if message:sub(1,1) ~= "/" then
		return
	end

	local cmd, param = string.match(message, "^/([^ ]+) *(.*)")
	if not cmd then
		core.chat_send_player(name, "-!- Empty command")
		return true
	end

	param = param or ""

	local cmd_def = core.registered_chatcommands[cmd]
	if not cmd_def then
		core.chat_send_player(name, "-!- Invalid command: " .. cmd)
		return true
	end
	local has_privs, missing_privs = core.check_player_privs(name, cmd_def.privs)
	if has_privs then
		core.set_last_run_mod(cmd_def.mod_origin)
		local _, result = cmd_def.func(name, param)
		if result then
			core.chat_send_player(name, result)
		end
	else
		core.chat_send_player(name, "You don't have permission"
				.. " to run this command (missing privileges: "
				.. table.concat(missing_privs, ", ") .. ")")
	end
	return true  -- Handled chat message
end)

if core.settings:get_bool("profiler.load") then
	-- Run after register_chatcommand and its register_on_chat_message
	-- Before any chatcommands that should be profiled
	profiler.init_chatcommand()
end

-- Parses a "range" string in the format of "here (number)" or
-- "(x1, y1, z1) (x2, y2, z2)", returning two position vectors
local function parse_range_str(player_name, str)
	local p1, p2
	local args = str:split(" ")

	if args[1] == "here" then
		p1, p2 = core.get_player_radius_area(player_name, tonumber(args[2]))
		if p1 == nil then
			return false, "Unable to get player " .. player_name .. " position"
		end
	else
		p1, p2 = core.string_to_area(str)
		if p1 == nil then
			return false, "Incorrect area format. Expected: (x1,y1,z1) (x2,y2,z2)"
		end
	end

	return p1, p2
end

--
-- Chat commands
--
core.register_chatcommand("me", {
	params = "<action>",
	description = "Show chat action (e.g., '/me orders a pizza' displays"
			.. " '<player name> orders a pizza')",
	privs = {shout=true},
	func = function(name, param)
		core.chat_send_all("* " .. name .. " " .. param)
	end,
})

core.register_chatcommand("admin", {
	description = "Show the name of the server owner",
	func = function(name)
		local admin = core.settings:get("name")
		if admin then
			return true, "The administrator of this server is " .. admin .. "."
		else
			return false, "There's no administrator named in the config file."
		end
	end,
})

core.register_chatcommand("privs", {
	params = "[<name>]",
	description = "Show privileges of yourself or another player",
	func = function(caller, param)
		param = param:trim()
		local name = (param ~= "" and param or caller)
		if not core.player_exists(name) then
			return false, "Player " .. name .. " does not exist."
		end
		return true, "Privileges of " .. name .. ": "
			.. core.privs_to_string(
				core.get_player_privs(name), ", ")
	end,
})

core.register_chatcommand("haspriv", {
	params = "<privilege>",
	description = "Return list of all online players with privilege.",
	privs = {basic_privs = true},
	func = function(caller, param)
		param = param:trim()
		if param == "" then
			return false, "Invalid parameters (see /help haspriv)"
		end
		if not core.registered_privileges[param] then
			return false, "Unknown privilege!"
		end
		local privs = core.string_to_privs(param)
		local players_with_priv = {}
		for _, player in pairs(core.get_connected_players()) do
			local player_name = player:get_player_name()
			if core.check_player_privs(player_name, privs) then
				table.insert(players_with_priv, player_name)
			end
		end
		return true, "Players online with the \"" .. param .. "\" privilege: " ..
			table.concat(players_with_priv, ", ")
	end
})

local function handle_grant_command(caller, grantname, grantprivstr)
	local caller_privs = core.get_player_privs(caller)
	if not (caller_privs.privs or caller_privs.basic_privs) then
		return false, "Your privileges are insufficient."
	end

	if not core.get_auth_handler().get_auth(grantname) then
		return false, "Player " .. grantname .. " does not exist."
	end
	local grantprivs = core.string_to_privs(grantprivstr)
	if grantprivstr == "all" then
		grantprivs = core.registered_privileges
	end
	local privs = core.get_player_privs(grantname)
	local privs_unknown = ""
	local basic_privs =
		core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
	for priv, _ in pairs(grantprivs) do
		if not basic_privs[priv] and not caller_privs.privs then
			return false, "Your privileges are insufficient."
		end
		if not core.registered_privileges[priv] then
			privs_unknown = privs_unknown .. "Unknown privilege: " .. priv .. "\n"
		end
		privs[priv] = true
	end
	if privs_unknown ~= "" then
		return false, privs_unknown
	end
	for priv, _ in pairs(grantprivs) do
		-- call the on_grant callbacks
		core.run_priv_callbacks(grantname, priv, caller, "grant")
	end
	core.set_player_privs(grantname, privs)
	core.log("action", caller..' granted ('..core.privs_to_string(grantprivs, ', ')..') privileges to '..grantname)
	if grantname ~= caller then
		core.chat_send_player(grantname, caller
				.. " granted you privileges: "
				.. core.privs_to_string(grantprivs, ' '))
	end
	return true, "Privileges of " .. grantname .. ": "
		.. core.privs_to_string(
			core.get_player_privs(grantname), ' ')
end

core.register_chatcommand("grant", {
	params = "<name> (<privilege> | all)",
	description = "Give privileges to player",
	func = function(name, param)
		local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)")
		if not grantname or not grantprivstr then
			return false, "Invalid parameters (see /help grant)"
		end
		return handle_grant_command(name, grantname, grantprivstr)
	end,
})

core.register_chatcommand("grantme", {
	params = "<privilege> | all",
	description = "Grant privileges to yourself",
	func = function(name, param)
		if param == "" then
			return false, "Invalid parameters (see /help grantme)"
		end
		return handle_grant_command(name, name, param)
	end,
})

core.register_chatcommand("revoke", {
	params = "<name> (<privilege> | all)",
	description = "Remove privileges from player",
	privs = {},
	func = function(name, param)
		if not core.check_player_privs(name, {privs=true}) and
				not core.check_player_privs(name, {basic_privs=true}) then
			return false, "Your privileges are insufficient."
		end
		local revoke_name, revoke_priv_str = string.match(param, "([^ ]+) (.+)")
		if not revoke_name or not revoke_priv_str then
			return false, "Invalid parameters (see /help revoke)"
		elseif not core.get_auth_handler().get_auth(revoke_name) then
			return false, "Player " .. revoke_name .. " does not exist."
		end
		local revoke_privs = core.string_to_privs(revoke_priv_str)
		local privs = core.get_player_privs(revoke_name)
		local basic_privs =
			core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
		for priv, _ in pairs(revoke_privs) do
			if not basic_privs[priv] and
					not core.check_player_privs(name, {privs=true}) then
				return false, "Your privileges are insufficient."
			end
		end
		if revoke_priv_str == "all" then
			revoke_privs = privs
			privs = {}
		else
			for priv, _ in pairs(revoke_privs) do
				privs[priv] = nil
			end
		end

		for priv, _ in pairs(revoke_privs) do
			-- call the on_revoke callbacks
			core.run_priv_callbacks(revoke_name, priv, name, "revoke")
		end

		core.set_player_privs(revoke_name, privs)
		core.log("action", name..' revoked ('
				..core.privs_to_string(revoke_privs, ', ')
				..') privileges from '..revoke_name)
		if revoke_name ~= name then
			core.chat_send_player(revoke_name, name
					.. " revoked privileges from you: "
					.. core.privs_to_string(revoke_privs, ' '))
		end
		return true, "Privileges of " .. revoke_name .. ": "
			.. core.privs_to_string(
				core.get_player_privs(revoke_name), ' ')
	end,
})

core.register_chatcommand("setpassword", {
	params = "<name> <password>",
	description = "Set player's password",
	privs = {password=true},
	func = function(name, param)
		local toname, raw_password = string.match(param, "^([^ ]+) +(.+)$")
		if not toname then
			toname = param:match("^([^ ]+) *$")
			raw_password = nil
		end

		if not toname then
			return false, "Name field required"
		end

		local act_str_past, act_str_pres
		if not raw_password then
			core.set_player_password(toname, "")
			act_str_past = "cleared"
			act_str_pres = "clears"
		else
			core.set_player_password(toname,
					core.get_password_hash(toname,
							raw_password))
			act_str_past = "set"
			act_str_pres = "sets"
		end

		if toname ~= name then
			core.chat_send_player(toname, "Your password was "
					.. act_str_past .. " by " .. name)
		end

		core.log("action", name .. " " .. act_str_pres ..
				" password of " .. toname .. ".")

		return true, "Password of player \"" .. toname .. "\" " .. act_str_past
	end,
})

core.register_chatcommand("clearpassword", {
	params = "<name>",
	description = "Set empty password for a player",
	privs = {password=true},
	func = function(name, param)
		local toname = param
		if toname == "" then
			return false, "Name field required"
		end
		core.set_player_password(toname, '')

		core.log("action", name .. " clears password of " .. toname .. ".")

		return true, "Password of player \"" .. toname .. "\" cleared"
	end,
})

core.register_chatcommand("auth_reload", {
	params = "",
	description = "Reload authentication data",
	privs = {server=true},
	func = function(name, param)
		local done = core.auth_reload()
		return done, (done and "Done." or "Failed.")
	end,
})

core.register_chatcommand("remove_player", {
	params = "<name>",
	description = "Remove a player's data",
	privs = {server=true},
	func = function(name, param)
		local toname = param
		if toname == "" then
			return false, "Name field required"
		end

		local rc = core.remove_player(toname)

		if rc == 0 then
			core.log("action", name .. " removed player data of " .. toname .. ".")
			return true, "Player \"" .. toname .. "\" removed."
		elseif rc == 1 then