root/trunk/umitCore/Paths.py @ 1296

Revision 1296, 9.3 kB (checked in by boltrix, 6 years ago)

More work on Windows installation scripts. Also, made some modifications to umitGUI.About. Linux installation scripts are working, but must make the installation step in which the umitCore.Path is going to be udpdated with the places where the configuration files where installed. The Mac OS X installation scripts are half way also, and must figure out why it is not been able to import cairo after the App generation.

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
22import os
23import os.path
24import re
25
26from umitCore.Logging 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
34#######
35# Paths
36class Paths(object):
37    """Paths
38    """
39    config_parser = UmitConfigParser()
40    paths_section = "paths"
41   
42    directories_list = ["locale_dir",
43                        "pixmaps_dir",
44                        "config_dir",
45                        "misc_dir",
46                        "docs_dir"]
47   
48    config_files_list = ["config_file",
49                         "target_list",
50                         "profile_editor",
51                         "wizard",
52                         "scan_profile",
53                         "recent_scans",
54                         "options",
55                         "umitdb",
56                         "umit_version"]
57   
58    share_files_list = ["umit_op",
59                        "umit_opi",
60                        "umit_opt",
61                        "umit_opf"]
62
63    misc_files_list = ["services_dump",
64                       "os_dump",
65                       "os_classification"]
66   
67    other_settings = ["nmap_command_path"]
68
69    config_file_set = False
70   
71    def set_umit_conf(self, umit_conf):
72        # Place supposed to have the user's config file
73        supposed_user_conf = os.path.join(base_paths['user_dir'],
74                                          base_paths['config_file'])
75        config_file = supposed_user_conf
76        parsed = False
77
78        if os.path.exists(supposed_user_conf)\
79               and check_access(supposed_user_conf, os.R_OK):
80            try:
81                self.config_parser.read(config_file)
82                log.debug(">>> Using config files in user home \
83directory: %s" % config_file)
84                parsed = True
85            except:
86                log.debug(">>> Failed to load config file from \
87user home directory")
88
89        if not parsed and not os.path.exists(supposed_user_conf)\
90                 and not check_access(base_paths['user_dir'], os.R_OK and os.W_OK):
91            try:
92                result = create_user_dir(umit_conf, HOME)
93                config_file = result['config_file']
94                self.config_parser.read(config_file)
95                [self.__setattr__(opt, result[opt]) for opt in result]
96                log.debug(">>> Using recently created config files in \
97user home: %s" % config_file)
98                parsed = True
99            except:
100                log.debug(">>> Failed to create user home")
101
102        if not parsed and type(umit_conf) == type([]):
103            config_file = self.config_parser.read(umit_conf)
104            if config_file != None and len(config_file) >= 1:
105                config_file = config_file[0]
106            else:
107                raise Exception("Couldn't load umit config file!")
108
109        # Should make the following only after reading the umit.conf file
110        self.config_file = config_file
111        self.config_file_set = True
112
113        log.debug(">>> Config file: %s" % config_file)
114
115    def root_dir(self):
116        """Retrieves root dir on current filesystem"""
117        curr_dir = os.getcwd()
118        while True:
119            splited = os.path.split(curr_dir)[0]
120            if curr_dir == splited:
121                break
122            curr_dir = splited
123
124        log.debug(">>> Root dir: %s" % curr_dir)
125        return curr_dir
126
127
128    def __getattr__(self, name):
129        if self.config_file_set:
130            if name in self.directories_list or name in self.other_settings:
131                return return_if_exists(self.config_parser.get(self.paths_section, name))
132            elif name in self.config_files_list:
133                return return_if_exists(os.path.join(self.config_parser.get(self.paths_section, "config_dir"),
134                                                     base_paths[name]))
135            elif name in self.share_files_list:
136                return return_if_exists(os.path.join(self.config_parser.get(self.paths_section, "pixmaps_dir"),
137                                                     base_paths[name]))
138            elif name in self.misc_files_list:
139                return return_if_exists(os.path.join(self.config_parser.get(self.paths_section, "misc_dir"),
140                                                     base_paths[name]))
141       
142            try:
143                return self.__dict__[name]
144            except:
145                raise NameError(name)
146        else:
147            raise Exception("Must set config file location first")
148
149    def __setattr__(self, name, value):
150        if name in self.directories_list or name in self.other_settings:   
151            self.config_parser.set(self.paths_section, name, value)
152        else:
153            self.__dict__[name] = value
154   
155
156####################################
157# Functions for directories creation
158
159def create_user_dir(config_list, user_home):
160    main_config = None
161    for config in config_list:
162        if os.path.exists(config):
163            main_config = config
164            break
165    else:
166        log.critical(">>> No useful configuration file found in this list: %s"\
167                 % config_list)
168        raise Exception(">>> No usefull configuration file found!")
169
170    log.debug(">>> Create user dir at given home: %s" % user_home)
171    log.debug(">>> Using %s as source" % main_config)
172    main_umit_conf = UmitConfigParser()
173    main_umit_conf.read(main_config)
174    paths_section = "paths"
175   
176    user_dir = os.path.join(user_home, base_paths['config_dir'])
177   
178    if os.path.exists(user_home)\
179           and os.access(user_home, os.R_OK and os.W_OK)\
180           and not os.path.exists(user_dir):
181        os.mkdir(user_dir)
182        log.debug(">>> Umit user dir successfully created! %s" % user_dir)
183    else:
184        log.warning(">>> No permissions to create user dir!")
185        return False
186
187    main_dir = os.path.split(main_config)[0]
188    copy_config_file("options.xml", main_dir, user_dir)
189    copy_config_file("profile_editor.xml", main_dir, user_dir)
190    copy_config_file("recent_scans.txt", main_dir, user_dir)
191    copy_config_file("scan_profile.usp", main_dir, user_dir)
192    copy_config_file("target_list.txt", main_dir, user_dir)
193    copy_config_file("umit_version", main_dir, user_dir)
194    copy_config_file("umit.db", main_dir, user_dir)
195    copy_config_file("wizard.xml", main_dir, user_dir)
196
197    return dict(user_dir = user_dir,
198                config_dir = user_dir,
199                config_file = copy_config_file("umit.conf", os.path.split(main_config)[0], user_dir))
200
201def copy_config_file(filename, dir_origin, dir_destiny):
202    log.debug(">>> copy_config_file %s to %s" % (filename, dir_destiny))
203   
204    origin = os.path.join(dir_origin, filename)
205    destiny = os.path.join(dir_destiny, filename)
206   
207    if not os.path.exists(destiny):
208        # Quick copy
209        open(destiny, 'w').write(open(origin).read())
210    return destiny
211
212def check_access(path, permission):
213    return os.path.exists(path) and os.access(path, permission)
214
215def return_if_exists(path):
216    if os.path.exists(path):
217        return os.path.abspath(path)
218    raise Exception("File '%s' does not exist or could not be found!" % path)
219
220#########
221# Singleton!
222Path = Paths()
223
224if __name__ == '__main__':
225    #create_user_dir(os.path.expanduser("~"))
226    __file__ = ".."
227    Path.set_umit_conf(os.path.join(os.path.split(__file__)[0], "config", "umit.conf"))
228
229    print ">>> SAVED DIRECTORIES:"
230    print ">>> LOCALE DIR:", Path.locale_dir
231    print ">>> PIXMAPS DIR:", Path.pixmaps_dir
232    print ">>> CONFIG DIR:", Path.config_dir
233    print
234    print ">>> FILES:"
235    print ">>> CONFIG FILE:", Path.config_file
236    print ">>> TARGET_LIST:", Path.target_list
237    print ">>> PROFILE_EDITOR:", Path.profile_editor
238    print ">>> WIZARD:", Path.wizard
239    print ">>> SCAN_PROFILE:", Path.scan_profile
240    print ">>> RECENT_SCANS:", Path.recent_scans
241    print ">>> OPTIONS:", Path.options
242    print
243    print ">>> UMIT_OP:", Path.umit_op
244    print ">>> UMIT_OPI:", Path.umit_opi
245    print ">>> UMIT_OPT:", Path.umit_opt
246    print ">>> UMIT_OPF:", Path.umit_opf
247    print ">>> UMITDB:", Path.umitdb
248    print ">>> SERVICES DUMP:", Path.services_dump
249    print ">>> OS DB DUMP:", Path.os_dump
250    print ">>> UMIT VERSION:", Path.umit_version
251    print ">>> OS CLASSIFICATION DUMP:", Path.os_classification
252    print ">>> NMAP COMMAND PATH:", Path.nmap_command_path
Note: See TracBrowser for help on using the browser.