aboutsummaryrefslogtreecommitdiffstats
path: root/RepSys/binrepo.py
blob: ad146658ac1ad94b0ff9cdc0d89a49a78e5e0075 (plain)
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
from RepSys import Error, config, mirror, layout
from RepSys.util import execcmd, rellink
from RepSys.svn import SVN

import sys
import os
import string
import stat
import shutil
import re
import tempfile
import hashlib
import urlparse
import threading
from cStringIO import StringIO

DEFAULT_TARBALLS_REPO = "/tarballs"
BINARIES_DIR_NAME = "SOURCES"
BINARIES_CHECKOUT_NAME = "SOURCES-bin"

PROP_USES_BINREPO = "mdv:uses-binrepo"
PROP_BINREPO_REV = "mdv:binrepo-rev"

BINREPOS_SECTION = "binrepos"

SOURCES_FILE = "sha1.lst"

class ChecksumError(Error):
    pass

def svn_baseurl(target):
    svn = SVN()
    info = svn.info2(target)
    if info is None:
        # unversioned resource
        newtarget = os.path.dirname(target)
        info = svn.info2(newtarget)
        assert info is not None, "svn_basedir should not be used with a "\
                "non-versioned directory"
    root = info["Repository Root"]
    url = info["URL"]
    kind = info["Node Kind"]
    path = url[len(root):]
    if kind == "directory":
        return url
    basepath = os.path.dirname(path)
    baseurl = mirror.normalize_path(url + "/" + basepath)
    return baseurl

def svn_root(target):
    svn = SVN()
    info = svn.info2(target)
    if info is None:
        newtarget = os.path.dirname(target)
        info = svn.info2(newtarget)
        assert info is not None
    return info["Repository Root"]

def enabled(url):
    #TODO use information from url to find out whether we have a binrepo
    # available for this url
    use = config.getbool("global", "use-binaries-repository", False)
    return use

def default_repo():
    base = config.get("global", "binaries-repository", None)
    if base is None:
        default_parent = config.get("global", "default_parent", None)
        if default_parent is None:
            raise Error, "no binaries-repository nor default_parent "\
                    "configured"
        comps = urlparse.urlparse(default_parent)
        base = comps[1] + ":" + DEFAULT_TARBALLS_REPO
    return base

def translate_url(url):
    url = mirror.normalize_path(url)
    main = mirror.normalize_path(layout.repository_url())
    subpath = url[len(main)+1:]
    # [binrepos]
    # updates/2009.0 = svn+ssh://svn.mandriva.com/svn/binrepo/20090/
    ## svn+ssh://svn.mandriva.com/svn/packages/2009.0/trafshow/current
    ## would translate to 
    ## svn+ssh://svn.mandriva.com/svn/binrepo/20090/updates/trafshow/current/
    binbase = None
    if BINREPOS_SECTION in config.sections():
        for option, value in config.walk(BINREPOS_SECTION):
            if subpath.startswith(option):
                binbase = value
                break
    binurl = mirror._joinurl(binbase or default_repo(), subpath)
    return binurl

def translate_topdir(path):
    """Returns the URL in the binrepo from a given path inside a SVN
       checkout directory.

    @path: if specified, returns a URL in the binrepo whose path is the
           same as the path inside the main repository.
    """
    baseurl = svn_baseurl(path)
    binurl = translate_url(baseurl)
    target = mirror.normalize_path(binurl)
    return target

def is_binary(path):
    raw = config.get("binrepo", "upload-match",
            "\.(7z|Z|bin|bz2|cpio|db|deb|egg|gem|gz|jar|jisp|lzma|"\
               "pdf|pgn\\.gz|pk3|rpm|rpm|run|sdz|smzip|tar|tbz|"\
               "tbz2|tgz|ttf|uqm|wad|war|xar|xpi|zip)$")
    maxsize = config.getint("binrepo", "upload-match-size", "1048576") # 1MiB
    expr = re.compile(raw)
    name = os.path.basename(path)
    if expr.search(name):
        return True
    st = os.stat(path)
    if st[stat.ST_SIZE] >= maxsize:
        return True
    return False

def find_binaries(paths):
    new = []
    for path in paths:
        if os.path.isdir(path):
            for name in os.listdir(path):
                fpath = os.path.join(path, name)
                if is_binary(fpath):
                    new.append(fpath)
        else:
            if is_binary(path):
                new.append(path)
    return new

def make_symlinks(source, dest):
    todo = []
    tomove = []
    for name in os.listdir(source):
        path = os.path.join(source, name)
        if not os.path.isdir(path) and not name.startswith("."):
            destpath = os.path.join(dest, name)
            linkpath = rellink(path, destpath)
            if os.path.exists(destpath):
                if (os.path.islink(destpath) and
                        os.readlink(destpath) == linkpath):
                    continue
                movepath = destpath + ".repsys-moved"
                if os.path.exists(movepath):
                    raise Error, "cannot create symlink, %s already "\
                            "exists (%s too)" % (destpath, movepath)
                tomove.append((destpath, movepath))
            todo.append((destpath, linkpath))
    for destpath, movepath in tomove:
        os.rename(destpath, movepath)
    for destpath, linkpath in todo:
        os.symlink(linkpath, destpath)

def download(targetdir, pkgdirurl=None, export=False, show=True,
        revision=None, symlinks=True, check=False):
    assert not export or (export and pkgdirurl)
    svn = SVN()
    sourcespath = os.path.join(targetdir, "SOURCES")
    binpath = os.path.join(targetdir, BINARIES_CHECKOUT_NAME)
    if pkgdirurl:
        topurl = translate_url(pkgdirurl)
    else:
        topurl = translate_topdir(targetdir)
    binrev = None
    if revision:
        if pkgdirurl:
            binrev = mapped_revision(pkgdirurl, revision)
        else:
            binrev = mapped_revision(targetdir, revision, wc=True)
    binurl = mirror._joinurl(topurl, BINARIES_DIR_NAME)
    if export:
        svn.export(binurl, binpath, rev=binrev, show=show)
    else:
        svn.checkout(binurl, binpath, rev=binrev, show=show)
    if symlinks:
        make_symlinks(binpath, sourcespath)
    if check:
        check_sources(targetdir)

def import_binaries(topdir, pkgname):
    """Import all binaries from a given package checkout

    (with pending svn adds)

    @topdir: the path to the svn checkout
    """
    svn = SVN()
    topurl = translate_topdir(topdir)
    sourcesdir = os.path.join(topdir, "SOURCES")
    bintopdir = tempfile.mktemp("repsys")
    try:
        svn.checkout(topurl, bintopdir)
        checkout = True
    except Error:
        bintopdir = tempfile.mkdtemp("repsys")
        checkout = False
    try:
        bindir = os.path.join(bintopdir, BINARIES_DIR_NAME)
        if not os.path.exists(bindir):
            if checkout:
                svn.mkdir(bindir)
            else:
                os.mkdir(bindir)
        binaries = find_binaries([sourcesdir])
        update = update_sources_threaded(topdir, added=binaries)
        for path in binaries:
            name = os.path.basename(path)
            binpath = os.path.join(bindir, name)
            os.rename(path, binpath)
            try:
                svn.remove(path)
            except Error:
                # file not tracked
                svn.revert(path)
            if checkout:
                svn.add(binpath)
        log = "imported binaries for %s" % pkgname
        if checkout:
            rev = svn.commit(bindir, log=log)
        else:
            rev = svn.import_(bintopdir, topurl, log=log)
        svn.propset(PROP_USES_BINREPO, "yes", topdir)
        svn.propset(PROP_BINREPO_REV, str(rev), topdir)
        update.join()
        svn.add(sources_path(topdir))
    finally:
        shutil.rmtree(bintopdir)

def create_package_dirs(bintopdir):
    svn = SVN()
    binurl = mirror._joinurl(bintopdir, BINARIES_DIR_NAME)
    silent = config.get("log", "ignore-string", "SILENT")
    message = "%s: created binrepo package structure" % silent
    svn.mkdir(binurl, log=message, parents=True)

def parse_sources(path):
    entries = {}
    f = open(path)
    for rawline in f:
        line = rawline.strip()
        try:
            sum, name = line.split(None, 1)
        except ValueError:
            # failed to unpack, line format error
            raise Error, "invalid line in sources file: %s" % rawline
        entries[name] = sum
    return entries

def check_hash(path, sum):
    newsum = file_hash(path)
    if newsum != sum:
        raise ChecksumError, "different checksums for %s: expected %s, "\
                "but %s was found" % (path, sum, newsum)

def check_sources(topdir):
    spath = sources_path(topdir)
    if not os.path.exists(spath):
        raise Error, "'%s' was not found" % spath
    entries = parse_sources(spath)
    for name, sum in entries.iteritems():
        fpath = os.path.join(topdir, "SOURCES", name)
        check_hash(fpath, sum)

def file_hash(path):
    sum = hashlib.sha1()
    f = open(path)
    while True:
        block = f.read(4096)
        if not block:
            break
        sum.update(block)
    f.close()
    return sum.hexdigest()

def sources_path(topdir):
    path = os.path.join(topdir, "SOURCES", SOURCES_FILE)
    return path

def update_sources(topdir, added=[], removed=[]):
    path = sources_path(topdir)
    entries = {}
    if os.path.isfile(path):
        entries = parse_sources(path)
    f = open(path, "w") # open before calculating hashes
    for name in removed:
        entries.pop(removed)
    for added_path in added:
        name = os.path.basename(added_path)
        entries[name] = file_hash(added_path)
    for name in sorted(entries):
        f.write("%s  %s\n" % (entries[name], name))
    f.close()

def update_sources_threaded(*args, **kwargs):
    t = threading.Thread(target=update_sources, args=args, kwargs=kwargs)
    t.start()
    t.join()
    return t

def upload(path, message=None):
    from RepSys.rpmutil import getpkgtopdir
    svn = SVN()
    if not os.path.exists(path):
        raise Error, "not found: %s" % path
    # XXX check if the path is under SOURCES/
    paths = find_binaries([path])
    if not paths:
        raise Error, "'%s' does not seem to have any tarballs" % path
    topdir = getpkgtopdir()
    bintopdir = translate_topdir(topdir)
    binurl = mirror._joinurl(bintopdir, BINARIES_DIR_NAME)
    sourcesdir = os.path.join(topdir, "SOURCES")
    bindir = os.path.join(topdir, BINARIES_CHECKOUT_NAME)
    silent = config.get("log", "ignore-string", "SILENT")
    if not os.path.exists(bindir):
        try:
            download(topdir, show=False)
        except Error:
            # possibly the package does not exist
            # (TODO check whether it is really a 'path not found' error)
            pass
        if not os.path.exists(bindir):
            create_package_dirs(bintopdir)
            svn.propset(PROP_USES_BINREPO, "yes", topdir)
            svn.commit(topdir, log="%s: created binrepo structure" % silent)
            download(topdir, show=False)
    for path in paths:
        if svn.info2(path):
            sys.stderr.write("'%s' is already tracked by svn, ignoring\n" %
                    path)
            continue
        name = os.path.basename(path)
        binpath = os.path.join(bindir, name)
        os.rename(path, binpath)
        svn.add(binpath)
    if not message:
        message = "%s: new binary files %s" % (silent, " ".join(paths))
    make_symlinks(bindir, sourcesdir)
    update = update_sources_threaded(topdir, added=paths)
    rev = svn.commit(binpath, log=message)
    svn.propset(PROP_BINREPO_REV, str(rev), topdir)
    sources = sources_path(topdir)
    svn.add(sources)
    update.join()
    svn.commit(topdir + " " + sources, log=message, nonrecursive=True)

def mapped_revision(target, revision, wc=False):
    """Maps a txtrepo revision to a binrepo datespec

    This datespec can is intended to be used by svn .. -r DATE.

    @target: a working copy path or a URL
    @revision: if target is a URL, the revision number used when fetching
         svn info
    @wc: if True indicates that 'target' must be interpreted as a
         the path of a svn working copy, otherwise it is handled as a URL
    """
    svn = SVN()
    binrev = None
    if wc:
        spath = sources_path(target)
        if os.path.exists(spath):
            infolines = svn.info(spath, xml=True)
            if infolines:
                rawinfo = "".join(infolines) # arg!
                found = re.search("<date>(.*?)</date>", rawinfo).groups()
                date = found[0]
            else:
                raise Error, "bogus 'svn info' for '%s'" % spath
        else:
            raise Error, "'%s' was not found" % spath
    else:
        url = mirror._joinurl(target, sources_path(""))
        date = svn.propget("svn:date", url, rev=revision, revprop=True)
        if not date:
            raise Error, "no valid date available for '%s'" % url
    binrev = "{%s}" % date
    return binrev

def markrelease(sourceurl, releasesurl, version, release, revision):
    svn = SVN()
    binrev = mapped_revision(sourceurl, revision)
    binsource = translate_url(sourceurl)
    binreleases = translate_url(releasesurl)
    versiondir = mirror._joinurl(binreleases, version)
    dest = mirror._joinurl(versiondir, release)
    svn.mkdir(binreleases, noerror=1, log="created directory for releases")
    svn.mkdir(versiondir, noerror=1, log="created directory for version %s" % version)
    svn.copy(binsource, dest, rev=binrev,
            log="%%markrelease ver=%s rel=%s rev=%s binrev=%s" % (version, release,
                revision, binrev))
lass="hl opt">}, { "kdebug", o_int, &kdebugflag, "Set kernel driver debug level", OPT_PRIO }, { "nodetach", o_bool, &nodetach, "Don't detach from controlling tty", OPT_PRIO | 1 }, { "-detach", o_bool, &nodetach, "Don't detach from controlling tty", OPT_ALIAS | OPT_PRIOSUB | 1 }, { "updetach", o_bool, &updetach, "Detach from controlling tty once link is up", OPT_PRIOSUB | OPT_A2CLR | 1, &nodetach }, { "holdoff", o_int, &holdoff, "Set time in seconds before retrying connection", OPT_PRIO }, { "idle", o_int, &idle_time_limit, "Set time in seconds before disconnecting idle link", OPT_PRIO }, { "maxconnect", o_int, &maxconnect, "Set connection time limit", OPT_PRIO | OPT_LLIMIT | OPT_NOINCR | OPT_ZEROINF }, { "domain", o_special, (void *)setdomain, "Add given domain name to hostname", OPT_PRIO | OPT_PRIV | OPT_A2STRVAL, &domain }, { "file", o_special, (void *)readfile, "Take options from a file", OPT_NOPRINT }, { "call", o_special, (void *)callfile, "Take options from a privileged file", OPT_NOPRINT }, { "persist", o_bool, &persist, "Keep on reopening connection after close", OPT_PRIO | 1 }, { "nopersist", o_bool, &persist, "Turn off persist option", OPT_PRIOSUB }, { "demand", o_bool, &demand, "Dial on demand", OPT_INITONLY | 1, &persist }, { "--version", o_special_noarg, (void *)showversion, "Show version number" }, { "--help", o_special_noarg, (void *)showhelp, "Show brief listing of options" }, { "-h", o_special_noarg, (void *)showhelp, "Show brief listing of options", OPT_ALIAS }, { "logfile", o_special, (void *)setlogfile, "Append log messages to this file", OPT_PRIO | OPT_A2STRVAL | OPT_STATIC, &logfile_name }, { "logfd", o_int, &log_to_fd, "Send log messages to this file descriptor", OPT_PRIOSUB | OPT_A2CLR, &log_default }, { "nolog", o_int, &log_to_fd, "Don't send log messages to any file", OPT_PRIOSUB | OPT_NOARG | OPT_VAL(-1) }, { "nologfd", o_int, &log_to_fd, "Don't send log messages to any file descriptor", OPT_PRIOSUB | OPT_ALIAS | OPT_NOARG | OPT_VAL(-1) }, { "linkname", o_string, linkname, "Set logical name for link", OPT_PRIO | OPT_PRIV | OPT_STATIC, NULL, MAXPATHLEN }, { "maxfail", o_int, &maxfail, "Maximum number of unsuccessful connection attempts to allow", OPT_PRIO }, { "ktune", o_bool, &tune_kernel, "Alter kernel settings as necessary", OPT_PRIO | 1 }, { "noktune", o_bool, &tune_kernel, "Don't alter kernel settings", OPT_PRIOSUB }, { "connect-delay", o_int, &connect_delay, "Maximum time (in ms) to wait after connect script finishes", OPT_PRIO }, { "unit", o_int, &req_unit, "PPP interface unit number to use if possible", OPT_PRIO | OPT_LLIMIT, 0, 0 }, { "dump", o_bool, &dump_options, "Print out option values after parsing all options", 1 }, { "dryrun", o_bool, &dryrun, "Stop after parsing, printing, and checking options", 1 }, #ifdef HAVE_MULTILINK { "multilink", o_bool, &multilink, "Enable multilink operation", OPT_PRIO | 1 }, { "mp", o_bool, &multilink, "Enable multilink operation", OPT_PRIOSUB | OPT_ALIAS | 1 }, { "nomultilink", o_bool, &multilink, "Disable multilink operation", OPT_PRIOSUB | 0 }, { "nomp", o_bool, &multilink, "Disable multilink operation", OPT_PRIOSUB | OPT_ALIAS | 0 }, { "bundle", o_string, &bundle_name, "Bundle name for multilink", OPT_PRIO }, #endif /* HAVE_MULTILINK */ #ifdef PLUGIN { "plugin", o_special, (void *)loadplugin, "Load a plug-in module into pppd", OPT_PRIV | OPT_A2LIST }, #endif #ifdef PPP_FILTER { "pdebug", o_int, &dflag, "libpcap debugging", OPT_PRIO }, { "pass-filter", 1, setpassfilter, "set filter for packets to pass", OPT_PRIO }, { "active-filter", 1, setactivefilter, "set filter for active pkts", OPT_PRIO }, #endif { NULL } }; #ifndef IMPLEMENTATION #define IMPLEMENTATION "" #endif static char *usage_string = "\ pppd version %s\n\ Usage: %s [ options ], where options are:\n\ <device> Communicate over the named device\n\ <speed> Set the baud rate to <speed>\n\ <loc>:<rem> Set the local and/or remote interface IP\n\ addresses. Either one may be omitted.\n\ asyncmap <n> Set the desired async map to hex <n>\n\ auth Require authentication from peer\n\ connect <p> Invoke shell command <p> to set up the serial line\n\ crtscts Use hardware RTS/CTS flow control\n\ defaultroute Add default route through interface\n\ file <f> Take options from file <f>\n\ modem Use modem control lines\n\ mru <n> Set MRU value to <n> for negotiation\n\ See pppd(8) for more options.\n\ "; /* * parse_args - parse a string of arguments from the command line. */ int parse_args(argc, argv) int argc; char **argv; { char *arg; option_t *opt; int n; privileged_option = privileged; option_source = "command line"; option_priority = OPRIO_CMDLINE; while (argc > 0) { arg = *argv++; --argc; opt = find_option(arg); if (opt == NULL) { option_error("unrecognized option '%s'", arg); usage(); return 0; } n = n_arguments(opt); if (argc < n) { option_error("too few parameters for option %s", arg); return 0; } if (!process_option(opt, arg, argv)) return 0; argc -= n; argv += n; } return 1; } /* * options_from_file - Read a string of options from a file, * and interpret them. */ int options_from_file(filename, must_exist, check_prot, priv) char *filename; int must_exist; int check_prot; int priv; { FILE *f; int i, newline, ret, err; option_t *opt; int oldpriv, n; char *oldsource; char *argv[MAXARGS]; char args[MAXARGS][MAXWORDLEN]; char cmd[MAXWORDLEN]; if (check_prot) seteuid(getuid()); f = fopen(filename, "r"); err = errno; if (check_prot) seteuid(0); if (f == NULL) { errno = err; if (!must_exist) { if (err != ENOENT && err != ENOTDIR) warn("Warning: can't open options file %s: %m", filename); return 1; } option_error("Can't open options file %s: %m", filename); return 0; } oldpriv = privileged_option; privileged_option = priv; oldsource = option_source; option_source = strdup(filename); if (option_source == NULL) option_source = "file"; ret = 0; while (getword(f, cmd, &newline, filename)) { opt = find_option(cmd); if (opt == NULL) { option_error("In file %s: unrecognized option '%s'", filename, cmd); goto err; } n = n_arguments(opt); for (i = 0; i < n; ++i) { if (!getword(f, args[i], &newline, filename)) { option_error( "In file %s: too few parameters for option '%s'", filename, cmd); goto err; } argv[i] = args[i]; } if (!process_option(opt, cmd, argv)) goto err; } ret = 1; err: fclose(f); privileged_option = oldpriv; option_source = oldsource; return ret; } /* * options_from_user - See if the use has a ~/.ppprc file, * and if so, interpret options from it. */ int options_from_user() { char *user, *path, *file; int ret; struct passwd *pw; size_t pl; pw = getpwuid(getuid()); if (pw == NULL || (user = pw->pw_dir) == NULL || user[0] == 0) return 1; file = _PATH_USEROPT; pl = strlen(user) + strlen(file) + 2; path = malloc(pl); if (path == NULL) novm("init file name"); slprintf(path, pl, "%s/%s", user, file); option_priority = OPRIO_CFGFILE; ret = options_from_file(path, 0, 1, privileged); free(path); return ret; } /* * options_for_tty - See if an options file exists for the serial * device, and if so, interpret options from it. * We only allow the per-tty options file to override anything from * the command line if it is something that the user can't override * once it has been set by root; this is done by giving configuration * files a lower priority than the command line. */ int options_for_tty() { char *dev, *path, *p; int ret; size_t pl; dev = devnam; if (strncmp(dev, "/dev/", 5) == 0) dev += 5; if (dev[0] == 0 || strcmp(dev, "tty") == 0) return 1; /* don't look for /etc/ppp/options.tty */ pl = strlen(_PATH_TTYOPT) + strlen(dev) + 1; path = malloc(pl); if (path == NULL) novm("tty init file name"); slprintf(path, pl, "%s%s", _PATH_TTYOPT, dev); /* Turn slashes into dots, for Solaris case (e.g. /dev/term/a) */ for (p = path + strlen(_PATH_TTYOPT); *p != 0; ++p) if (*p == '/') *p = '.'; option_priority = OPRIO_CFGFILE; ret = options_from_file(path, 0, 0, 1); free(path); return ret; } /* * options_from_list - process a string of options in a wordlist. */ int options_from_list(w, priv) struct wordlist *w; int priv; { char *argv[MAXARGS]; option_t *opt; int i, n, ret = 0; struct wordlist *w0; privileged_option = priv; option_source = "secrets file"; option_priority = OPRIO_SECFILE; while (w != NULL) { opt = find_option(w->word); if (opt == NULL) { option_error("In secrets file: unrecognized option '%s'", w->word); goto err; } n = n_arguments(opt); w0 = w; for (i = 0; i < n; ++i) { w = w->next; if (w == NULL) { option_error( "In secrets file: too few parameters for option '%s'", w0->word); goto err; } argv[i] = w->word; } if (!process_option(opt, w0->word, argv)) goto err; w = w->next; } ret = 1; err: return ret; } /* * match_option - see if this option matches an option_t structure. */ static int match_option(name, opt, dowild) char *name; option_t *opt; int dowild; { int (*match) __P((char *, char **, int)); if (dowild != (opt->type == o_wild)) return 0; if (!dowild) return strcmp(name, opt->name) == 0; match = (int (*) __P((char *, char **, int))) opt->addr; return (*match)(name, NULL, 0); } /* * find_option - scan the option lists for the various protocols * looking for an entry with the given name. * This could be optimized by using a hash table. */ static option_t * find_option(name) const char *name; { option_t *opt; struct option_list *list; int i, dowild; for (dowild = 0; dowild <= 1; ++dowild) { for (opt = general_options; opt->name != NULL; ++opt) if (match_option(name, opt, dowild)) return opt; for (opt = auth_options; opt->name != NULL; ++opt) if (match_option(name, opt, dowild)) return opt; for (list = extra_options; list != NULL; list = list->next) for (opt = list->options; opt->name != NULL; ++opt) if (match_option(name, opt, dowild)) return opt; for (opt = the_channel->options; opt->name != NULL; ++opt) if (match_option(name, opt, dowild)) return opt; for (i = 0; protocols[i] != NULL; ++i) if ((opt = protocols[i]->options) != NULL) for (; opt->name != NULL; ++opt) if (match_option(name, opt, dowild)) return opt; } return NULL; } /* * process_option - process one new-style option. */ static int process_option(opt, cmd, argv) option_t *opt; char *cmd; char **argv; { u_int32_t v; int iv, a; char *sv; int (*parser) __P((char **)); int (*wildp) __P((char *, char **, int)); char *optopt = (opt->type == o_wild)? "": " option"; int prio = option_priority; option_t *mainopt = opt; if ((opt->flags & OPT_PRIVFIX) && privileged_option) prio += OPRIO_ROOT; while (mainopt->flags & OPT_PRIOSUB) --mainopt; if (mainopt->flags & OPT_PRIO) { if (prio < mainopt->priority) { /* new value doesn't override old */ if (prio == OPRIO_CMDLINE && mainopt->priority > OPRIO_ROOT) { option_error("%s%s set in %s cannot be overridden\n", opt->name, optopt, mainopt->source); return 0; } return 1; } if (prio > OPRIO_ROOT && mainopt->priority == OPRIO_CMDLINE) warn("%s%s from %s overrides command line", opt->name, optopt, option_source); } if ((opt->flags & OPT_INITONLY) && phase != PHASE_INITIALIZE) { option_error("%s%s cannot be changed after initialization", opt->name, optopt); return 0; } if ((opt->flags & OPT_PRIV) && !privileged_option) { option_error("using the %s%s requires root privilege", opt->name, optopt); return 0; } if ((opt->flags & OPT_ENABLE) && *(bool *)(opt->addr2) == 0) { option_error("%s%s is disabled", opt->name, optopt); return 0; } if ((opt->flags & OPT_DEVEQUIV) && devnam_fixed) { option_error("the %s%s may not be changed in %s", opt->name, optopt, option_source); return 0; } switch (opt->type) { case o_bool: v = opt->flags & OPT_VALUE; *(bool *)(opt->addr) = v; if (opt->addr2 && (opt->flags & OPT_A2COPY)) *(bool *)(opt->addr2) = v; break; case o_int: iv = 0; if ((opt->flags & OPT_NOARG) == 0) { if (!int_option(*argv, &iv)) return 0; if ((((opt->flags & OPT_LLIMIT) && iv < opt->lower_limit) || ((opt->flags & OPT_ULIMIT) && iv > opt->upper_limit)) && !((opt->flags & OPT_ZEROOK && iv == 0))) { char *zok = (opt->flags & OPT_ZEROOK)? " zero or": ""; switch (opt->flags & OPT_LIMITS) { case OPT_LLIMIT: option_error("%s value must be%s >= %d", opt->name, zok, opt->lower_limit); break; case OPT_ULIMIT: option_error("%s value must be%s <= %d", opt->name, zok, opt->upper_limit); break; case OPT_LIMITS: option_error("%s value must be%s between %d and %d", opt->name, opt->lower_limit, opt->upper_limit); break; } return 0; } } a = opt->flags & OPT_VALUE; if (a >= 128) a -= 256; /* sign extend */ iv += a; if (opt->flags & OPT_INC) iv += *(int *)(opt->addr); if ((opt->flags & OPT_NOINCR) && !privileged_option) { int oldv = *(int *)(opt->addr); if ((opt->flags & OPT_ZEROINF) ? (oldv != 0 && (iv == 0 || iv > oldv)) : (iv > oldv)) { option_error("%s value cannot be increased", opt->name); return 0; } } *(int *)(opt->addr) = iv; if (opt->addr2 && (opt->flags & OPT_A2COPY)) *(int *)(opt->addr2) = iv; break; case o_uint32: if (opt->flags & OPT_NOARG) { v = opt->flags & OPT_VALUE; if (v & 0x80) v |= 0xffffff00U; } else if (!number_option(*argv, &v, 16)) return 0; if (opt->flags & OPT_OR) v |= *(u_int32_t *)(opt->addr); *(u_int32_t *)(opt->addr) = v; if (opt->addr2 && (opt->flags & OPT_A2COPY)) *(u_int32_t *)(opt->addr2) = v; break; case o_string: if (opt->flags & OPT_STATIC) { strlcpy((char *)(opt->addr), *argv, opt->upper_limit); } else { sv = strdup(*argv); if (sv == NULL) novm("option argument"); *(char **)(opt->addr) = sv; } break; case o_special_noarg: case o_special: parser = (int (*) __P((char **))) opt->addr; if (!(*parser)(argv)) return 0; if (opt->flags & OPT_A2LIST) { struct option_value *ovp, **pp; ovp = malloc(sizeof(*ovp) + strlen(*argv)); if (ovp != 0) { strcpy(ovp->value, *argv); ovp->source = option_source; ovp->next = NULL; pp = (struct option_value **) &opt->addr2; while (*pp != 0) pp = &(*pp)->next; *pp = ovp; } } break; case o_wild: wildp = (int (*) __P((char *, char **, int))) opt->addr; if (!(*wildp)(cmd, argv, 1)) return 0; break; } if (opt->addr2 && (opt->flags & (OPT_A2COPY|OPT_ENABLE |OPT_A2PRINTER|OPT_A2STRVAL|OPT_A2LIST)) == 0) *(bool *)(opt->addr2) = !(opt->flags & OPT_A2CLR); mainopt->source = option_source; mainopt->priority = prio; mainopt->winner = opt - mainopt; return 1; } /* * override_value - if the option priorities would permit us to * override the value of option, return 1 and update the priority * and source of the option value. Otherwise returns 0. */ int override_value(option, priority, source) const char *option; int priority; const char *source; { option_t *opt; opt = find_option(option); if (opt == NULL) return 0; while (opt->flags & OPT_PRIOSUB) --opt; if ((opt->flags & OPT_PRIO) && priority < opt->priority) return 0; opt->priority = priority; opt->source = source; opt->winner = -1; return 1; } /* * n_arguments - tell how many arguments an option takes */ static int n_arguments(opt) option_t *opt; { return (opt->type == o_bool || opt->type == o_special_noarg || (opt->flags & OPT_NOARG))? 0: 1; } /* * add_options - add a list of options to the set we grok. */ void add_options(opt) option_t *opt; { struct option_list *list; list = malloc(sizeof(*list)); if (list == 0) novm("option list entry"); list->options = opt; list->next = extra_options; extra_options = list; } /* * check_options - check that options are valid and consistent. */ void check_options() { if (logfile_fd >= 0 && logfile_fd != log_to_fd) close(logfile_fd); } /* * print_option - print out an option and its value */ static void print_option(opt, mainopt, printer, arg) option_t *opt, *mainopt; void (*printer) __P((void *, char *, ...)); void *arg; { int i, v; char *p; if (opt->flags & OPT_NOPRINT) return; switch (opt->type) { case o_bool: v = opt->flags & OPT_VALUE; if (*(bool *)opt->addr != v) /* this can happen legitimately, e.g. lock option turned off for default device */ break; printer(arg, "%s", opt->name); break; case o_int: v = opt->flags & OPT_VALUE; if (v >= 128) v -= 256; i = *(int *)opt->addr; if (opt->flags & OPT_NOARG) { printer(arg, "%s", opt->name); if (i != v) { if (opt->flags & OPT_INC) { for (; i > v; i -= v) printer(arg, " %s", opt->name); } else printer(arg, " # oops: %d not %d\n", i, v); } } else { printer(arg, "%s %d", opt->name, i); } break; case o_uint32: printer(arg, "%s", opt->name); if ((opt->flags & OPT_NOARG) == 0) printer(arg, " %x", *(u_int32_t *)opt->addr); break; case o_string: if (opt->flags & OPT_HIDE) { p = "??????"; } else { p = (char *) opt->addr; if ((opt->flags & OPT_STATIC) == 0) p = *(char **)p; } printer(arg, "%s %q", opt->name, p); break; case o_special: case o_special_noarg: case o_wild: if (opt->type != o_wild) { printer(arg, "%s", opt->name); if (n_arguments(opt) == 0) break; printer(arg, " "); }