ulg.py 26.6 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
import urllib
31
import hashlib
32 33
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
    def __genSessionId__(self):
93
        return hashlib.md5(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,user=None):
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
        self.user = user
388

389 390 391 392 393

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


394 395 396 397 398 399 400 401 402
    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')
403

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

410 411 412 413 414 415 416 417 418 419 420 421
        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:
422
            ulgmodel.log("Locking mechanism update failure: "+str(e))
423
            return False
424

425 426 427 428 429 430 431 432 433
    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')
434

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

441 442 443 444 445 446 447 448 449 450 451 452
        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:
453
            ulgmodel.log("Locking mechanism update failure: "+str(e))
454 455 456 457 458 459
            pass

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

460 461 462 463
    def stopSessionAccessDenied(self,session):
        session.setResult(defaults.STRING_SESSION_ACCESSDENIED)
        session.setFinished()

464 465
    def getRefreshInterval(self,datalength=None):
        if(datalength):
466
            return (datalength/(1024*100))*defaults.refresh_interval + defaults.refresh_interval
467 468 469
        else:
            return defaults.refresh_interval

470 471 472 473 474 475 476 477 478 479
    def getCommonParams(self):
        res = {}
        for r in config.routers:
            for c in r.listCommands():
                for ps in c.getParamSpecs():
                    if(ps.getType() == 'commonselect'):
                        res[ps.getID()] = ps            

        return res

480 481 482 483 484 485 486 487 488 489 490
    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

491
    def runCommand(self,session,user=None):
492 493 494 495 496 497 498
        class FakeSessionFile(object):
            def __init__(self,session):
                self.session = session

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

499 500 501 502 503
        # 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))
504
                session.getCommand().finishHook(session)
505 506 507 508 509 510 511 512
            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()

513 514 515 516 517 518
        # check router ACL
        if user:
            if not session.getRouter().checkACL(user):
                self.stopSessionAccessDenied(session)
                return

519 520 521 522
        # try to increase usage counter
        if(self.increaseUsage()):
            # start new thread if needed
            if(defaults.always_start_thread or session.getRouter().getForkNeeded()):
523
                # fork a daemon process (fork two times to decouple with parent)
524 525 526 527 528 529 530 531 532
                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
533
                    ulgmodel.debug("Running in a forked process...")
534
                    commandThreadBody(session,self.decreaseUsage)
535
                    ulgmodel.debug("Forked process finished...")
536 537 538

                    # exit the child
                    sys.exit(0)
539 540
                else:
                    ulgmodel.debug("Forked a new process PID: "+str(child_pid))
541

542
            else:
543
                # directly run the selected action, DEPRECATED
544 545 546 547
                commandThreadBody(session,self.decreaseUsage)
        else:
            # stop and report no-op
            self.stopSessionOverlimit(session)
548
            return
549 550


551 552
    def renderULGIndex(self,routerid=0,commandid=0,sessionid=None):
        template = self.loader.load(defaults.index_template_file)
553

554 555
        return template.generate(defaults=defaults,
                                 routers=config.routers,
556
                                 commonparams=self.getCommonParams(),
557 558 559
                                 default_routerid=routerid,
                                 default_commandid=commandid,
                                 default_sessionid=sessionid,
560 561
                                 getFormURL=self.decorator_helper.getRuncommandURL,
                                 user=self.user
562
                                 ).render('html', doctype='html', encoding='utf-8')
563 564


565 566 567
    def renderULGAction(self,routerid=0,commandid=0,sessionid=None,**moreparams):
        routerid=int(routerid)
        commandid=int(commandid)
568

569 570
        # create and register session
        session = Session(sessionid=sessionid,routerid=routerid,commandid=commandid)
571
        session.clearResult()
572 573 574 575 576
    
        # extract parameters
        session.cleanParameters()
        for pidx,ps in enumerate(session.getCommand().getParamSpecs()):
            if('param'+str(pidx) in moreparams.keys()):
577
                session.addParameter(str(moreparams['param'+str(pidx)]))
578 579
            else:
                session.addParameter(ps.getDefault())
580

581
        # run the command (possibly in a separate process)
582
        self.runCommand(session)
583

584
        # redirect to the session display
585
        return self.HTTPRedirect(self.decorator_helper.getDisplayURL(session.getSessionId()))
586 587


588 589
    def renderULGResult(self,sessionid=None,resrange=0):
        def getRangeStepURLs(session,decorator_helper):
590 591 592
            if(not session.showRange()):
                return None

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
            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

622
        if(sessionid==None):
623
            return self.HTTPRedirect(self.decorator_helper.getErrorURL())
624

625
        session = loadSession(sessionid)
626
        if(session == None):
627
            return self.HTTPRedirect(self.decorator_helper.getErrorURL())
628

629 630
        session.setRange(int(resrange))

631
        result_text = session.getDecoratedResult(self.decorator_helper,session.getRange(),session.isFinished())
632

633 634
        if(session.isFinished()):
            refresh=None
635
        else:
636 637 638 639
            if(result_text):
                refresh = self.getRefreshInterval(len(result_text))
            else:
                refresh = self.getRefreshInterval()
640 641 642 643

        template = self.loader.load(defaults.index_template_file)
        return template.generate(defaults=defaults,
                                 routers=config.routers,
644
                                 commonparams=self.getCommonParams(),
645 646 647 648
                                 default_routerid=session.getRouterId(),
                                 default_commandid=session.getCommandId(),
                                 default_params=session.getParameters(),
                                 default_sessionid=sessionid,
649
                                 result=Markup(result_text) if(result_text) else None,
650
                                 refresh=refresh,
651 652 653
                                 getFormURL=self.decorator_helper.getRuncommandURL,
                                 resrange=str(session.getRange()),
                                 resrangeb=getRangeStepURLs(session,self.decorator_helper),
654
                                 user=self.user,
655
                                 ).render('html', doctype='html', encoding='utf-8')
656 657 658 659 660 661

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

        result_text = defaults.STRING_ARBITRARY_ERROR

662
        session = loadSession(sessionid)
663
        if(session!=None):
664
            result_text=self.decorator_helper.pre(self.sessions[sessionid].getError())
665 666 667

        return template.generate(defaults=defaults,
                                 routers=config.routers,
668
                                 commonparams=self.getCommonParams(),
669 670 671
                                 default_routerid=0,
                                 default_commandid=0,
                                 default_sessionid=None,
672
                                 result=Markup(result_text) if(result_text) else None,
673
                                 refresh=0,
674 675
                                 getFormURL=self.decorator_helper.getRuncommandURL,
                                 user=self.user
676
                                 ).render('html', doctype='html', encoding='utf-8')
677 678 679 680 681 682 683 684 685 686 687
    
    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,
688
                                 commonparams=self.getCommonParams(),
689 690 691
                                 default_routerid=0,
                                 default_commandid=0,
                                 default_sessionid=None,
692
                                 result=Markup(result_text) if(result_text) else None,
693
                                 refresh=0,
694 695
                                 getFormURL=self.decorator_helper.getRuncommandURL(),
                                 user=self.user
696
                                 ).render('html', doctype='html', encoding='utf-8')
697

698 699 700 701 702

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

703
        session = loadSession(sessionid)
704 705 706
        if(session == None):
            return self.HTTPRedirect(self.decorator_helper.getErrorURL())

707 708
        # speciality here: the function is responsible for printing the output itself
        session.getCommand().getSpecialContent(session,**params)
709

710 711 712 713 714 715 716 717 718
    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
719 720 721 722

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

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

726
        res = whois.lookup(key)
727
        return template.generate(result=res,
728 729
                                 url=url,
                                 url_caption=urlc,
730
                                 ).render('html', doctype='html', encoding='utf-8')
731

732

733
    def index(self, **params):
734
        self.print_text_html()
735 736
        if('sessionid' in params.keys()):
            print self.renderULGIndex(sessionid=params['sessionid'])
737
        else:
738
            print self.renderULGIndex()
739

740
    def runcommand(self,routerid=0,commandid=0,sessionid=None,**params):
741
        self.print_text_html()
742
        print self.renderULGAction(routerid,commandid,sessionid,**params)
743

744
    def display(self,sessionid=None,**params):
745
        self.print_text_html()
746
        print self.renderULGResult(sessionid,**params)
747

748
    def getfile(self,sessionid=None,**params):
749
        self.getULGSpecialContent(sessionid,**params)
750

751 752 753 754 755 756 757
    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())

758
    def error(self,sessionid=None,**params):
759
        self.print_text_html()
760
        print self.renderULGError(sessionid,**params)
761

762
    def debug(self,**params):
763
        self.print_text_html()
764
        print self.renderULGDebug(**params)
765

766
# main
767

768
if __name__=="__main__":
769 770
    try:
        form = cgi.FieldStorage()
771 772 773 774
        user=None
        if 'REMOTE_USER' in os.environ:
            user=os.environ['REMOTE_USER']
        handler = ULGCgi(user)
775

776 777
        action = form.getvalue('action',None)
        params = dict([(k,form.getvalue(k)) for k in form.keys() if k != 'action'])
778

779 780 781 782
        if("REMOTE_ADDR" in os.environ):
            ulgmodel.log("Request from "+os.environ["REMOTE_ADDR"]+" with action="+str(action)+" params="+str(params)+'.')
        else:
            ulgmodel.log("Request from console with action="+str(action)+" params="+str(params)+'.')
783
    
784 785 786 787 788 789 790
        if(action):
            if(action == 'index'):
                handler.index(**params)
            elif(action == 'runcommand'):
                handler.runcommand(**params)
            elif(action == 'display'):
                handler.display(**params)
791 792
            elif(action == 'getfile'):
                handler.getfile(**params)
793 794
            elif(action == 'whois'):
                handler.whois(**params)
795
            elif(action == 'error'):
796
                handler.error(**params)
797 798 799 800 801 802 803
            elif(action == 'debug'):
                handler.debug(**params)
            else:
                ulgmodel.log('ERROR: Unknown action called: '+action+'\n')
                handler.display(**params)

        else:
804
            handler.index(**params)
805 806
    except Exception as e:
        ulgmodel.log("ERROR in CGI: "+traceback.format_exc())