root/branch/ggpolo/umitCore/Paths.py @ 1349

Revision 1349, 13.0 kB (checked in by ggpolo, 6 years ago)

Merged with trunk. Removed scripts dir, scheduler_control has been renamed to scheduler-umit and is on root directory now. Treeviews uses single clicks to activate rows now

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