root/trunk/umitCore/Paths.py @ 1996

Revision 1996, 11.5 kB (checked in by boltrix, 6 years ago)

Working on the so reported bug arround webbrowser

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, environ, getcwd
23from os.path import exists, join, split, abspath, dirname
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 = environ.get("UMIT_VERSION", "0.4.5")
32REVISION = environ.get("UMIT_REVISION", "1567")
33
34main_dir = ""
35if hasattr(sys, "frozen"):
36    main_dir = dirname(sys.executable)
37
38CONFIG_DIR = join(main_dir, "share", "umit", "config")
39UMIT_ICON = join(main_dir, "share", "icons", "umit_48.ico")
40LOCALE_DIR = join(main_dir, "share", "umit", "locale")
41MISC_DIR = join(main_dir, "share", "umit", "misc")
42ICONS_DIR = join(main_dir, "share", "icons")
43PIXMAPS_DIR = join(main_dir, "share", "pixmaps")
44DOCS_DIR = join(main_dir, "share", "umit", "docs")
45
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                 "docs_dir",
60                 "umit_icon"]
61
62    config_files_list = ["config_file",
63                         "target_list",
64                         "profile_editor",
65                         "wizard",
66                         "scan_profile",
67                         "recent_scans",
68                         "options",
69                         "umitdb",
70                         "umit_version"]
71
72    share_files_list = ["umit_op",
73                        "umit_opi",
74                        "umit_opt",
75                        "umit_opf"]
76
77    misc_files_list = ["services_dump",
78                       "os_dump",
79                       "os_classification"]
80
81    other_settings = ["nmap_command_path"]
82
83    config_file_set = False
84   
85    def set_umit_conf(self, base_dir):
86        main_config_dir = ""
87        main_config_file = ""
88        if exists(CONFIG_DIR) and \
89            exists(join(CONFIG_DIR, base_paths['config_file'])):
90            main_config_dir = CONFIG_DIR
91
92        elif exists(join(base_dir, CONFIG_DIR)) and\
93            exists(join(base_dir,
94                                        CONFIG_DIR,
95                                        base_paths['config_file'])):
96            main_config_dir = join(base_dir, CONFIG_DIR)
97
98        elif exists(join(split(base_dir)[0], CONFIG_DIR)) and \
99            exists(join(split(base_dir)[0],
100                                        CONFIG_DIR,
101                                        base_paths['config_file'])):
102            main_config_dir = join(split(base_dir)[0], CONFIG_DIR)
103
104        else:
105            raise Exception("Couldn't find the Umit's Config Directory! \
106Aborting...")
107
108        # Main config file, based on the main_config_dir got above
109        main_config_file = join(main_config_dir, base_paths['config_file'])
110
111        # This is the expected place in which umit.conf should be placed
112        supposed_file = join(base_paths['user_dir'], base_paths['config_file'])
113        config_dir = ""
114        config_file = ""
115
116        if exists(supposed_file)\
117               and check_access(supposed_file, R_OK and W_OK):
118            config_dir = base_paths['user_dir']
119            config_file = supposed_file
120            log.debug(">>> Using config files in user home \
121directory: %s" % config_file)
122
123        elif not exists(supposed_file)\
124             and not check_access(base_paths['user_dir'],
125                                  R_OK and W_OK):
126            try:
127                result = create_user_dir(join(main_config_dir,
128                                              base_paths['config_file']),
129                                         HOME)
130                if type(result) == type({}):
131                    config_dir = result['config_dir']
132                    config_file = result['config_file']
133                    log.debug(">>> Using recently created config files in \
134user home: %s" % config_file)
135                else:
136                    raise Exception()
137            except:
138                log.debug(">>> Failed to create user home")
139
140        if config_dir and config_file:
141            # Checking if the version of the configuration files are the same
142            # as this Umit's version
143            if not self.check_version(config_dir):
144                log.debug(">>> The config files versions are different!")
145                log.debug(">>> Running update scripts...")
146                self.update_config_dir(config_dir)
147
148        else:
149            log.debug(">>> There is no way to create nor use home connfigs.")
150            log.debug(">>> Trying to use main configuration files...")
151
152            config_dir = main_config_dir
153            config_file = main_config_file
154
155        # Parsing the umit main config file
156        self.config_parser.read(config_file)
157
158        # Should make the following only after reading the umit.conf file
159        self.config_dir = config_dir
160        self.config_file = config_file
161        self.config_file_set = True
162        self.locale_dir = LOCALE_DIR
163        self.pixmaps_dir = PIXMAPS_DIR
164        self.icons_dir = ICONS_DIR
165        self.misc_dir = MISC_DIR
166        self.docs_dir = DOCS_DIR
167        self.umit_icon = UMIT_ICON
168
169        log.debug(">>> Config file: %s" % config_file)
170
171    def update_config_dir(self, config_dir):
172        pass
173
174    def check_version(self, config_dir):
175        ver = open(join(config_dir,
176                        base_paths['umit_version'])).readlines()[0].\
177                                                     split("\n")[0].\
178                                                     split("\r")[0]
179
180        log.debug(">>> This Umit Version: %s" % VERSION)
181        log.debug(">>> Version of the files in %s: %s" % (config_dir, ver))
182
183        if VERSION == ver:
184            return True
185        return False
186
187    def root_dir(self):
188        """Retrieves root dir on current filesystem"""
189        curr_dir = getcwd()
190        while True:
191            splited = split(curr_dir)[0]
192            if curr_dir == splited:
193                break
194            curr_dir = splited
195
196        log.debug(">>> Root dir: %s" % curr_dir)
197        return curr_dir
198
199    def __getattr__(self, name):
200        if self.config_file_set:
201            if name in self.other_settings:
202                return self.config_parser.get(self.paths_section, name)
203
204            elif name in self.hardcoded:
205                return self.__dict__[name]
206
207            elif name in self.config_files_list:
208                return return_if_exists(join(self.__dict__['config_dir'],
209                                             base_paths[name]))
210
211            elif name in self.share_files_list:
212                return return_if_exists(join(self.__dict__['pixmaps_dir'],
213                                             base_paths[name]))
214
215            elif name in self.misc_files_list:
216                return return_if_exists(join(self.__dict__["misc_dir"],
217                                                     base_paths[name]))
218
219            try:
220                return self.__dict__[name]
221            except:
222                raise NameError(name)
223        else:
224            raise Exception("Must set config file location first")
225
226    def __setattr__(self, name, value):
227        if name in self.other_settings:
228            self.config_parser.set(self.paths_section, name, value)
229        else:
230            self.__dict__[name] = value
231
232####################################
233# Functions for directories creation
234
235def create_user_dir(config_file, user_home):
236    log.debug(">>> Create user dir at given home: %s" % user_home)
237    log.debug(">>> Using %s as source" % config_file)
238
239    main_umit_conf = UmitConfigParser()
240    main_umit_conf.read(config_file)
241    paths_section = "paths"
242
243    user_dir = join(user_home, base_paths['config_dir'])
244
245    if exists(user_home)\
246           and access(user_home, R_OK and W_OK)\
247           and not exists(user_dir):
248        mkdir(user_dir)
249        log.debug(">>> Umit user dir successfully created! %s" % user_dir)
250    else:
251        log.warning(">>> No permissions to create user dir!")
252        return False
253
254    main_dir = split(config_file)[0]
255    copy_config_file("options.xml", main_dir, user_dir)
256    copy_config_file("profile_editor.xml", main_dir, user_dir)
257    copy_config_file("recent_scans.txt", main_dir, user_dir)
258    copy_config_file("scan_profile.usp", main_dir, user_dir)
259    copy_config_file("target_list.txt", main_dir, user_dir)
260    copy_config_file("umit_version", main_dir, user_dir)
261    copy_config_file("wizard.xml", main_dir, user_dir)
262
263    return dict(user_dir = user_dir,
264                config_dir = user_dir,
265                config_file = copy_config_file("umit.conf",
266                                               split(config_file)[0],
267                                               user_dir))
268
269def copy_config_file(filename, dir_origin, dir_destiny):
270    log.debug(">>> copy_config_file %s to %s" % (filename, dir_destiny))
271
272    origin = join(dir_origin, filename)
273    destiny = join(dir_destiny, filename)
274
275    if not exists(destiny):
276        # Quick copy
277        open(destiny, 'w').write(open(origin).read())
278    return destiny
279
280def check_access(path, permission):
281    return exists(path) and access(path, permission)
282
283def return_if_exists(path):
284    if exists(path):
285        return abspath(path)
286    raise Exception("File '%s' does not exist or could not be found!" % path)
287
288############
289# Singleton!
290Path = Paths()
291
292if __name__ == '__main__':
293    Path.set_umit_conf(split(sys.argv[0])[0])
294
295    print ">>> SAVED DIRECTORIES:"
296    print ">>> LOCALE DIR:", Path.locale_dir
297    print ">>> PIXMAPS DIR:", Path.pixmaps_dir
298    print ">>> CONFIG DIR:", Path.config_dir
299    print
300    print ">>> FILES:"
301    print ">>> CONFIG FILE:", Path.config_file
302    print ">>> TARGET_LIST:", Path.target_list
303    print ">>> PROFILE_EDITOR:", Path.profile_editor
304    print ">>> WIZARD:", Path.wizard
305    print ">>> SCAN_PROFILE:", Path.scan_profile
306    print ">>> RECENT_SCANS:", Path.recent_scans
307    print ">>> OPTIONS:", Path.options
308    print
309    print ">>> UMIT_OP:", Path.umit_op
310    print ">>> UMIT_OPI:", Path.umit_opi
311    print ">>> UMIT_OPT:", Path.umit_opt
312    print ">>> UMIT_OPF:", Path.umit_opf
313    print ">>> UMITDB:", Path.umitdb
314    print ">>> SERVICES DUMP:", Path.services_dump
315    print ">>> OS DB DUMP:", Path.os_dump
316    print ">>> UMIT VERSION:", Path.umit_version
317    print ">>> OS CLASSIFICATION DUMP:", Path.os_classification
318    print ">>> NMAP COMMAND PATH:", Path.nmap_command_path
Note: See TracBrowser for help on using the browser.