Project

General

Profile

Download (14.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
    Copyright (C) 2007 Marcel Wiget <mwiget@mac.com>.
4
    All rights reserved.
5
    
6
    Redistribution and use in source and binary forms, with or without
7
    modification, are permitted provided that the following conditions are met:
8
    
9
    1. Redistributions of source code must retain the above copyright notice,
10
       this list of conditions and the following disclaimer.
11
    
12
    2. Redistributions in binary form must reproduce the above copyright
13
       notice, this list of conditions and the following disclaimer in the
14
       documentation and/or other materials provided with the distribution.
15
    
16
    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
17
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
18
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
20
    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25
    POSSIBILITY OF SUCH DAMAGE.
26

    
27
*/
28
    
29
/* include all configuration functions */
30
require_once("config.inc");
31

    
32
/* 
33
 *Authenticate a voucher and return the remaining time credit in minutes
34
 * if $test is set, don't mark the voucher as used nor add it to the list
35
 * of active vouchers
36
 */
37
function voucher_auth($voucher_received, $test = 0) {
38

    
39
    global $g, $config, $dirtyfile;
40

    
41
    // if $test is set, simply test the voucher. Don't change anything
42
    // but return a more verbose error and result message back
43

    
44
    if (! $test)
45
        $voucherlck = lock('voucher');
46

    
47
    // read rolls into assoc array with rollid as key and minutes as value
48
    $a_roll = &$config['voucher']['roll'];
49
    foreach ($a_roll as $rollent) {
50
        $tickets_per_roll[$rollent['number']] = $rollent['count'];
51
        $minutes_per_roll[$rollent['number']] = $rollent['minutes'];
52
    }
53

    
54
    // split into an array. Useful for multiple vouchers given
55
    $a_vouchers_received = split("[\t\n\r ]+",$voucher_received); 
56
    $error = 0;
57
    $test_result = array();     // used to display for voucher test option in GUI
58
    $total_minutes = 0;
59
    $first_voucher = "";
60
    $first_voucher_roll = 0;
61

    
62
    // go through all received vouchers, check their valid and extract
63
    // Roll# and Ticket# using the external readvoucher binary
64

    
65
    foreach ($a_vouchers_received as $voucher) {
66

    
67
        $v = escapeshellarg($voucher);
68
        if (strlen($voucher) < 3)
69
            continue;   // seems too short to be a voucher!
70

    
71
        $result = exec("/usr/local/bin/voucher -c {$g['varetc_path']}/voucher.cfg -k {$g['varetc_path']}/voucher.public -- $v");
72
        list($status, $roll, $nr) = explode(" ", $result);
73
        if ($status == "OK") {
74
            if (!$first_voucher) 
75
            {
76
                $first_voucher = $voucher;  // store first voucher. Thats the one we give the timecredit
77
                $first_voucher_roll = $roll;
78
            }
79
            // check if we have this ticket on a registered roll for this ticket 
80
            if ($tickets_per_roll[$roll] && ($nr <= $tickets_per_roll[$roll])) {
81
                // voucher is from a registered roll. 
82
                if (!isset($active_vouchers[$roll]))
83
                    $active_vouchers[$roll] = voucher_read_active_db($roll);
84
                // valid voucher. Store roll# and ticket#
85
                if ($line = $active_vouchers[$roll][$voucher]) {
86
                    list($timestamp,$minutes) = explode(",", $line);
87
                    // we have an already active voucher here.
88
                    $remaining = intval((($timestamp + 60*$minutes) - time())/60);
89
                    $test_result[] = "$voucher ($roll/$nr) active and good for $remaining Minutes";
90
                    $total_minutes += $remaining;
91
                } else {
92
                    // voucher not used. Check if ticket Id is on the roll (not too high)
93
                    // and if the ticket is marked used.
94
                    // check if voucher already marked as used
95
                    if (!isset($bitstring[$roll]))
96
                        $bitstring[$roll] = voucher_read_used_db($roll);
97
                    $pos = $nr >> 3; // divide by 8 -> octet
98
                    $mask = 1 << ($nr % 8);
99
                    if (ord($bitstring[$roll][$pos]) & $mask) {
100
                        $test_result[] = "$voucher ($roll/$nr) already used and expired";
101
                        $total_minutes = -1;    // voucher expired
102
                        $error++;
103
                    } else {
104
                        // mark bit for this voucher as used
105
                        $bitstring[$roll][$pos] = chr(ord($bitstring[$roll][$pos]) | $mask);
106
                        $test_result[] = "$voucher ($roll/$nr) good for {$minutes_per_roll[$roll]} Minutes";
107
                        $total_minutes += $minutes_per_roll[$roll];
108
                    }
109
                }
110
            } else {
111
                $test_result[] = "$voucher ($roll/$nr): not found on any registererd Roll";
112
            }
113
        } else {
114
            // hmm, thats weired ... not what I expected
115
            $test_result[] = "$voucher invalid: $result !!";
116
            $error++;
117
        }
118
    }
119

    
120
    // if this was a test call, we're done. Return the result.
121
    if ($test) {
122
        if ($error) {
123
            $test_result[] = "Access denied!";
124
        } else {
125
            $test_result[] = "Access granted for $total_minutes Minutes in total.";
126
        }
127
	unlock($voucherlck);
128
        return $test_result;
129
    }
130

    
131
    // if we had an error (one of the vouchers is invalid), return 0.
132
    // Discussion: we could return the time remaining for good vouchers, but then
133
    // the user wouldn't know that he used at least one invalid voucher.
134

    
135
    if ($error) {
136
	unlock($voucherlck);
137
        if ($total_minutes > 0)     // probably not needed, but want to make sure
138
            $total_minutes = 0;     // we only report -1 (expired) or 0 (no access)
139
        return $total_minutes;       // well, at least one voucher had errors. Say NO ACCESS
140
    }
141

    
142
    // All given vouchers were valid and this isn't simply a test.
143
    // Write back the used DB's
144

    
145
    if (is_array($bitstring))
146
        foreach ($bitstring as $roll => $used)
147
            voucher_write_used_db($roll, base64_encode($used));
148

    
149
    // Active DB: we only add the first voucher if multiple given
150
    // and give that one all the time credit. This allows the user to logout and
151
    // log in later using just the first voucher. It also keeps username limited
152
    // to one voucher and that voucher shows the correct time credit in 'active vouchers'
153

    
154
    if ($line = $active_vouchers[$first_voucher_roll][$first_voucher]) {
155
        list($timestamp, $minutes) = explode(",", $line);
156
    } else {
157
        $timestamp = time();    // new voucher
158
        $minutes = $total_minutes;
159
    }
160

    
161
    $active_vouchers[$first_voucher_roll][$first_voucher] = "$timestamp,$minutes";
162
    voucher_write_active_db($roll, $active_vouchers[$first_voucher_roll]);
163

    
164
    // mark the DB's as dirty.
165
    if ($fd = fopen($dirtyfile, "w"))
166
        fclose($fd);
167

    
168
    unlock($voucherlck);
169

    
170
    return $total_minutes;
171
}
172

    
173
function voucher_configure() {
174
    global $config, $g;
175
    
176
    /* kill any running minicron */
177
    killbypid("{$g['varrun_path']}/vouchercron.pid");
178

    
179
    if (isset($config['voucher']['enable'])) {
180

    
181
        if ($g['booting']) {
182
            echo "Enabling voucher support... ";
183
        }
184

    
185
        // start cron if we're asked to save runtime DB periodically
186
        // to XML config if it changed
187
        $croninterval = $config['voucher']['saveinterval'] * 60; // need seconds. Config has minutes
188
        if ($croninterval) {
189
            /* start pruning process (interval defaults to 60 seconds) */
190
            mwexec("/usr/local/bin/minicron $croninterval {$g['varrun_path']}/vouchercron.pid " .
191
                    "/etc/rc.savevoucher");
192
        }
193

    
194
	$voucherlck = lock('voucher');
195
        /* write public key used to verify vouchers */
196
        $pubkey = base64_decode($config['voucher']['publickey']);
197
        $fd = fopen("{$g['varetc_path']}/voucher.public", "w");
198
        if (!$fd) {
199
            printf("Error: cannot write voucher.public\n");
200
	    unlock($voucherlck);
201
            return 1;
202
        }
203
        chmod("{$g['varetc_path']}/voucher.public", 0600);
204
        fwrite($fd, $pubkey);
205
        fclose($fd);
206

    
207
        /* write config file used by voucher binary to decode vouchers */
208
        $fd = fopen("{$g['varetc_path']}/voucher.cfg", "w");
209
        if (!$fd) {
210
            printf("Error: cannot write voucher.cfg\n");
211
	    unlock($voucherlck);
212
            return 1;
213
        }
214
        chmod("{$g['varetc_path']}/voucher.cfg", 0600);
215
        fwrite($fd, "{$config['voucher']['rollbits']},{$config['voucher']['ticketbits']},{$config['voucher']['checksumbits']},{$config['voucher']['magic']},{$config['voucher']['charset']}\n");
216
        fclose($fd);
217
	unlock($voucherlck);
218

    
219
        if ($g['booting']) {
220

    
221
            // create active and used DB per roll on ramdisk from config
222
            $a_roll = &$config['voucher']['roll'];
223
	    $voucherlck = lock('voucher');
224

    
225
            foreach ($a_roll as $rollent) {
226

    
227
                $roll = $rollent['number'];
228
                voucher_write_used_db($roll, $rollent['used']);
229
                $minutes = $rollent['minutes'];
230
                $active_vouchers = array();
231
                $a_active = &$rollent['active'];
232
                if (is_array($a_active)) {
233
                    foreach ($a_active as $activent) {
234
                        $voucher = $activent['voucher'];
235
                        $timestamp = $activent['timestamp'];
236
                        $minutes = $activent['minutes'];
237
                        // its tempting to check for expired timestamps, but during
238
                        // bootup, we most likely don't have the correct time time.
239
                        $active_vouchers[$voucher] = "$timestamp,$minutes";
240
                    }
241
                }
242
                voucher_write_active_db($roll, $active_vouchers);
243
            }
244
		
245
	    unlock($voucherlck);
246
            echo "done\n";
247
        }
248
    }
249
    return 0;
250
}
251

    
252
/* write bitstring of used vouchers to ramdisk. 
253
 * Bitstring must already be base64_encoded!
254
 */
255
function voucher_write_used_db($roll, $vdb) {
256

    
257
    global $g;
258

    
259
    $fd = fopen("{$g['vardb_path']}/voucher_used_$roll.db", "w");
260
    if ($fd) {
261
        fwrite($fd, $vdb . "\n");
262
        fclose($fd);
263
    } else {
264
        voucher_log(LOG_ERR, "cant write {$g['vardb_path']}/voucher_used_$roll.db");
265
    }
266
}
267

    
268
/* return assoc array of active vouchers with activation timestamp
269
 * voucher is index. 
270
 */
271
function voucher_read_active_db($roll) {
272

    
273
    global $g;
274

    
275
    $active = array();
276
    $dirty = 0;
277
    $file = "{$g['vardb_path']}/voucher_active_$roll.db";
278
    if (file_exists($file)) {
279
        $fd = fopen($file, "r");
280
        if ($fd) {
281
            while (!feof($fd)) {
282
                $line = trim(fgets($fd));
283
                if ($line) {
284
                    list($voucher,$timestamp,$minutes) = explode(",", $line); // voucher,timestamp
285
                    if ((($timestamp + 60*$minutes) - time()) > 0) {
286
                        $active[$voucher] = "$timestamp,$minutes";
287
                    } else {
288
                        $dirty=1;
289
                    }
290
                }
291
            }
292
            fclose($fd);
293
            if ($dirty) // if we found expired entries, lets save our snapshot
294
                voucher_write_active_db($roll, $active);
295
        }
296
    }
297
    return $active;
298
}
299

    
300
/* store array of active vouchers back to DB */
301
function voucher_write_active_db($roll, $active) {
302

    
303
    global $g;
304

    
305
    $fd = fopen("{$g['vardb_path']}/voucher_active_$roll.db", "w");
306
    if ($fd) {
307
        foreach($active as $voucher => $value)
308
            fwrite($fd, "$voucher,$value\n");
309
        fclose($fd);
310
    }
311
}
312

    
313
/* return how many vouchers are marked used on a roll */
314
function voucher_used_count($roll) {
315

    
316
    global $g;
317

    
318
    $bitstring = voucher_read_used_db($roll);
319
    $max = strlen($bitstring) * 8;
320
    $used = 0;
321
    for ($i = 1; $i <= $max; $i++) {
322
        // check if ticket already used or not. 
323
        $pos = $i >> 3;            // divide by 8 -> octet
324
        $mask = 1 << (($i % 8)-1);  // mask to test bit in octet
325
        if (ord($bitstring[$pos]) & $mask)
326
            $used++;
327
    }   
328
    return $used;
329
}
330

    
331
function voucher_read_used_db($roll) {
332

    
333
    global $g;
334

    
335
    $vdb = "";
336
    $file = "{$g['vardb_path']}/voucher_used_$roll.db";
337
    if (file_exists($file)) {
338
        $fd = fopen($file, "r");
339
        if ($fd) {
340
            $vdb = trim(fgets($fd));
341
            fclose($fd);
342
        } else {
343
            voucher_log(LOG_ERR, "cant read {$g['vardb_path']}/voucher_used_$roll.db");
344
        }
345
    }
346
    return base64_decode($vdb);
347
}
348

    
349
function voucher_unlink_db($roll) {
350

    
351
    global $g;
352
    unlink("{$g['vardb_path']}/voucher_used_$roll.db");
353
    unlink("{$g['vardb_path']}/voucher_active_$roll.db");
354
}
355

    
356
/* we share the log with captiveportal for now */
357
function voucher_log($priority, $message) {
358

    
359
    define_syslog_variables();
360
    $message = trim($message);
361
    openlog("logportalauth", LOG_PID, LOG_LOCAL4);
362
    syslog($priority, "Voucher: " . $message);
363
    closelog();
364
}
365

    
366
/* Save active and used voucher DB into XML config and write it to flash
367
 * Called during reboot -> system_reboot_cleanup() and minicron
368
 */
369
function voucher_save_db_to_config() {
370

    
371
    global $config, $g, $dirtyfile;
372
    
373
    if (!isset($config['voucher']['enable']) || $config['voucher']['saveinterval'] == 0) 
374
        return;   // no vouchers or don't want to save DB's
375

    
376
    if (!file_exists($dirtyfile))
377
        return;     // nothing changed.
378

    
379
    $voucherlck = lock('voucher');
380

    
381
    // walk all active rolls and save runtime DB's to flash
382
    $a_roll = &$config['voucher']['roll'];
383
//    foreach ($a_roll as $rollent) {
384
    while (list($key, $value) = each($a_roll)) {
385
        $rollent = &$a_roll[$key];
386
        $roll = $rollent['number'];
387
        $bitmask = voucher_read_used_db($roll);
388
        $rollent['used'] = base64_encode($bitmask);
389
        $active_vouchers = voucher_read_active_db($roll);
390
        $db = array();
391
        foreach($active_vouchers as $voucher => $line) {
392
            list($timestamp,$minutes) = explode(",", $line);
393
            $activent['voucher'] = $voucher;
394
            $activent['timestamp'] = $timestamp;
395
            $activent['minutes'] = $minutes;
396
            $db[] = $activent;
397
        }
398
        $rollent['active'] = $db;
399
    }
400
    unlock($voucherlck);
401
    unlink($dirtyfile);
402
    write_config();
403
    return;
404
}
405

    
406
?>
(35-35/41)