Ejemplo n.º 1
0
def board_func(args,u413):
	args=args.split(' ')
	if len(args)==0:
		u413.type('Invalid board ID.')
	#BOARD id
	elif len(args)==1:
		if args[0].upper()=="ALL":
			args[0]=0
		if util.isint(args[0]):
			output_board(int(args[0]),1,u413)
		else:
			u413.type('Invalid board ID.')
	#BOARD id page
	else:
		if args[0].upper()=="ALL":
			args[0]=0
		if args[1].upper()=='LAST':
			args[1]=db.count_posts(args[0])
			if args[1]==0:
				args[1]=1
			else:
				args[1]=math.ceil(args[1]/10.0)
		elif not util.isint(args[1]):
			args[1]=1
		else:
			args[1]=int(args[1])
		output_board(int(args[0]),args[1],u413)
Ejemplo n.º 2
0
def create(i):
    isint(i.userid)
    isvarchar(i.name,1,50)

    return db.insert('groups',
                userid=i.userid,name=i.name,createdate=datetime.now(),
                _test=is_debug)
Ejemplo n.º 3
0
def topic_func(args,u413):
	params=args.split(' ',2)
	if len(params)==0 or not util.isint(params[0]):
		u413.type("Invalid topic ID.")
		return
	topic=int(params[0])
	if len(params)==1:
		page=1
		output_page(topic,1,u413)
	elif len(params)==2:
		if params[1].upper()=="REPLY":
			u413.j["Command"]="REPLY"
			u413.cmddata["topic"]=topic
			u413.continue_cmd()
		else:
			page=1
			if util.isint(params[1]):
				page=int(params[1])
			elif params[1].upper()=='LAST':
				page=db.count_posts(topic)
				if page==0:
					page=1
				else:
					page=math.ceil(page/10.0)
			output_page(topic,page,u413)
	elif params[1].upper()=="REPLY":
		db.query("INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());"%(topic,u413.user.userid,db.escape(util.htmlify(params[3]))))
		u413.type("Reply made successfully.")
Ejemplo n.º 4
0
def topic_func(args, u413):
    params = args.split(' ', 2)
    if len(params) == 0 or not util.isint(params[0]):
        u413.type("Invalid topic ID.")
        return
    topic = int(params[0])
    if len(params) == 1:
        page = 1
        output_page(topic, 1, u413)
    elif len(params) == 2:
        if params[1].upper() == "REPLY":
            u413.j["Command"] = "REPLY"
            u413.cmddata["topic"] = topic
            u413.continue_cmd()
        else:
            page = 1
            if util.isint(params[1]):
                page = int(params[1])
            elif params[1].upper() == 'LAST':
                page = db.count_posts(topic)
                if page == 0:
                    page = 1
                else:
                    page = math.ceil(page / 10.0)
            output_page(topic, page, u413)
    elif params[1].upper() == "REPLY":
        db.query(
            "INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());"
            % (topic, u413.user.userid, db.escape(util.htmlify(params[3]))))
        u413.type("Reply made successfully.")
Ejemplo n.º 5
0
def board_func(args,u413):
	args=args.split(' ')
	if len(args)==0:
		u413.type('Invalid board ID.')
	#BOARD id
	elif len(args)==1:
		if args[0].upper()=="ALL":
			args[0]=0
		if util.isint(args[0]):
			output_board(int(args[0]),1,u413)
		else:
			u413.type('Invalid board ID.')
	#BOARD id page
	else:
		if args[0].upper()=="ALL":
			args[0]=0
		if args[1].upper()=='LAST':
			args[1]=db.count_posts(args[0])
			if args[1]==0:
				args[1]=1
			else:
				args[1]=math.ceil(args[1]/10.0)
		elif not util.isint(args[1]):
			args[1]=1
		else:
			args[1]=int(args[1])
		output_board(int(args[0]),args[1],u413)
Ejemplo n.º 6
0
def delete_func(args,u413):
	#DELETE already requested continuation
	if "step" in u413.cmddata:
		#ID>
		post=int(db.query("SELECT owner FROM posts WHERE id=%i;"%int(args))[0]["owner"])
		owner=int(db.query("SELECT access FROM users WHERE id=%i;"%post)[0]["access"])
		if post!=u413.user.userid:
			if u413.user.level<user.User.mod or u413.user.level<=owner:
				u413.type("You do not have permission to edit other user's posts.")
				return
		db.query("DELETE FROM posts WHERE id=%i;"%int(args))
		u413.type("Post deleted.")
	#DELETE used for the first time
	else:
		params=args.split(' ',1)
		#DELETE
		if len(args)==0:
			u413.cmddata["step"]=1
			u413.type("Enter the post's ID:")
			u413.set_context("Post ID")
			u413.continue_cmd()
		#DELETE id
		else:
			if util.isint(args):
				post=int(db.query("SELECT owner FROM posts WHERE id=%i;"%int(args))[0]["owner"])
				owner=int(db.query("SELECT access FROM users WHERE id=%i;"%post)[0]["access"])
				if post!=u413.user.userid:
					if u413.user.level<user.User.halfmod or u413.user.level<=owner:
						u413.type("You do not have permission to edit other user's posts.")
						return
				db.query("DELETE FROM posts WHERE id=%i;"%int(args))
				u413.type("Post deleted.")
			else:
				u413.type("Invalid post ID")
Ejemplo n.º 7
0
    def generate_js(self):
        """
            Generates JS code: ropchain and relocs arrays
            Note: For JS we generate arrays where each item is 4 bytes, because JS cannot work with 8 bytes.
            As such you need to work on qword-level in JS. (see exploit.js)
        """
        rop_chain = []
        rop_relocs = []

        rop = [0] + self.rop[:]  # NB: PC is *second* pointer in output

        for qword in rop:
            if isint(qword):
                reloc = 0
            elif isinstance(qword, Relocatable):
                reloc = qword.tag
                qword = qword.imm
            else:
                raise RuntimeError("unknown qword: {}".format(qword))
            rop_chain.append(qword & 0xFFFFFFFF)  # lo
            rop_chain.append(qword >> 32)  # hi
            rop_relocs.append(reloc)
            rop_relocs.append(0)

        js = "rop_chain = {};\nrop_relocs = {};\n".format(
            self.js_array(rop_chain), self.js_array(rop_relocs))
        return js
Ejemplo n.º 8
0
 def generate_binary(self, relocs):
     """ Generate a ROP chain with relocs applied """
     output = [0]  # NB: PC is *second* pointer in output
     for qword in self.rop:
         if isint(qword):
             output.append(qword)
         elif isinstance(qword, Relocatable):
             output.append(qword.imm + relocs[qword.tag])
         else:
             raise RuntimeError("unknown qword: {}".format(qword))
     return "".join(struct.pack("<Q", x) for x in output)
Ejemplo n.º 9
0
    def compile(self):
        """
        Compiles rop chain.
        Doesn't return anything, access compiled_rop/compiled_relocs
        """

        if self.compiled:
            raise RuntimeError("you can't call compile() multiple times!")
        self.compiled = True

        # Go through the ropchain, find immediate strings and allocate them into the data section
        for x in range(len(self.rop)):
            if isinstance(self.rop[x], str):
                # make sure to null-terminate here as well
                self.rop[x] = self._alloc(self.rop[x].encode("utf-8") + b"\x00")

        self._write_data_section()

        self.compiled_rop = []
        self.compiled_relocs = []

        for item in self.rop:
            word = None
            reloc = None

            # really, you can put either int or Relocatable inside Load[]
            # whether it's Load or whatever's inside only matters during call type resolution
            # in call()
            if isinstance(item, Load):
                item = item.addr

            if isint(item):
                word = item
                reloc = 0
            elif isinstance(item, Relocatable):
                word = item.imm
                reloc = item.tag

            if word is None or reloc is None:
                print("for ropchain={}".format(self.rop))
                raise RuntimeError("compilation failed at item={}".format(item))

            assert(word is not None)
            assert(reloc is not None)

            if word < 0:
                word &= 0xFFFFFFFF
            
            self.compiled_rop.append(word)
            self.compiled_relocs.append(reloc)
Ejemplo n.º 10
0
    def pre_alloc_var(self, value):
        """
        Same as pre_alloc_data, but it's not pushed into self.data
        so especially useful for temporary-temporary storage, e.g. see RopThread
        """

        if isint(value):
            ptr = self._alloc(b"\x00" * value)
        elif isinstance(value, str):
            # make sure to null-terminate strings!
            ptr = self._alloc(value.encode("utf-8") + b"\x00")
        elif isinstance(value, bytes):
            ptr = self._alloc(value)
        else:
            raise RuntimeError("tried to allocate unknown type: {}".format(type(value)))

        return ptr
Ejemplo n.º 11
0
def history_func(args,u413):
	params=args.split(' ',1)
	if args.strip()=='':
		u413.type("User command history (1-32 of %i):"%len(u413.user.history))
		out='<br/><table>'
		for cmd in u413.user.history[::-1][:32][::-1]:
			out+='<tr><td style="width:2em;"></td><td>'+cmd+'</td></tr>'
		u413.donttype(out+'</table>')
	elif params[0].upper()=="--CLEAR":
		u413.user.history=[]
		u413.type("History cleared")
	elif util.isint(params[0]):
		u413.type("User command history (%i-%i of %i):"%(int(params[0]),int(params[0])+32,len(u413.user.history)))
		out='<br/><table>'
		for cmd in u413.user.history[::-1][int(params[0]):int(params[0])+32][::-1]:
			out+='<tr><td style="width:2em;"></td><td>'+cmd+'</td></tr>'
		u413.donttype(out+'</table>')
Ejemplo n.º 12
0
def respond(cli,u413,ashtml=True):
	cmdarg=cli.split(' ',1)
	cmd=cmdarg[0].upper()
	args=""
	if len(cmdarg)>1:
		args=cmdarg[1]

	#update history and cmd if it's not a command that handles sensitive data
	sensitive=['LOGIN','REGISTER']
	if u413.user.cmd not in sensitive and cmd not in sensitive:
		if args!='':
			u413.user.history.append(cmd+' '+args)
		else:
			u413.user.history.append(cmd)

	if u413.user.cmd=='':
		u413.j["Command"]=cmd
		if cmd in cmds and cmds[cmd].level<=u413.user.level:
			cmds[cmd].callback(args,u413)
		else:
			a=getalias(cli,u413)
			if a!=None:
				execalias(cli,a,u413)
			elif util.isint(cmd):
				if u413.user.context!='TOPIC' and 'TOPIC' in u413.user.context:
					cmds["TOPIC"].callback('%i %i'%(int(u413.user.context.split(' ')[1]),int(cmd)),u413)
				elif u413.user.context!='BOARD' and 'BOARD' in u413.user.context:
					cmds["BOARD"].callback('%s %i'%(u413.user.context.split(' ')[1],int(cmd)),u413)
				else:
					u413.type('"%s" is not a valid command or is not available in the current context.'%cmd)
			else:
				u413.type('"%s" is not a valid command or is not available in the current context.'%cmd)
	else:
		u413.j["Command"]=u413.user.cmd.upper()
		if cmd=="CANCEL":
			#Note: this works because commands must actively request continuation
			u413.type("Action cancelled.")
			u413.set_context("")
		else:
			cmds[u413.user.cmd.upper()].callback(cli,u413)
	
	db.query("UPDATE sessions SET history='%s' WHERE id='%s';"%(db.escape(str(u413.user.history)),u413.user.session))

	#change title if user is logged in
	if u413.user.name!="Guest":
		u413.set_title("Terminal - "+u413.user.name)
Ejemplo n.º 13
0
def respond(cli,u413,ashtml=True):
	cmdarg=cli.split(' ',1)
	cmd=cmdarg[0].upper()
	args=""
	if len(cmdarg)>1:
		args=cmdarg[1]

	#update history and cmd if it's not a command that handles sensitive data
	sensitive=['LOGIN','REGISTER']
	if u413.user.cmd not in sensitive and cmd not in sensitive:
		if args!='':
			u413.user.history.append(cmd+' '+args)
		else:
			u413.user.history.append(cmd)

	if u413.user.cmd=='':
		u413.j["Command"]=cmd
		if cmd in cmds and cmds[cmd].level<=u413.user.level:
			cmds[cmd].callback(args,u413)
		else:
			a=getalias(cli,u413)
			if a!=None:
				execalias(cli,a,u413)
			elif util.isint(cmd):
				if u413.user.context!='TOPIC' and 'TOPIC' in u413.user.context:
					cmds["TOPIC"].callback('%i %i'%(int(u413.user.context.split(' ')[1]),int(cmd)),u413)
				elif u413.user.context!='BOARD' and 'BOARD' in u413.user.context:
					cmds["BOARD"].callback('%s %i'%(u413.user.context.split(' ')[1],int(cmd)),u413)
				else:
					u413.type('"%s" is not a valid command or is not available in the current context.'%cmd)
			else:
				u413.type('"%s" is not a valid command or is not available in the current context.'%cmd)
	else:
		u413.j["Command"]=u413.user.cmd.upper()
		if cmd=="CANCEL":
			#Note: this works because commands must actively request continuation
			u413.type("Action cancelled.")
			u413.set_context("")
		else:
			cmds[u413.user.cmd.upper()].callback(cli,u413)
	
	db.query("UPDATE sessions SET history='%s' WHERE id='%s';"%(db.escape(str(u413.user.history)),u413.user.session))

	#change title if user is logged in
	if u413.user.name!="Guest":
		u413.set_title("Terminal - "+u413.user.name)
Ejemplo n.º 14
0
 def call(self, func, *args, **kwargs):
     """ Generic call function that will do argument matching and execute a proper call* handler """
     # Generate argument signature
     sig = ""
     for arg in args:
         if isint(arg) or isinstance(arg, Relocatable):
             sig += "v"
         elif arg is Ret:
             sig += "r"
         else:
             raise RuntimeError(
                 "unsupported function argument: {}".format(arg))
     for match, f in self._call_funcs.items():
         if match.startswith(sig):
             return f(self, func, *args, **kwargs)
     raise RuntimeError("didn't match sig: {} for args: {}".format(
         sig, args))
Ejemplo n.º 15
0
def delete_func(args, u413):
    #DELETE already requested continuation
    if "step" in u413.cmddata:
        #ID>
        post = int(
            db.query("SELECT owner FROM posts WHERE id=%i;" %
                     int(args))[0]["owner"])
        owner = int(
            db.query("SELECT access FROM users WHERE id=%i;" %
                     post)[0]["access"])
        if post != u413.user.userid:
            if u413.user.level < user.User.mod or u413.user.level <= owner:
                u413.type(
                    "You do not have permission to edit other user's posts.")
                return
        db.query("DELETE FROM posts WHERE id=%i;" % int(args))
        u413.type("Post deleted.")
    #DELETE used for the first time
    else:
        params = args.split(' ', 1)
        #DELETE
        if len(args) == 0:
            u413.cmddata["step"] = 1
            u413.type("Enter the post's ID:")
            u413.set_context("Post ID")
            u413.continue_cmd()
        #DELETE id
        else:
            if util.isint(args):
                post = int(
                    db.query("SELECT owner FROM posts WHERE id=%i;" %
                             int(args))[0]["owner"])
                owner = int(
                    db.query("SELECT access FROM users WHERE id=%i;" %
                             post)[0]["access"])
                if post != u413.user.userid:
                    if u413.user.level < user.User.halfmod or u413.user.level <= owner:
                        u413.type(
                            "You do not have permission to edit other user's posts."
                        )
                        return
                db.query("DELETE FROM posts WHERE id=%i;" % int(args))
                u413.type("Post deleted.")
            else:
                u413.type("Invalid post ID")
Ejemplo n.º 16
0
 def call(self, func, *args, **kwargs):
     """ Generic call function that will do argument matching and execute a proper call* handler """
     # Generate argument signature
     sig = ""
     for arg in args:
         if isint(arg) or isinstance(arg, Relocatable):
             sig += "v"
         elif arg is Ret:
             sig += "r"
         elif isinstance(arg, str):
             # It will be allocated in compile() and essentially same as int
             sig += "v"
         elif isinstance(arg, Load):
             sig += "l"
         else:
             raise RuntimeError("unsupported function argument: {}".format(arg))
     for match, f in self._call_funcs.items():
         if match.startswith(sig):
             return f(self, func, *args, **kwargs)
     raise RuntimeError("didn't match sig: {} for args: {}".format(sig, args))
Ejemplo n.º 17
0
def history_func(args, u413):
    params = args.split(' ', 1)
    if args.strip() == '':
        u413.type("User command history (1-32 of %i):" %
                  len(u413.user.history))
        out = '<br/><table>'
        for cmd in u413.user.history[::-1][:32][::-1]:
            out += '<tr><td style="width:2em;"></td><td>' + cmd + '</td></tr>'
        u413.donttype(out + '</table>')
    elif params[0].upper() == "--CLEAR":
        u413.user.history = []
        u413.type("History cleared")
    elif util.isint(params[0]):
        u413.type(
            "User command history (%i-%i of %i):" %
            (int(params[0]), int(params[0]) + 32, len(u413.user.history)))
        out = '<br/><table>'
        for cmd in u413.user.history[::-1][int(params[0]):int(params[0]) +
                                           32][::-1]:
            out += '<tr><td style="width:2em;"></td><td>' + cmd + '</td></tr>'
        u413.donttype(out + '</table>')
Ejemplo n.º 18
0
def reply_func(args, u413):
    #already used REPLY
    if "step" in u413.cmddata:
        if args.strip() == '':
            u413.type("Action cancelled.")
            u413.set_context("")
        #ID>
        elif u413.cmddata["step"] == 1:
            if util.isint(args):
                u413.cmddata["step"] = 2
                u413.cmddata["topic"] = int(args)
                u413.type("Enter your reply:")
                u413.set_context("REPLY")
                u413.continue_cmd()
            else:
                u413.type("Invalid topic ID.")
                u413.set_context("")
        #REPLY>
        elif u413.cmddata["step"] == 2:
            db.query(
                "INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());"
                % (u413.cmddata["topic"], u413.user.userid,
                   db.escape(util.htmlify(args))))
            reload_topic(u413.cmddata["topic"], u413.cmddata["page"], u413)
    #first use of REPLY
    else:
        params = args.split(' ', 1)
        context = u413.user.context.split(' ')
        #REPLY
        if args.strip() == '':
            if "TOPIC" in u413.user.context:
                u413.cmddata["step"] = 2
                u413.cmddata["topic"] = int(u413.user.context.split(' ')[1])
                u413.type("Enter your reply:")
                u413.set_context("REPLY")
                u413.continue_cmd()
            else:
                u413.cmddata["step"] = 1
                u413.type("Enter the topic ID:")
                u413.set_context("TOPIC ID")
                u413.continue_cmd()
        #REPLY [id]
        elif len(params) == 1:
            if util.isint(params[0]):
                u413.cmddata["step"] = 2
                u413.cmddata["topic"] = int(params[0])
                u413.type("Enter your reply:")
                u413.continue_cmd()
            elif "TOPIC" in u413.user.context:
                topic = int(u413.user.context.split(' ')[1])
                db.query(
                    "INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());"
                    % (topic, u413.user.userid, db.escape(util.htmlify(args))))
                page = 1
                if len(context) > 2:
                    page = int(context[2])
                reload_topic(int(context[1]), page, u413)
            else:
                u413.type("Invalid topic ID.")
        #REPLY [[id] message]
        else:
            if util.isint(params[0]):
                if len(params) == 2:
                    db.query(
                        "INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());"
                        % (int(params[0]), u413.user.userid,
                           db.escape(util.htmlify(params[1]))))
                    page = 1
                    if len(context) > 2:
                        page = int(context[2])
                    u413.type("Reply added successfully.")
                else:
                    u413.cmddata["step"] = 2
                    u413.cmddata["topic"] = int(params[0])
                    u413.type("Enter your reply:")
                    u413.set_context("REPLY")
                    u413.continue_cmd()
            elif "TOPIC" in u413.user.context:
                topic = int(u413.user.context.split(' ')[1])
                db.query(
                    "INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());"
                    % (topic, u413.user.userid, db.escape(util.htmlify(args))))
                page = 1
                if len(context) > 2:
                    page = int(context[2])
                reload_topic(topic, page, u413)
            else:
                u413.type("Topic ID required.")
        u413.cmddata["page"] = 1
        if len(context) > 2:
            u413.cmddata["page"] = int(context[2])
Ejemplo n.º 19
0
 def __sub__(self, x):
     if not isint(x):
         raise RuntimeError("cannot __sub__ a {}".format(x))
     return Relocatable(self.tag, self.imm - x)
Ejemplo n.º 20
0
def reply_func(args,u413):
	#already used REPLY
	if "step" in u413.cmddata:
		if args.strip()=='':
			u413.type("Action cancelled.")
			u413.set_context("")
		#ID>
		elif u413.cmddata["step"]==1:
			if util.isint(args):
				u413.cmddata["step"]=2
				u413.cmddata["topic"]=int(args)
				u413.type("Enter your reply:")
				u413.set_context("REPLY")
				u413.continue_cmd()
			else:
				u413.type("Invalid topic ID.")
				u413.set_context("")
		#REPLY>
		elif u413.cmddata["step"]==2:
			db.query("INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());"%(u413.cmddata["topic"],u413.user.userid,db.escape(util.htmlify(args))))
			reload_topic(u413.cmddata["topic"],u413.cmddata["page"],u413)
	#first use of REPLY
	else:
		params=args.split(' ',1)
		context=u413.user.context.split(' ')
		#REPLY
		if args.strip()=='':
			if "TOPIC" in u413.user.context:
				u413.cmddata["step"]=2
				u413.cmddata["topic"]=int(u413.user.context.split(' ')[1])
				u413.type("Enter your reply:")
				u413.set_context("REPLY")
				u413.continue_cmd()
			else:
				u413.cmddata["step"]=1
				u413.type("Enter the topic ID:")
				u413.set_context("TOPIC ID")
				u413.continue_cmd()
		#REPLY [id]
		elif len(params)==1:
			if util.isint(params[0]):
				u413.cmddata["step"]=2
				u413.cmddata["topic"]=int(params[0])
				u413.type("Enter your reply:")
				u413.continue_cmd()
			elif "TOPIC" in u413.user.context:
				topic=int(u413.user.context.split(' ')[1])
				db.query("INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());"%(topic,u413.user.userid,db.escape(util.htmlify(args))))
				page=1
				if len(context)>2:
					page=int(context[2])
				reload_topic(int(context[1]),page,u413)
			else:
				u413.type("Invalid topic ID.")
		#REPLY [[id] message]
		else:
			if util.isint(params[0]):
				if len(params)==2:
					db.query("INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());"%(int(params[0]),u413.user.userid,db.escape(util.htmlify(params[1]))))
					page=1
					if len(context)>2:
						page=int(context[2])
					u413.type("Reply added successfully.")
				else:
					u413.cmddata["step"]=2
					u413.cmddata["topic"]=int(params[0])
					u413.type("Enter your reply:")
					u413.set_context("REPLY")
					u413.continue_cmd()
			elif "TOPIC" in u413.user.context:
				topic=int(u413.user.context.split(' ')[1])
				db.query("INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());"%(topic,u413.user.userid,db.escape(util.htmlify(args))))
				page=1
				if len(context)>2:
					page=int(context[2])
				reload_topic(topic,page,u413)
			else:
				u413.type("Topic ID required.")
		u413.cmddata["page"]=1
		if len(context)>2:
			u413.cmddata["page"]=int(context[2])
Ejemplo n.º 21
0
def edit_func(args, u413):
    #EDIT already requested continuation
    if "step" in u413.cmddata:
        #ID>
        if u413.cmddata["step"] == 1:
            u413.donttype('"' + args + '"')
            if util.isint(args):
                u413.cmddata["id"] = int(args)
                u413.cmddata["step"] = 2
                u413.set_context("NEW BODY")
                u413.type("Enter the new post body:")
                u413.edit_text(
                    util.dehtmlify(
                        db.query("SELECT post FROM posts WHERE id=%i;" %
                                 int(args))[0]["post"]))
                u413.continue_cmd()
            else:
                u413.type("Invalid post ID.")
                u413.set_context("")
        #NEW BODY>
        elif u413.cmddata["step"] == 2:
            post = int(
                db.query("SELECT owner FROM posts WHERE id=%i;" %
                         u413.cmddata["id"])[0]["owner"])
            owner = int(
                db.query("SELECT access FROM users WHERE id=%i;" %
                         post)[0]["access"])
            if post != u413.user.userid:
                if u413.user.level < user.User.halfmod or u413.user.level <= owner:
                    u413.type(
                        "You do not have permission to edit other user's posts."
                    )
                    return
            db.query(
                "UPDATE posts SET post='%s',editor=%i,edited=NOW() WHERE id=%i;"
                % (db.escape(
                    util.htmlify(args)), u413.user.userid, u413.cmddata["id"]))
            u413.type("Post edited successfully.")
            u413.set_context(u413.cmddata["context"])
    #EDIT used for the first time
    else:
        params = args.split(' ', 1)
        #EDIT
        if len(args) == 0:
            u413.cmddata["step"] = 1
            u413.cmddata["context"] = u413.user.context
            u413.type("Enter the post's ID:")
            u413.set_context("Post ID")
            u413.continue_cmd()
        #EDIT id
        elif len(params) == 1:
            if util.isint(args):
                u413.cmddata["step"] = 2
                u413.cmddata["context"] = u413.user.context
                u413.cmddata["id"] = int(args)
                u413.type("Enter the new post body:")
                u413.set_context("NEW BODY")
                u413.edit_text(
                    util.dehtmlify(
                        db.query("SELECT post FROM posts WHERE id=%i;" %
                                 int(args))[0]["post"]))
                u413.continue_cmd()
            else:
                u413.type("Invalid post ID.")
        #EDIT id body
        else:
            if util.isint(params[0]):
                post = int(
                    db.query("SELECT owner FROM posts WHERE id=%i;" %
                             int(params[0]))[0]["owner"])
                owner = int(
                    db.query("SELECT access FROM users WHERE id=%i;" %
                             post)[0]["access"])
                if post != u413.user.userid:
                    if u413.user.level < user.User.halfmod or u413.user.level <= owner:
                        u413.type(
                            "You do not have permission to edit other user's posts."
                        )
                        return
                db.query(
                    "UPDATE posts SET post='%s',editor=%i,edited=NOW() WHERE id=%i;"
                    % (db.escape(util.htmlify(
                        params[1])), u413.user.userid, int(params[0])))
                u413.type("Post edited successfully.")
                u413.set_context("")
            else:
                u413.type("Invalid post ID.")
Ejemplo n.º 22
0
def main(repo = None, dont_push = None, silence = None):
    repo, is_git_repo = util.get_valid_repo( repo )

    groups = util.get_groups_dict(repo)

    #Sanity check expirations
    try:
        expirationsyaml = file( os.path.join(repo, 'expirations.yaml') , 'r')
        expirations = hotcidr.state.load(expirationsyaml)
    except IOError:
        print('Error: ' + os.path.join(repo, 'expirations.yaml') + ' is missing, and is necessary for expiration checking.',file=sys.stderr)
        return 1
    except yaml.scanner.ScannerError as e:
        print('Error: expirations.yaml is not properly formatted:\n' + str(e), file=sys.stderr)
        print('expirations.yaml is necessary for expiration checking.', file=sys.stderr)
        return 1

    if expirations:
        if 'rules' in expirations:
            expirations = expirations['rules']
        else:
            print('Error: expirations.yaml is not properly formatted. Rules must be under a \'rules:\' tag.', file=sys.stderr)

    #Immediately terminate if there are no groups, or else a division by 0 will occur later
    groups_num = len(groups)
    if groups_num == 0:
        print('ERROR: No groups loaded.',file=sys.stderr)
        return 1

    if not silence:
        i = 0

    any_rules_removed = False
    for group in groups:
        #Print processing
        if not silence:
            print('Processing ' + groups[group], file=sys.stderr)
            sys.stderr.flush()

        try:
            rulesyaml = file( os.path.join(repo, groups[group]) , 'r')
            rules = hotcidr.state.load(rulesyaml)
        except IOError:
            print('Warning: ' + os.path.join(repo, groups[group]) + ' is missing. It will be skipped.',file=sys.stderr)
            continue
        except yaml.scanner.ScannerError as e:
            print('Warning: ' + os.path.join(repo, groups[group]) + ' is not properly formatted and will be skipped:\n' + str(e), file=sys.stderr)
            continue

        added_rules = util.get_added_deleted_rules( repo, groups[group] )['added']
        rules_removed = False

        for added_rule in added_rules:

            #Handle expirations.yaml: add expiration field to all matching rules
            if expirations:
                for expired_rule in expirations:
                    if 'expiration' in expired_rule and isint(expired_rule['expiration']):
                        #TODO: Rather than count the fields in expired_rule, check that they are each in util.expected_rule_fields
                        if len(expired_rule.keys()) >= 2:
                            rule_is_expired = True
                            for field in util.expected_rule_fields:
                                if not field in added_rule or not field in expired_rule:
                                    continue

                                if not added_rule[field] == expired_rule[field]:
                                    rule_is_expired = False
                                    break

                            #Give the rule an expiration, so it will be seen as if it was originally added in <group>.yaml
                            if rule_is_expired:
                                added_rule['expiration'] = int(expired_rule['expiration'])
                        else:
                            print('Warning: rule in expirations.yaml has no fields to match: ' + expired_rule)
                    else:
                        print('Warning: rule in expirations.yaml is missing a valid expiration field: ' + expired_rule)

            #Handle expirations in <group>.yaml
            if 'expiration' in added_rule and isint(added_rule['expiration']):
                if int(added_rule['expiration']) < int(time.time()) - int(added_rule['date']):
                    if not silence:
                        print('Removed rule: ' + str(added_rule))
                    added_rules.remove(added_rule)
                    rules_removed = True

        #Prepare added_rules for loading back into yaml file
        for added_rule in added_rules:
            del added_rule['hexsha']
            del added_rule['author']
            del added_rule['date']

        if rules_removed:
            any_rules_removed = True

            #Edit yaml with new rules
            rules['rules'] = added_rules
            f = open( os.path.join( repo, groups[group] ), 'w' )
            f.write( hotcidr.state.dump(rules, default_flow_style=False) )
            f.close()

        #Print progress
        if not silence:
            i += 1
            print('Progress: ' + str(int(100*i/groups_num)), file=sys.stderr)

    #Commit and push changes if there were any rule changes
    if any_rules_removed:
        #Commit and push file
        git.Git( repo ).add( groups[group] ) 
        git.Git( repo ).commit('-m','Automatically removed expired rule')

        if not dont_push:
            try:
                git.Git( repo ).push()
            except git.exc.GitCommandError:
                print('Error: ' + repo + ' cannot be pushed: no remote exists? Try specifying the --dont-push argument.')
                return 1

    #Remove temporary git repo
    if is_git_repo:
        rmtree( repo )

    return 0
Ejemplo n.º 23
0
def update(i):
    isint(i.id)
    isvarchar(i.name,1,50)
    id = i.id
    db.update('groups',where='id=$id',name=i.name,
            vars=locals(),_test=is_debug)
Ejemplo n.º 24
0
def edit_func(args, u413):
    # EDIT already requested continuation
    if "step" in u413.cmddata:
        # ID>
        if u413.cmddata["step"] == 1:
            u413.donttype('"' + args + '"')
            if util.isint(args):
                u413.cmddata["id"] = int(args)
                u413.cmddata["step"] = 2
                u413.set_context("NEW BODY")
                u413.type("Enter the new post body:")
                u413.edit_text(util.dehtmlify(db.query("SELECT post FROM posts WHERE id=%i;" % int(args))[0]["post"]))
                u413.continue_cmd()
            else:
                u413.type("Invalid post ID.")
                u413.set_context("")
                # NEW BODY>
        elif u413.cmddata["step"] == 2:
            post = int(db.query("SELECT owner FROM posts WHERE id=%i;" % u413.cmddata["id"])[0]["owner"])
            owner = int(db.query("SELECT access FROM users WHERE id=%i;" % post)[0]["access"])
            if post != u413.user.userid:
                if u413.user.level < user.User.halfmod or u413.user.level <= owner:
                    u413.type("You do not have permission to edit other user's posts.")
                    return
            db.query(
                "UPDATE posts SET post='%s',editor=%i,edited=NOW() WHERE id=%i;"
                % (db.escape(util.htmlify(args)), u413.user.userid, u413.cmddata["id"])
            )
            u413.type("Post edited successfully.")
            u413.set_context(u413.cmddata["context"])
            # EDIT used for the first time
    else:
        params = args.split(" ", 1)
        # EDIT
        if len(args) == 0:
            u413.cmddata["step"] = 1
            u413.cmddata["context"] = u413.user.context
            u413.type("Enter the post's ID:")
            u413.set_context("Post ID")
            u413.continue_cmd()
            # EDIT id
        elif len(params) == 1:
            if util.isint(args):
                u413.cmddata["step"] = 2
                u413.cmddata["context"] = u413.user.context
                u413.cmddata["id"] = int(args)
                u413.type("Enter the new post body:")
                u413.set_context("NEW BODY")
                u413.edit_text(util.dehtmlify(db.query("SELECT post FROM posts WHERE id=%i;" % int(args))[0]["post"]))
                u413.continue_cmd()
            else:
                u413.type("Invalid post ID.")
                # EDIT id body
        else:
            if util.isint(params[0]):
                post = int(db.query("SELECT owner FROM posts WHERE id=%i;" % int(params[0]))[0]["owner"])
                owner = int(db.query("SELECT access FROM users WHERE id=%i;" % post)[0]["access"])
                if post != u413.user.userid:
                    if u413.user.level < user.User.halfmod or u413.user.level <= owner:
                        u413.type("You do not have permission to edit other user's posts.")
                        return
                db.query(
                    "UPDATE posts SET post='%s',editor=%i,edited=NOW() WHERE id=%i;"
                    % (db.escape(util.htmlify(params[1])), u413.user.userid, int(params[0]))
                )
                u413.type("Post edited successfully.")
                u413.set_context("")
            else:
                u413.type("Invalid post ID.")
Ejemplo n.º 25
0
 def __sub__(self, x):
     if not isint(x):
         raise RuntimeError("cannot __sub__ a {}".format(x))
     return Relocatable(self.tag, self.imm - x)