ulg.py 25.1 KB
Newer Older
1 2 3
#!/usr/bin/env python
#
# ULG - Universal Looking Glass
4
# (C) 2012 CZ.NIC, z.s.p.o.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# Imports
21
import os, sys
22 23
from genshi.template import TemplateLoader
from genshi.core import Markup
24 25 26
import cgi
import cgitb; cgitb.enable()
import pickle
27
import re
28
import fcntl
29
import traceback
30 31 32 33
import urllib
import md5
import time
import random
34 35 36

import defaults

37
import ulgmodel
38
import whois
39

40 41
config = ulgmodel.import_config()

42 43 44
IPV4_ANNOTATE_REGEXP = '([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(/[0-9]{1,2})?)'
ipv4_annotate_regexp = re.compile(IPV4_ANNOTATE_REGEXP)

45 46 47
IPV6_ANNOTATE_REGEXP = '(([0-9a-fA-F]{1,4}:|:){2,7}([0-9a-fA-F]{1,4}|:)(/[0-9]{1,2})?)'
ipv6_annotate_regexp = re.compile(IPV6_ANNOTATE_REGEXP)

48
### CGI output handler
49

50 51 52 53 54 55 56 57 58 59 60 61
def getSessionFileName(sessionid):
    if(re.compile('^[a-zA-Z0-9]{10,128}$').match(sessionid)):
        return defaults.session_dir+'/'+'ulg-'+sessionid+'.session'
    else:
        raise Exception('Invalid session id passed. Value was: '+sessionid)

def getSessionOutputFileName(sessionid):
    if(re.compile('^[a-zA-Z0-9]{10,128}$').match(sessionid)):
        return defaults.session_dir+'/'+'ulg-'+sessionid+'.out.session'
    else:
        raise Exception('Invalid session id passed. Value was: '+sessionid)

62
class Session(object):
63 64 65 66 67 68 69 70 71 72
    def __init__(self,sessionid=None,routerid=None,commandid=None,parameters=[],result=None,finished=False,error=None,resrange=None,copy=None):
        if(copy):
            self.sessionid=copy.sessionid
            self.routerid=copy.routerid
            self.commandid=copy.commandid
            self.parameters=copy.parameters
            self.error=copy.error
            self.finished=copy.finished
            self.range=copy.range
            self.resultlen=copy.resultlen
73
            self.data=copy.data
74

75
        else:
76 77 78 79
            if(sessionid == None):
                self.sessionid = self.__genSessionId__()
            else:
                self.sessionid=sessionid
80

81 82 83 84 85 86 87
            self.routerid=routerid
            self.commandid=commandid
            self.parameters=parameters
            self.error=error
            self.finished=finished
            self.range=resrange
            self.resultlen=0
88
            self.data=None
89

90
        self.save()
91

92 93
    def __genSessionId__(self):
        return md5.new(str(time.time())+str(random.randint(1,1000000))).hexdigest()
94

95 96
    def save(self):
        try:
97
            fn = getSessionFileName(self.getSessionId())
98 99 100
            f = open(fn,'wb')
            pickle.dump(self, f)
            f.close()
101 102
        except:
            ulgmodel.log("Saving session failed: " + traceback.format_exc())
103

104 105
    def getSessionId(self):
        return self.sessionid
106

107 108 109
    def setFinished(self):
        self.finished=True
        self.save()
110

111 112
    def isFinished(self):
        return self.finished
113

114 115 116
    def setRouterId(self,router):
        self.routerid=routerid
        self.save()
117

118 119
    def getRouterId(self):
        return self.routerid
120

121 122 123
    def setCommandId(self,command):
        self.commandid = commandid
        self.save()
124

125 126 127 128 129 130
    def getCommandId(self):
        return self.commandid

    def cleanParameters(self):
        self.parameters = []
        self.save()
131

132 133 134 135 136
    def addParameter(self,parameter):
        if(not self.parameters):
            self.parameters = []
        self.parameters.append(parameter)
        self.save()
137

138 139
    def getParameters(self):
        return self.parameters
140

141
    def setResult(self,result):
142
        fn = getSessionOutputFileName(self.sessionid)
143 144 145 146

        f = open(fn, 'w')
        f.write(result)
        f.close()
147

148
    def getResult(self):
149
        try:
150
            fn = getSessionOutputFileName(self.sessionid)
151 152 153 154 155 156 157 158 159 160

            if(os.path.isfile(fn)):
                f = open(fn, 'r')
                result = f.read()
                f.close()
                return result
            else:
                return None
        except:
            return None
161

162
    def getDecoratedResult(self,decorator_helper,resrange=0,finished=False):
163
        if(self.getError()):
164
            # TODO
165 166
            return decorator_helper.pre(self.getResult())
        else:
167 168 169
            dr = self.getCommand().decorateResult(self,decorator_helper)

            if(dr):
170 171
                self.resultlines = dr[1]
                return dr[0]
172
            else:
173 174
                self.resultlines = 0
                return ''
175

176
    def appendResult(self,result_fragment):
177
        fn = getSessionOutputFileName(self.sessionid)
178 179 180 181 182 183 184

        f = open(fn, 'a')
        f.write(result_fragment)
        f.close()

    def clearResult(self):
        try:
185
            fn = getSessionOutputFileName(self.sessionid)
186 187 188 189

            if(os.path.isfile(fn)):
                f=open(fn,'w')
                f.close()
190 191

            self.resultlines = 0
192 193
        except:
            pass
194 195 196 197

    def getRouter(self):
        if(self.getRouterId()!=None):
            return config.routers[self.getRouterId()]
198 199 200
        else:
            return None

201 202 203 204 205
    def getCommand(self):
        if(self.getRouterId()!=None)and(self.getCommandId()!=None):
            return self.getRouter().listCommands()[self.getCommandId()]
        else:
            return None
206

207 208 209 210 211
    def getError(self):
        return self.error

    def setError(self,error=None):
        self.error=error
212 213 214 215 216 217 218 219 220
        self.save()

    def getRange(self):
        return self.range

    def setRange(self,resrange):
        self.range=resrange
        self.save()

221 222 223
    def showRange(self):
        return self.getCommand().showRange()

224 225
    def getMaxRange(self):
        return self.resultlines
226

227 228 229 230 231 232 233
    def getData(self):
        return self.data

    def setData(self,data):
        self.data = data
        self.save()

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
def loadSession(sessionid):
    if(sessionid == None):
        return None

    try:
        fn = getSessionFileName(sessionid)

        if(os.path.isfile(fn)):
            f = open(fn, 'rb')
            s = pickle.load(f)
            f.close()
            return s
        else:
            return None
            
    except Exception:
        return None

252

253
class DecoratorHelper:
254 255
    def __init__(self):
        pass
256

257 258
    def getScriptURL(self):
        return os.path.basename(__file__)
259

260
    def getURL(self,action,parameters={}):
261
        url=self.getScriptURL() + ("?action=%s" % urllib.quote(action))
262
        for k in parameters.keys():
263
            url = url + '&' + k + '=' + urllib.quote(parameters[k])
264
        return url
265

266 267
    def getIndexURL(self):
        return self.getURL('index')
268

269 270
    def getRuncommandURL(self,parameters={}):
        return self.getURL('runcommand',parameters)
271

272 273 274 275 276
    def getDisplayURL(self,sessionid,resrange=None):
        if(resrange):
            return self.getURL('display',{'sessionid':sessionid,'resrange':resrange})
        else:
            return self.getURL('display',{'sessionid':sessionid})
277

278 279 280 281 282 283
    def getDebugURL(self,parameters={}):
        return self.getURL('debug',parameters)

    def getErrorURL(self,parameters={}):
        return self.getURL('error',parameters)

284 285 286
    def getSpecialContentURL(self,sessionid,parameters={}):
        return self.getURL('getfile',dict({'sessionid':sessionid},**parameters))

287 288 289 290 291 292
    def getWhoisURL(self,key,objtype=None):
        if(objtype):
            return self.getURL('whois',dict({'key':key,'objtype':objtype}))
        else:
            return self.getURL('whois',dict({'key':key}))

293
    def getRouterID(self,router):
294 295 296 297
        for ridx,r in enumerate(config.routers):
            if(r == router):
                return ridx

298
        return 0
299

300
    def getCommandID(self,router,command):
301 302 303 304
        for cidx,c in enumerate(router.listCommands()):
            if(c == command):
                return cidx

305
        return 0
306

307 308 309 310
    def pre(self,text):
        return ('<pre>%s</pre>' % text)

    def ahref(self,url,text):
311
        return ('<a href=%s>%s</a>' % (str(url),str(text)))
312

313 314 315
    def copy_session(self,session):
        return Session(copy=session)

316 317 318 319 320 321
    def img(self,url,alternative_text=None):
        if(alternative_text):
            return ('<img src="%s" alt="%s">' % (url,alternative_text))
        else:
            return ('<img src="%s">' % url)

322 323 324 325 326
    def mwin(self,url,label=None):
        if(label == None):
            label = url
        return """<span style="cursor: pointer" onclick="TINY.box.show({iframe:'%s',boxid:'frameless',fixed:false,width:750,height:450,closejs:function(){closeJS()}})"><u>%s</u></span>""" % (url,label)

327
    def decorateASN(self,asn,prefix="AS"):
328
        asn = re.sub('[Aa][Ss][Nn]?([0-9]+)','\\1',asn)
329
        return self.mwin(self.getWhoisURL('AS'+str(asn),'AS'),prefix+str(asn))
330

331
    def decoratePrefix(self,ip):
332
        return self.mwin(self.getWhoisURL(ip,'IP'),ip)
333

334
    def annotatePrefixes4(self,line):
335 336 337 338 339 340 341 342
        s=0
        r=''
        for m in ipv4_annotate_regexp.finditer(line):
            r = r + line[s:m.start()]
            r = r + self.decoratePrefix(line[m.start():m.end()])
            s = m.end()
        return r + line[s:]

343
    def annotateIPs4(self,line):
344 345 346 347 348 349 350
        s=0
        r=''
        for m in ipv4_annotate_regexp.finditer(line):
            r = r + line[s:m.start()]
            r = r + self.decoratePrefix(line[m.start():m.end()])
            s = m.end()
        return r + line[s:]
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376

    def annotatePrefixes6(self,line):
        s=0
        r=''
        for m in ipv6_annotate_regexp.finditer(line):
            r = r + line[s:m.start()]
            r = r + self.decoratePrefix(line[m.start():m.end()])
            s = m.end()
        return r + line[s:]

    def annotateIPs6(self,line):
        s=0
        r=''
        for m in ipv6_annotate_regexp.finditer(line):
            r = r + line[s:m.start()]
            r = r + self.decoratePrefix(line[m.start():m.end()])
            s = m.end()
        return r + line[s:]

    def annotatePrefixes(self,line):
#        return self.annotatePrefixes4(line)
        return self.annotatePrefixes6(self.annotatePrefixes4(line))

    def annotateIPs(self,line):
#        return self.annotateIPs4(line)
        return self.annotateIPs6(self.annotatePrefixes4(line))
377

378

379
class ULGCgi:
380
    def __init__(self):
381 382 383 384
        self.loader=TemplateLoader(
            os.path.join(os.path.dirname(__file__), defaults.template_dir),
            auto_reload=True
            )
385

386
        self.decorator_helper = DecoratorHelper()
387

388 389 390 391 392

    def print_text_html(self):
        print "Content-Type: text/html\n"


393 394 395 396 397 398 399 400 401
    def increaseUsage(self):
        u = 0
        try:
            # Open files
            if(os.path.isfile(defaults.usage_counter_file)):
                lf = open(defaults.usage_counter_file,'r+')
                u = int(lf.readline())
            else:
                lf = open(defaults.usage_counter_file,'w')
402

403 404
            # Acquire lock
            fcntl.lockf(lf, fcntl.LOCK_EX)
405
        except (IOError,ValueError) as e:
406
            ulgmodel.log("Locking mechanism failure: "+str(e))
407
            return False
408

409 410 411 412 413 414 415 416 417 418 419 420
        try:
            if(u < defaults.usage_limit):
                # write a new value and release lock
                lf.seek(0)
                lf.write(str(u+1)+'\n')
                lf.close()
                return True
            else:
                # release lock
                lf.close()
                return False
        except IOError as e:
421
            ulgmodel.log("Locking mechanism update failure: "+str(e))
422
            return False
423

424 425 426 427 428 429 430 431 432
    def decreaseUsage(self):
        u = 1
        try:
            # Open files
            if(os.path.isfile(defaults.usage_counter_file)):
                lf = open(defaults.usage_counter_file,'r+')
                u = int(lf.readline())
            else:
                lf = open(defaults.usage_counter_file,'w')
433

434 435 436
            # Acquire lock
            fcntl.lockf(lf, fcntl.LOCK_EX)
        except IOError,ValueError:
437
            ulgmodel.log("Locking mechanism failure: "+str(e))
438
            return False
439

440 441 442 443 444 445 446 447 448 449 450 451
        try:
            if(u>0):
                # write a new value and release lock
                lf.seek(0)
                lf.write(str(u-1)+'\n')
                lf.close()
                return
            else:
                # release lock
                lf.close()
                return
        except IOError as e:
452
            ulgmodel.log("Locking mechanism update failure: "+str(e))
453 454 455 456 457 458
            pass

    def stopSessionOverlimit(self,session):
        session.setResult(defaults.STRING_SESSION_OVERLIMIT)
        session.setFinished()

459 460
    def getRefreshInterval(self,datalength=None):
        if(datalength):
461
            return (datalength/(1024*100))*defaults.refresh_interval + defaults.refresh_interval
462 463 464
        else:
            return defaults.refresh_interval

465 466 467 468 469 470 471 472 473 474 475 476
    def HTTPRedirect(self,url):
        return """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Redirect!</title>
<meta http-equiv="REFRESH" content="0;url=%s">
</head>
<body>
</body>
</html>""" % url

    def runCommand(self,session):
477 478 479 480 481 482 483
        class FakeSessionFile(object):
            def __init__(self,session):
                self.session = session

            def write(self,string):
                self.session.appendResult(string)

484 485 486 487 488
        # define trivial thread function
        def commandThreadBody(session,decreaseUsageMethod):
            ulgmodel.debug("Running command: "+session.getCommand().getName())
            try:
                session.getRouter().runAsyncCommand(session.getCommand(),session.getParameters(),FakeSessionFile(session))
489
                session.getCommand().finishHook(session)
490 491 492 493 494 495 496 497
            except Exception as e:
                ulgmodel.log("ERROR: Exception occured while running a command:" + traceback.format_exc())
                session.setResult("ERROR in commandThreadBody:\n"+traceback.format_exc())
            finally:
                ulgmodel.debug("Command finished: "+session.getCommand().getName())
                session.setFinished()
                decreaseUsageMethod()

498 499 500 501
        # try to increase usage counter
        if(self.increaseUsage()):
            # start new thread if needed
            if(defaults.always_start_thread or session.getRouter().getForkNeeded()):
502
                # fork a daemon process (fork two times to decouple with parent)
503 504 505 506 507 508 509 510 511
                sys.stdout.flush()
                child_pid = os.fork()
                if(child_pid == 0):
                    # detach process
                    devnull = open(os.devnull,'w')
                    os.dup2(devnull.fileno(),sys.stdout.fileno())
                    os.dup2(devnull.fileno(),sys.stderr.fileno())

                    # run the command
512
                    ulgmodel.debug("Running in a forked process...")
513
                    commandThreadBody(session,self.decreaseUsage)
514
                    ulgmodel.debug("Forked process finished...")
515 516 517

                    # exit the child
                    sys.exit(0)
518 519
                else:
                    ulgmodel.debug("Forked a new process PID: "+str(child_pid))
520

521
            else:
522
                # directly run the selected action, DEPRECATED
523 524 525 526
                commandThreadBody(session,self.decreaseUsage)
        else:
            # stop and report no-op
            self.stopSessionOverlimit(session)
527 528


529 530
    def renderULGIndex(self,routerid=0,commandid=0,sessionid=None):
        template = self.loader.load(defaults.index_template_file)
531

532 533 534 535 536
        return template.generate(defaults=defaults,
                                 routers=config.routers,
                                 default_routerid=routerid,
                                 default_commandid=commandid,
                                 default_sessionid=sessionid,
537
                                 getFormURL=self.decorator_helper.getRuncommandURL
538
                                 ).render('html', doctype='html')
539 540


541 542 543
    def renderULGAction(self,routerid=0,commandid=0,sessionid=None,**moreparams):
        routerid=int(routerid)
        commandid=int(commandid)
544

545 546
        # create and register session
        session = Session(sessionid=sessionid,routerid=routerid,commandid=commandid)
547
        session.clearResult()
548 549 550 551 552
    
        # extract parameters
        session.cleanParameters()
        for pidx,ps in enumerate(session.getCommand().getParamSpecs()):
            if('param'+str(pidx) in moreparams.keys()):
553
                session.addParameter(str(moreparams['param'+str(pidx)]))
554 555
            else:
                session.addParameter(ps.getDefault())
556

557
        # run the command (possibly in a separate process)
558
        self.runCommand(session)
559

560
        # redirect to the session display
561
        return self.HTTPRedirect(self.decorator_helper.getDisplayURL(session.getSessionId()))
562 563


564 565
    def renderULGResult(self,sessionid=None,resrange=0):
        def getRangeStepURLs(session,decorator_helper):
566 567 568
            if(not session.showRange()):
                return None

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
            cur_range = session.getRange()
            max_range = session.getMaxRange()

            if(max_range < defaults.range_step):
                return None

            res = []
            if((cur_range - defaults.range_step * 100) >= 0):
                res.append(('<<',decorator_helper.getDisplayURL(session.getSessionId(),str(cur_range - defaults.range_step * 100))))
            if((cur_range - defaults.range_step * 10) >= 0):
                res.append(('<',decorator_helper.getDisplayURL(session.getSessionId(),str(cur_range - defaults.range_step * 10))))

            boundary_size = 8
            leftb = max(0,cur_range - boundary_size*defaults.range_step)
            rightb = min(leftb + 2*boundary_size*defaults.range_step,max_range)

            for rb in range(leftb,rightb,defaults.range_step):
                if(rb != cur_range):
                    res.append((str(rb),decorator_helper.getDisplayURL(session.getSessionId(),str(rb))))
                else:
                    res.append((str(rb),None))

            if((cur_range + defaults.range_step * 10) < max_range):
                res.append(('>',decorator_helper.getDisplayURL(session.getSessionId(),str(cur_range + defaults.range_step * 10))))
            if((cur_range + defaults.range_step * 100) < max_range):
                res.append(('>>',decorator_helper.getDisplayURL(session.getSessionId(),str(cur_range + defaults.range_step * 100))))

            return res

598
        if(sessionid==None):
599
            return self.HTTPRedirect(self.decorator_helper.getErrorURL())
600

601
        session = loadSession(sessionid)
602
        if(session == None):
603
            return self.HTTPRedirect(self.decorator_helper.getErrorURL())
604

605 606
        session.setRange(int(resrange))

607
        result_text = session.getDecoratedResult(self.decorator_helper,session.getRange(),session.isFinished())
608

609 610
        if(session.isFinished()):
            refresh=None
611
        else:
612 613 614 615
            if(result_text):
                refresh = self.getRefreshInterval(len(result_text))
            else:
                refresh = self.getRefreshInterval()
616 617 618 619 620 621 622 623

        template = self.loader.load(defaults.index_template_file)
        return template.generate(defaults=defaults,
                                 routers=config.routers,
                                 default_routerid=session.getRouterId(),
                                 default_commandid=session.getCommandId(),
                                 default_params=session.getParameters(),
                                 default_sessionid=sessionid,
624
                                 result=Markup(result_text) if(result_text) else None,
625
                                 refresh=refresh,
626 627 628
                                 getFormURL=self.decorator_helper.getRuncommandURL,
                                 resrange=str(session.getRange()),
                                 resrangeb=getRangeStepURLs(session,self.decorator_helper),
629 630 631 632 633 634 635
                                 ).render('html', doctype='html')

    def renderULGError(self,sessionid=None,**params):
        template = self.loader.load(defaults.index_template_file)

        result_text = defaults.STRING_ARBITRARY_ERROR

636
        session = loadSession(sessionid)
637
        if(session!=None):
638
            result_text=self.decorator_helper.pre(self.sessions[sessionid].getError())
639 640 641 642 643 644

        return template.generate(defaults=defaults,
                                 routers=config.routers,
                                 default_routerid=0,
                                 default_commandid=0,
                                 default_sessionid=None,
645
                                 result=Markup(result_text) if(result_text) else None,
646
                                 refresh=0,
647
                                 getFormURL=self.decorator_helper.getRuncommandURL
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
                                 ).render('html', doctype='html')
    
    def renderULGDebug(self,**params):
        template = self.loader.load(defaults.index_template_file)

        result_text = "<h1>DEBUG</h1>\n<pre>\nPARAMS:\n"
        for k in params.keys():
            result_text = result_text + str(k) + "=" + str(params[k]) + "\n"
        result_test = result_text + "\n<pre>"

        return template.generate(defaults=defaults,
                                 routers=config.routers,
                                 default_routerid=0,
                                 default_commandid=0,
                                 default_sessionid=None,
663
                                 result=Markup(result_text) if(result_text) else None,
664
                                 refresh=0,
665
                                 getFormURL=self.decorator_helper.getRuncommandURL()
666 667
                                 ).render('html', doctype='html')

668 669 670 671 672

    def getULGSpecialContent(self,sessionid,**params):
        if(sessionid==None):
            return self.HTTPRedirect(self.decorator_helper.getErrorURL())

673
        session = loadSession(sessionid)
674 675 676
        if(session == None):
            return self.HTTPRedirect(self.decorator_helper.getErrorURL())

677 678
        # speciality here: the function is responsible for printing the output itself
        session.getCommand().getSpecialContent(session,**params)
679

680 681 682 683 684 685 686 687 688
    def runULGWhois(self,key,objtype):
        url=None
        urlc=None
        if(objtype == 'IP'):
            url=defaults.getIPPrefixURL(key)
            urlc=defaults.STRING_DETAILS+' '+str(key)
        elif(objtype == 'AS'):
            url=defaults.getASNURL(key)
            urlc=defaults.STRING_DETAILS+' '+key
689 690 691 692

        m = re.match('^\s*([^/]+)/[0-9]+\s*$',key)
        if(m):
            key = m.group(1)
693 694 695

        template = self.loader.load(defaults.whois_template_file)

696
        res = whois.lookup(key)
697 698 699 700 701
        return template.generate(result=Markup(res),
                                 url=url,
                                 url_caption=urlc,
                                 ).render('html', doctype='html')

702

703
    def index(self, **params):
704
        self.print_text_html()
705 706
        if('sessionid' in params.keys()):
            print self.renderULGIndex(sessionid=params['sessionid'])
707
        else:
708
            print self.renderULGIndex()
709

710
    def runcommand(self,routerid=0,commandid=0,sessionid=None,**params):
711
        self.print_text_html()
712
        print self.renderULGAction(routerid,commandid,sessionid,**params)
713

714
    def display(self,sessionid=None,**params):
715
        self.print_text_html()
716
        print self.renderULGResult(sessionid,**params)
717

718
    def getfile(self,sessionid=None,**params):
719
        self.getULGSpecialContent(sessionid,**params)
720

721 722 723 724 725 726 727
    def whois(self,key,objtype=None):
        self.print_text_html()
        if(key):
            print self.runULGWhois(key,objtype)
        else:
            print self.HTTPRedirect(self.decorator_helper.getErrorURL())

728
    def error(self,sessionid=None,**params):
729
        self.print_text_html()
730
        print self.renderULGError(sessionid,**params)
731

732
    def debug(self,**params):
733
        self.print_text_html()
734
        print self.renderULGDebug(**params)
735

736
# main
737

738
if __name__=="__main__":
739 740 741
    try:
        form = cgi.FieldStorage()
        handler = ULGCgi()
742

743 744
        action = form.getvalue('action',None)
        params = dict([(k,form.getvalue(k)) for k in form.keys() if k != 'action'])
745 746

        ulgmodel.log("Request from "+os.environ["REMOTE_ADDR"]+" with action="+str(action)+" params="+str(params)+'.')
747
    
748 749 750 751 752 753 754
        if(action):
            if(action == 'index'):
                handler.index(**params)
            elif(action == 'runcommand'):
                handler.runcommand(**params)
            elif(action == 'display'):
                handler.display(**params)
755 756
            elif(action == 'getfile'):
                handler.getfile(**params)
757 758
            elif(action == 'whois'):
                handler.whois(**params)
759
            elif(action == 'error'):
760
                handler.error(**params)
761 762 763 764 765 766 767
            elif(action == 'debug'):
                handler.debug(**params)
            else:
                ulgmodel.log('ERROR: Unknown action called: '+action+'\n')
                handler.display(**params)

        else:
768
            handler.index(**params)
769 770
    except Exception as e:
        ulgmodel.log("ERROR in CGI: "+traceback.format_exc())