root/branch/NetworkInventory/umitCore/Paths.py @ 3840

Revision 3840, 14.0 kB (checked in by gpolo, 4 years ago)

Removed remaining reference to UMIT_ICON

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