Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 392 lines (320 sloc) 9.691 kb
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
# -*- coding: utf-8 -*-
#
# Cherokee-admin
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2001-2010 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#

import os
import sys
import glob
import socket
import subprocess

import CTK


#
# Deal with os.popen and subprocess issues in Python 2.4
#
def run (command, stdout=True, stderr=False, retcode=False):
    returns = 0

    args = {'shell': True, 'close_fds': True}
    if stdout:
        args['stdout'] = subprocess.PIPE
        returns += 1
    if stderr:
        args['stderr'] = subprocess.PIPE
        returns += 1
    if retcode:
        returns += 1

    p = subprocess.Popen (command, **args)

    if stdout:
        stdout_output = p.stdout.read()
    if stderr:
        stderr_output = p.stderr.read()

    if stdout:
        p.stdout.close()
    if stderr:
        p.stderr.close()

    ret = p.poll()

    if returns > 1:
        d = {}
        if stdout:
            d['stdout'] = stdout_output
        if stderr:
            d['stderr'] = stderr_output
        if retcode:
            d['retcode'] = ret
        return d

    if stdout:
        return stdout_output
    elif stderr:
        return stderr_output
    elif retcode:
        return ret

    assert False, "Should not happened"


#
# Strings
#
def bool_to_active (b):
    return (_('Inactive'), _('Active'))[bool(b)]

def bool_to_onoff (b):
    return (_('Off'), _('On'))[bool(b)]

def bool_to_yesno (b):
    return (_('No'), _('Yes'))[bool(b)]

def trans_options (options):
    """Translate the options with gettext"""
    return [(x[0], _(x[1])) for x in options]


#
# Virtual Server
#

def cfg_vsrv_get_next():
    """ Get the prefix of the next vserver """
    tmp = [int(x) for x in CTK.cfg.keys("vserver")]
    tmp.sort()
    next = str(tmp[-1] + 10)
    return "vserver!%s" % (next)

def cfg_vsrv_rule_get_next (pre):
    """ Get the prefix of the next rule of a vserver """
    tmp = [int(x) for x in CTK.cfg.keys("%s!rule"%(pre))]
    tmp.sort()
    if tmp:
        next = tmp[-1] + 100
    else:
        next = 100
    return (next, "%s!rule!%d" % (pre, next))

def cfg_vsrv_rule_find_extension (pre, extension):
    """Find an extension rule in a virtual server """
    for r in CTK.cfg.keys("%s!rule"%(pre)):
        p = "%s!rule!%s" % (pre, r)
        if CTK.cfg.get_val ("%s!match"%(p)) == "extensions":
            if extension in CTK.cfg.get_val ("%s!match!extensions"%(p)):
                return p

def cfg_vsrv_rule_find_regexp (pre, regexp):
    """Find a regular expresion rule in a virtual server """
    for r in CTK.cfg.keys("%s!rule"%(pre)):
        p = "%s!rule!%s" % (pre, r)
        if CTK.cfg.get_val ("%s!match"%(p)) == "request":
            if regexp == CTK.cfg.get_val ("%s!match!request"%(p)):
                return p

#
# Information Sources
#

def cfg_source_get_next ():
    tmp = [int(x) for x in CTK.cfg.keys("source")]
    if not tmp:
        return (1, "source!1")
    tmp.sort()
    next = tmp[-1] + 10
    return (next, "source!%d" % (next))

def cfg_source_find_interpreter (in_interpreter = None,
                                 in_nick = None):
    for i in CTK.cfg.keys("source"):
        if CTK.cfg.get_val("source!%s!type"%(i)) != 'interpreter':
            continue

        if (in_interpreter and
            in_interpreter in CTK.cfg.get_val("source!%s!interpreter"%(i))):
            return "source!%s" % (i)

        if (in_nick and
            in_nick in CTK.cfg.get_val("source!%s!nick"%(i))):
            return "source!%s" % (i)

def cfg_source_find_empty_port (n_ports=1):
    ports = []
    for i in CTK.cfg.keys("source"):
        host = CTK.cfg.get_val ("source!%s!host"%(i))
        if not host: continue

        colon = host.rfind(':')
        if colon < 0: continue

        port = int (host[colon+1:])
        if port < 1024: continue

        ports.append (port)

    pport = 1025
    while pport+n_ports < 65535:
        pports = range(pport, pport + n_ports)
        for x in pports:
            if x in ports:
                pport += 1
                break
            return pport

    assert (False)

def cfg_source_find_free_port (host_name='localhost'):
    """Return a port not currently running anything"""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((host_name, 0))
    addr, port = s.getsockname()
    s.close()
    return port

def cfg_source_get_localhost_addr ():
    x, x, addrs = socket.gethostbyname_ex('localhost')
    if addrs:
        return addrs[0]
    return None

def cfg_get_surrounding_repls (macro, value, n_minus=9, n_plus=9):
    replacements = {}

    tmp = value.split('!')
    pre = '!'.join(tmp[:-1])
    num = int(tmp[-1])

    for n in range(n_minus):
        replacements['%s_minus%d'%(macro,n+1)] = '%s!%d' %(pre, num-(n+1))

    for n in range(n_plus):
        replacements['%s_plus%d'%(macro,n+1)] = '%s!%d' %(pre, num+(n+1))

    return replacements

#
# Version strings management
#

def version_to_int (v):
    num = 0
    tmp = v.split('.')

    if len(tmp) >= 3:
        num += int(tmp[2]) * (10**3)
    if len(tmp) >= 2:
        num += int(tmp[1]) * (10**6)
    if len(tmp) >= 1:
        num += int(tmp[0]) * (10**9)

    return num

def version_cmp (x, y):
    xp = x.split('b')
    yp = y.split('b')

    if len(xp) > 1:
        x_ver = version_to_int(xp[0])
        x_beta = xp[1]
    else:
        x_ver = version_to_int(xp[0])
        x_beta = None

    if len(yp) > 1:
        y_ver = version_to_int(yp[0])
        y_beta = yp[1]
    else:
        y_ver = version_to_int(yp[0])
        y_beta = None

    if x_ver == y_ver:
        if not x_beta and not y_beta: return 0
        if not y_beta: return -1
        if not x_beta: return 1
        return cmp(int(x_beta),int(y_beta))

    elif x_ver > y_ver:
        return 1

    return -1


#
# Paths
#

def path_find_binary (executable, extra_dirs=[], custom_test=None):
    """Find an executable.
It checks 'extra_dirs' and the PATH.
The 'executable' parameter can be either a string or a list.
"""

    assert (type(executable) in [str, list])

    # Extra dirs evaluation
    dirs = []
    for d in extra_dirs:
        if '*' in d or '?' in d:
            dirs += glob.glob (d)
        else:
            dirs.append(d)

    # $PATH
    env_path = os.getenv("PATH")
    if env_path:
        dirs += filter (lambda x: x, env_path.split(":"))

    # Check
    if type(executable) != list:
        executable = [executable]

    for exe in executable:
        for dir in dirs:
            fp = os.path.join (dir, exe)
            if os.path.exists (fp):
                if custom_test:
                    if not custom_test(fp):
                        continue
                return fp

def path_find_w_default (path_list, default=''):
    """Find a path.
It checks a list of paths (that can contain wildcards),
if none exists default is returned.
"""
    for path in path_list:
        if '*' in path or '?' in path:
            to_check = glob.glob (path)
        else:
            to_check = [path]
        for p in to_check:
            if os.path.exists (p):
                return p
    return default

def path_eval_exist (path_list):
    """Evaluate a list of potential paths.
Returns the paths that actually exist.
"""
    exist = []
    for path in path_list:
        if '*' in path or '?' in path:
            to_check = glob.glob (path)
        else:
            to_check = [path]
        for p in to_check:
            if os.path.exists (p):
                exist.append (p)
    return exist



#
# OS
#
def os_get_document_root():
    if sys.platform == 'darwin':
        return "/Library/WebServer/Documents"
    elif sys.platform == 'linux2':
        if os.path.exists ("/etc/redhat-release"):
            return '/var/www'
        elif os.path.exists ("/etc/fedora-release"):
            return '/var/www'
        elif os.path.exists ("/etc/SuSE-release"):
            return '/srv/www/htdocs'
        elif os.path.exists ("/etc/debian_version"):
            return '/var/www'
        elif os.path.exists ("/etc/gentoo-release"):
            return '/var/www'
        elif os.path.exists ("/etc/slackware-version"):
            return '/var/www'
        return '/var/www'

    return ''


#
# Misc
#
def split_list (value):
    ids = []
    for t1 in value.split(','):
        for t2 in t1.split(' '):
            id = t2.strip()
            if not id:
                continue
            ids.append(id)
    return ids


def lists_differ (a, b):
    """Compare lists disregarding order"""
    if len(a) != len(b):
        return True
    if bool (set(a)-set(b)):
        return True
    if bool (set(b)-set(a)):
        return True
    return False


def get_real_path (name, nochroot=False):
    """Get real path accounting for chrooted environments"""
    chroot = CTK.cfg.get_val('server!chroot')
    if chroot and not nochroot:
        fullname = os.path.normpath (chroot + os.path.sep + name)
    else:
        fullname = name

    return fullname
Something went wrong with that request. Please try again.