/usr/lib/znc/modpython/znc.py is in znc-python 1.6.3-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 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 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 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 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 | #
# Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from functools import wraps
import imp
import re
import traceback
import collections
from znc_core import *
class Socket:
ADDR_MAP = {
'ipv4': ADDR_IPV4ONLY,
'ipv6': ADDR_IPV6ONLY,
'all': ADDR_ALL
}
def _Accepted(self, host, port):
return getattr(self.OnAccepted(host, port), '_csock', None)
def GetModule(self):
return AsPyModule(self._csock.GetModule()).GetNewPyObj()
def Listen(self, addrtype='all', port=None, bindhost='', ssl=False,
maxconns=GetSOMAXCONN(), timeout=0):
try:
addr = self.ADDR_MAP[addrtype.lower()]
except KeyError:
raise ValueError(
"Specified addrtype [{0}] isn't supported".format(addrtype))
args = (
"python socket for {0}".format(self.GetModule()),
bindhost,
ssl,
maxconns,
self._csock,
timeout,
addr
)
if port is None:
return self.GetModule().GetManager().ListenRand(*args)
if self.GetModule().GetManager().ListenHost(port, *args):
return port
return 0
def Connect(self, host, port, timeout=60, ssl=False, bindhost=''):
return self.GetModule().GetManager().Connect(
host,
port,
'python conn socket for {0}'.format(self.GetModule()),
timeout,
ssl,
bindhost,
self._csock
)
def Write(self, data):
if (isinstance(data, str)):
return self._csock.Write(data)
raise TypeError(
'socket.Write needs str. If you want binary data, use WriteBytes')
def Init(self, *a, **b):
pass
def OnConnected(self):
pass
def OnDisconnected(self):
pass
def OnTimeout(self):
pass
def OnConnectionRefused(self):
pass
def OnReadData(self, bytess):
pass
def OnReadLine(self, line):
pass
def OnAccepted(self, host, port):
pass
def OnShutdown(self):
pass
class Timer:
def GetModule(self):
return AsPyModule(self._ctimer.GetModule()).GetNewPyObj()
def RunJob(self):
pass
def OnShutdown(self):
pass
class ModuleNVIter(collections.Iterator):
def __init__(self, cmod):
self._cmod = cmod
self.it = cmod.BeginNV_()
def __next__(self):
if self.it.is_end(self._cmod):
raise StopIteration
res = self.it.get()
self.it.plusplus()
return res
class ModuleNV(collections.MutableMapping):
def __init__(self, cmod):
self._cmod = cmod
def __setitem__(self, key, value):
self._cmod.SetNV(key, value)
def __getitem__(self, key):
if not self._cmod.ExistsNV(key):
raise KeyError
return self._cmod.GetNV(key)
def __contains__(self, key):
return self._cmod.ExistsNV(key)
def __delitem__(self, key):
self._cmod.DelNV(key)
def keys(self):
return ModuleNVIter(self._cmod)
__iter__ = keys
def __len__(self):
raise NotImplemented
class Module:
description = '< Placeholder for a description >'
module_types = [CModInfo.NetworkModule]
wiki_page = ''
has_args = False
args_help_text = ''
def __str__(self):
return self.GetModName()
def OnLoad(self, sArgs, sMessage):
return True
def _GetSubPages(self):
return self.GetSubPages()
def CreateSocket(self, socketclass=Socket, *the, **rest):
socket = socketclass()
socket._csock = CreatePySocket(self._cmod, socket)
socket.Init(*the, **rest)
return socket
def CreateTimer(self, timer, interval=10, cycles=1, label='pytimer',
description='Some python timer'):
t = timer()
t._ctimer = CreatePyTimer(self._cmod, interval, cycles, label,
description, t)
return t
def GetSubPages(self):
pass
def OnShutdown(self):
pass
def OnBoot(self):
pass
def WebRequiresLogin(self):
pass
def WebRequiresAdmin(self):
pass
def GetWebMenuTitle(self):
pass
def OnWebPreRequest(self, WebSock, sPageName):
pass
def OnWebRequest(self, WebSock, sPageName, Tmpl):
pass
def OnPreRehash(self):
pass
def OnPostRehash(self):
pass
def OnIRCDisconnected(self):
pass
def OnIRCConnected(self):
pass
def OnIRCConnecting(self, IRCSock):
pass
def OnIRCConnectionError(self, IRCSock):
pass
def OnIRCRegistration(self, sPass, sNick, sIdent, sRealName):
pass
def OnBroadcast(self, sMessage):
pass
def OnChanPermission(self, OpNick, Nick, Channel, uMode, bAdded,
bNoChange):
pass
def OnOp(self, OpNick, Nick, Channel, bNoChange):
pass
def OnDeop(self, OpNick, Nick, Channel, bNoChange):
pass
def OnVoice(self, OpNick, Nick, Channel, bNoChange):
pass
def OnDevoice(self, OpNick, Nick, Channel, bNoChange):
pass
def OnMode(self, OpNick, Channel, uMode, sArg, bAdded, bNoChange):
pass
def OnRawMode(self, OpNick, Channel, sModes, sArgs):
pass
def OnRaw(self, sLine):
pass
def OnStatusCommand(self, sCommand):
pass
def OnModCommand(self, sCommand):
pass
def OnModNotice(self, sMessage):
pass
def OnModCTCP(self, sMessage):
pass
def OnQuit(self, Nick, sMessage, vChans):
pass
def OnNick(self, Nick, sNewNick, vChans):
pass
def OnKick(self, OpNick, sKickedNick, Channel, sMessage):
pass
def OnJoining(self, Channel):
pass
def OnJoin(self, Nick, Channel):
pass
def OnPart(self, Nick, Channel, sMessage=None):
pass
def OnChanBufferStarting(self, Chan, Client):
pass
def OnChanBufferEnding(self, Chan, Client):
pass
def OnChanBufferPlayLine(self, Chan, Client, sLine):
pass
def OnPrivBufferPlayLine(self, Client, sLine):
pass
def OnClientLogin(self):
pass
def OnClientDisconnect(self):
pass
def OnUserRaw(self, sLine):
pass
def OnUserCTCPReply(self, sTarget, sMessage):
pass
def OnUserCTCP(self, sTarget, sMessage):
pass
def OnUserAction(self, sTarget, sMessage):
pass
def OnUserMsg(self, sTarget, sMessage):
pass
def OnUserNotice(self, sTarget, sMessage):
pass
def OnUserJoin(self, sChannel, sKey):
pass
def OnUserPart(self, sChannel, sMessage):
pass
def OnUserTopic(self, sChannel, sTopic):
pass
def OnUserTopicRequest(self, sChannel):
pass
def OnCTCPReply(self, Nick, sMessage):
pass
def OnPrivCTCP(self, Nick, sMessage):
pass
def OnChanCTCP(self, Nick, Channel, sMessage):
pass
def OnPrivAction(self, Nick, sMessage):
pass
def OnChanAction(self, Nick, Channel, sMessage):
pass
def OnPrivMsg(self, Nick, sMessage):
pass
def OnChanMsg(self, Nick, Channel, sMessage):
pass
def OnPrivNotice(self, Nick, sMessage):
pass
def OnChanNotice(self, Nick, Channel, sMessage):
pass
def OnTopic(self, Nick, Channel, sTopic):
pass
def OnServerCapAvailable(self, sCap):
pass
def OnServerCapResult(self, sCap, bSuccess):
pass
def OnTimerAutoJoin(self, Channel):
pass
def OnEmbeddedWebRequest(self, WebSock, sPageName, Tmpl):
pass
def OnAddNetwork(self, Network, sErrorRet):
pass
def OnDeleteNetwork(self, Network):
pass
def OnSendToClient(self, sLine, Client):
pass
def OnSendToIRC(self, sLine):
pass
# Global modules
def OnAddUser(self, User, sErrorRet):
pass
def OnDeleteUser(self, User):
pass
def OnClientConnect(self, pSock, sHost, uPort):
pass
def OnLoginAttempt(self, Auth):
pass
def OnFailedLogin(self, sUsername, sRemoteIP):
pass
def OnUnknownUserRaw(self, pClient, sLine):
pass
def OnClientCapLs(self, pClient, ssCaps):
pass
def IsClientCapSupported(self, pClient, sCap, bState):
pass
def OnClientCapRequest(self, pClient, sCap, bState):
pass
def OnModuleLoading(self, sModName, sArgs, eType, bSuccess, sRetMsg):
pass
def OnModuleUnloading(self, pModule, bSuccess, sRetMsg):
pass
def OnGetModInfo(self, ModInfo, sModule, bSuccess, sRetMsg):
pass
def OnGetAvailableMods(self, ssMods, eType):
pass
# In python None is allowed value, so python modules may continue using OnMode and not OnMode2
def OnChanPermission2(self, OpNick, Nick, Channel, uMode, bAdded, bNoChange):
return self.OnChanPermission(OpNick, Nick, Channel, uMode, bAdded, bNoChange)
def OnOp2(self, OpNick, Nick, Channel, bNoChange):
return self.OnOp(OpNick, Nick, Channel, bNoChange)
def OnDeop2(self, OpNick, Nick, Channel, bNoChange):
return self.OnDeop(OpNick, Nick, Channel, bNoChange)
def OnVoice2(self, OpNick, Nick, Channel, bNoChange):
return self.OnVoice(OpNick, Nick, Channel, bNoChange)
def OnDevoice2(self, OpNick, Nick, Channel, bNoChange):
return self.OnDevoice(OpNick, Nick, Channel, bNoChange)
def OnMode2(self, OpNick, Channel, uMode, sArg, bAdded, bNoChange):
return self.OnMode(OpNick, Channel, uMode, sArg, bAdded, bNoChange)
def OnRawMode2(self, OpNick, Channel, sModes, sArgs):
return self.OnRawMode(OpNick, Channel, sModes, sArgs)
def make_inherit(cl, parent, attr):
def make_caller(parent, name, attr):
return lambda self, *a: parent.__dict__[name](self.__dict__[attr], *a)
while True:
for x in parent.__dict__:
if not x.startswith('_') and x not in cl.__dict__:
setattr(cl, x, make_caller(parent, x, attr))
if '_s' in parent.__dict__:
parent = parent._s
else:
break
make_inherit(Socket, CPySocket, '_csock')
make_inherit(Module, CPyModule, '_cmod')
make_inherit(Timer, CPyTimer, '_ctimer')
def find_open(modname):
'''Returns (pymodule, datapath)'''
for d in CModules.GetModDirs():
# d == (libdir, datadir)
try:
x = imp.find_module(modname, [d[0]])
except ImportError:
# no such file in dir d
continue
# x == (<open file './modules/admin.so', mode 'rb' at 0x7fa2dc748d20>,
# './modules/admin.so', ('.so', 'rb', 3))
# x == (<open file './modules/pythontest.py', mode 'U' at
# 0x7fa2dc748d20>, './modules/pythontest.py', ('.py', 'U', 1))
if x[0] is None and x[2][2] != imp.PKG_DIRECTORY:
# the same
continue
if x[2][0] == '.so':
try:
pymodule = imp.load_module(modname, *x)
except ImportError:
# found needed .so but can't load it...
# maybe it's normal (non-python) znc module?
# another option here could be to "continue"
# search of python module in other moddirs.
# but... we respect C++ modules ;)
return (None, None)
finally:
x[0].close()
else:
# this is not .so, so it can be only python module .py or .pyc
try:
pymodule = imp.load_module(modname, *x)
finally:
if x[0]:
x[0].close()
return (pymodule, d[1]+modname)
else:
# nothing found
return (None, None)
_py_modules = set()
def load_module(modname, args, module_type, user, network, retmsg, modpython):
'''Returns 0 if not found, 1 on loading error, 2 on success'''
if re.search(r'[^a-zA-Z0-9_]', modname) is not None:
retmsg.s = 'Module names can only contain letters, numbers and ' \
'underscores, [{0}] is invalid.'.format(modname)
return 1
pymodule, datapath = find_open(modname)
if pymodule is None:
return 0
if modname not in pymodule.__dict__:
retmsg.s = "Python module [{0}] doesn't have class named [{1}]".format(
pymodule.__file__, modname)
return 1
cl = pymodule.__dict__[modname]
if module_type not in cl.module_types:
retmsg.s = "Module [{}] doesn't support type.".format(modname)
return 1
module = cl()
module._cmod = CreatePyModule(user, network, modname, datapath, module, modpython)
module.nv = ModuleNV(module._cmod)
module.SetDescription(cl.description)
module.SetArgs(args)
module.SetModPath(pymodule.__file__)
module.SetType(module_type)
_py_modules.add(module)
if module_type == CModInfo.UserModule:
if not user:
retmsg.s = "Module [{}] is UserModule and needs user.".format(modname)
unload_module(module)
return 1
cont = user
elif module_type == CModInfo.NetworkModule:
if not network:
retmsg.s = "Module [{}] is Network module and needs a network.".format(modname)
unload_module(module)
return 1
cont = network
elif module_type == CModInfo.GlobalModule:
cont = CZNC.Get()
else:
retmsg.s = "Module [{}] doesn't support that module type.".format(modname)
unload_module(module)
return 1
cont.GetModules().append(module._cmod)
try:
loaded = True
if not module.OnLoad(args, retmsg):
if retmsg.s == '':
retmsg.s = 'Module [{0}] aborted.'.format(modname)
else:
retmsg.s = 'Module [{0}] aborted: {1}'.format(modname,
retmsg.s)
loaded = False
except BaseException:
if retmsg.s == '':
retmsg.s = 'Got exception: {0}'.format(traceback.format_exc())
else:
retmsg.s = '{0}; Got exception: {1}'.format(retmsg.s,
traceback.format_exc())
loaded = False
except:
if retmsg.s == '':
retmsg.s = 'Got exception.'
else:
retmsg.s = '{0}; Got exception.'.format(retmsg.s)
loaded = False
if loaded:
if retmsg.s == '':
retmsg.s = "[{0}]".format(pymodule.__file__)
else:
retmsg.s = "[{1}] [{0}]".format(pymodule.__file__,
retmsg.s)
return 2
print(retmsg.s)
unload_module(module)
return 1
def unload_module(module):
if (module not in _py_modules):
return False
module.OnShutdown()
_py_modules.discard(module)
cmod = module._cmod
if module.GetType() == CModInfo.UserModule:
cont = cmod.GetUser()
elif module.GetType() == CModInfo.NetworkModule:
cont = cmod.GetNetwork()
elif module.GetType() == CModInfo.GlobalModule:
cont = CZNC.Get()
cont.GetModules().removeModule(cmod)
del module._cmod
cmod.DeletePyModule()
del cmod
return True
def unload_all():
while len(_py_modules) > 0:
mod = _py_modules.pop()
# add it back to set, otherwise unload_module will be sad
_py_modules.add(mod)
unload_module(mod)
def gather_mod_info(cl, modinfo):
modinfo.SetDescription(cl.description)
modinfo.SetWikiPage(cl.wiki_page)
modinfo.SetDefaultType(cl.module_types[0])
modinfo.SetArgsHelpText(cl.args_help_text);
modinfo.SetHasArgs(cl.has_args);
for module_type in cl.module_types:
modinfo.AddType(module_type)
def get_mod_info(modname, retmsg, modinfo):
'''0-not found, 1-error, 2-success'''
pymodule, datadir = find_open(modname)
if pymodule is None:
return 0
if modname not in pymodule.__dict__:
retmsg.s = "Python module [{0}] doesn't have class named [{1}]".format(
pymodule.__file__, modname)
return 1
cl = pymodule.__dict__[modname]
modinfo.SetName(modname)
modinfo.SetPath(pymodule.__file__)
gather_mod_info(cl, modinfo)
return 2
def get_mod_info_path(path, modname, modinfo):
try:
x = imp.find_module(modname, [path])
except ImportError:
return 0
# x == (<open file './modules/admin.so', mode 'rb' at 0x7fa2dc748d20>,
# './modules/admin.so', ('.so', 'rb', 3))
# x == (<open file './modules/pythontest.py', mode 'U' at 0x7fa2dc748d20>,
# './modules/pythontest.py', ('.py', 'U', 1))
if x[0] is None and x[2][2] != imp.PKG_DIRECTORY:
return 0
try:
pymodule = imp.load_module(modname, *x)
except ImportError:
return 0
finally:
if x[0]:
x[0].close()
if modname not in pymodule.__dict__:
return 0
cl = pymodule.__dict__[modname]
modinfo.SetName(modname)
modinfo.SetPath(pymodule.__file__)
gather_mod_info(cl, modinfo)
return 1
CONTINUE = CModule.CONTINUE
HALT = CModule.HALT
HALTMODS = CModule.HALTMODS
HALTCORE = CModule.HALTCORE
UNLOAD = CModule.UNLOAD
HaveSSL = HaveSSL_()
HaveIPv6 = HaveIPv6_()
HaveCharset = HaveCharset_()
Version = GetVersion()
VersionMajor = GetVersionMajor()
VersionMinor = GetVersionMinor()
VersionExtra = GetVersionExtra()
def CreateWebSubPage(name, title='', params=dict(), admin=False):
vpair = VPair()
for k, v in params.items():
VPair_Add2Str_(vpair, k, v)
flags = 0
if admin:
flags |= CWebSubPage.F_ADMIN
return CreateWebSubPage_(name, title, vpair, flags)
CUser.GetNetworks = CUser.GetNetworks_
CIRCNetwork.GetChans = CIRCNetwork.GetChans_
CChan.GetNicks = CChan.GetNicks_
CZNC.GetUserMap = CZNC.GetUserMap_
def FreeOwnership(func):
"""
Force release of python ownership of user object when adding it to znc
This solves #462
"""
@wraps(func)
def _wrap(self, obj, *args):
# Bypass if first argument is not an SWIG object (like base type str)
if not hasattr(obj, 'thisown'):
return func(self, obj, *args)
# Change ownership of C++ object from SWIG/python to ZNC core if function was successful
if func(self, obj, *args):
# .thisown is magic SWIG's attribute which makes it call C++ "delete" when python's garbage collector deletes python wrapper
obj.thisown = 0
return True
else:
return False
return _wrap
CZNC.AddListener = FreeOwnership(func=CZNC.AddListener)
CZNC.AddUser = FreeOwnership(func=CZNC.AddUser)
CZNC.AddNetworkToQueue = FreeOwnership(func=CZNC.AddNetworkToQueue)
CUser.AddNetwork = FreeOwnership(func=CUser.AddNetwork)
CIRCNetwork.AddChan = FreeOwnership(func=CIRCNetwork.AddChan)
CModule.AddSocket = FreeOwnership(func=CModule.AddSocket)
CModule.AddSubPage = FreeOwnership(func=CModule.AddSubPage)
class ModulesIter(collections.Iterator):
def __init__(self, cmod):
self._cmod = cmod
def __next__(self):
if self._cmod.is_end():
raise StopIteration
module = self._cmod.get()
self._cmod.plusplus()
return module
CModules.__iter__ = lambda cmod: ModulesIter(CModulesIter(cmod))
def str_eq(self, other):
if str(other) == str(self):
return True
return id(self) == id(other)
CChan.__eq__ = str_eq
CNick.__eq__ = str_eq
CUser.__eq__ = str_eq
CIRCNetwork.__eq__ = str_eq
CPyRetString.__eq__ = str_eq
|