<commit_before>#!/usr/bin/env python

##
# Copyright (c) 2006-2009 Apple Inc. All rights reserved.
#
# 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.
##

import sys
import os
import itertools
import operator
from getopt import getopt, GetoptError
from uuid import UUID
from pwd import getpwnam
from grp import getgrnam


from twisted.python import log
from twisted.python.reflect import namedClass
from twisted.python.util import switchUID
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.address import IPv4Address
from twisted.internet.defer import inlineCallbacks, returnValue, succeed
from twisted.web2.dav import davxml

from twext.web2.dav.davxml import sname2qname, qname2sname

from twistedcaldav import caldavxml
from twistedcaldav import memcachepool
from twistedcaldav.config import config, defaultConfigFile, ConfigurationError
from twistedcaldav.customxml import calendarserver_namespace
from twistedcaldav.directory.directory import DirectoryService, DirectoryRecord
from twistedcaldav.directory.principal import DirectoryPrincipalProvisioningResource
from twistedcaldav.log import setLogLevelForNamespace
from twistedcaldav.notify import installNotificationClient
from twistedcaldav.static import CalendarHomeProvisioningFile

from calendarserver.tools.util import UsageError, booleanArgument, autoDisableMemcached
from calendarserver.tools.util import loadConfig, getDirectory, dummyDirectoryRecord
from calendarserver.provision.root import RootResource

def usage(e=None):
    if e:
        print e
        print ""

    name = os.path.basename(sys.argv[0])
    print "usage: %s [options] actions principal [principal ...]" % (name,)
    print ""
    print "  Performs the given actions against the giving principals."
    print ""
    print "  Principals are identified by one of the following:"
    print "    Type and shortname (eg.: users:wsanchez)"
   #print "    A principal path (eg.: /principals/users/wsanchez/)"
    print "    A GUID (eg.: E415DBA7-40B5-49F5-A7CC-ACC81E4DEC79)"
    print ""
    print "options:"
    print "  -h --help: print this help and exit"
    print "  -f --config <path>: Specify caldavd.plist configuration path"
    print ""
    print "actions:"
   #print "  --search <search-string>: search for matching resources"
    print "  -P, --read-property=property: read DAV property (eg.: {DAV:}group-member-set)"
    print "  --list-read-proxies: list proxies with read-only access"
    print "  --list-write-proxies: list proxies with read-write access"
    print "  --list-proxies: list all proxies"
    print "  --add-read-proxy=principal: add a read-only proxy"
    print "  --add-write-proxy=principal: add a read-write proxy"
    print "  --remove-proxy=principal: remove a proxy"
    print "  --set-auto-schedule={true|false}: set auto-accept state"
    print "  --get-auto-schedule: read auto-schedule state"

    if e:
        sys.exit(64)
    else:
        sys.exit(0)

def main():

    #
    # Send logging output to stdout
    #
    logFileName = "/dev/stdout"
    observer = log.FileLogObserver(open(logFileName, "a"))
    log.addObserver(observer.emit)



    try:
        (optargs, args) = getopt(
            sys.argv[1:], "hf:P:", [
                "help",
                "config=",
               #"search=",
                "read-property=",
                "list-read-proxies",
                "list-write-proxies",
                "list-proxies",
                "add-read-proxy=",
                "add-write-proxy=",
                "remove-proxy=",
                "set-auto-schedule=",
                "get-auto-schedule",
            ],
        )
    except GetoptError, e:
        usage(e)

    #
    # Get configuration
    #
    configFileName = None
    actions = []

    for opt, arg in optargs:
        if opt in ("-h", "--help"):
            usage()

        elif opt in ("-f", "--config"):
            configFileName = arg

        elif opt in ("-P", "--read-property"):
            try:
                qname = sname2qname(arg)
            except ValueError, e:
                abort(e)
            actions.append((action_readProperty, qname))

        elif opt in ("", "--list-read-proxies"):
            actions.append((action_listProxies, "read"))

        elif opt in ("", "--list-write-proxies"):
            actions.append((action_listProxies, "write"))

        elif opt in ("-L", "--list-proxies"):
            actions.append((action_listProxies, "read", "write"))

        elif opt in ("--add-read-proxy", "--add-write-proxy"):
            if "read" in opt:
                proxyType = "read"
            elif "write" in opt:
                proxyType = "write"
            else:
                raise AssertionError("Unknown proxy type")

            try:
                principalForPrincipalID(arg, checkOnly=True)
            except ValueError, e:
                abort(e)

            actions.append((action_addProxy, proxyType, arg))

        elif opt in ("", "--remove-proxy"):
            try:
                principalForPrincipalID(arg, checkOnly=True)
            except ValueError, e:
                abort(e)

            actions.append((action_removeProxy, arg))

        elif opt in ("", "--set-auto-schedule"):
            try:
                autoSchedule = booleanArgument(arg)
            except ValueError, e:
                abort(e)

            actions.append((action_setAutoSchedule, autoSchedule))

        elif opt in ("", "--get-auto-schedule"):
            actions.append((action_getAutoSchedule,))

        else:
            raise NotImplementedError(opt)

    if not args:
        usage("No principals specified.")

    #
    # Get configuration
    #
    try:
        loadConfig(configFileName)
        setLogLevelForNamespace(None, "warn")

        # Shed privileges
        if config.UserName and config.GroupName:
            uid = getpwnam(config.UserName).pw_uid
            gid = getgrnam(config.GroupName).gr_gid
            switchUID(uid, uid, gid)

        os.umask(config.umask)

        config.directory = getDirectory()<commit_msg>Don't try to switchUID if you aren't root.<commit_after>#!/usr/bin/env python

##
# Copyright (c) 2006-2009 Apple Inc. All rights reserved.
#
# 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.
##

import sys
import os
import itertools
import operator
from getopt import getopt, GetoptError
from uuid import UUID
from pwd import getpwnam
from grp import getgrnam


from twisted.python import log
from twisted.python.reflect import namedClass
from twisted.python.util import switchUID
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.internet.address import IPv4Address
from twisted.internet.defer import inlineCallbacks, returnValue, succeed
from twisted.web2.dav import davxml

from twext.web2.dav.davxml import sname2qname, qname2sname

from twistedcaldav import caldavxml
from twistedcaldav import memcachepool
from twistedcaldav.config import config, defaultConfigFile, ConfigurationError
from twistedcaldav.customxml import calendarserver_namespace
from twistedcaldav.directory.directory import DirectoryService, DirectoryRecord
from twistedcaldav.directory.principal import DirectoryPrincipalProvisioningResource
from twistedcaldav.log import setLogLevelForNamespace
from twistedcaldav.notify import installNotificationClient
from twistedcaldav.static import CalendarHomeProvisioningFile

from calendarserver.tools.util import UsageError, booleanArgument, autoDisableMemcached
from calendarserver.tools.util import loadConfig, getDirectory, dummyDirectoryRecord
from calendarserver.provision.root import RootResource

def usage(e=None):
    if e:
        print e
        print ""

    name = os.path.basename(sys.argv[0])
    print "usage: %s [options] actions principal [principal ...]" % (name,)
    print ""
    print "  Performs the given actions against the giving principals."
    print ""
    print "  Principals are identified by one of the following:"
    print "    Type and shortname (eg.: users:wsanchez)"
   #print "    A principal path (eg.: /principals/users/wsanchez/)"
    print "    A GUID (eg.: E415DBA7-40B5-49F5-A7CC-ACC81E4DEC79)"
    print ""
    print "options:"
    print "  -h --help: print this help and exit"
    print "  -f --config <path>: Specify caldavd.plist configuration path"
    print ""
    print "actions:"
   #print "  --search <search-string>: search for matching resources"
    print "  -P, --read-property=property: read DAV property (eg.: {DAV:}group-member-set)"
    print "  --list-read-proxies: list proxies with read-only access"
    print "  --list-write-proxies: list proxies with read-write access"
    print "  --list-proxies: list all proxies"
    print "  --add-read-proxy=principal: add a read-only proxy"
    print "  --add-write-proxy=principal: add a read-write proxy"
    print "  --remove-proxy=principal: remove a proxy"
    print "  --set-auto-schedule={true|false}: set auto-accept state"
    print "  --get-auto-schedule: read auto-schedule state"

    if e:
        sys.exit(64)
    else:
        sys.exit(0)

def main():

    #
    # Send logging output to stdout
    #
    logFileName = "/dev/stdout"
    observer = log.FileLogObserver(open(logFileName, "a"))
    log.addObserver(observer.emit)



    try:
        (optargs, args) = getopt(
            sys.argv[1:], "hf:P:", [
                "help",
                "config=",
               #"search=",
                "read-property=",
                "list-read-proxies",
                "list-write-proxies",
                "list-proxies",
                "add-read-proxy=",
                "add-write-proxy=",
                "remove-proxy=",
                "set-auto-schedule=",
                "get-auto-schedule",
            ],
        )
    except GetoptError, e:
        usage(e)

    #
    # Get configuration
    #
    configFileName = None
    actions = []

    for opt, arg in optargs:
        if opt in ("-h", "--help"):
            usage()

        elif opt in ("-f", "--config"):
            configFileName = arg

        elif opt in ("-P", "--read-property"):
            try:
                qname = sname2qname(arg)
            except ValueError, e:
                abort(e)
            actions.append((action_readProperty, qname))

        elif opt in ("", "--list-read-proxies"):
            actions.append((action_listProxies, "read"))

        elif opt in ("", "--list-write-proxies"):
            actions.append((action_listProxies, "write"))

        elif opt in ("-L", "--list-proxies"):
            actions.append((action_listProxies, "read", "write"))

        elif opt in ("--add-read-proxy", "--add-write-proxy"):
            if "read" in opt:
                proxyType = "read"
            elif "write" in opt:
                proxyType = "write"
            else:
                raise AssertionError("Unknown proxy type")

            try:
                principalForPrincipalID(arg, checkOnly=True)
            except ValueError, e:
                abort(e)

            actions.append((action_addProxy, proxyType, arg))

        elif opt in ("", "--remove-proxy"):
            try:
                principalForPrincipalID(arg, checkOnly=True)
            except ValueError, e:
                abort(e)

            actions.append((action_removeProxy, arg))

        elif opt in ("", "--set-auto-schedule"):
            try:
                autoSchedule = booleanArgument(arg)
            except ValueError, e:
                abort(e)

            actions.append((action_setAutoSchedule, autoSchedule))

        elif opt in ("", "--get-auto-schedule"):
            actions.append((action_getAutoSchedule,))

        else:
            raise NotImplementedError(opt)

    if not args:
        usage("No principals specified.")

    #
    # Get configuration
    #
    try:
        loadConfig(configFileName)
        setLogLevelForNamespace(None, "warn")

        # Shed privileges
        if config.UserName and config.GroupName and os.getuid() == 0:
            uid = getpwnam(config.UserName).pw_uid
            gid = getgrnam(config.GroupName).gr_gid
            switchUID(uid, uid, gid)

        os.umask(config.umask)

        config.directory = getDirectory()
{'fraction_non_alphanumeric': 0.1041289933694997, 'fraction_numerical': 0.005952380952380952, 'mean_word_length': 2.39984631147541, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 8}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2471627', 'n_tokens_mistral': 3846, 'n_tokens_neox': 3698, 'n_words': 1079}