root/trunk/umitCore/Paths.py @ 4135

Revision 4135, 13.9 kB (checked in by gpolo, 4 years ago)

* Explicitly fail when a path has no change to succeed in
Path.force_set_umit_conf;
* No longer always using force_set_umit_conf in umit_scheduler, that
only happens when explicitly told so.

Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4# Copyright (C) 2005-2006 Insecure.Com LLC.
5# Copyright (C) 2007-2008 Adriano Monteiro Marques
6#
7# Author: Adriano Monteiro Marques <adriano@umitproject.org>
8#
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22
23import os
24import sys
25
26from umitCore.UmitLogging import log
27from umitCore.UmitConfigParser import UmitConfigParser
28from umitCore.TempConf import create_temp_conf_dir
29from umitCore.Version import VERSION
30from umitCore.BasePaths import base_paths, HOME
31from umitCore.BasePaths import CONFIG_DIR, LOCALE_DIR, MISC_DIR
32from umitCore.BasePaths import ICONS_DIR, PIXMAPS_DIR, DOCS_DIR
33
34
35def root_dir():
36    """Retrieves root dir on current filesystem"""
37    curr_dir = os.getcwd()
38    while True:
39        splited = os.path.split(curr_dir)[0]
40        if curr_dir == splited:
41            break
42        curr_dir = splited
43
44    log.debug(">>> Root dir: %s" % curr_dir)
45    return curr_dir
46
47#######
48# Paths
49class Paths(object):
50    """Paths
51    """
52    config_parser = UmitConfigParser()
53    paths_section = "paths"
54
55    hardcoded = ["locale_dir",
56                 "pixmaps_dir",
57                 "icons_dir",
58                 "misc_dir",
59                 "config_dir",
60                 "docs_dir"]
61
62    config_files_list = ["config_file",
63                         "profile_editor",
64                         "wizard",
65                         "scan_profile",
66                         "options",
67                         "umitdb_ng",
68                         "tl_conf",
69                         "tl_colors_std",
70                         "sched_schemas",
71                         "sched_profiles",
72                         "sched_log",
73                         "smtp_schemas",
74                         "umit_version"]
75
76    empty_config_files_list = ["target_list",
77                               "recent_scans",
78                               "umitdb"]
79
80    share_files_list = ["umit_opt",
81                        "umit_opf"]
82
83    misc_files_list = ["services_dump",
84                       "os_dump",
85                       "os_classification",
86                       "sched_running"]
87
88    other_settings = ["nmap_command_path"]
89
90    config_file_set = False
91
92    def _parse_and_set_dirs(self, config_file, config_dir):
93        """Parse the given config_file and then set the directories."""
94        # Parsing the umit main config file
95        self.config_parser.read(config_file)
96
97        # Should make the following only after reading the umit.conf file
98        self.config_dir = config_dir
99        self.config_file = config_file
100        self.config_file_set = True
101        self.locale_dir = LOCALE_DIR
102        self.pixmaps_dir = PIXMAPS_DIR
103        self.icons_dir = ICONS_DIR
104        self.misc_dir = MISC_DIR
105        self.docs_dir = DOCS_DIR
106
107    def get_running_path(self):
108        return self.__runpath
109
110    def set_running_path(self, path):
111        """
112        Sets path for current umit instance.
113        """
114        self.__runpath = path
115
116    def get_umit_conf(self):
117        """
118        Returns umit conf file being used.
119        """
120        if self.config_file_set:
121            return self.config_file
122
123    def force_set_umit_conf(self, config_dir):
124        if not os.path.exists(config_dir):
125            raise Exception("Path specified (%r) does not exist" % config_dir)
126
127        config_file = os.path.join(config_dir, base_paths['config_file'])
128        self._parse_and_set_dirs(config_file, config_dir)
129
130    def set_umit_conf(self, base_dir):
131        main_config_dir = ""
132        main_config_file = ""
133
134        if (os.path.exists(CONFIG_DIR) and
135                os.path.exists(os.path.join(CONFIG_DIR,
136                    base_paths['config_file']))):
137            main_config_dir = CONFIG_DIR
138
139        elif (
140                os.path.exists(os.path.join(base_dir, CONFIG_DIR)) and
141                os.path.exists(os.path.join(
142                    base_dir, CONFIG_DIR, base_paths['config_file']))):
143            main_config_dir = os.path.join(base_dir, CONFIG_DIR)
144
145        elif (
146                os.path.exists(os.path.join(os.path.split(base_dir)[0],
147                    CONFIG_DIR)) and
148                os.path.exists(os.path.join(os.path.split(base_dir)[0],
149                    CONFIG_DIR, base_paths['config_file']))):
150            main_config_dir = (
151                    os.path.join(os.path.split(base_dir)[0], CONFIG_DIR))
152
153        else:
154            main_config_dir = create_temp_conf_dir(VERSION)
155
156        # Main config file, based on the main_config_dir got above
157        main_config_file = os.path.join(main_config_dir,
158                base_paths['config_file'])
159
160        # This is the expected place in which umit.conf should be placed
161        supposed_file = os.path.join(base_paths['user_dir'],
162                base_paths['config_file'])
163        config_dir = ""
164        config_file = ""
165
166        if os.path.exists(supposed_file)\
167               and check_access(supposed_file, os.R_OK and os.W_OK):
168            config_dir = base_paths['user_dir']
169            config_file = supposed_file
170            log.debug(">>> Using config files in user home directory: %s" \
171                      % config_file)
172
173        elif not os.path.exists(supposed_file)\
174             and not check_access(base_paths['user_dir'],
175                                  os.R_OK and os.W_OK):
176            try:
177                result = create_user_dir(os.path.join(main_config_dir,
178                                              base_paths['config_file']),
179                                         HOME)
180                if type(result) == type({}):
181                    config_dir = result['config_dir']
182                    config_file = result['config_file']
183                    log.debug(">>> Using recently created config files in \
184                                user home: %s" % config_file)
185                else:
186                    raise Exception()
187            except:
188                log.debug(">>> Failed to create user home")
189
190        if config_dir and config_file:
191            # Checking if the version of the configuration files are the same
192            # as this Umit's version
193            if not self.check_version(config_dir):
194                log.debug(">>> The config files versions are different!")
195                log.debug(">>> Running update scripts...")
196                self.update_config_dir(config_dir)
197
198        else:
199            log.debug(">>> There is no way to create nor use home connfigs.")
200            log.debug(">>> Trying to use main configuration files...")
201
202            config_dir = main_config_dir
203            config_file = main_config_file
204
205        self._parse_and_set_dirs(config_file, config_dir)
206
207        for plug_path in ('plugins', 'plugins-download', 'plugins-temp'):
208            dir_path = os.path.join(config_dir, plug_path)
209            try:
210                if not os.path.exists(dir_path):
211                    os.makedirs(dir_path)
212            except:
213                pass
214
215        log.debug(">>> Config file: %s" % config_file)
216        log.debug(">>> Locale: %s" % self.locale_dir)
217        log.debug(">>> Pixmaps: %s" % self.pixmaps_dir)
218        log.debug(">>> Icons: %s" % self.icons_dir)
219        log.debug(">>> Misc: %s" % self.misc_dir)
220        log.debug(">>> Docs: %s" % self.docs_dir)
221
222    def update_config_dir(self, config_dir):
223        # Do any updates of configuration files. Not yet implemented.
224        pass
225
226    def check_version(self, config_dir):
227        version_file = os.path.join(config_dir, base_paths['umit_version'])
228
229        if os.path.exists(version_file):
230            ver = open(version_file).readline().strip()
231
232            log.debug(">>> This Umit Version: %s" % VERSION)
233            log.debug(">>> Version of the files in %s: %s" % (config_dir, ver))
234
235            if VERSION == ver:
236                return True
237        return False
238
239    def __getattr__(self, name):
240        if self.config_file_set:
241            if name in self.other_settings:
242                return self.config_parser.get(self.paths_section, name)
243
244            elif name in self.hardcoded:
245                return self.__dict__[name]
246
247            elif name in self.config_files_list:
248                return return_if_exists(os.path.join(
249                    self.__dict__['config_dir'], base_paths[name]))
250
251            elif name in self.empty_config_files_list:
252                return return_if_exists(os.path.join(
253                    self.__dict__['config_dir'], base_paths[name]),
254                    True)
255
256            elif name in self.share_files_list:
257                return return_if_exists(os.path.join(
258                    self.__dict__['pixmaps_dir'], base_paths[name]))
259
260            elif name in self.misc_files_list:
261                return return_if_exists(os.path.join(
262                    self.__dict__["misc_dir"], base_paths[name]))
263
264            try:
265                return self.__dict__[name]
266            except:
267                raise NameError(name)
268        else:
269            raise Exception("Must set config file location first")
270
271    def __setattr__(self, name, value):
272        if name in self.other_settings:
273            self.config_parser.set(self.paths_section, name, value)
274        else:
275            self.__dict__[name] = value
276
277####################################
278# Functions for directories creation
279
280def create_user_dir(config_file, user_home):
281    log.debug(">>> Create user dir at given home: %s" % user_home)
282    log.debug(">>> Using %s as source" % config_file)
283
284    main_umit_conf = UmitConfigParser()
285    main_umit_conf.read(config_file)
286
287    user_dir = os.path.join(user_home, base_paths['config_dir'])
288
289    if os.path.exists(user_home)\
290           and os.access(user_home, os.R_OK and os.W_OK)\
291           and not os.path.exists(user_dir):
292        os.mkdir(user_dir)
293        os.mkdir(os.path.join(user_dir, "plugins"))
294        os.mkdir(os.path.join(user_dir, "plugins-download"))
295        os.mkdir(os.path.join(user_dir, "plugins-temp"))
296        log.debug(">>> Umit user dir successfully created! %s" % user_dir)
297    else:
298        log.warning(">>> No permissions to create user dir!")
299        return False
300
301    main_dir = os.path.split(config_file)[0]
302    copy_config_file("options.xml", main_dir, user_dir)
303    copy_config_file("profile_editor.xml", main_dir, user_dir)
304    copy_config_file("scan_profile.usp", main_dir, user_dir)
305    copy_config_file("umit_version", main_dir, user_dir)
306    copy_config_file("umitng.db", main_dir, user_dir)
307    copy_config_file("timeline-settings.conf", main_dir, user_dir)
308    copy_config_file("tl_colors_evt_std.conf", main_dir, user_dir)
309    copy_config_file("scheduler-schemas.conf", main_dir, user_dir)
310    copy_config_file("scheduler-profiles.conf", main_dir, user_dir)
311    copy_config_file("scheduler.log", main_dir, user_dir)
312    copy_config_file("smtp-schemas.conf", main_dir, user_dir)
313    copy_config_file("wizard.xml", main_dir, user_dir)
314
315    return dict(user_dir = user_dir,
316                config_dir = user_dir,
317                config_file = copy_config_file("umit.conf",
318                                               os.path.split(config_file)[0],
319                                               user_dir))
320
321def copy_config_file(filename, dir_origin, dir_destiny):
322    log.debug(">>> copy_config_file %s to %s" % (filename, dir_destiny))
323
324    origin = os.path.join(dir_origin, filename)
325    destiny = os.path.join(dir_destiny, filename)
326
327    if not os.path.exists(destiny):
328        # Quick copy
329        origin_file = open(origin, 'rb')
330        destiny_file = open(destiny, 'wb')
331        destiny_file.write(origin_file.read())
332        origin_file.close()
333        destiny_file.close()
334    return destiny
335
336def check_access(path, permission):
337    if isinstance(path, basestring):
338        return os.path.exists(path) and os.access(path, permission)
339    return False
340
341def return_if_exists(path, create=False):
342    path = os.path.abspath(path)
343    if os.path.exists(path):
344        return path
345    elif create:
346        f = open(path, "w")
347        f.close()
348        return path
349    raise Exception("File '%s' does not exist or could not be found!" % path)
350
351############
352# Singleton!
353Path = Paths()
354
355if __name__ == '__main__':
356    Path.set_umit_conf(os.path.split(sys.argv[0])[0])
357
358    print ">>> SAVED DIRECTORIES:"
359    print ">>> LOCALE DIR:", Path.locale_dir
360    print ">>> PIXMAPS DIR:", Path.pixmaps_dir
361    print ">>> CONFIG DIR:", Path.config_dir
362    print
363    print ">>> FILES:"
364    print ">>> CONFIG FILE:", Path.config_file
365    print ">>> TARGET_LIST:", Path.target_list
366    print ">>> PROFILE_EDITOR:", Path.profile_editor
367    print ">>> WIZARD:", Path.wizard
368    print ">>> SCAN_PROFILE:", Path.scan_profile
369    print ">>> RECENT_SCANS:", Path.recent_scans
370    print ">>> OPTIONS:", Path.options
371    print
372    print ">>> UMIT_OPT:", Path.umit_opt
373    print ">>> UMIT_OPF:", Path.umit_opf
374    print ">>> UMITDB:", Path.umitdb
375    print ">>> UMITDB (New generation):", Path.umitdb_ng
376    print ">>> SERVICES DUMP:", Path.services_dump
377    print ">>> OS DB DUMP:", Path.os_dump
378    print ">>> UMIT VERSION:", Path.umit_version
379    print ">>> OS CLASSIFICATION DUMP:", Path.os_classification
380    print ">>> NMAP COMMAND PATH:", Path.nmap_command_path
Note: See TracBrowser for help on using the browser.