root/trunk/umitCore/Paths.py @ 2929

Revision 2929, 11.3 kB (checked in by gpolo, 5 years ago)

Applied patch attached in Ticket #21

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