root/trunk/umitCore/Paths.py @ 3940

Revision 3940, 12.1 kB (checked in by gpolo, 4 years ago)

Fix for ticket 181. "When copying files we must treat them as binary to not have problems under Windows"

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