root/trunk/umitCore/Paths.py @ 2793

Revision 2793, 11.6 kB (checked in by xvg, 6 years ago)

Merge r5973 from Nmap umit branch.

Remove unused mentions of umit_icon and UMIT_ICON from the source. This was
something that was ostensibly to be configurable in umit.conf but this didn't
work because it was hardcoded in umitCore/Paths.py.

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