~wifixers/wifix/0.3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
#!/usr/bin/python
# Author: bmartin (blakecmartin@gmail.com)
# Author: Buran Ayuthia (the.ayuthias@gmail.com)
# Author: Samuel A. Dieck (https://launchpad.net/~sam-dieck)

"""
This file is part of WiFix.

WiFix is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

WiFix is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

# The idea here is to polymorphically run commands depending on which operating
# system is detected (e.g., BSD, Linux).

import commands
import httplib
import os
import string
import sys
import urllib
import time

import messages

class __Platform:
    """
    Provides an interface for OS-dependent calls.
    """

    def execute(self, command):
        """
        Executes the given command within a terminal. All output resulting from
        executing the given command should be displayed in the terminal.
        """

        raise NotImplementedError

    def get_devices(self):
        """
        Retrieves a listing of all PCI and USB device IDs of network devices on the computer.
        """

        raise NotImplementedError

    def get_installer_command(self, arguments):
        """
        Retrieves the command to run the installer with the given arguments.
        """

        raise NotImplementedError

    def has_display(self):
        """
        Returns True if a display is available; False otherwise.
        """

        raise NotImplementedError

    def is_root(self):
        """
        Returns True if the current process is being executed with elevated
        privileges, False otherwise.
        """

        raise NotImplementedError

    def message(self, message):
        """
        Displays a message to the user.
        """

        raise NotImplementedError

    def message_yesno(self, message):
        """
        Displays a yes/no message to the user.
        """

        raise NotImplementedError

    def __get_pci_devices(self):
        """
        Retrieves a listing of PCI IDs of all PCI network devices on the
        computer.
        """

        raise NotImplementedError

    def __get_usb_devices(self):
        """
        Retrieves a listing of USB IDs of all USB network devices on the
        computer.
        """

        raise NotImplementedError

class PlatformLinux(__Platform):
    """
    OS-specific calls for the Linux implementation.
    """
    def get_debug_info (self, pm):
        pci_devices = []
        usb_devices = []
        device_label = [] 

        # retrieve PCI networking devices
        pm.start("Gathering info", messages.no_driver) 
        for pci_device in self.__get_pci_devices():
            device_label.append(commands.getoutput('lspci -nn | grep ' + pci_device + ' | sed "s|.*: ||g"'))

        # retrieve USB devices
        for usb_device in self.__get_usb_devices():
            device_label.append(usb_device)

	#build the timestamp (yyyymmddhhmmss)
        y = str(time.localtime ()[0]) 
        m = str(time.localtime ()[1]).zfill (2)
        d = str(time.localtime ()[2]).zfill (2)
        h = str(time.localtime ()[3]).zfill (2)
        mi = str(time.localtime ()[4]).zfill (2)
        s = str(time.localtime ()[5]).zfill (2)
        timestamp = y + m + d + h + mi + s 
        pm.stop()

        return timestamp + '\n' + string.join(device_label, '\n')	

    def get_devices(self, pm):
        options_list = []
        pci_devices = []
        usb_devices = []
        device_label = dict()

        # retrieve PCI networking devices
        pm.start("Gathering devices", "Searching for PCI adaptors")
        for pci_device in self.__get_pci_devices():
            pci_devices.append(pci_device + ".P")
            device_label[pci_device] = commands.getoutput('lspci -nn | grep ' + pci_device + ' | sed "s|.*: ||g"')
        pm.stop()

        # retrieve USB networking devices
        pm.start("Gathering devices", "Searching for USB adaptors")
        for usb_device in self.__get_usb_devices():
            usb_devices.append(usb_device + ".U")
            device_label[usb_device] = commands.getoutput('lsusb | grep ' + usb_device + ' | sed "s|.*: ID ||g"')
        pm.stop()

        devices = string.join(pci_devices, ';') + ";" + string.join(usb_devices, ';')
        params = urllib.urlencode({'cards': devices})
        headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}

        # Call PHP page to retrieve available drivers
        pm.start("Querying database", "Fetching driver information from database")
        try:
            die = False
            conn = httplib.HTTPConnection("wifix.sourceforge.net:80")
            conn.request("POST", "/get-driver.php", params, headers)
            response = conn.getresponse()
            data = response.read()
            # TODO might want to do something with response.status, response.reason
        except Error, description:
            self.message("Unable to connect to database: " + description)
            die = True
        finally:
            conn.close()
            pm.stop()
            if die:
                sys.exit()

        card = dict()

        for line in data.split("<br>"):
            # find the first "=" in the string
            index = line.find("=")
            if (index == -1):
                # no "=" present; not driver info
                if card.has_key('arguments'):
                    # add card info to list
                    if card['arguments'] != "":
                        card['label'] = device_label[card['id'][0:9]]
                        options_list.append(card)
                        card = dict()
            else:
                # add key:value pair
                key=line[0:index]
                value=line[index + 1:]
                card[key] = value
        return options_list

    def get_installer_command(self, arguments):
        args = arguments.split(';')
        arguments = string.join(args, ' ')
        return 'bash linux-install-wifi ' + arguments

    def __get_pci_devices(self):
        wifi_pci = commands.getoutput('d="[0-9a-f]" ; pci_id="$d$d$d$d":"$d$d$d$d" ; p="[0-9]" ; bus="$p$p:$p$p\.$p" ; pcis=$(lshw -C network | grep "bus info: pci@" | grep -o "$bus") ; lspci -nn | grep -F "$pcis" | grep -o "$pci_id"')
	# skip line 0 (lshw su warning) to only return actual devices)
        return wifi_pci.splitlines()[1:]

    def __get_usb_devices(self):
        wifi_usb = commands.getoutput('d="[0-9a-f]" ; pci_id="$d$d$d$d":"$d$d$d$d" ; lsusb | grep -o "${pci_id}" | grep -v "0000:0000"')
        return wifi_usb.splitlines()

    def is_root(self):
        return not os.system('[ $(id -u) = 0 ]')

    def message(self, message):
        return os.system("zenity --info --text='" + message + "'")

    def message_yesno(self, message):
        return os.system("zenity --question --text='" + message + "'") == 0

    def has_display(self):
        if (commands.getoutput('echo $DISPLAY') != ""):
            return True
        else:
            return False

    def execute(self, command):
        return os.system(command)

class PlatformBSD(__Platform):
    """
    OS-specific calls for the BSD implementation.
    """

    pass