coldcore
./ColdCore-3.0a10/coldcore · 2.2 MB
From the archive ColdCore3.0a10.tar.gz
Download the archive « Back to the archive contents
object $root;
var $root manager = $root;
var $root trusted = [];
var $root child_index = 0;
var $root inited = 0;
var $root quota = 75000;
var $root managed = 0;
var $root writers = [$root];
var $root created_on = 0;
var $root flags = ['methods, 'code, 'core, 'variables];
var $root quota_exempt = 0;
var $root writes = 0;
var $root trusted_by = 0;
var $root help_node = 0;
var $root settings = 0;
var $root defined_settings = #[["help-node", #[['get, ['help_node]], ['set, ['set_help_node_setting]], ['parse, ['parse_help_node_setting]], ['format, ['format_help_node_setting]]]]];
var $root semaphores = 0;
var $root credit = 0;
root method .init_root(): nooverride {
.change_manager(this());
flags = ['variables, 'methods, 'code];
created_on = time();
};
root method .uninit_root(): nooverride {
var obj;
(| manager.del_managed_obj() |);
catch any {
for obj in (.managed())
obj.change_manager($reaper);
}
catch any {
for obj in (.writers('literal))
.del_writer(obj);
}
catch any {
for obj in (.writes())
obj.del_writer(this());
}
catch any {
for obj in (.trusted('literal))
.del_trusted(obj);
}
catch any {
for obj in (.trusted_by())
obj.del_trusted(this());
}
// tell $sys we are going away
$sys.sender_going_away();
};
public method .initialize(): nooverride {
var ancestors, pos, len, method, a, def;
if ((caller() != $sys) && (sender() != this()))
throw(~perm, "Caller is not $sys and sender is not this.");
if (inited)
throw(~perm, "Already initialized.");
ancestors = ancestors();
len = ancestors.length();
for pos in [0 .. len - 1] {
refresh();
a = ancestors[len - pos];
if (!(method = (| tosym("init_" + tostr(a.objname())) |)))
continue;
if ((def = (| find_method(method) |))) {
if (def != a) {
(| (def.manager()).tell(((("Initialization method for " + a) + " in wrong place (") + find_method(method)) + ")") |);
} else {
catch any {
.(method)();
} with {
if (def) {
(| (def.manager()).tell(((("INIT ERROR " + this()) + "<") + def) + ">:") |);
(| (def.manager()).tell_traceback(traceback()) |);
}
}
}
}
}
inited = 1;
};
public method .uninitialize(): nooverride {
arg @destroyed;
var a, v, d, definer, method, descendants, str;
(> .perms(caller(), $root, $sys) <);
destroyed = destroyed ? 1 : 0;
descendants = (.descendants()) + [this()];
// call [ancestors...].uninit_ancestor() on the object being destroyed
for a in (ancestors()) {
method = tosym("uninit_" + (a.objname()));
if ((definer = (| find_method(method) |))) {
if (definer != a) {
// scream madly and run around--everybody should know this
str = "UNINIT ERROR: uninit method for " + a;
str += (" in wrong place (" + definer) + ")";
(| (definer.manager()).tell(str) |);
(| (a.manager()).tell(str) |);
(| sender().tell(str) |);
continue;
}
catch any {
.(method)();
} with {
// try and let somebody know they made a boo-boo somewhere
str = ((("UNINIT ERROR " + this()) + "<") + definer) + ">:";
if (definer) {
(| (definer.manager()).tell(str) |);
(| (definer.manager()).tell_traceback(traceback()) |);
}
(| sender().tell(str) |);
(| sender().tell_traceback(traceback()) |);
(| sender().tell("Continuing uninit..") |);
}
}
refresh();
}
// if we have descendants, clean anything from the object being dested
method = tosym("uninit_" + (.objname()));
if ((definer = (| find_method(method) |))) {
if (definer != this()) {
// scream madly and run around--everybody should know this
str = "UNINIT ERROR: uninit method for " + a;
str += (" in wrong place (" + definer) + ")";
(| (definer.manager()).tell(str) |);
(| (.manager()).tell(str) |);
(| sender().tell(str) |);
} else {
for d in (descendants) {
catch any {
d.(method)();
} with {
// try and let somebody know they made a boo-boo somewhere
str = ((("UNINIT ERROR " + d) + "<") + this()) + ">:";
(| (.manager()).tell(str) |);
(| (.manager()).tell_traceback(traceback()) |);
(| sender().tell(str) |);
(| sender().tell_traceback(traceback()) |);
(| sender().tell("Continuing uninit..") |);
}
refresh();
}
}
}
// clear vars
if ((!destroyed) && descendants)
$sys.clear_definer_vars(this(), descendants);
};
public method .perms(): nooverride {
arg what, @args;
var flag;
if (!args)
args = ['writer];
if (type(args[1]) == 'symbol) {
switch (args[1]) {
case 'system:
if (!($sys.is_system(what)))
throw(~perm, ("Permission Denied: " + what) + " is not of the system.", what);
case 'manager:
if (((.manager()) != what) && (!($sys.is_system(what))))
throw(~perm, ("Permission Denied: " + what) + " is not the manager.", what);
case 'trusts:
if (!(.trusts(what)))
throw(~perm, ("Permission Denied: " + what) + " is not a trustee.", what);
case 'command:
if ((what != $user) && (what != $body))
throw(~perm, what + " is not a valid command invoking object.");
default:
if (!(.is_writable_by(what)))
throw(~perm, ("Permission Denied: " + what) + " is not a writer.", what);
}
} else if (type(what) == 'objnum) {
if (!(what in args))
throw(~perm, (what + " is not one of: ") + ((args.mmap('namef, 'ref)).to_english()), what);
}
};
public method .chparents() {
arg @parents;
var parent, cur;
if (!(| .perms(sender(), 'manager) |))
(> .perms(caller(), $root, $sys) <);
(> $sys.touch() <);
if (!parents)
throw(~noparents, "There must be at least 1 parent for each object.");
// Notify new parents of impending change.
cur = parents();
for parent in (parents) {
if (!(parent in cur))
(> parent.will_inherit(sender()) <);
}
// Everything's okay, go ahead and try it.
.change_parents(parents);
};
public method .will_inherit() {
arg who;
if (this() in (sender().parents()))
throw(~perm, ((sender() + " already has ") + this()) + " as a parent.");
if ((!(.has_flag('fertile, sender()))) && (!(.trusts(who))))
throw(~perm, ((this() + " refuses to be parent of ") + sender()) + ".");
};
public method .manager(): nooverride {
return manager || $reaper;
};
public method .writers(): nooverride {
arg @literal;
if (literal)
return writers || [];
// for speed, just add rather than setadd, use .compress() later if necessary
return (writers || []) + [.manager(), this()];
};
public method .trusted(): nooverride {
arg @literal;
if (literal)
return trusted || [];
return (trusted || []) + (.writers());
};
public method .is_writable_by(): nooverride {
arg obj;
return (| obj in (.writers()) |) || ($sys.is_system(obj));
};
public method .trusts(): nooverride {
arg obj;
return (| obj in (.trusted()) |) || ((obj in [$scheduler, $directories]) || ($sys.is_system(obj)));
};
public method .change_manager(): nooverride {
arg new;
var old;
if ((caller() != definer()) && (!($sys.is_system(sender()))))
throw(~perm, "You must have system privileges to change the manager.");
(> $sys.touch() <);
if (type(new) != 'objnum)
throw(~invarg, "Managers must be given as a single dbref.");
old = .manager();
manager = new;
old.del_managed_obj();
new.add_managed_obj();
};
public method .add_writer(): nooverride {
arg obj;
(> .perms(sender(), 'manager) <);
(> $sys.touch('coreok) <);
writers = (writers || []).setadd(obj);
obj.add_writable_obj();
};
public method .del_writer(): nooverride {
arg obj;
(caller() == definer()) || (> .perms(sender(), 'manager) <);
writers = (writers || []).setremove(obj);
(> $sys.touch('coreok) <);
if (!writers)
(| clear_var('writers) |);
obj.del_writable_obj();
};
public method .add_trusted(): nooverride {
arg obj;
(caller() == definer()) || (> .perms(sender(), 'manager) <);
(> $sys.touch('coreok) <);
trusted = (trusted || []).setadd(obj);
obj.add_trusted_obj();
};
public method .del_trusted(): nooverride {
arg obj;
(> .perms(sender(), 'manager) <);
(> $sys.touch('coreok) <);
trusted = (trusted || []).setremove(obj);
if (!trusted)
clear_var('trusted);
obj.del_trusted_obj();
};
public method .as_this_run() {
arg obj, method, args;
if (!((caller() == $scheduler) || (caller().is($http_interface))))
throw(~perm, "Sender not allowed to gain access to object perms.");
return (> obj.(method)(@args) <);
};
public method .add_parent() {
arg parent;
(> .perms(sender(), 'manager) <);
(> $sys.touch() <);
(> parent.will_inherit(sender()) <);
if (.has_ancestor(parent))
throw(~perm, ((this() + " already has ") + parent) + " as an ancestor.");
.change_parents(parents() + [parent]);
};
public method .del_parent() {
arg parent;
var parents;
(> .perms(sender(), 'manager) <);
(> $sys.touch() <);
if (!valid(parent))
throw(~type, "Not a valid parent, must send a valid object.");
parents = .parents();
if (!(parent in parents))
throw(~parentnf, ((parent + " is not a parent of ") + this()) + ".");
parents = parents.setremove(parent);
(> .change_parents(parents) <);
};
public method .spawn(): nooverride {
arg @suffix;
var obj, tmp, objname, mngr, na;
(> .will_spawn(sender()) <);
suffix = (> .get_obj_suffix(@suffix) <);
return $sys.spawn_sender(suffix, sender());
};
public method .destroy(): nooverride {
// This doesn't actually destroy us immediately, but we will go away when
// nothing is holding onto us any more.
(> .perms(sender(), 'manager) <);
if (.has_flag('core))
throw(~perm, "This object is a core object, and cannot be destroyed!");
(| .uninitialize('destroy) |);
destroy();
};
public method .add_var(): nooverride {
arg name, @args;
var tmp, kid;
(> .perms(sender()) <);
(> $sys.touch() <);
if (!(tostr(name).valid_ident()))
throw(~invident, name + " is not a valid ident.");
(> add_var(name) <);
// The following code is a kludge as we can't send a default value to the
// primitive.
if (args) {
tmp = tosym((("__set_" + tostr(name)) + "_") + time());
catch any {
add_method([((tostr(name) + " = ") + toliteral(args[1])) + ";"], tmp);
.(tmp)();
if (((args.length()) > 1) && ((args[2]) == 'inherit)) {
for kid in (.descendants())
kid.(tmp)();
}
del_method(tmp);
} with {
del_method(tmp);
rethrow(error());
}
}
};
public method .variables(): nooverride {
if (!(.has_flag('variables, sender())))
throw(~perm, (sender() + " doesn't have permission to find methods on ") + this());
return variables();
};
public method .del_var(): nooverride {
arg name;
var n, obj;
(caller() == definer()) || (> .perms(sender()) <);
(> $sys.touch() <);
// try and clear the variable on all of the descendants, before deleting
// the variable...
(> .clear_variable(name) <);
// now delete the variable
(> del_var(name) <);
};
public method .del_method() {
arg name;
(> .perms(sender()) <);
(> del_method(name) <);
};
public method .methods(): nooverride {
if (!(.has_flag('methods, sender())))
throw(~perm, (sender() + " doesn't have permission to find methods on ") + this());
return methods();
};
public method .parents(): nooverride {
return parents();
};
public method .children(): nooverride {
return children();
};
public method .ancestors(): nooverride {
arg @args;
return ancestors(@args);
};
public method .find_method(): nooverride {
arg name;
if (!(.has_flag('methods, sender())))
throw(~perm, (sender() + " doesn't have permission to find methods on ") + this());
return (> find_method(name) <);
};
public method .find_next_method(): nooverride {
arg name, after;
if (!(.has_flag('methods, sender())))
throw(~perm, (sender() + " doesn't have permission to find methods on ") + this());
return (> find_next_method(name, after) <);
};
private method .corify_descendants_of(): nooverride {
arg obj;
var d, name, l;
name = (| tosym("core_" + (obj.objname())) |);
catch ~methodnf {
if ((> obj.find_method(name) <) != obj) {
$sys.log(((("** Coremethod for " + obj) + " in wrong place (on ") + (obj.find_method(name))) + ") **");
return;
}
} with {
return;
}
for d in ([obj] + (obj.descendants())) {
catch any {
(> d.(name)() <);
} with {
$sys.log(((("** ERROR encountered in " + d) + ".") + name) + "():");
for l in ($parse_lib.traceback(traceback()))
$sys.log(l);
}
refresh();
}
};
public method .add_method() {
arg code, name, @evalonly;
var l, m, line, errs;
(> .perms(sender()) <);
if (evalonly && (caller() in [$root, $sys, $programmer]))
(> $sys.touch('lockok) <);
else
(> $sys.touch() <);
// check for a few things only admins can do
if (!(sender().is($admin))) {
for l in [1 .. listlen(code)] {
line = code[l];
if ((m = line.match_regexp("[^a-z0-9_.]anticipate_assignment\("))) {
(> sender().tell($code_lib.point_to_line("ERROR: call to anticipate_assignment()", ((m[1])[1]) + 2, ((m[1])[2]) - 2, l, line)) <);
throw(~perm, "anticipate_assignment() may only be used by an administrator.");
}
}
}
errs = (> add_method(code, name) <);
for l in [1 .. listlen(errs)] {
line = errs[l];
if (match_regexp(line, "Line [0-9]+: Unknown function length.")) {
line = substr(line, 1, strlen(line) - 1);
errs = replace(errs, l, line + "(), try listlen(), strlen() or buflen()");
}
}
return errs;
};
public method .has_ancestor(): nooverride {
arg obj;
return (> has_ancestor(obj) <);
};
public method .eval(): nooverride {
arg code, @dest;
var errors, result, method;
dest = dest ? (dest[1]) : this();
if (!(sender() in [$scheduler, $root]))
(> .perms(sender()) <);
// Compile the code.
method = tosym("tmp_eval_" + tostr(time()));
errors = .add_method(code, method);
if (errors)
return ['errors, errors, 0, 0];
// Evaluate the expression. Be sure to remove it afterwards, so that no
// one else can call it.
catch any {
result = (> dest.(method)() <);
} with {
(| del_method(method) |);
rethrow(error());
}
(| del_method(method) |);
return ['result, result];
};
public method .method_info(): nooverride {
arg @args;
return (> method_info(@args) <);
};
public method .data(): nooverride {
arg @parent;
var par, data, out;
if (!(.has_flag('variables, sender())))
throw(~perm, ((sender().namef('ref)) + " is not allowed to read variables on ") + (.namef('ref)));
if (parent) {
if (type(parent[1]) != 'objnum)
throw(~type, (parent[1]) + " is not an object.");
return (> data(parent[1]) <);
} else {
data = (> data() <);
out = #[];
for par in (data) {
// if the parent doesn't exist anymore, just let them see the data.
if ((!valid(par[1])) || ((par[1]).has_flag('variables, sender())))
out = out.add(par[1], par[2]);
else
out = out.add(par[1], ["*** Permission Denied ***"]);
}
return out;
}
};
public method .size(): nooverride {
arg @args;
[(args ?= 'int)] = args;
switch (args) {
case 'string:
return tostr(size());
case 'english:
return size().to_english();
default:
return size();
}
};
public method .descendants(): nooverride {
var kids, i, c, child, d;
d = #[];
for child in (children())
d = dict_add(d, child, 1);
while ((| (c = dict_keys(d)[++i]) |)) {
for child in (c.children()) {
pause();
d = dict_add(d, child, 1);
}
pause();
}
return dict_keys(d);
};
public method .get_quota(): nooverride {
arg @args;
return quota;
};
public method .quota_valid(): nooverride {
if (quota_exempt)
return 1;
if (!(.is($user)))
return 0;
return (.quota_byte_usage()) < (.quota());
};
public method .match_children() {
arg string;
var children, child_names, c;
children = .children();
child_names = children.mmap('name);
// direct matches first.
for c in (child_names) {
if (c == string)
return children[c in child_names];
}
// ok, try partial matches
for c in (child_names) {
if ($string.match_begin(c, string))
return children[c in child_names];
}
return 0;
};
public method .del_flag(): nooverride {
arg flag;
(> .perms(sender(), 'manager) <);
(> $sys.touch('coreok) <);
if ((flag == 'core) && (!($sys.writable_core())))
throw(~perm, this() + " is a core object, and the core isn't writable.");
// let them add any flag they want
flags = (flags || []).setremove(flag);
};
public method ._display_descendants() {
arg space, checked, levels, maxlev;
var c, anc, list, id, perms;
id = ((space + this()) + " ") + ($object_lib.see_perms(this()));
for anc in (dict_keys(checked)) {
if (.has_ancestor(anc))
return [];
// [id + " (above)"];
}
if (((.parents()).length()) > 1)
id += " (MI)";
list = [id];
space += " ";
levels++;
// check children
if ((!maxlev) || (maxlev != levels)) {
for c in (.children()) {
list += c._display_descendants(space, checked, levels, maxlev);
checked = dict_add(checked, c, 1);
pause();
}
}
return list;
};
public method ._get_method_info(): nooverride {
arg anc, method;
var code, lines, dis_flag, meth_args, flags, first_comment;
code = anc.list_method(method);
lines = code.length();
if (lines > 5)
code = code.subrange(1, 5);
flags = anc.method_flags(method);
if (code) {
meth_args = regexp(code[1], "arg ([^;]);");
if (meth_args) {
meth_args = meth_args[1];
code = code.delete(1);
} else {
meth_args = "";
}
if (code && ((!(code[1])) || (((code[1])[1]) == "v")))
code = code.delete(1);
if (code && ((!(code[1])) || (((code[1])[1]) == "v")))
code = code.delete(1);
first_comment = code ? ((code[1]) + " ") : " ";
first_comment = (((first_comment[1]) == "/") || ((first_comment[1]) == "r")) ? first_comment : "";
} else {
meth_args = "";
first_comment = "";
}
return [anc, method, meth_args, flags, lines, first_comment];
};
public method .namef() {
arg type;
return tostr(this());
};
public method .match_descendants() {
arg string;
var match, child;
match = .match_children(string);
if (match)
return match;
for child in (.children()) {
match = child.match_descendants(string);
if (match)
return match;
}
return 0;
};
public method .debug() {
arg @stuff;
var x, line, mngr, meth, stack, out;
stack = stack();
meth = (| (((stack[2])[3]) + "() line ") + ((stack[2])[4]) |);
if (meth)
line = ((("DEBUG " + sender()) + ".") + meth) + ":";
else
line = ("DEBUG " + sender()) + ":";
out = [line];
for x in (stuff)
out += ($data_lib.unparse_indent(x)).prefix("DEBUG ");
(| (.manager()).tell(out) |);
};
public method .set_quota(): nooverride {
arg value;
(> .perms(caller(), $user, @$sys.system(), $root, $admin) <);
quota = value;
};
public method .name() {
arg @args;
return tostr(this());
};
public method .quota(): nooverride {
return quota;
};
public method .quota_byte_usage(): nooverride {
var total, obj;
for obj in (.managed()) {
if (!valid(obj))
continue;
total += obj.size();
}
return total;
};
public method .corify(): nooverride {
var d;
if (sender() != $sys)
throw(~sysonly, "This should only be called by $sys.make_core().");
// reverse engineer it--if coreify_<object> exists,
// call it on this object and all of its descendants.
for d in (((.descendants()).setremove($sys)) + [$sys]) {
.corify_descendants_of(d);
refresh();
}
};
root method .change_parents(): nooverride {
arg parents;
var old_a, old_p, a, obj, new_a, definer, branch, method, str;
if (!parents)
throw(~noparents, "Objects must have at least 1 parent");
// remember a few things
old_a = setremove(ancestors(), this());
old_p = .parents();
branch = (.descendants()) + [this()];
// build the new ancestors list by hand, so we can figure out what is
// changing, and uninitialize those ancestors that are going away
new_a = [];
for obj in (parents)
new_a = new_a.union(obj.ancestors());
// uninit any ancestors going away
for a in (old_a.set_difference(new_a)) {
// call this ancestor's uninit on the obj and all its children
method = tosym("uninit_" + (a.objname()));
if ((definer = (| find_method(method) |))) {
if (definer != a) {
// scream madly and run around--everybody should know this
str = "UNINIT ERROR: uninit method for " + a;
str += (" in wrong place (" + definer) + ")";
(| (definer.manager()).tell(str) |);
(| (a.manager()).tell(str) |);
(| sender().tell(str) |);
continue;
}
// call the uninit method on this object only
catch any {
.(method)();
} with {
// try and let somebody know they made a boo-boo somewhere
str = ((("UNINIT ERROR " + obj) + "<") + this()) + ">:";
(| (.manager()).tell(str) |);
(| (.manager()).tell_traceback(traceback()) |);
(| sender().tell(str) |);
(| sender().tell_traceback(traceback()) |);
(| sender().tell("Continuing chparent..") |);
}
}
// cleanup any old obj vars left lying around
// if (branch)
// $sys.clear_definer_vars(a, branch);
$sys.clear_definer_vars(a, [this()]);
refresh();
}
// make the change
(> chparents(parents) <);
// init anybody new to the family
for a in (ancestors().set_difference(old_a)) {
method = tosym("init_" + (a.objname()));
if ((definer = (| find_method(method) |))) {
if (definer != a) {
// scream madly and run around--everybody should know this
// (damn inlaws, can't ever get things right)
str = "INIT ERROR: uninit method for " + a;
str += (" in wrong place (" + definer) + ")";
(| (definer.manager()).tell(str) |);
(| (a.manager()).tell(str) |);
(| sender().tell(str) |);
continue;
}
// introduce the new ancestor
catch any {
.(method)();
} with {
// try and let somebody know they made a boo-boo somewhere
str = ((("INIT ERROR " + obj) + "<") + this()) + ">:";
(| (.manager()).tell(str) |);
(| (.manager()).tell_traceback(traceback()) |);
(| sender().tell(str) |);
(| sender().tell_traceback(traceback()) |);
(| sender().tell("Continuing chparent..") |);
}
}
refresh();
}
};
public method .objname(): nooverride {
return (> objname() <);
};
public method .set_objname() {
arg objname;
(> .perms(sender()) <);
if (.has_flag('core))
throw(~perm, this() + " is a core object; you cannot change its object name!");
(> $sys.touch() <);
// Make sure first argument is a symbol.
if (type(objname) != 'symbol)
throw(~type, "New objname is not a symbol.");
// Make sure everything is lowercase.
objname = tosym(tostr(objname).lowercase());
// Do nothing if objname isn't different.
if (objname == (| objname() |))
return;
return (> set_objname(objname) <);
};
public method .created_on(): nooverride {
return created_on;
};
public method .is_of(): nooverride {
arg obj;
return obj in ancestors();
};
public method .is(): nooverride {
arg @args;
if (!args)
throw(~invarg, "Must have one argument.");
if (type(args[1]) == 'dictionary)
return has_ancestor(args[2]);
return has_ancestor(args[1]);
};
public method .hname() {
arg @args;
return ((("<a href=\"/bin/display?" + this()) + "\">") + this()) + "</a>";
};
public method .add_flag(): nooverride {
arg flag;
(> .perms(sender(), 'manager) <);
(> $sys.touch('coreok) <);
if ((flag == 'core) && (!($sys.is_system(sender()))))
throw(~perm, "Only system objects can set the 'core flag.");
(flag == 'fertile) && (> .perms(sender(), 'manager) <);
// let them add any flag they want
flags = (flags || []).setadd(flag);
};
public method .build_name() {
arg @args;
var output, type, part, rval;
output = "";
for part in (args) {
type = type(part);
if (type == 'list)
output += (| .(part[1])(@part.subrange(2)) |) || "";
else if (type == 'string)
output += part;
}
return output;
};
public method .clear_variable(): nooverride {
arg name;
var n, obj;
(> .perms(sender()) <);
n = tosym("_clear_var_" + tostr(time()));
catch any {
.add_method([("clear_var(" + toliteral(name)) + ");"], n);
for obj in (.descendants()) {
(| obj.(n)() |);
pause();
}
(| del_method(n) |);
} with {
(| del_method(n) |);
}
};
public method .ancestors_to(): nooverride {
arg checked, levels, maxlev;
var c, list;
list = [this()];
levels++;
// check parents
if ((!maxlev) || (maxlev != levels)) {
for c in (.parents()) {
list += [c.ancestors_to(checked, levels, maxlev)];
checked = checked.setadd(c);
}
}
return list;
};
public method .descendants_to(): nooverride {
arg checked, levels, maxlev;
var c, list;
list = [this()];
levels++;
// check parents
if ((!maxlev) || (maxlev != levels)) {
for c in (.children()) {
list += [c.descendants_to(checked, levels, maxlev)];
checked = checked.setadd(c);
}
}
return list;
};
public method .ancestry(): nooverride {
arg gen;
var i, out;
out = [];
if (type(gen) == 'objnum) {
for i in (.ancestors()) {
if (i.has_ancestor(gen))
out += [i];
}
return out;
}
if (gen != 0) {
for i in (.parents())
out = out.union(i.ancestry(gen - 1));
}
return out;
};
public method .generations(): nooverride {
arg gen;
var p, out;
out = [this()];
if (gen != 0) {
for p in (.parents())
out = out.union(p.generations(gen - 1));
}
return out;
};
public method .variable_info() {
arg gen, def, fltr, match;
var ancs, data, pp, p;
if (!(.has_flag('variables, sender())))
throw(~perm, (sender() + " cannot read variables on ") + this());
if (def)
ancs = [def];
else
ancs = .(gen[1])(gen[2]) || [this()];
data = [];
for pp in ((data().to_list()).reverse()) {
if (valid(pp[1]) && ((pp[1]) in ancs)) {
for p in (pp[2]) {
if (tostr(p[1]).(match)(fltr) != 0)
data += [[pp[1], @p]];
}
}
}
return data;
};
public method .method_flags(): nooverride {
arg method;
if (!(.has_flag('methods, sender())))
throw(~perm, (sender() + " doesn't have permission to find methods on ") + this());
return (> method_flags(method) <);
};
public method .method_access(): nooverride {
arg method;
if (!(.has_flag('methods, sender())))
throw(~perm, (sender() + " doesn't have permission to find methods on ") + this());
return (> method_access(method) <);
};
public method .set_method_flags(): nooverride {
arg method, flags;
var current;
if (!(.is_writable_by(sender())))
throw(~perm, (sender() + " cannot write to ") + this());
(> $sys.touch() <);
current = method_flags(method);
if ((('locked in flags) && (!('locked in current))) && (!($sys.is_system(sender()))))
throw(~perm, "Only administrators can set the locked method flag.");
if ((('nooverride in flags) && (!('nooverride in current))) && (!($sys.is_system(sender()))))
throw(~perm, "Only administrators can set the nooverride method flag.");
return set_method_flags(method, flags);
};
public method .set_method_access(): nooverride {
arg method, state;
if (!(.is_writable_by(sender())))
throw(~perm, (sender() + " cannot write to ") + this());
(> $sys.touch() <);
return (> set_method_access(method, state) <);
};
public method .set_flags(): nooverride {
arg new_flags;
(> .perms(sender(), 'manager) <);
(> $sys.touch() <);
if (type(new_flags) != 'list)
throw(~invflags, "Flags must be submitted as a list of symbols.");
if ((!new_flags) && flags)
return clear_var('flags);
if ((('core in new_flags) && (!('core in flags))) && (!($sys.is_system(sender()))))
throw(~perm, "Only system objects can set the 'core flag.");
if (('fertile in new_flags) && (!('fertile in flags)))
(> .perms(sender(), 'manager) <);
flags = new_flags;
};
public method .managed(): nooverride {
return managed || [];
};
root method .add_managed_obj(): nooverride {
managed = (managed || []).setadd(sender());
};
root method .del_managed_obj(): nooverride {
managed = (managed || []).setremove(sender());
if (!managed)
clear_var('managed);
};
public method .writes(): nooverride {
(> .perms(sender(), 'trusts) <);
return writes || [];
};
root method .add_writable_obj(): nooverride {
writes = (writes || []).setadd(sender());
};
root method .del_writable_obj(): nooverride {
writes = (writes || []).setremove(sender());
if (!writes)
clear_var('writes);
};
public method .trusted_by(): nooverride {
return trusted_by || [];
};
root method .add_trusted_obj(): nooverride {
trusted_by = (trusted_by || []).setadd(sender());
};
root method .del_trusted_obj(): nooverride {
trusted_by = (trusted_by || []).setremove(sender());
if (!trusted_by)
clear_var('trusted_by);
};
public method .has_flag(): nooverride {
arg flag, @sender;
[(sender ?= sender())] = sender;
if (flag == 'core)
return flag in (.flags());
return (flag in (.flags())) || (.trusts(sender));
};
public method .flags(): nooverride {
return flags || [];
};
public method .quota_exempt(): nooverride {
return quota_exempt;
};
public method .clean_root() {
var obj;
// Called by $sys.clean_database()
(> .perms(caller(), $sys) <);
(| ._clean_root('trusted, 'trusted_by) |);
(| ._clean_root('trusted_by, 'trusted) |);
(| ._clean_root('writers, 'writes) |);
(| ._clean_root('writes, 'writers) |);
if (!manager) {
manager = this();
.change_manager($reaper);
}
if (managed) {
managed = managed.valid_objects();
for obj in (managed) {
refresh();
if ((obj.manager()) != this())
managed = setremove(managed, obj);
}
if (!managed)
clear_var('managed);
}
};
public method .objnum(): nooverride {
return objnum();
};
public method .list_methods() {
arg gen, def, fltr, match;
var ancs, a, m, i, methods;
if (!(.has_flag('methods, sender())))
throw(~perm, (sender() + " cannot view methods on ") + this());
if (def)
ancs = [def];
else
ancs = .(gen[1])(gen[2]) || [this()];
methods = #[];
for a in (ancs) {
for m in (a.methods()) {
if (tostr(m).(match)(fltr) != 0) {
i = a.method_info(m);
methods = methods.add_elem(i[5], [a, m, @i]);
}
}
}
return methods;
};
public method .method_bytecode() {
arg method;
return (> method_bytecode(method) <);
};
public method .rename_method() {
arg now, new;
(> .perms(sender()) <);
(> $sys.touch() <);
return (> rename_method(now, new) <);
};
public method .examine() {
return [];
};
public method .new_descendants() {
var kid, kids;
kids = #[];
for kid in (children()) {
kids = kids.add(kid, 1);
kids = kids.union(kid.new_descendants());
pause();
}
return kids.keys();
};
private method ._clean_root() {
arg v, m;
var obj, value;
if ((value = get_var(v))) {
value = value.valid_objects();
for obj in (value) {
if (!(this() in obj.(m)()))
value = value.setremove(obj);
refresh();
}
if (value)
set_var(v, value);
else
clear_var(v);
}
};
public method .set_quota_exempt(): nooverride {
arg bool;
(> .perms(caller(), $user, @$sys.system(), $root) <);
if (bool)
quota_exempt = 1;
else
(| clear_var('quota_exempt) |);
};
public method .help_node() {
arg @args;
return help_node;
};
public method .parse_help_node_setting() {
arg value, @args;
if (!value)
return 0;
value = (> $object_lib.to_dbref(value) <);
if (!(value.is($help_node)))
throw(~perm, (value.namef('ref)) + " is not a $help_node.");
return value;
};
public method .list_method() {
arg @args;
if (!(.has_flag('code, sender())))
throw(~perm, (("Method code on " + (.namef('ref))) + " is not readable by ") + (sender().namef('ref)));
return (> list_method(@args) <);
};
public method .new() {
arg @suffix;
var obj, tmp, objname, mngr, na;
// this difference between this and .spawn() is that you
// can override this method to return a frob instead.
(> .will_spawn(sender()) <);
suffix = (> .get_obj_suffix(@suffix) <);
return $sys.spawn_sender(suffix, sender());
};
public method .will_spawn(): nooverride {
arg who;
if (!(.has_flag('fertile, who)))
throw(~perm, "Not fertile or readable.");
// available quota?
if (!(who.quota_valid()))
throw(~quota, "Sender does not have the available quota");
};
public method .get_obj_suffix() {
arg @suffix;
var objname, tmp;
// Figure out the suffix from the arguments and child index.
[(suffix ?= 0)] = suffix;
if (suffix) {
// so they dont confuse child_index:
if (suffix.is_numeric())
throw(~perm, "You cannot specify a numeric suffix.");
// so we get correct symbols & it is always lowercase:
suffix = lowercase(strsed(suffix, "[^a-z0-9_]+", "", "g"));
} else {
// get the next valid objname
objname = tostr((| .objname() |) || "unknown");
tmp = tosym(objname);
while ((| lookup(tmp) |)) {
child_index++;
tmp = tosym((objname + "_") + tostr(child_index));
}
suffix = tostr(child_index);
}
return suffix;
};
public method ._display_ancestors() {
arg space, checked, levels, maxlev;
var c, anc, list, id, perms;
id = ((space + this()) + " ") + ($object_lib.see_perms(this()));
for anc in (dict_keys(checked)) {
if (.has_ancestor(anc))
return [];
// [id + " (above)"];
}
if (((.parents()).length()) > 1)
id += " (MI)";
list = [id];
space += " ";
levels++;
// check parents
if ((!maxlev) || (maxlev != levels)) {
for c in (.parents()) {
list += c._display_ancestors(space, checked, levels, maxlev);
checked = dict_add(checked, c, 1);
pause();
}
}
return list;
};
public method .format_descendants() {
arg ind, done, depth, max, yes, no, above;
var c, anc, list, id, perms, f, show, myflags;
myflags = .flags();
show = 1;
if (yes) {
for f in (yes) {
if (!(f in myflags)) {
show = 0;
break;
}
}
}
if (no) {
for f in (myflags) {
if (f in no) {
show = 0;
break;
}
}
}
if (show) {
id = ((ind + this()) + " ") + ($object_lib.see_perms(this()));
for anc in (dict_keys(done)) {
if (has_ancestor(anc))
return above ? [id + " (ABOVE)"] : [];
}
if (listlen(parents()) > 1)
id += " (MI)";
list = [id];
} else {
list = [];
}
ind += " ";
depth++;
// check children
if ((!max) || (max != depth)) {
for c in (children()) {
list += c.format_descendants(ind, done, depth, max, yes, no, above);
done = dict_add(done, c, 1);
pause();
}
}
return list;
};
public method .undefine_setting(): nooverride {
arg name;
var d;
(> .perms(sender()) <);
if (!((.defined_settings()).contains(name)))
throw(~setnf, (("Setting \"" + name) + "\" is not defined by ") + this());
// clear it on all descendants, then us
for d in ((.descendants()) + [this()]) {
d._clear_setting(name);
pause();
}
// bye bye
defined_settings = dict_del(defined_settings, name);
if (!defined_settings)
clear_var('defined_settings);
};
public method .define_setting(): nooverride {
arg name, @info;
var i;
(> .perms(sender()) <);
if (info) {
info = info[1];
for i in (info) {
if (!(> .valid_setting_attr(@i) <))
info = dict_del(info, i[1]);
}
} else {
info = #[];
}
if ((.all_defined_settings()).contains(name))
throw(~setexists, ("Setting \"" + name) + "\" is already defined.");
if (!($code_lib.valid_setting_id(name)))
throw(~setbad, ("Setting name \"" + name) + "\" is unacceptable.");
defined_settings = (.defined_settings()).add(name, info);
return defined_settings[name];
};
public method .all_defined_settings(): nooverride {
if (!(.has_flag('variables, sender())))
throw(~perm, ((sender().namef('ref)) + " does not have permission to view settings on ") + (.name('ref)));
return ._all_defined_settings();
};
public method .defined_settings(): nooverride {
return defined_settings || #[];
};
public method .settings(): nooverride {
(> .perms(sender()) <);
return settings || #[];
};
public method .setting_info(): nooverride {
arg setting;
return defined_settings[setting];
};
public method .get_setting(): nooverride {
arg name, definer;
var i;
i = definer.setting_info(name);
if (dict_contains(i, 'access))
(> .((i['access])[1])(name, sender(), caller(), @sublist(i['access], 2)) <);
if (dict_contains(i, 'get))
return (> .((i['get])[1])(name, definer, @sublist(i['get], 2)) <);
catch any
return settings[name];
with
return (> definer.get_default_setting(name) <);
};
public method .get_default_setting(): nooverride {
arg name;
return settings[name];
};
public method .clear_setting(): nooverride {
arg name, definer;
var info, args;
(caller() == definer()) || (> .perms(sender()) <);
info = (> definer.setting_info(name) <);
if (dict_contains(info, 'clear)) {
args = sublist(info['clear], 2);
(> .((info['clear])[1])(name) <);
} else if (settings && dict_contains(settings, name)) {
settings = dict_del(settings, name);
if (!settings)
clear_var('settings);
}
};
public method .format_setting(): nooverride {
arg name, definer, value;
var i, args;
i = definer.setting_info(name);
if (dict_contains(i, 'format)) {
args = sublist(i['format], 2);
catch ~methodnf
return (> .((i['format])[1])(value, @args) <);
with
return (> $settings.((i['format])[1])(value, @args) <);
}
if (type(value) == 'objnum)
return value.namef('ref);
else
return "" + value;
};
public method .set_setting_attr(): nooverride {
arg name, attr, value;
var info;
(> .perms(sender()) <);
if ((!defined_settings) || (!dict_contains(defined_settings, name)))
throw(~setnf, (("Setting \"" + name) + "\" is not defined on ") + this());
if (value && (!(> .valid_setting_attr(attr, value) <)))
return;
info = defined_settings[name];
if (!value)
info = dict_del(info, attr);
else
info = dict_add(info, attr, value);
defined_settings = dict_add(defined_settings, name, info);
};
public method .get_setting_attr(): nooverride {
arg name, attr;
return (defined_settings[name])[attr];
};
public method .setting_definer(): nooverride {
arg name;
var a;
for a in (ancestors()) {
if (dict_contains(a.defined_settings(), name))
return a;
}
throw(~setnf, ("Setting \"" + name) + "\" is not defined.");
};
public method .set_setting(): nooverride {
arg name, definer, value;
var i, args;
(> .perms(sender()) <);
i = (> definer.setting_info(name) <);
if (dict_contains(i, 'parse)) {
args = sublist(i['parse], 2);
catch ~methodnf
value = (> .((i['parse])[1])(value, @args) <);
with
value = (> $settings.((i['parse])[1])(value, @args) <);
}
if (dict_contains(i, 'set))
(> .((i['set])[1])(name, definer, value, @sublist(i['set], 2)) <);
else
settings = dict_add(settings || #[], name, value);
};
public method .valid_setting_attr(): nooverride {
arg name, value;
if (!(name in ['get, 'set, 'parse, 'clear, 'format, 'access]))
throw(~setattr, "Invalid setting attribute '" + name);
if (!value)
return 0;
else if (type(value) != 'list)
throw(~setattr, "Setting attribute must be a list");
else if (type(value[1]) != 'symbol)
throw(~setattr, "Setting attribute[1] is not a symbol");
return 1;
};
private method ._clear_setting(): nooverride {
arg name;
if (settings && dict_contains(settings, name)) {
settings = dict_del(settings, name);
if (!settings)
clear_var('settings);
}
};
public method .get_local_setting(): nooverride {
arg name, definer;
var i;
i = definer.setting_info(name);
if (dict_contains(i, 'access))
(> .((i['access])[1])(name, sender(), caller(), @sublist(i['access], 2)) <);
return (| settings[name] |) || (> definer.get_default_setting(name) <);
};
protected method ._all_defined_settings(): nooverride {
var a, all, d;
all = #[];
for a in (ancestors()) {
catch any {
for d in (dict_keys(a.defined_settings()))
all = dict_add(all, d, a);
}
}
return all;
};
public method .ancestors_descending() {
arg obj;
var anc;
return filter anc in (.ancestors()) where (anc.has_ancestor(obj));
};
public method .anc2(): nooverride {
var i, c, parent, d;
d = #[];
for parent in (parents())
d = dict_add(d, parent, 1);
while ((| (c = dict_keys(d)[++i]) |)) {
for parent in (c.parents()) {
pause();
d = dict_add(d, parent, 1);
}
pause();
}
return dict_keys(d);
};
root method .core_root() {
(| clear_var('child_index) |) || (child_index = 0);
};
protected method .set_help_node_setting() {
arg name, definer, value;
if (!value)
(| clear_var('help_node) |);
else
help_node = value;
};
public method .format_help_node_setting() {
arg node;
if (node)
return node.namef('ref);
return "";
};
public method .release_semaphore(): nooverride {
arg type;
if ((| (semaphores[type]) == task_id() |))
semaphores = dict_del(semaphores, type);
if (!semaphores)
clear_var('semaphores);
};
public method .poll_semaphore(): nooverride {
arg type;
var t;
if (!(caller().has_flag('core)))
return;
while (1) {
if (!semaphores) {
semaphores = #[[type, task_id()]];
return;
}
if ((type((| (t = semaphores[type]) |)) == 'error) || (!(t in tasks()))) {
semaphores = dict_add(semaphores, type, task_id());
return;
}
pause();
pause();
pause();
}
};
public method .query_semaphore() {
arg type;
var t;
return (type((| (t = semaphores[type]) |)) != 'error) && ((t in tasks()) && (t != task_id()));
};
public method .poll_semaphores() {
arg type, @s;
var i;
if (!(caller().has_flag('core)))
return;
refresh();
while (find i in (s) where (i.query_semaphore(type))) {
pause();
pause();
pause();
}
for i in (s)
i.poll_semaphore(type);
};
public method .nop() {
// the no operation, operation, woowoo
};
public method .credit() {
return credit || [];
};
public method .set_credit() {
arg newcopy;
var x;
(> .perms(sender(), 'manager) <);
if (newcopy == 0)
return (| clear_var('credit) |);
if ((type(newcopy) != 'list) || find x in (newcopy) where (type(x) != 'string))
throw(~type, "You must submit a list of strings for the credit.");
credit = newcopy;
};
object $sys: $root;
var $sys admins = [];
var $sys agents = [$root, $daemon];
var $sys startup = #[['objects, [$login_daemon, $http_daemon, $smtp_daemon, $world, $dns, $lag_watcher]], ['heartbeat_interval, 2]];
var $sys starting = #[['quota, 76800], ['new_user_class, $admin], ['anonymous_user_class, $guest]];
var $root defined_settings = #[["loggers", #[['get, ['loggers]], ['set, ['set_loggers]], ['parse, ['parse_itemlist, 'parse_object]], ['format, ['format_itemlist]]]], ["deny-hosts", #[['get, ['deny_hosts]], ['set, ['set_deny_hosts]], ['parse, ['parse_itemlist, 'parse_deny_host]], ['format, ['format_itemlist]]]], ["deny-users", #[['get, ['deny_users]], ['set, ['set_deny_users]], ['parse, ['parse_itemlist, 'parse_deny_user]], ['format, ['format_itemlist]]]], ["backup-interval", #[['get, ['get_backup_interval]], ['set, ['set_backup_interval]], ['parse, ['parse_backup_interval]], ['format, ['fmt_backup_interval]]]], ["validate-email-addresses", #[['parse, ['is_boolean]], ['format, ['format_boolean]], ['get, ['validate_email_addresses]], ['set, ['set_validate_email_addresses]]]], ["initial-quota", #[['get, ['get_initial_quota]], ['set, ['set_initial_quota]], ['parse, ['parse_initial_quota]], ['format, ['fmt_initial_quota]]]], ["new-user-class", #[['get, ['get_new_user_class]], ['set, ['set_new_user_class]], ['parse, ['parse_new_user_class]], ['format, ['format_object]]]], ["anonymous-user-class", #[['get, ['get_anon_user_class]], ['set, ['set_anon_user_class]], ['parse, ['parse_anon_user_class]], ['format, ['format_object]]]], ["startup-objects", #[['get, ['get_startup_objects]], ['set, ['set_startup_objects]], ['parse, ['parse_itemlist, 'parse_startup_object]], ['format, ['format_itemlist]]]], ["writable-core", #[['get, ['writable_core]], ['set, ['set_writable_core]], ['parse, ['is_boolean]], ['format, ['format_boolean]]]], ["valid-genders", #[['parse, ['parse_itemlist, 'parse_valid_genders]], ['get, ['get_valid_genders]], ['set, ['set_valid_genders]], ['format, ['format_itemlist]]]], ["heartbeat-interval", #[['get, ['get_heartbeat_interval]], ['set, ['set_heartbeat_interval]], ['parse, ['parse_heartbeat_interval]], ['format, ['fmt_heartbeat_interval]]]]];
var $sys core_version = "3.0a10";
var $sys validate_email_addresses = 0;
var $sys backup = #[['interval, 3600], ['last, 0], ['next, 0]];
var $sys system = [$sys, $root];
var $sys touched = 0;
var $sys loggers = [$daemon, $user, $connection, $dns];
var $root created_on = 796268969;
var $root inited = 1;
var $root flags = ['methods, 'code, 'core, 'variables];
var $root quota_exempt = 1;
var $root manager = $sys;
var $sys bindings = #[['atomic, $sys], ['create, $sys], ['backup, $sys], ['shutdown, $sys], ['set_heartbeat, $sys], ['cancel, $scheduler], ['task_info, $scheduler], ['execute, $sys], ['bind_function, $sys], ['unbind_function, $sys], ['bind_port, $daemon], ['unbind_port, $daemon], ['open_connection, $connection], ['reassign_connection, $daemon], ['fopen, $file], ['fstat, $file], ['fchmod, $file], ['fmkdir, $file], ['frmdir, $file], ['files, $file], ['fremove, $file], ['frename, $file], ['fclose, $file], ['fseek, $file], ['feof, $file], ['fwrite, $file], ['fread, $file], ['fflush, $file], ['chparents, $root], ['destroy, $root], ['dblog, $sys], ['add_var, $root], ['del_var, $root], ['variables, $root], ['list_method, $root], ['add_method, $root], ['del_method, $root], ['method_bytecode, $root], ['methods, $root], ['rename_method, $root], ['set_method_access, $root], ['set_method_flags, $root], ['data, $root], ['del_objname, $root], ['set_objname, $root], ['suspend, $scheduler], ['resume, $scheduler], ['set_user, $user], ['config, $sys], ['cache_info, $sys]];
var $root managed = [$sys];
var $sys deny_hosts = [];
var $sys deny_users = [];
var $sys writable_core = 0;
var $sys valid_genders = [$gender_male, $gender_female, $gender_neuter];
var $sys configured = #[];
var $sys config_set = ['new_user_class, 'server_name, 'server_title, 'daemons];
public method .next_objnum(): native;
public method .version(): native;
driver method .startup() {
arg args;
var opt, str, obj, f, ver, firsttime, doinit;
set_heartbeat(0);
// clean db?
if ("-clean" in args) {
catch any {
dblog("** Cleaning Database..");
(> .clean_database() <);
dblog("** Done.");
if (dict_contains(startup, 'time))
startup = dict_del(startup, 'time);
} with {
.log($parse_lib.traceback(traceback()));
}
doinit = "-init" in args;
} else {
doinit = ("-init" in args) || (!dict_contains(startup, 'time));
}
// init?
if (doinit) {
catch any {
dblog("** Initializing Database..");
(> .init_database() <);
dblog("** Done.");
} with {
.log($parse_lib.traceback(traceback()));
}
}
// done?
if ("-quit" in args) {
dblog("** Shutting down.");
.shutdown();
return;
}
// make core?
if ((opt = find opt in (args) where (opt.match_begin("-makecore=")))) {
ver = regexp(args[opt], "-MAKECORE=(.*)$")[1];
dblog(("** Calling .make_core(\"" + ver) + "\")..");
.make_core(ver);
return;
}
// Standard startup..
startup = startup.add('time, time());
backup = backup.add('next, time() + (backup['interval]));
catch any {
// get back the heartbeat
set_heartbeat(startup['heartbeat_interval]);
// Bind functions for security
for f in (bindings) {
catch any
bind_function(@f);
with
dblog((("** Unable to bind function " + (f[1])) + "() to ") + (f[2]));
}
// tell objects who should know, that we are online
if (type(args) != 'list)
args = [];
for obj in (startup['objects]) {
.log(("Calling " + obj) + ".startup()");
catch any
(> obj.startup(@args) <);
with
.log($parse_lib.traceback(traceback()));
}
} with {
.log(("** Startup ERROR at " + ctime()) + ":");
.log(toliteral(traceback()));
.log($parse_lib.traceback(traceback(), -1, ""));
}
};
public method .server_info() {
arg what, @long;
var tmp;
switch (what) {
case 'up_time:
return time() - (startup['time]);
case 'startup_time:
return startup['time];
case 'server_hostname:
return $dns.hostname("");
case 'server_ip:
return $dns.ip("");
case 'last_backup:
return backup['last];
case 'driver_version:
tmp = .version();
return (((((((long ? "Genesis " : "") + (tmp[1])) + ".") + (tmp[2])) + "p") + (tmp[3])) + "-") + ((listlen(tmp) == 3) ? "NEED TO UPGRADE" : (tmp[4]));
case 'core_version:
return (long ? "ColdCore " : "") + core_version;
case 'version:
tmp = .version();
return ((((((((("Genesis/" + (tmp[1])) + ".") + (tmp[2])) + "p") + (tmp[3])) + "-") + (tmp[4])) + " ") + "ColdCore/") + core_version;
default:
throw(~unknown, "Unknown flag.");
}
};
public method .create_user() {
arg name, password, email, @type;
var user;
if ((!(| caller() == $login_interface |)) && (type((| .perms(sender(), 'system) |)) == 'error))
throw(~perm, "Caller and Sender are not allowed to call this method.");
[(type ?= 'new_user_class)] = type;
catch any {
user = (starting[type]).spawn(name);
user.set_name(name);
if (type == 'new_user_class)
user.set_password(password);
user.change_manager(user);
user.set_user_info("rl-email", $user_info, email);
} with {
// Failed to initialize the child; destroy it.
(| user.destroy() |);
rethrow(error());
}
return user;
};
public method .admins() {
return admins;
};
public method .is_admin() {
arg obj;
return (obj == $sys) || (obj in admins);
};
public method .shutdown() {
var opt, str, obj;
(> .perms(sender(), $sys) <);
// tell startup objects that we are closing shop
for obj in (startup['objects]) {
.log(("Calling " + obj) + ".shutdown()");
catch any
(> obj.shutdown() <);
with
.log($parse_lib.traceback(traceback()));
}
touched = 0;
return shutdown();
};
public method .spawn_sender() {
arg suffix, manager;
var namestr;
(> .perms(caller(), $root, $sys) <);
namestr = (tostr(sender().objname()) + "_") + suffix;
return .create([sender()], tosym(namestr), manager);
};
public method .is_system() {
arg obj;
return obj in system;
};
public method .log() {
arg text;
var l;
if ((!sender()) in loggers) {
if ((!(| .perms(sender(), 'system) |)) && (!(| .perms(caller(), 'system) |)))
throw(~perm, "Only system objects can log.");
}
if (type(text) == 'list) {
for l in (text)
.log(l);
} else {
dblog((("[" + ($time.format("%d %h %y %H:%M"))) + "] ") + text);
}
};
driver method .heartbeat() {
(| $scheduler.pulse() |);
if (time() > (backup['next]))
.do_backup(this(), 'interval);
};
public method .do_backup() {
arg @args;
var line, who, how, name, dirty;
(> .perms(sender(), 'system) <);
dirty = .dirty();
[(who ?= sender()), (how ?= 'request)] = args;
if (!valid(who))
who = sender();
backup = backup.add('next, time() + (backup['interval]));
backup = backup.add('last, time());
if ((how == 'interval) && (!dirty))
return;
catch any {
name = who.namef('ref);
.log(("BACKUP (" + name) + ") ");
line = (("Backup started at " + ($time.format("%r"))) + " by ") + name;
$channel_ui._broadcast('System, line);
}
// double pause will hopefully let people know about it before it happens
pause();
pause();
backup = backup.add('started, time());
(> backup() <);
};
public method .set_startup() {
arg what, value;
var valid;
(> .perms(sender(), 'system) <);
valid = startup.keys();
if ((!what) in valid)
throw(~type, "Key must be one of " + toliteral(valid));
startup = startup.add(what, value);
};
public method .host_denied() {
arg remote;
var t;
for t in (deny_hosts) {
if (match_begin(remote, t) != 0)
return 1;
}
return 0;
};
public method .new_admin() {
if (caller() != $admin)
throw(~perm, "Caller is not $admin.");
admins = setadd(admins, sender());
};
public method .agents() {
return agents;
};
public method .get_startup() {
arg what;
return startup[what];
};
public method .set_starting() {
arg what, value;
var valid;
(> .perms(sender(), 'system) <);
valid = starting.keys();
if ((!what) in valid)
throw(~type, "Key must be one of " + toliteral(valid));
starting = starting.add(what, value);
};
public method .execute() {
arg script, args, @background;
(> .perms(sender(), 'system) <);
(> execute(script, args, @background) <);
};
public method .get_starting() {
arg what;
return starting[what];
};
private method .create() {
arg parents, name, manager;
var new;
new = create(parents);
catch any {
new.set_objname(name);
new.initialize();
new.change_manager(manager);
} with {
// Failed to initialize the child; destroy it.
(| new.destroy() |);
rethrow(error());
}
return new;
};
public method .system() {
return system;
};
public method .deny_hosts() {
arg @args;
return deny_hosts;
};
protected method .set_loggers() {
arg name, definer, value;
switch (value[1]) {
case 'set:
loggers = value[2];
case 'add:
loggers = setadd(loggers, value[2]);
case 'del:
loggers = setremove(loggers, value[2]);
default:
throw(~type, "Unknown action: " + (value[1]));
}
};
public method .add_method() {
arg code, name, @evalonly;
var line;
(> .perms(sender()) <);
line = (("SYSTEM: ." + tostr(name)) + "() ") + (evalonly ? "EVAL" : "MODIFIED");
line = (line + " by ") + (sender().namef('ref));
.log(line);
return (> pass(code, name, @evalonly) <);
};
public method .atomic() {
arg @args;
(> .perms(sender(), 'system) <);
return (> atomic(@args) <);
};
public method .fmt_backup_interval() {
arg data;
return $time.to_english(data);
};
public method .get_backup_interval() {
arg @args;
return backup['interval];
};
public method .validate_email_addresses() {
arg @args;
return validate_email_addresses;
};
public method .parse_backup_interval() {
arg value, @args;
value = (> $time.from_english(value) <);
if (value < 300)
throw(~perm, "You cannot set your backup interval to less than 5 minutes");
return value;
};
driver method .signal() {
arg signal;
var line;
// the driver will send the following signals:
// HUP -- driver will drop out of atomic mode and will flush i/o
// USR2 -- driver does nothing
// USR1 -- driver aborts all currently executing tasks, not suggested
// QUIT -- For both of these the driver will shutdown after current
// INT tasks finish their current execution frame. Note: do not
// preempt tasks at this point as they will not resume.
line = ("** Received Signal: " + signal) + " **";
(| $channel_ui._broadcast('System, line) |);
if (signal in ['QUIT, 'INT]) {
(| $channel_ui._broadcast('all, "******************************") |);
(| $channel_ui._broadcast('all, "** IMMINENT SERVER SHUTDOWN **") |);
(| $channel_ui._broadcast('all, "******************************") |);
}
};
root method .sender_going_away() {
admins = admins.setremove(sender());
agents = agents.setremove(sender());
system = system.setremove(sender());
};
public method ._status(): native;
bind_native .status() ._status();
public method .status() {
return (> ._status() <) + [backup['interval], backup['last], backup['next]];
};
private method ._loop_for_core() {
arg code;
var obj;
$root.add_method(code, '___coretmp);
for obj in ($root.descendants()) {
obj.___coretmp();
pause();
}
$root.del_method('___coretmp);
};
private method .initialize_core() {
var obj;
(| .clean_database() |);
// reset child indices
._loop_for_core(["child_index = 0;"]);
};
private method .clean_database() {
var obj, p, c, cmd;
// cleanup some of $root's messiness
for obj in ($root.descendants()) {
(| obj.clean_root() |);
refresh();
}
// purge all command caches
for obj in ($command_cache.descendants()) {
(| obj.purge_cache() |);
refresh();
}
// check user info (move'em home etc)
for obj in ($user.descendants()) {
if ((| (obj.home()) != (obj.location()) |))
(| obj.move_to(obj.home()) |);
refresh();
}
// validate all locations and location content's
for obj in ($physical.descendants()) {
(| obj.validate_contents() |);
if (obj.has_ancestor($located)) {
if ((!valid(obj.location())) || (!(obj in ((obj.location()).contents()))))
obj.move_to((| obj.home() |) || $lost_and_found);
}
refresh();
}
};
protected method .set_backup_interval() {
arg name, definer, value;
backup = backup.add('interval, value);
};
public method .add_to_system() {
arg obj;
if (!(.is_admin(sender())))
throw(~perm, "Sender is not an admin.");
if (!((obj in admins) || (obj in agents)))
throw(~perm, "Object is not an agent or admin.");
system = system.union([obj]);
};
public method .del_from_system() {
arg obj;
if (!(.is_admin(sender())))
throw(~perm, "Sender is not an admin.");
if (!((obj in admins) || (obj in agents)))
throw(~perm, "Object is not an agent or admin.");
system = system.setremove(obj);
};
public method .touch() {
arg @nocorelock;
if ((!nocorelock) && ((sender().has_flag('core)) && (!writable_core)))
throw(~perm, sender() + " is a core object, and the core isn't writable.");
touched = time();
};
public method .touched() {
return touched;
};
public method .backup() {
return backup;
};
public method .dirty() {
return touched > (backup['last]);
};
public method .do_shutdown() {
arg time, why;
var increments, line, name, mins, secs;
if ((!($sys.is_admin(sender()))) || (definer() != this()))
throw(~perm, "Sender is not an admin.");
increments = [600, 300, 180, 60];
secs = time * 60;
while (increments && (secs < (increments[1])))
increments = increments.delete(1);
if (increments && (secs > (increments[1])))
increments = [secs] + increments;
name = sender().namef('xref);
.log(("*** SHUTDOWN called by " + name) + " ***");
if (why) {
why = ("*** REASON: " + why) + " ***";
.log(why);
}
while (1) {
if (!increments) {
$channel_ui._broadcast('All, "*** SYSTEM SHUTDOWN ***");
if (why)
$channel_ui._broadcast('All, why);
break;
}
line = "*** SYSTEM SHUTDOWN IN ";
mins = (increments[1]) / 60;
line = ((line + tostr(mins)) + " MINUTE") + ((mins == 1) ? "" : "S");
line = ((line + " CALLED BY ") + name) + " ***";
$channel_ui._broadcast('All, line);
if (why)
$channel_ui._broadcast('All, why);
if ((increments.length()) > 1)
$scheduler.sleep((increments[1]) - (increments[2]));
else
$scheduler.sleep(increments[1]);
increments = increments.delete(1);
}
pause();
pause();
return .shutdown();
};
public method .loggers() {
arg @args;
return loggers;
};
root method .core_sys(): nooverride {
deny_hosts = (deny_users = []);
touched = 0;
system = [$sys, $root];
backup = #[['interval, 3600], ['last, 0], ['next, 0]];
validate_email_addresses = 0;
starting = #[['quota, 76800], ['new_user_class, $admin], ['anonymous_user_class, $guest]];
startup = #[['objects, [$login_daemon, $http_daemon, $smtp_daemon, $world, $dns, $lag_watcher]], ['heartbeat_interval, 2]];
agents = [$root, $daemon];
admins = [];
writable_core = 0;
configured = #[];
};
driver method .backup_done() {
var elapsed;
elapsed = time() - (backup['started]);
backup = backup.del('started);
catch any {
$channel_ui._broadcast('System, "Backup completed, elapsed time " + ($time.to_english(elapsed)));
$channel_ui._broadcast('System, "Executing filesystem cleanup.. ");
pause();
pause();
.execute("backup", []);
}
};
private method .make_core() {
arg ver;
var obj, obj2, d, o, top, x, admin, tmp, name;
// core rooms should be +core, and cant be destroyed
// traverse the list inverseley, less unseen heirarchial shuffling
dblog("** Starting Core Extraction " + ctime());
d = $root.descendants();
top = listlen(d);
core_version = ver;
dblog(("** " + top) + " objects total, tidying up core objects...");
// tidy up core objects first
for obj in (d) {
refresh();
if (obj.has_flag('core)) {
tmp++;
catch any {
obj.change_manager(obj);
for o in (obj.writers('literal)) {
refresh();
obj.del_writer(o);
}
} with {
dblog(("** TIDY " + obj) + " traceback: ");
for o in ($parse_lib.traceback(traceback()))
dblog("** " + o);
}
}
}
// nuke anything not core
dblog(("** " + tmp) + " core objects, destroying non-core objects...");
for x in [1 .. top] {
refresh();
obj = d[(top - x) + 1];
if (!valid(obj)) {
// dblog(".. Skipping invalid object " + obj);
continue;
}
if (!(obj.has_flag('core))) {
if (obj.children()) {
for obj2 in (obj.children()) {
if (obj2.has_flag('core)) {
dblog("** ABORTING: A NON CORE OBJECT HAS CORE CHILDREN: ");
dblog((("** " + obj) + " => ") + (obj.children()));
shutdown();
}
}
}
catch any {
// dblog(".. Destroying " + obj);
obj.destroy();
} with {
dblog(("** " + obj) + ".destroy() traceback: ");
for o in ($parse_lib.traceback(traceback()))
dblog("** " + o);
}
}
}
// shutdown this task so that references can have
// a chance to clear out, on destroyed objects.
dblog("** done, suspending for new task **");
// do this the hard way, to be secure
set_heartbeat(1);
.add_var('TMP_HEARTBEAT_CODE, .list_method('heartbeat));
.add_method([".finish_core();"], 'heartbeat);
};
public method .task_info() {
arg @args;
(> .perms(sender(), 'system) <);
return (> task_info(@args) <);
};
public method .destroy_sender() {
// potential problem spot, but sometimes its needed
// add core definer items to the list, if you want them to call it
(> .perms(caller(), $path, $connection, $connection_interface) <);
(> sender().destroy() <);
};
private method .finish_core() {
// cleanup heartbeat
set_heartbeat(0);
.add_method(TMP_HEARTBEAT_CODE, 'heartbeat);
.del_var('TMP_HEARTBEAT_CODE);
// ok, finish up
catch any {
dblog("** corifying remaining objects");
$root.corify();
dblog("** cleaning database..");
.clean_database();
dblog("** shutting down..");
shutdown();
} with {
dblog("traceback: " + traceback());
}
};
public method .old_admin() {
if (caller() != $admin)
throw(~perm, "Caller is not $admin.");
admins = setremove(admins, sender());
system = setremove(system, sender());
};
root method .clear_definer_vars(): nooverride {
arg definer, objs;
var code, v, a, meth, errs, d;
code = [];
for v in (definer.variables())
code += [("(| clear_var('" + v) + ") |);"];
meth = tosym("_root_tmp_" + time());
if (!(definer.add_method(code, meth, 1))) {
for d in (objs) {
pause();
(| d.(meth)() |);
}
(| definer.del_method(meth) |);
}
};
public method .spawn_selfmanager() {
arg name, @writers;
var obj, w;
// Differs from .spawn_sender in that the object created manages itself.
// Add to this list as necessary:
(> .perms(sender(), $mail_message) <);
obj = (> .create([sender()], name, this()) <);
for w in (writers)
obj.add_writer(w);
obj.change_manager(obj);
return obj;
};
private method .init_database() {
var obj, p, c, cmd, other;
// re-init caches
$remote_cache.rehash_cache();
// only rehash non-general caches--general caches should be initialized
// as they are needed, by .cache_server_init().
other = ($command_cache.children()).setremove($user_interfaces);
other = ((other.mmap('descendants)).flatten()).compress();
for obj in (filter obj in (other) where (!(obj.is_general_cache()))) {
(| obj.rehash_cache() |);
refresh();
}
};
public method .startup_dnsserv() {
if (sender() != $dns)
(> .perms(sender(), 'system) <);
execute("dnsstartup", [], 1);
};
protected method .set_deny_hosts() {
arg name, definer, value;
switch (value[1]) {
case 'set:
deny_hosts = value[2];
case 'add:
deny_hosts = setadd(deny_hosts, value[2]);
case 'del:
deny_hosts = setremove(deny_hosts, value[2]);
default:
throw(~type, "Unknown action: " + (value[1]));
}
};
public method .parse_deny_host() {
arg value, @args;
var parts;
// DNS Hostnames are not used due to the extreme slowdown it would
// cause to _ALL_ services
if (match_regexp(value, "[^0-9.]"))
throw(~type, "Invalid Internet Host IP address or subnet: " + value);
parts = explode(value, ".");
if (listlen(parts) < 2)
throw(~type, "Do you really want to deny an entire class A network?");
if (listlen(parts) > 4)
throw(~type, "Invalid IP Address: " + (parts.join(".")));
return parts.join(".");
};
public method .deny_users() {
arg @args;
return deny_users;
};
public method .user_denied() {
arg user;
return user in deny_users;
};
protected method .set_deny_users() {
arg name, definer, value;
switch (value[1]) {
case 'set:
deny_users = value[2];
case 'add:
deny_users = setadd(deny_users, value[2]);
case 'del:
deny_users = setremove(deny_users, value[2]);
default:
throw(~type, "Unknown action: " + (value[1]));
}
};
public method .parse_deny_user() {
arg value, @args;
var obj;
if (value && ((value[1]) == "$")) {
obj = (> $object_lib.to_dbref(value) <);
if (!(obj.is($user)))
throw(~perm, (obj.namef('ref)) + " is not a user.");
} else {
obj = (> $user_db.search(value) <);
}
return obj;
};
protected method .set_validate_email_addresses() {
arg name, definer, value;
validate_email_addresses = value;
};
public method .fmt_initial_quota() {
arg data;
return data.to_bytes();
};
public method .get_initial_quota() {
arg @args;
return starting['quota];
};
public method .parse_initial_quota() {
arg value, @args;
value = (> value.to_bytes() <);
if (value < 1024)
throw(~perm, "You cannot set your initial quota to less than 1 kb");
return value;
};
protected method .set_initial_quota() {
arg name, definer, value;
starting = starting.add('quota, value);
};
public method .get_new_user_class() {
arg @args;
return starting['new_user_class];
};
public method .parse_new_user_class() {
arg value, @args;
value = (> $object_lib.to_dbref(value) <);
if (!(value.is($user)))
throw(~perm, (value.namef('ref)) + " is not a $user object.");
if (!(value.has_flag('command_cache)))
throw(~perm, (value.namef('ref)) + " is not a command cache object.");
return value;
};
protected method .set_new_user_class() {
arg name, definer, value;
starting = starting.add('new_user_class, value);
};
public method .get_anon_user_class() {
arg @args;
return starting['anonymous_user_class];
};
public method .parse_anon_user_class() {
arg value, @args;
value = (> $object_lib.to_dbref(value) <);
if (!(value.is($user)))
throw(~perm, (value.namef('ref)) + " is not a $user object.");
if (!(value.has_flag('command_cache)))
throw(~perm, (value.namef('ref)) + " is not a command cache object.");
return value;
};
protected method .set_anon_user_class() {
arg name, definer, value;
starting = starting.add('anon_user_class, value);
};
protected method .set_startup_objects() {
arg name, definer, value;
switch (value[1]) {
case 'set:
startup = startup.add('objects, value[2]);
case 'add:
startup = startup.add('objects, setadd(startup['objects], value[2]));
case 'del:
startup = startup.add('objects, setremove(startup['objects], value[2]));
default:
throw(~type, "Unknown action: " + (value[1]));
}
};
public method .configure_core() {
var list, l, x, t, err, s;
if (caller() != $admin)
(> .perms(sender()) <);
s = sender();
// if there is nothing left to config, leave..
if (configured) {
if (!(list = config_set.set_difference(configured.keys())))
return;
} else {
configured = #[];
}
.add_to_system(s);
// wait for other things to finish printing messages to them
pause();
pause();
// expand on this as we go
s.tell(["*" * 78, strfmt("%78{*}c", " Welcome to ColdCore "), "*" * 78]);
s.tell(("This is an interactive configuration system which any admin who connects (until it is completed) is sent through. You must complete this configuration before you can do anything else. You can skip a specific question at any time by typing '@skip'. Suggested default values will be enclosed in square brackets. Pressing enter without any value will use the default value.".wrap_lines(78)).mmap('center, 78));
s.tell("*" * 78);
// first question please
if (!(configured.contains('new_user_class))) {
s.tell("What class should new users be created as? Available classes:");
list = filter x in ($user.descendants()) where ('command_cache in (x.flags()));
t = .get_new_user_class();
list = map x in (list) to ((list == t) ? (x + " (current class)") : x);
s.tell(list.prefix(" "));
while (!l) {
refresh();
l = s.prompt(("New User Class [" + t) + "] ");
if (l == "@skip") {
s.tell("Skipping..");
break;
}
if (l) {
catch any {
l = $object_lib.to_dbref(l);
if (!(l in list))
s.tell("Invalid selection, try again.");
} with {
s.tell(("Invalid selection '" + l) + "'");
continue;
}
} else {
l = t;
}
.set_setting("new-user-class", $sys, l);
configured = configured.add('new_user_class, 1);
s.tell("New User Class set to: " + l);
}
s.tell(["", "You can set this at any time, with the command:"]);
s.tell(" @set $sys:new-user-class=" + l);
}
refresh();
// server name/title
if (!(configured.contains('server_name))) {
s.tell(["", "---"]);
t = $motd.server_name();
l = (s.prompt(("What is your server name? [" + t) + "] ")) || t;
if (l == "@skip") {
s.tell("Skipping..");
} else {
$motd.set_setting("server-name", $motd, l);
configured = configured.add('server_name, 1);
s.tell("Server name set to: " + l);
}
s.tell(["", "You can set this at any time, with the command:"]);
s.tell(" @set $motd:server-name=" + l);
}
refresh();
if (!(configured.contains('server_title))) {
s.tell(["", "---"]);
t = $motd.server_title();
l = (s.prompt(("What is your server title? [" + t) + "] ")) || t;
if (l == "@skip") {
s.tell("Skipping..");
} else {
$motd.set_setting("server-title", $motd, l);
configured = configured.add('server_title, 1);
s.tell("Server title set to: " + l);
}
s.tell(["", "You can set this at any time, with the command:"]);
s.tell(" @set $motd:server-title=" + l);
}
refresh();
if (!(configured.contains('daemons))) {
s.tell(["", "---"]);
while (1) {
refresh();
list = ($daemon.children()).setremove($login_daemon);
s.tell("Which network daemons do you want to have automatically startup,");
s.tell("Other than $login_daemon. Available daemons:");
t = filter l in (startup['objects]) where (l.is($daemon));
for l in (list) {
if (l in t)
s.tell(strfmt(" %20s (auto starting)", l));
else
s.tell(" " + l);
}
l = s.prompt(("Auto-Start: [" + (t.join(", "))) + "] ");
if (l == "@skip") {
s.tell("Skipping..");
break;
} else if (!l) {
s.tell("Using existing daemons: " + (t.join(", ")));
configured = configured.add('daemons, 1);
break;
} else {
err = 0;
for x in (l.explode_english_list()) {
catch any {
.set_setting("startup-objects", $sys, "+" + x);
s.tell(("Added " + x) + " as a startup daemon.");
} with {
s.tell(("Unable to add '" + x) + "' as a daemon:");
s.tell("=> " + ((traceback()[1])[2]));
err++;
}
}
if (!err) {
configured = configured.add('daemons, 1);
break;
}
s.tell("Errors occurred...");
}
}
s.tell(["", "You can set this at any time, with the command:"]);
s.tell(" @set $motd:startup-objects=OBJECTS...");
}
// Other things to add: HTTP Virtual Hosting info,
// Let them know, if they actually saw anything..
s.tell(["", strfmt("%79{*}c", " Configuration Complete ")]);
};
public method .parse_startup_object() {
arg value, action, @args;
value = (> $object_lib.to_dbref(value) <);
if (action == 'del) {
if (!(value in (startup['objects])))
throw(~failed, ("The object '" + value) + "' is not set, and thus cannot be removed");
return value;
}
return value;
};
public method .writable_core() {
arg @args;
return writable_core;
};
protected method .set_writable_core() {
arg name, definer, value;
writable_core = value;
};
protected method .set_valid_genders() {
arg name, definer, value;
switch (value[1]) {
case 'set:
valid_genders = value[2];
case 'add:
valid_genders += [value[2]];
case 'del:
valid_genders = valid_genders.del(value[2]);
default:
throw(~type, "Unknown action: " + (value[1]));
}
};
public method .get_valid_genders() {
arg @ignored;
return valid_genders;
};
public method .parse_valid_genders() {
arg value, action, @args;
var obj, kids, i;
if (!(| (obj = $object_lib.to_dbref("gender_" + value)) |))
(> (obj = $object_lib.to_dbref(value)) <);
if (action == 'del) {
if ((!obj) in (.get_valid_genders()))
throw(~set, ("The object '" + value) + "' is not set, and thus cannot be removed");
return obj;
}
if ((!obj) in ($gender.children()))
throw(~set, ("The object '" + value) + "' is not a child of $gender");
return obj;
};
public method .get_startup_objects() {
arg @args;
return startup['objects];
};
public method .cache_info() {
return cache_info();
};
public method .fmt_heartbeat_interval() {
arg data;
return $time.to_english(data);
};
public method .get_heartbeat_interval() {
arg @args;
return startup['heartbeat_interval];
};
public method .parse_heartbeat_interval() {
arg value, @args;
value = (> $time.from_english(value) <);
if (value < 1)
throw(~perm, "You cannot set your heartbeat interval to less than 1 second");
return value;
};
protected method .set_heartbeat_interval() {
arg name, definer, value;
startup = startup.add('heartbeat_interval, value);
set_heartbeat(value);
};
new object $mutex: $root;
var $root manager = $mutex;
var $mutex locks = 0;
var $root flags = ['variables, 'methods, 'code, 'core];
var $root created_on = 858071384;
var $root inited = 1;
var $mutex suspended = 0;
var $mutex tasks = 0;
var $mutex queues = 0;
var $root help_node = $help_mutex;
var $root managed = [$mutex];
private method ._test_locks() {
arg tid, values;
var i;
return filter i in (values) where (!(._test_lock(tid, i)));
};
private method ._add_to_lock() {
arg tid, val;
if ((| ((locks[val])[1]) == tid |))
locks = locks.add(val, [tid, ((locks[val])[2]) + 1]);
else
locks = locks.add(val, [tid, 1]);
};
public method .release_all() {
.release(@tasks[task_id()]);
};
private method ._del_from_lock() {
arg tid, val;
var i, l;
if (((| (l = locks[val]) |)[1]) != tid)
return;
if ((l[2]) == 1) {
(| (locks = locks.del(val)) |);
._del_from_queue(val);
} else {
locks = locks.add(val, [tid, (l[2]) - 1]);
}
};
private method ._test_lock() {
arg tid, val;
var i;
if ((| ((locks[val])[1]) != tid |)) {
queues = queues.add(val, (| (queues[val]) + [tid] |) || [tid]);
return 0;
}
return 1;
};
public method .release() {
arg @values;
var tid, t, vlist, i, obj;
values ?= [0];
tid = task_id();
vlist = tasks[tid];
for obj in (.descendants())
obj.release(@values);
for i in (values) {
vlist = vlist.setremove(i);
._del_from_lock(tid, i);
}
if (vlist)
tasks = tasks.add(tid, vlist);
else
tasks = tasks.del(tid);
};
public method .grab() {
arg @values;
var i, tid, l, obj;
values ?= [0];
tid = task_id();
for obj in (.descendants())
obj.grab(@values);
tasks = tasks.add(tid, (| (tasks[tid]) + [values] |) || values);
while (1) {
if (!(l = ._test_locks(tid, values))) {
for i in (values)
._add_to_lock(tid, i);
return;
} else {
suspended = suspended.add(tid, l.length());
$scheduler.suspend(this());
}
}
};
private method ._del_from_queue() {
arg val;
var tid, s, q;
q = (| queues[val] |) || [];
(| (queues = queues.del(val)) |);
for tid in (q) {
if ((s = suspended[tid]) == 1) {
suspended = suspended.del(tid);
(| $scheduler.resume(tid) |);
} else {
suspended = suspended.add(tid, s - 1);
}
}
};
public method .cleanup_dead_tasks() {
var t, i, j;
t = tasks();
for i in (tasks.keys()) {
if (!(i in t)) {
for j in (tasks[i])
._del_from_lock(i, j);
tasks = tasks.del(i);
}
}
};
root method .init_mutex() {
tasks = (suspended = (queues = (locks = #[])));
};
new object $mutex_access: $mutex;
var $root manager = $mutex_access;
var $root flags = ['variables, 'methods, 'code, 'core];
var $root created_on = 858089211;
var $root inited = 1;
var $root managed = [$mutex_access];
new object $mutex_mail: $mutex_access;
var $root manager = $mutex_mail;
var $root flags = ['variables, 'methods, 'code, 'core];
var $root created_on = 858089236;
var $root inited = 1;
var $root managed = [$mutex_mail];
new object $mutex_vr: $mutex;
var $root manager = $mutex_vr;
var $root flags = ['variables, 'methods, 'code, 'core];
var $root created_on = 858089305;
var $root inited = 1;
var $root managed = [$mutex_vr];
new object $mutex_building: $mutex_access, $mutex_vr;
var $root manager = $mutex_building;
var $root flags = ['variables, 'methods, 'code, 'core];
var $root created_on = 858089261;
var $root inited = 1;
var $root managed = [$mutex_building];
new object $mutex_location: $mutex_access, $mutex_vr;
var $root manager = $mutex_location;
var $root flags = ['variables, 'methods, 'code, 'core];
var $root created_on = 858089228;
var $root inited = 1;
var $mutex tasks = #[];
var $mutex locks = #[];
var $mutex queues = #[];
var $mutex suspended = #[];
var $root managed = [$mutex_location];
new object $dmi_data: $root;
var $root manager = $dmi_data;
var $dmi_data descriptions = #[];
var $root flags = ['variables, 'methods, 'code, 'core];
var $root created_on = 860904004;
var $root inited = 1;
var $root managed = [$dmi_data];
root method .init_dmi_data() {
descriptions = #[];
};
root method .uninit_dmi_data() {
var i;
descriptions ?= #[];
for i in (descriptions.keys())
$interface_registry.del_description(this(), i);
descriptions = 0;
};
public method .add_description_to_db() {
arg method, description;
if (caller() != $interface_registry)
(> .perms(sender()) <);
descriptions ?= #[];
descriptions = (> descriptions.add(method, description) <);
};
public method .del_description_from_db() {
arg method;
if (caller() != $interface_registry)
(> .perms(sender()) <);
descriptions = (| descriptions.del(method) |);
};
public method .describe_method() {
arg method;
return (> descriptions[method] <);
};
public method .add_data_to_method() {
arg method, identifier, @data;
var method_data, identifier_data;
(> .perms(sender()) <);
method_data = (| descriptions[method] |) || #[];
if ((data.length()) == 1) {
method_data = method_data.add(identifier, @data);
} else if ((data.length()) == 2) {
identifier_data = (| method_data[identifier] |) || #[];
identifier_data = identifier_data.add(data[1], data[2]);
method_data = method_data.add(identifier, identifier_data);
}
descriptions = descriptions.add(method, method_data);
};
public method .del_data_from_method() {
arg method, identifier, @data;
var method_data, identifier_data;
(> .perms(sender()) <);
method_data = (| descriptions[method] |) || #[];
if ((data.length()) == 0) {
(| (method_data = method_data.del(identifier)) |);
} else if ((data.length()) == 1) {
identifier_data = (| method_data[identifier] |) || #[];
(| (identifier_data = identifier_data.del(data[1])) |);
method_data = method_data.add(identifier, identifier_data);
}
descriptions = descriptions.add(method, method_data);
};
new object $core: $root, $dmi_data;
var $root inited = 1;
var $root created_on = 796268969;
var $root flags = ['methods, 'code, 'core, 'variables];
var $root managed = [$core];
var $root manager = $core;
new object $libraries: $core;
var $root inited = 1;
var $root created_on = 796268969;
var $root flags = ['methods, 'code, 'fertile, 'core, 'variables];
var $root manager = $libraries;
var $root managed = [$libraries];
new object $dictionary: $libraries;
var $root inited = 1;
var $root created_on = 796268969;
var $root flags = ['methods, 'code, 'variables, 'core];
var $root manager = $dictionary;
var $root managed = [$dictionary];
public method .to_list() {
arg dict;
var x;
// merges into an associated list.
return map x in (dict) to (x);
};
public method .nunion() {
arg dict1, dict2;
var key;
// like union() but for dictionaries. adds any keys from dict2 that don't
// already exist in dict1 to dict1 and returns the result. Order of keys in
// result is not guaranteed.
if (((dict1.keys()).length()) < ((dict2.keys()).length())) {
for key in (dict1)
dict2 = dict_add(dict2, @key);
return dict2;
} else {
for key in (dict2)
dict1 = dict_add(dict1, @key);
return dict1;
}
};
public method .values(): native;
public method .replace() {
arg dict, key, value;
// GOING AWAY!
anticipate_assignment();
return dict_add(dict, key, value);
};
public method .apply() {
arg tdict, list;
var x;
// Apply a translation-dict to a list
for x in [1 .. list.length()] {
catch ~keynf
list = list.replace(x, tdict[list[x]]);
}
return list;
};
public method .apply_to_keys() {
arg tdict, dict;
var x, newdict;
// Apply a t-dict to the keys of a dict
newdict = #[];
for x in (dict) {
catch ~keynf
x = x.replace(1, tdict[x[1]]);
newdict = newdict.add(@x);
}
return newdict;
};
public method .apply_to_values() {
arg tdict, dict;
var x, newdict;
// Apply a t-dict to the values of a dict
newdict = #[];
for x in (dict) {
catch ~keynf
x = x.replace(2, tdict[x[2]]);
newdict = newdict.add(@x);
}
return newdict;
};
public method .invert() {
arg dict;
var x;
// Invert a dict keys and values
return hash x in (dict) to ([x[2], x[1]]);
};
public method .add_elem() {
arg dict, key, elem;
var value;
// Add an element to the list value of a dictionary key
value = (| dict[key] |);
if ((type(value) != 'list) && (type(value) != 'error))
throw(~type, ((("Value for key " + key) + " (") + value) + ") is not a list.");
anticipate_assignment();
if (value) {
// reduce references to 'value'
dict = dict_add(dict, key, 0);
value += [elem];
} else {
value = [elem];
}
return dict_add(dict, key, value);
};
public method .del_elem() {
arg dict, key, elem;
var value;
value = (| dict[key] |);
if ((type(value) != 'list) && (type(value) != 'error))
throw(~type, ((("Value for key " + key) + " (") + value) + ") is not a list.");
anticipate_assignment();
dict = dict_add(dict, key, 0);
value = setremove(value, elem);
if (!value)
return dict_del(dict, key);
return dict_add(dict, key, value);
};
public method .add(): native;
public method .del(): native;
public method .keys(): native;
public method .contains(): native;
public method .to_trie() {
arg dict;
var i, trie;
trie = $trie.new();
for i in (dict) {
trie = trie.add(i[1], i[2]);
refresh();
}
return trie;
};
public method .union(): native;
public method .setadd_elem() {
arg dict, key, elem;
var value;
value = (| dict[key] |);
if ((type(value) != 'list) && (type(value) != 'error))
throw(~type, ((("Value for key " + key) + " (") + value) + ") is not a list.");
anticipate_assignment();
if (value) {
dict = dict_add(dict, key, 0);
value = setadd(value, elem);
} else {
value = [elem];
}
return dict_add(dict, key, value);
};
public method .mmap() {
arg list, method, @args;
var x;
// call 'method on each object, return results.
return map x in (list) to (x.(method)(@args));
};
new object $buffer: $libraries;
var $root trusted = [];
var $root inited = 1;
var $root created_on = 796268969;
var $root flags = ['methods, 'code, 'variables, 'core];
var $root manager = $buffer;
var $root managed = [$buffer];
public method .to_list() {
arg buf;
var i, list;
return map i in [1 .. buflen(buf)] to (buf[i]);
};
public method .from_list() {
arg list;
var buf, i;
// this differs from $list.to_buffer()
buf = `[];
for i in (list)
buf += `[i];
return buf;
};
public method .length(): native;
public method .to_string(): native;
public method .to_strings(): native;
public method .from_string(): native;
public method .from_strings(): native;
public method .replace(): native;
public method .subrange(): native;
public method .to_veil_pkts(): native;
public method .from_veil_pkts(): native;
public method .break_lines() {
arg buf;
var i, sub, out;
// break a buffer by \r or \n but keep its sub contents as buffers
out = [];
while ((i = 10 in buf)) {
sub = subbuf(buf, 1, i - 1);
buf = subbuf(buf, i + 1);
while ((i = 13 in sub)) {
if (buflen(sub) == i)
sub = subbuf(sub, 1, i - 1);
else
sub = subbuf(sub, 1, i - 1) + subbuf(sub, i + 1);
}
out += [sub];
}
if (buf) {
while ((i = 13 in buf)) {
if (buflen(buf) == i)
buf = subbuf(buf, 1, i - 1);
else
buf = subbuf(buf, 1, i - 1) + subbuf(buf, i + 1);
}
if (buf)
out += [buf];
}
return out;
};
public method .bufsub() {
arg buf, a, b;
var i, la, lb, lt;
// do we need a builtin for this?
// shagged from Kipp's core, until I write a builtin, optimized by Brandon
if ((a == b) || ((buflen(a) > buflen(buf)) || ((!a) || (!buf))))
return buf;
la = buflen(a);
lb = buflen(b);
lt = buflen(buf) - la;
i = 1;
anticipate_assignment();
while ((i < lt) && (i = bufidx(buf, a, i))) {
buf = (subbuf(buf, 1, i - 1) + b) + subbuf(buf, i + la);
i += lb;
}
return buf;
};
new object $string: $libraries;
var $root inited = 1;
var $root created_on = 796268969;
var $root flags = ['methods, 'code, 'variables, 'core];
var $string alphabet = "abcdefghijklmnopqrstuvwxyz";
var $string numbers = "0123456789";
var $string non_alphanumeric = "!@#$%^&*()_+-=~`'{}[]|/?\",.<>;: ";
var $root manager = $string;
var $string number_names = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
var $string base64str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var $root managed = [$string];
public method .left() {
arg str, width, @fchar;
// will not chop off 'str' if it is longer than width, use pad() for that.
[(fchar ?= " ")] = fchar;
if (strlen(str) < width)
return str + pad("", width - (str.length()), fchar);
return str;
};
public method .center() {
arg text, width, @args;
var fill, sides;
// args[1] <op> == what to fill the left|right side with.
// args[2] <op> == if exists also fill the right side.
[(fill ?= " "), (sides ?= 'left)] = args;
if (sides == 'both)
return strfmt(("%*{" + fill) + "}c", width, text);
else
return pad("", (width - strlen(text)) / 2, fill) + text;
};
public method .trim(): native;
public method .right() {
arg str, width, @fchar;
// will not chop off 'str' if it is longer than width (unlike pad())
[(fchar ?= " ")] = fchar;
if (strlen(str) < width)
return pad(str, -width, fchar);
return str;
};
public method .alphabet() {
return alphabet;
};
public method .numbers() {
return numbers;
};
public method .capitalize(): native;
public method .is_numeric() {
arg string;
return toint(string) || (| ((string.trim())[1]) == "0" |);
};
public method .a_or_an() {
arg string;
return $english_lib.indef_article(string);
};
public method .strip() {
arg string, @strip;
anticipate_assignment();
if (!strip)
return strsed(string, "[][!@#$%^&*()_+=~`'{}|/?\"\,.<>;: -]", "", "g");
else
return strsed(string, ("[" + (strip[1])) + "]", "", "g");
};
public method .non_alphanumeric() {
return non_alphanumeric;
};
public method .chop() {
arg str, len, @end;
// chops string off end.length() characters before len and appends len
[(end ?= "...")] = end;
if ((strlen(str) < len) || (strlen(str) < strlen(end)))
return str;
anticipate_assignment();
return pad(str, len - strlen(end)) + end;
};
public method .replace(): native;
public method .explode_english_list() {
arg line, @opts;
var x, output, tmp;
if (!line)
return [];
// explodes an english list ("foo, bar and zoo").
line = line.explode(",");
output = [];
for x in (line) {
x = .trim(x);
if ((| x.subrange(1, 4) |) == "and ")
output += [.trim(x.subrange(4))];
else
output += [x];
}
// check the last element, if they didn't specify 'noand
if (!('noand in opts)) {
line = (output[output.length()]).explode();
tmp = "";
for x in [1 .. line.length()] {
if ((line[x]) == "and") {
output = output.delete(output.length());
if (tmp)
output += [tmp];
tmp = (line.subrange(x + 1)).join();
if (tmp)
output += [tmp];
// only bother with the first "and"
break;
}
tmp = (tmp + (tmp ? " " : "")) + (line[x]);
}
}
return output;
};
public method .explode_delimited() {
arg str, left, right;
var pattern, parsed, matched, match_num, match_result;
// parse str looking for anything surrounded by left and right
// ;$string.explode_delimited("foo<bar>baz", "<", ">")
// => [["foo", 1, "baz"], ["bar"]]
pattern = ((("*" + left) + "*") + right) + "*";
parsed = [];
matched = [];
match_num = 0;
anticipate_assignment();
while (str) {
match_result = match_pattern(str, pattern);
if (match_result) {
match_num++;
parsed += [match_result[1], match_num];
matched += [match_result[2]];
str = match_result[3];
} else {
parsed += [str];
str = "";
}
}
return [parsed, matched];
};
public method .wrap_line() {
arg str, len, @stuff;
var output, cutoff, firstline, prefix, plen;
// takes string and wraps it by words, compared to length, breaks with \n
[(prefix ?= ""), (firstline ?= 0)] = stuff;
output = "";
if (firstline)
str = Showing the first 100 KB of 2.2 MB. Download the archive for the full file.