aboutsummaryrefslogtreecommitdiffstats
path: root/phpBB/mcp.php
blob: e1f1b0662fcdf1417c8b9be451ed8a5655ae0e1e (plain)
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
<?php
/** 
*
* @package mcp
* @version $Id$
* @copyright (c) 2005 phpBB Group 
* @license http://opensource.org/licenses/gpl-license.php GNU Public License 
*
*/

/**
* @ignore
*/
define('IN_PHPBB', true);
$phpbb_root_path = './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.'.$phpEx);
include($phpbb_root_path . 'includes/functions_admin.'.$phpEx);
require($phpbb_root_path . 'includes/functions_module.'.$phpEx);

/**
*/

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup('mcp');

$module = new p_master();

// Basic parameter data
$id = request_var('i', '');

if (is_array($_REQUEST['mode']))
{
	list($mode, ) = each(request_var('mode', array('')));
}
else
{
	$mode = request_var('mode', '');
}

if (isset($_REQUEST['quick']))
{
	$mode = request_var('mode2', '');
	$action = '';
}

// Make sure we are using the correct module
if ($mode == 'approve' || $mode == 'disapprove')
{
	$id = 'queue';
}

// Only Moderators can go beyond this point
if (!$user->data['is_registered'])
{
	if ($user->data['is_bot'])
	{
		redirect("index.$phpEx$SID");
	}

	login_box('', $user->lang['LOGIN_EXPLAIN_MCP']);
}

$quickmod = (isset($_REQUEST['quickmod'])) ? true : false;
$action = request_var('action', '');
$action_ary = request_var('action', array('' => 0));

if (sizeof($action_ary))
{
	list($action, ) = each($action);
}
unset($action_ary);

if ($action == 'merge_select')
{
	$mode = 'forum_view';
}

// Topic view modes
if (in_array($mode, array('split', 'split_all', 'split_beyond', 'merge', 'merge_posts')))
{
	$_REQUEST['action'] = $action = $mode;
	$mode = 'topic_view';
	$quickmod = false;
}

// Forum view modes
if (in_array($mode, array('resync')))
{
	$_REQUEST['action'] = $action = $mode;
	$mode = 'forum_view';
	$quickmod = false;
}

if (!$quickmod)
{
	$post_id = request_var('p', 0);
	$topic_id = request_var('t', 0);
	$forum_id = request_var('f', 0);
	$user_id = request_var('u', 0);
	$username = request_var('username', '');


	if ($post_id)
	{
		// We determine the topic and forum id here, to make sure the moderator really has moderative rights on this post
		$sql = 'SELECT topic_id, forum_id
			FROM ' . POSTS_TABLE . "
			WHERE post_id = $post_id";
		$result = $db->sql_query($sql);
		$row = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		$topic_id = (int) $row['topic_id'];
		$forum_id = (int) $row['forum_id'];
	}

	if ($topic_id && !$forum_id)
	{
		$sql = 'SELECT forum_id
			FROM ' . TOPICS_TABLE . "
			WHERE topic_id = $topic_id";
		$result = $db->sql_query($sql);
		$row = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);

		$forum_id = (int) $row['forum_id'];
	}

	// If we do not have a forum id and the user is not a super moderator (global options are set to false, even if the user is able to moderator at least one forum
	if (!$forum_id && !$auth->acl_get('m_'))
	{
		$forum_list = get_forum_list('m_');

		if (!sizeof($forum_list))
		{
			trigger_error('MODULE_NOT_EXIST');
		}

		// We do not check all forums, only the first one should be sufficiant.
		$forum_id = $forum_list[0];
	}

	// Instantiate module system and generate list of available modules
	$module->list_modules('mcp');

	// Select the active module
	$module->set_active($id, $mode);

	// Hide some of the options if we don't have the relevant information to use them
	if (!$post_id)
	{
		$module->set_display('post_details', false);
		$module->set_display('post', false);
	}
	if (!$topic_id)
	{
		$module->set_display('topic_view', false);
	}
	if (!$forum_id)
	{
		$module->set_display('forum_view', false);
	}
	if (!$user_id && $username == '')
	{
		$module->set_display('user_notes', false);
	}

	// Load and execute the relevant module
	$module->load_active();

	// Assign data to the template engine for the list of modules
	$module->assign_tpl_vars("mcp.$phpEx$SID");

	// Generate the page
	page_header($user->lang['MCP_MAIN']);

	$template->set_filenames(array(
		'body' => $module->get_tpl_name())
	);

	page_footer();

}

switch ($mode)
{
	case 'lock':
	case 'unlock':
	case 'lock_post':
	case 'unlock_post':
		$module->load('mcp', 'main', $mode);
		break;
	case 'make_sticky':
	case 'make_announce':
	case 'make_global':
	case 'make_normal':
		$module->load('mcp', 'main', $mode);
		break;
	case 'fork':
	case 'move':
		$module->load('mcp', 'main', $mode);
		break;
	case 'delete_post':
	case 'delete_topic':
		$module->load('mcp', 'main', $mode);
		break;
	default:
		trigger_error("$mode not allowed as quickmod");
}

/**
* Functions used to generate additional URL paramters
*/
function _module_main_forum_view_url()
{
	return extra_url();
}

function _module_main_topic_view_url()
{
	return extra_url();
}

function _module_main_post_details_url()
{
	return extra_url();
}

function extra_url()
{
	global $forum_id, $topic_id, $post_id;
	$url_extra = '';
	$url_extra .= ($forum_id) ? "&amp;f=$forum_id" : '';
	$url_extra .= ($topic_id) ? "&amp;t=$topic_id" : '';
	$url_extra .= ($post_id) ? "&amp;p=$post_id" : '';
	return $url_extra;
}

/**
* Get simple topic data
*/
function get_topic_data($topic_ids, $acl_list = false)
{
	global $auth, $db;
	$rowset = array();

	if (implode(', ', $topic_ids) == '')
	{
		return array();
	}

	$sql = 'SELECT f.*, t.*
		FROM ' . TOPICS_TABLE . ' t
			LEFT JOIN ' . FORUMS_TABLE . ' f ON t.forum_id = f.forum_id
		WHERE t.topic_id IN (' . implode(', ', $topic_ids) . ')';
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		if ($acl_list && !$auth->acl_get($acl_list, $row['forum_id']))
		{
			continue;
		}

		$rowset[$row['topic_id']] = $row;
	}

	return $rowset;
}

/**
* Get simple post data
*/
function get_post_data($post_ids, $acl_list = false)
{
	global $db, $auth;
	$rowset = array();

	$sql = 'SELECT p.*, u.*, t.*, f.*
		FROM (' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u, ' . TOPICS_TABLE . ' t)
			LEFT JOIN ' . FORUMS_TABLE . ' f ON (f.forum_id = p.forum_id)
		WHERE p.post_id IN (' . implode(', ', $post_ids) . ')
			AND u.user_id = p.poster_id
			AND t.topic_id = p.topic_id';
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		if ($acl_list && !$auth->acl_get($acl_list, $row['forum_id']))
		{
			continue;
		}

		if (!$row['post_approved'] && !$auth->acl_get('m_approve', $row['forum_id']))
		{
			// Moderators without the permission to approve post should at least not see them. ;)
			continue;
		}

		$rowset[$row['post_id']] = $row;
	}

	return $rowset;
}

/**
* Get simple forum data
*/
function get_forum_data($forum_id, $acl_list = 'f_list')
{
	global $auth, $db;
	$rowset = array();

	$sql = 'SELECT *
		FROM ' . FORUMS_TABLE . '
		WHERE forum_id ' . ((is_array($forum_id)) ? 'IN (' . implode(', ', $forum_id) . ')' : "= $forum_id");
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		if ($acl_list && !$auth->acl_get($acl_list, $row['forum_id']))
		{
			continue;
		}
		if ($auth->acl_get('m_approve', $row['forum_id']))
		{
			$row['forum_topics'] = $row['forum_topics_real'];
		}

		$rowset[$row['forum_id']] = $row;
	}

	return $rowset;
}

/**
* sorting in mcp
*/
function mcp_sorting($mode, &$sort_days, &$sort_key, &$sort_dir, &$sort_by_sql, &$sort_order_sql, &$total, $forum_id = 0, $topic_id = 0, $where_sql = 'WHERE')
{
	global $db, $user, $auth, $template;

	$sort_days = request_var('sort_days', 0);
	$min_time = ($sort_days) ? time() - ($sort_days * 86400) : 0;

	switch ($mode)
	{
		case 'viewforum':
			$type = 'topics';
			$default_key = 't';
			$default_dir = 'd';
			$sql = 'SELECT COUNT(topic_id) AS total
				FROM ' . TOPICS_TABLE . "
				$where_sql forum_id = $forum_id
					AND topic_type NOT IN (" . POST_ANNOUNCE . ', ' . POST_GLOBAL . ")
					AND topic_last_post_time >= $min_time";

			if (!$auth->acl_get('m_approve', $forum_id))
			{
				$sql .= 'AND topic_approved = 1';
			}
			break;

		case 'viewtopic':
			$type = 'posts';
			$default_key = 't';
			$default_dir = 'a';
			$sql = 'SELECT COUNT(post_id) AS total
				FROM ' . POSTS_TABLE . "
				$where_sql topic_id = $topic_id
					AND post_time >= $min_time";
			if (!$auth->acl_get('m_approve', $forum_id))
			{
				$sql .= 'AND post_approved = 1';
			}
			break;

		case 'unapproved_posts':
			$type = 'posts';
			$default_key = 't';
			$default_dir = 'd';
			$sql = 'SELECT COUNT(post_id) AS total
				FROM ' . POSTS_TABLE . "
				$where_sql forum_id IN (" . (($forum_id) ? $forum_id : implode(', ', get_forum_list('m_approve'))) . ')
					AND post_approved = 0
					AND post_time >= ' . $min_time;
			break;

		case 'unapproved_topics':
			$type = 'topics';
			$default_key = 't';
			$default_dir = 'd';
			$sql = 'SELECT COUNT(topic_id) AS total
				FROM ' . TOPICS_TABLE . "
				$where_sql forum_id IN (" . (($forum_id) ? $forum_id : implode(', ', get_forum_list('m_approve'))) . ')
					AND topic_approved = 0
					AND topic_time >= ' . $min_time;
			break;

		case 'reports':
			$type = 'reports';
			$default_key = 'p';
			$default_dir = 'd';
			$limit_time_sql = ($min_time) ? "AND r.report_time >= $min_time" : '';

			if ($topic_id)
			{
				$where_sql .= ' p.topic_id = ' . $topic_id;
			}
			else if ($forum_id)
			{
				$where_sql .= ' p.forum_id = ' . $forum_id;
			}
			else
			{
				$where_sql .= ' p.forum_id IN (' . implode(', ', get_forum_list('m_')) . ')';
			}
			$sql = 'SELECT COUNT(r.report_id) AS total
				FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . " p
				$where_sql
					AND p.post_id = r.post_id
					$limit_time_sql";
			break;

		case 'viewlogs':
			$type = 'logs';
			$default_key = 't';
			$default_dir = 'd';
			$sql = 'SELECT COUNT(log_id) AS total
				FROM ' . LOG_TABLE . "
				$where_sql forum_id IN (" . (($forum_id) ? $forum_id : implode(', ', get_forum_list('m_'))) . ')
					AND log_time >= ' . $min_time . '
					AND log_type = ' . LOG_MOD;
			break;
	}

	$sort_key = request_var('sk', $default_key);
	$sort_dir = request_var('sd', $default_dir);
	$sort_dir_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);

	switch ($type)
	{
		case 'topics':
			$limit_days = array(0 => $user->lang['ALL_TOPICS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 364 => $user->lang['1_YEAR']);
			$sort_by_text = array('a' => $user->lang['AUTHOR'], 't' => $user->lang['POST_TIME'], 'tt' => $user->lang['TOPIC_TIME'], 'r' => $user->lang['REPLIES'], 's' => $user->lang['SUBJECT'], 'v' => $user->lang['VIEWS']);

			$sort_by_sql = array('a' => 't.topic_first_poster_name', 't' => 't.topic_last_post_time', 'tt' => 't.topic_time', 'r' => (($auth->acl_get('m_approve', $forum_id)) ? 't.topic_replies_real' : 't.topic_replies'), 's' => 't.topic_title', 'v' => 't.topic_views');
			$limit_time_sql = ($min_time) ? "AND t.topic_last_post_time >= $min_time" : '';
			break;

		case 'posts':
			$limit_days = array(0 => $user->lang['ALL_POSTS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 364 => $user->lang['1_YEAR']);
			$sort_by_text = array('a' => $user->lang['AUTHOR'], 't' => $user->lang['POST_TIME'], 's' => $user->lang['SUBJECT']);
			$sort_by_sql = array('a' => 'u.username', 't' => 'p.post_id', 's' => 'p.post_subject');
			$limit_time_sql = ($min_time) ? "AND p.post_time >= $min_time" : '';
			break;

		case 'reports':
			$limit_days = array(0 => $user->lang['ALL_REPORTS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 364 => $user->lang['1_YEAR']);
			$sort_by_text = array('p' => $user->lang['REPORT_PRIORITY'], 'r' => $user->lang['REPORTER'], 't' => $user->lang['REPORT_TIME']);
			$sort_by_sql = array('p' => 'rr.reason_priority', 'r' => 'u.username', 't' => 'r.report_time');
			break;

		case 'logs':
			$limit_days = array(0 => $user->lang['ALL_ENTRIES'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 364 => $user->lang['1_YEAR']);
			$sort_by_text = array('u' => $user->lang['SORT_USERNAME'], 't' => $user->lang['SORT_DATE'], 'i' => $user->lang['SORT_IP'], 'o' => $user->lang['SORT_ACTION']);

			$sort_by_sql = array('u' => 'l.user_id', 't' => 'l.log_time', 'i' => 'l.log_ip', 'o' => 'l.log_operation');
			$limit_time_sql = ($min_time) ? "AND l.log_time >= $min_time" : '';
			break;
	}

	$sort_order_sql = $sort_by_sql[$sort_key] . ' ' . (($sort_dir == 'd') ? 'DESC' : 'ASC');

	$s_limit_days = $s_sort_key = $s_sort_dir = $sort_url = '';
	gen_sort_selects($limit_days, $sort_by_text, $sort_days, $sort_key, $sort_dir, $s_limit_days, $s_sort_key, $s_sort_dir, $sort_url);

	$template->assign_vars(array(
		'S_SELECT_SORT_DIR'	=>	$s_sort_dir,
		'S_SELECT_SORT_KEY' =>	$s_sort_key,
		'S_SELECT_SORT_DAYS'=>	$s_limit_days)
	);

	if (($sort_days && $mode != 'viewlogs') || $mode == 'reports' || $where_sql != 'WHERE')
	{
		$result = $db->sql_query($sql);
		$total = ($row = $db->sql_fetchrow($result)) ? $row['total'] : 0;
	}
	else
	{
		$total = -1;
	}
}

/**
* Validate ids
*/
function check_ids(&$ids, $table, $sql_id, $acl_list = false)
{
	global $db, $auth;

	if (!is_array($ids) || !$ids)
	{
		return 0;
	}

	// a small logical error, since global announcement are assigned to forum_id == 0
	// If the first topic id is a global announcement, we can force the forum. Though only global announcements can be
	// tricked... i really do not know how to prevent this atm.

	// With those two queries we make sure all ids are within one forum...
	$sql = "SELECT forum_id FROM $table
		WHERE $sql_id = {$ids[0]}";
	$result = $db->sql_query($sql);
	$forum_id = (int) $db->sql_fetchfield('forum_id', 0, $result);
	$db->sql_freeresult($result);

	if (!$forum_id)
	{
		// Global Announcement?
		$forum_id = request_var('f', 0);
	}

	if ($acl_list && !$auth->acl_get($acl_list, $forum_id))
	{
		trigger_error('NOT_AUTHORIZED');
	}

	if (!$forum_id)
	{
		trigger_error('Missing forum_id, has to be in url if global announcement...');
	}

	$sql = "SELECT $sql_id FROM $table
		WHERE $sql_id IN (" . implode(', ', $ids) . ")
			AND (forum_id = $forum_id OR forum_id = 0)";
	$result = $db->sql_query($sql);

	$ids = array();
	while ($row = $db->sql_fetchrow($result))
	{
		$ids[] = $row[$sql_id];
	}
	$db->sql_freeresult($result);

	return $forum_id;
}

// LITTLE HELPER
//

?>
s="hl opt">)), ) : (), }; } @l = sort { $a->{host} <=> $b->{host} || $a->{channel} <=> $b->{channel} || $a->{id} <=> $b->{id} || $a->{lun} <=> $b->{lun} } @l; complete_usb_storage_info(@l); foreach (@l) { $_->{media_type} = 'fd' if $_->{media_type} eq 'hd' && isFloppyUsb($_); } get_sys_cdrom_info(@l); get_scsi_driver(@l); @l; } my %hd_vendors = ( "ASUS" => "Asus", "ATA Maxtor" => "Maxtor", "CD-ROM CDU" => "Sony", "CD-ROM Drive/F5D" => "ASUSTeK", "Compaq" => "Compaq", "CONNER" => "Conner Peripherals", "IBM" => "IBM", "FUJITSU" => "Fujitsu", "HITACHI" => "Hitachi", "Lite-On" => "Lite-On Technology Corp.", "LITE-ON" => "Lite-On Technology Corp.", "LTN" => "Lite-On Technology Corp.", "IOMEGA" => "Iomega", "MAXTOR" => "Maxtor", "Maxtor" => "Maxtor", "Micropolis" => "Micropolis", "Pioneer" => "Pioneer", "PLEXTOR" => "Plextor", "QUANTUM" => "Quantum", "SAMSUNG" => "Samsung", "Seagate " => "Seagate Technology", "ST3" => "Seagate Technology", "TEAC" => "Teac", "TOSHIBA" => "Toshiba", "WDC" => "Western Digital Corp.", ); # return ($vendor, $model) sub _get_hd_vendor { my ($info) = @_; foreach my $name (keys %hd_vendors) { next if !$name; return ($hd_vendors{$name}, $2) if $info =~ /^$name(-|\s)*(.*)/; } return ("Hitachi", $info) if $info =~ /^HD[ST][0-9]/; } sub getIDE() { my @idi; #- what about a system with absolutely no IDE on it, like some sparc machine. -e "/proc/ide" or return (); #- Great. 2.2 kernel, things are much easier and less error prone. foreach my $d (sort @{[glob_('/proc/ide/hd*')]}) { my $t = chomp_(cat_("$d/media")); my $type = ${{ disk => 'hd', cdrom => 'cdrom', tape => 'tape', floppy => 'fd' }}{$t} or next; my $info = chomp_(cat_("$d/model")) || "(none)"; my $num = ord(($d =~ /(.)$/)[0]) - ord 'a'; my ($vendor, $model) = _get_hd_vendor($info); my $host = $num; ($host, my $id) = divide($host, 2); ($host, my $channel) = divide($host, 2); push @idi, { media_type => $type, device => basename($d), info => $info, host => $host, channel => $channel, id => $id, bus => 'ide', if_($vendor, Vendor => $vendor), if_($model, Model => $model) }; } get_sys_cdrom_info(@idi); @idi; } sub block_devices() { -d '/sys/block' ? map { s|!|/|; $_ } all('/sys/block') : map { $_->{dev} } do { require fs::proc_partitions; fs::proc_partitions::read_raw() }; } sub getCompaqSmartArray() { my (@idi, $f); foreach ('array/ida', 'cpqarray/ida', 'cciss/cciss') { my $prefix = "/proc/driver/$_"; my ($name) = m|/(.*)|; for (my $i = 0; -r ($f = "${prefix}$i"); $i++) { my @raw_devices = cat_($f) =~ m|^\s*($name/.*?):|gm; #- this is ugly and buggy. keeping it for 2007.0 #- on a cciss, cciss/cciss0 didn't contain c0d0, but cciss/cciss1 did contain c0d1 #- the line below adds both c0d0 and c0d1 for cciss0, and so some duplicates @raw_devices or @raw_devices = grep { m!^$name/! } block_devices(); foreach my $raw_device (@raw_devices) { my $device = -d "/dev/$raw_device" ? "$raw_device/disc" : $raw_device; push @idi, { device => $device, prefix => $raw_device . 'p', info => "Compaq RAID logical disk", media_type => 'hd', bus => $name }; } } } #- workaround the buggy code above. this should be safe though uniq_ { $_->{device} } @idi; } sub getDAC960() { my %idi; #- We are looking for lines of this format:DAC960#0: #- /dev/rd/c0d0: RAID-7, Online, 17928192 blocks, Write Thru0123456790123456789012 foreach (syslog()) { my ($device, $info) = m|/dev/(rd/.*?): (.*?),| or next; $idi{$device} = { info => $info, media_type => 'hd', device => $device, bus => 'dac960' }; } values %idi; } sub getATARAID() { my %l; foreach (syslog()) { my ($device) = m|^\s*(ataraid/d\d+):| or next; $l{$device} = { info => 'ATARAID block device', media_type => 'hd', device => $device, bus => 'ataraid' }; log::l("ATARAID: $device"); } values %l; } sub getXenBlk() { -d '/sys/bus/xen/devices' or return; map { s/block://; { device => basename($_), info => "Xen block device", media_type => 'hd', bus => 'xen' }; } glob("/sys/block/xvd*"); } sub getVirtIO() { -d '/sys/bus/virtio/devices' or return; map { { device => basename($_), info => "VirtIO block device", media_type => 'hd', bus => 'virtio' }; } glob("/sys/bus/virtio/devices/*/block/*"); } sub getMmcBlk() { -d '/sys/bus/mmc/devices' or return; map { { device => basename($_), info => "MMC block device", media_type => 'hd', bus => 'mmc' }; } glob("/sys/bus/mmc/devices/*/block/*"); } # cpu_name : arch() =~ /^alpha/ ? "cpu " : # arch() =~ /^ppc/ ? "processor" : "vendor_id" # cpu_model : arch() =~ /^alpha/ ? "cpu model" : # arch() =~ /^ppc/ ? "cpu " : "model name" # cpu_freq = arch() =~ /^alpha/ ? "cycle frequency [Hz]" : # arch() =~ /^ppc/ ? "clock" : "cpu MHz" sub getCPUs() { my (@cpus, $cpu); foreach (cat_("/proc/cpuinfo")) { if (/^processor/) { # ix86 specific push @cpus, $cpu if $cpu; $cpu = {}; } $cpu->{$1} = $2 if /^([^\t]+).*:\s(.*)$/; $cpu->{processor}++ if $1 eq "processor"; } push @cpus, $cpu; @cpus; } sub ix86_cpu_frequency() { cat_('/proc/cpuinfo') =~ /cpu MHz\s*:\s*(\d+)/ && $1; } sub probe_category { my ($category) = @_; require list_modules; my @modules = list_modules::category2modules($category); if_($category =~ /sound/ && arch() =~ /ppc/ && get_mac_model() !~ /IBM/, { driver => 'snd_powermac', description => 'Macintosh built-in' }, ), grep { if ($category eq 'network/isdn') { my $b = $_->{driver} =~ /ISDN:([^,]*),?([^,]*)(?:,firmware=(.*))?/; if ($b) { $_->{driver} = $1; $_->{type} = $2; $_->{type} =~ s/type=//; $_->{firmware} = $3; $_->{driver} eq "hisax" and $_->{options} .= " id=HiSax"; } $b; } else { member($_->{driver}, @modules); } } probeall(); } sub getSoundDevices() { probe_category('multimedia/sound'); } sub isTVcardConfigurable { member($_[0]{driver}, qw(bttv cx88 saa7134)) } sub getTVcards() { probe_category('multimedia/tv') } sub getInputDevices() { my (@devices, $device); my $event; foreach (cat_('/proc/bus/input/devices')) { if (/^I:/) { $device = {}; $device->{vendor} = /Vendor=(\w+)/ && $1; $device->{id} = /Product=(\w+)/ && $1; $device->{bustype} = /Bus=(\w+)/ && $1; } elsif (/N: Name="(.*)"/) { my $descr = $1; $device->{description} = "|$descr"; #- I: Bus=0011 Vendor=0002 Product=0008 Version=7321 #- N: Name="AlpsPS/2 ALPS GlidePoint" #- P: Phys=isa0060/serio1/input0 #- H: Handlers=mouse1 event2 ts1 #- B: EV=f #- B: KEY=420 0 70000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE BTN_TOOL_FINGER BTN_TOUCH #- or B: KEY=420 0 670000 0 0 0 0 0 0 0 0 #=> same with BTN_BACK #- B: REL=3 #=> X Y #- B: ABS=1000003 #=> X Y PRESSURE #- I: Bus=0011 Vendor=0002 Product=0008 Version=2222 #- N: Name="AlpsPS/2 ALPS DualPoint TouchPad" #- P: Phys=isa0060/serio1/input0 #- S: Sysfs=/class/input/input2 #- H: Handlers=mouse1 ts1 event2 #- B: EV=f #- B: KEY=420 0 70000 0 0 0 0 0 0 0 0 #- B: REL=3 #- B: ABS=1000003 #- I: Bus=0011 Vendor=0002 Product=0007 Version=0000 #- N: Name="SynPS/2 Synaptics TouchPad" #- P: Phys=isa0060/serio1/input0 #- S: Sysfs=/class/input/input1 #- H: Handlers=mouse0 event1 ts0 #- B: EV=b #- B: KEY=6420 0 70000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE BTN_TOOL_FINGER BTN_TOUCH BTN_TOOL_DOUBLETAP BTN_TOOL_TRIPLETAP #- or B: KEY=6420 0 670000 0 0 0 0 0 0 0 0 #=> same with BTN_BACK #- or B: KEY=420 30000 670000 0 0 0 0 0 0 0 0 #=> same without BTN_TOOL_TRIPLETAP but with BTN_B #- B: ABS=11000003 #=> X Y PRESSURE TOOL_WIDTH #- I: Bus=0003 Vendor=056a Product=0065 Version=0108 #- N: Name="Wacom Bamboo" #- B: KEY=1c63 0 70033 0 0 0 0 0 0 0 0 #=> BTN_0 BTN_1 BTN_4 BTN_5 BTN_LEFT BTN_RIGHT BTN_MIDDLE TOOL_PEN TOOL_RUBBER TOOL_BRUSH TOOL_FINGER TOOL_MOUSE TOUCH STYLUS STYLUS2 #- B: ABS=100 3000103 #=> X Y WHEEL PRESSURE DISTANCE MISC #- I: Bus=0003 Vendor=056a Product=0011 Version=0201 #- N: Name="Wacom Graphire2 4x5" #- B: KEY=1c43 0 70000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE TOOL_PEN TOOL_RUBBER TOOL_FINGER TOOL_MOUSE TOUCH STYLUS STYLUS2 #- B: ABS=100 3000003 #=> X Y PRESSURE DISTANCE MISC #I: Bus=0003 Vendor=049f Product=0024 Version=0001 #N: Name="Compaq Compaq Numeric Keypad" #P: Phys=usb-0000:00:03.2-2/input0 #S: Sysfs=/class/input/input7 #H: Handlers=kbd event3 #B: EV=120003 #B: KEY=10000 7 ff800000 7ff febeffdf ffefffff ffffffff fffffffe #B: LED=1f $device->{Synaptics} = $descr eq 'SynPS/2 Synaptics TouchPad'; $device->{ALPS} = $descr =~ m!^AlpsPS/2 ALPS!; $device->{Elantech} = $descr eq 'ETPS/2 Elantech Touchpad'; $device->{Numpad} = $descr =~ /Numeric Keypad/; } elsif (/H: Handlers=(.*)/) { my @l = split(' ', $1); $device->{driver} = $l[0]; #- keep it for compatibility $device->{Handlers} = +{ map { (/^(.*?)\d*$/ ? $1 : $_, $_) } split(' ', $1) }; $event = $device->{Handlers}{event}; } elsif (/S: Sysfs=(.+)/) { $device->{sysfs_path} = $1; } elsif (/P: Phys=(.*)/) { $device->{location} = $1; $device->{bus} = 'isa' if $device->{location} =~ /^isa/; $device->{bus} = 'usb' if $device->{location} =~ /^usb/i; } elsif (/B: REL=(.* )?(.*)/) { #- REL=3 #=> X Y #- REL=103 #=> X Y WHEEL #- REL=143 #=> X Y HWHEEL WHEEL #- REL=1c3 #=> X Y HWHEEL DIAL WHEEL my $REL = hex($2); $device->{HWHEEL} = 1 if $REL & (1 << 6); $device->{WHEEL} = 1 if $REL & (1 << 8); #- not reliable ("Mitsumi Apple USB Mouse" says REL=103 and KEY=1f0000 ...) } elsif (/B: KEY=(\S+)/) { #- some KEY explained: #- (but note that BTN_MIDDLE can be reported even if missing) #- (and "Mitsumi Apple USB Mouse" reports 1f0000) #- KEY=30000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT #- KEY=70000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE #- KEY=1f0000 0 0 0 0 0 0 0 0 #=> BTN_LEFT BTN_RIGHT BTN_MIDDLE BTN_SIDE BTN_EXTRA if (!$> && ! -f "/dev/input/$event") { devices::make("/dev/input/$event"); } if (-r "/dev/input/$event") { my @KEYS = c::EVIocGBitKey("/dev/input/$event"); $device->{SIDE} = 1 if $KEYS[0] & (1 << 0x13); } else { my $KEY = hex($1); $device->{SIDE} = 1 if $KEY & (1 << 0x13); } } elsif (/^\s*$/) { push @devices, $device if $device; undef $device; } } @devices; } sub getInputDevices_and_usb() { my @l = getInputDevices(); foreach my $usb (usb_probe()) { if (my $e = find { hex($_->{vendor}) == $usb->{vendor} && hex($_->{id}) == $usb->{id} } @l) { $e->{usb} = $usb; } } @l; } sub serialPorts() { map { "ttyS$_" } 0..7 } sub serialPort2text { $_[0] =~ /ttyS(\d+)/ ? "$_[0] / COM" . ($1 + 1) : $_[0]; } sub getSerialModem { my ($modules_conf, $o_mouse) = @_; my $mouse = $o_mouse || {}; $mouse->{device} = readlink "/dev/mouse"; my $serdev = arch() =~ /ppc/ ? "macserial" : arch() =~ /mips/ ? "8250" : "serial"; eval { modules::load($serdev) }; my @modems; probeSerialDevices(); foreach my $port (serialPorts()) { next if $mouse->{device} =~ /$port/; my $device = "/dev/$port"; next if !-e $device || !hasModem($device); $serialprobe{$device}{device} = $device; push @modems, $serialprobe{$device}; } my @devs = pcmcia_probe(); foreach my $modem (@modems) { #- add an alias for macserial on PPC $modules_conf->set_alias('serial', $serdev) if arch() =~ /ppc/ && $modem->{device}; foreach (@devs) { $_->{device} and $modem->{device} = $_->{device} } } @modems; } our $detect_serial_modem = 1; sub getModem { my ($modules_conf) = @_; ($detect_serial_modem ? getSerialModem($modules_conf, {}) : ()), get_winmodems(); } sub get_winmodems() { matching_driver__regexp('www\.linmodems\.org'), matching_driver(list_modules::category2modules('network/modem'), list_modules::category2modules('network/slmodem')); } sub getBewan() { matching_desc__regexp('Bewan Systems\|.*ADSL|BEWAN ADSL USB|\[Unicorn\]'); } # generate from the following from eci driver sources: # perl -e 'while (<>) { print qq("$1$2",\n"$3$4",\n) if /\b([a-z\d]*)\s*([a-z\d]*)\s*([a-z\d]*)\s*([a-z\d]*)$/ }' <modems.db|sort|uniq sub getECI() { my @ids = ( "05090801", "05472131", "06590915", "071dac81", "08ea00c9", "09150001", "09150002", "091500ca", "091500e7", "09150101", "09150102", "09150204", "09150206", "09150802", "09150916", "09158000", "09158001", "0915ac82", "0baf00e6", "0e600100", "0e600101", "0fe88000", "16900203", "16900205", ); grep { member(sprintf("%04x%04x%04x%04x", $_->{vendor}, $_->{id}, $_->{subvendor}, $_->{subid}), @ids) } usb_probe(); } sub get_xdsl_usb_devices() { my @bewan = detect_devices::getBewan(); $_->{driver} = $_->{bus} eq 'USB' ? 'unicorn_usb_atm' : 'unicorn_pci_atm' foreach @bewan; my @eci = detect_devices::getECI(); $_->{driver} = 'eciusb' foreach @eci; my @usb = detect_devices::probe_category('network/usb_dsl'); $_->{description} = "USB ADSL modem (eagle chipset)" foreach grep { $_->{driver} eq 'ueagle_atm' && $_->{description} eq '(null)' } @usb; @usb, @bewan, @eci; } sub is_lan_interface { #- we want LAN like interfaces here (eg: ath|br|eth|fddi|plip|ra|tr|usb|wlan). #- there's also bnep%d for bluetooth, bcp%d... #- we do this by blacklisting the following interfaces: #- hso%d are created by drivers/net/usb/hso.c #- ippp|isdn|plip|ppp (initscripts suggest that isdn%d can be created but kernel sources claim not) #- ippp%d are created by drivers/isdn/i4l/isdn_ppp.c #- plip%d are created by drivers/net/plip.c #- ppp%d are created by drivers/net/ppp_generic.c #- pan%d are created by bnep is_useful_interface($_[0]) && $_[0] !~ /^(?:hso|ippp|isdn|plip|ppp|pan)/; } sub is_useful_interface { #- sit0 which is *always* created by net/ipv6/sit.c, thus is always created since net.agent loads ipv6 module #- wifi%d are created by 3rdparty/hostap/hostap_hw.c (pseudo statistics devices, #14523) #- wmaster%d are created by net/mac80211/ieee80211.c ("master" 802.11 device) #- ax*, rose*, nr*, bce* and scc* are Hamradio devices (#28776) $_[0] !~ /^(?:lo|sit0|wifi|wmaster|ax|rose|nr|bce|scc)/; } sub is_wireless_interface { my ($interface) = @_; #- some wireless drivers don't always support the SIOCGIWNAME ioctl #- ralink devices need to be up to support it #- wlan-ng (prism2_*) need some special tweaks to support it #- use sysfs as fallback to detect wireless interfaces, #- i.e interfaces for which get_wireless_stats() is available c::isNetDeviceWirelessAware($interface) || -e "/sys/class/net/$interface/wireless" || -e "/sys/class/net/$interface/phy80211"; } sub get_all_net_devices() { #- we need both detection schemes since: #- get_netdevices() use the SIOCGIFCONF ioctl that does not list interfaces that are down #- /proc/net/dev does not list VLAN and IP aliased interfaces uniq( (map { if_(/^\s*([A-Za-z0-9:\.]*):/, $1) } cat_("/proc/net/dev")), c::get_netdevices(), ); } sub get_lan_interfaces() { grep { is_lan_interface($_) } get_all_net_devices() } sub get_net_interfaces() { grep { is_useful_interface($_) } get_all_net_devices() } sub get_wireless_interface() { find { is_wireless_interface($_) } get_lan_interfaces() } sub is_bridge_interface { my ($interface) = @_; -f "/sys/class/net/$interface/bridge/bridge_id"; } sub get_ids_from_sysfs_device { my ($dev_path) = @_; my $dev_cat = sub { chomp_(cat_("$dev_path/$_[0]")) }; my $usb_root = -f "$dev_path/bInterfaceNumber" && "../" || -f "$dev_path/idVendor" && ""; my $is_pcmcia = -f "$dev_path/card_id"; my $sysfs_ids; my $bus = get_sysfs_field_from_link($dev_path, "subsystem"); #- FIXME: use $bus if ($is_pcmcia) { $sysfs_ids = { modalias => $dev_cat->('modalias') }; } else { $sysfs_ids = $bus eq 'ieee1394' ? { version => "../vendor_id", specifier_id => "specifier_id", specifier_version => "version", } : defined $usb_root ? { id => $usb_root . 'idProduct', vendor => $usb_root . 'idVendor' } : { id => "device", subid => "subsystem_device", vendor => "vendor", subvendor => "subsystem_vendor" }; $_ = hex($dev_cat->($_)) foreach values %$sysfs_ids; if ($bus eq 'pci') { my $device = basename(readlink $dev_path); my @ids = $device =~ /^(.{4}):(.{2}):(.{2})\.(.+)$/; @$sysfs_ids{qw(pci_domain pci_bus pci_device pci_function)} = map { hex($_) } @ids if @ids; } } $sysfs_ids; } sub device_matches_sysfs_ids { my ($device, $sysfs_ids) = @_; every { defined $device->{$_} && member($device->{$_}, $sysfs_ids->{$_}, 0xffff) } keys %$sysfs_ids; } sub device_matches_sysfs_device { my ($device, $dev_path) = @_; device_matches_sysfs_ids($device, get_ids_from_sysfs_device($dev_path)); } sub getUPS() { # MGE serial PnP devices: (map { $_->{port} = $_->{DEVICE}; $_->{bus} = "Serial"; $_->{driver} = "mge-utalk" if $_->{MODEL} =~ /0001/; $_->{driver} = "mge-shut" if $_->{MODEL} =~ /0002/; $_->{media_type} = 'UPS'; $_->{description} = "MGE UPS SYSTEMS|UPS - Uninterruptible Power Supply" if $_->{MODEL} =~ /000[12]/; $_; } grep { $_->{DESCRIPTION} =~ /MGE UPS/ } values %serialprobe), # USB UPSs; (map { ($_->{name} = $_->{description}) =~ s/.*\|//; $_ } map { if ($_->{description} =~ /^American Power Conversion\|Back-UPS/ && $_->{driver} eq 'usbhid') { #- FIXME: should not be hardcoded, use $_->{sysfs_device} . */usb:(hiddev\d+) #- the device should also be assigned to the ups user $_->{port} = "/dev/hiddev0"; $_->{driver} = 'hidups'; $_; } elsif ($_->{description} =~ /^MGE UPS Systems\|/ && $_->{driver} =~ /ups$/) { $_->{port} = "auto"; $_->{media_type} = 'UPS'; $_->{driver} = 'newhidups'; $_; } else { (); } } usb_probe()); } $pcitable_addons = <<'EOF'; # add here lines conforming the pcitable format (0xXXXX\t0xXXXX\t"\w+"\t".*") EOF $usbtable_addons = <<'EOF'; # add here lines conforming the usbtable format (0xXXXX\t0xXXXX\t"\w+"\t".*") EOF sub install_addons { my ($prefix) = @_; #- this test means install_addons can only be called after ldetect-lst has been installed. if (-d "$prefix/usr/share/ldetect-lst") { my $update = 0; foreach ([ 'pcitable.d', $pcitable_addons ], [ 'usbtable.d', $usbtable_addons ]) { my ($dir, $str) = @$_; -d "$prefix/usr/share/ldetect-lst/$dir" && $str =~ /^[^#]/m and $update = 1 and output "$prefix/usr/share/ldetect-lst/$dir/95drakx.lst", $str; } $update and run_program::rooted($prefix, "/usr/sbin/update-ldetect-lst"); } } sub add_addons { my ($addons, @l) = @_; foreach (split "\n", $addons) { /^\s/ and die qq(bad detect_devices::probeall_addons line "$_"); s/^#.*//; s/"(.*?)"/$1/g; next if /^$/; my ($vendor, $id, $driver, $description) = split("\t", $_, 4) or die qq(bad detect_devices::probeall_addons line "$_"); foreach (@l) { $_->{vendor} == hex $vendor && $_->{id} == hex $id or next; put_in_hash($_, { driver => $driver, description => $description }); } } @l; } sub get_pci_sysfs_path { my ($l) = @_; sprintf('%04x:%02x:%02x.%d', $l->{pci_domain}, $l->{pci_bus}, $l->{pci_device}, $l->{pci_function}); } my (@pci, @usb); sub pci_probe__real() { add_addons($pcitable_addons, map { my $l = $_; $l->{bus} = 'PCI'; $l->{sysfs_device} = '/sys/bus/pci/devices/' . get_pci_sysfs_path($l); $l; } c::pci_probe()); } sub pci_probe() { state $done; if (!$done) { @pci = pci_probe__real() if !@pci; foreach (@pci) { $_->{nice_bus} = $_->{is_pciexpress} ? "PCI Express" : "PCI"; } } @pci; } sub usb_probe__real() { -e "/sys/kernel/debug/usb/devices" or return; add_addons($usbtable_addons, map { my $l = $_; $l->{media_type} = join('|', grep { $_ ne '(null)' } split('\|', $l->{media_type})); $l->{sysfs_device} = "/sys/bus/usb/devices/$l->{pci_bus}-" . ($l->{usb_port} + 1); $l->{bus} = 'USB'; $l; } c::usb_probe()); } sub usb_probe() { if ($::isStandalone && @usb) { @usb; } else { @usb = usb_probe__real(); } } sub firewire_probe() { my $dev_dir = '/sys/bus/ieee1394/devices'; my @l = map { my $dir = "$dev_dir/$_"; my $get = sub { chomp_(cat_($_[0])) }; { version => hex($get->("$dir/../vendor_id")), specifier_id => hex($get->("$dir/specifier_id")), specifier_version => hex($get->("$dir/version")), bus => 'Firewire', sysfs_device => $dir, }; } grep { -f "$dev_dir/$_/specifier_id" } all($dev_dir); my $e; foreach (cat_('/proc/bus/ieee1394/devices')) { if (m!Vendor/Model ID: (.*) \[(\w+)\] / (.*) \[(\w+)\]!) { push @l, $e = { vendor => hex($2), id => hex($4), description => join('|', $1, $3), bus => 'Firewire', }; } elsif (/Software Specifier ID: (\w+)/) { $e->{specifier_id} = hex $1; } elsif (/Software Version: (\w+)/) { $e->{specifier_version} = hex $1; } } foreach (@l) { if ($_->{specifier_id} == 0x00609e && $_->{specifier_version} == 0x010483) { add2hash($_, { driver => 'sbp2', description => "Generic Firewire Storage Controller" }); } elsif ($_->{specifier_id} == 0x00005e && $_->{specifier_version} == 0x000001) { add2hash($_, { driver => 'eth1394', description => "IEEE 1394 IPv4 Driver (IPv4-over-1394 as per RFC 2734)" }); } } @l; } sub pcmcia_controller_probe() { my ($controller) = probe_category('bus/pcmcia'); if (!$controller && !$::testing && !$::noauto && arch() =~ /i.86/) { my $driver = c::pcmcia_probe(); $controller = { driver => $driver, description => "PCMCIA controller ($driver)" } if $driver; } $controller; } sub pcmcia_probe() { require modalias; require modules; my $dev_dir = '/sys/bus/pcmcia/devices'; map { my $dir = "$dev_dir/$_"; my $get = sub { chomp_(cat_("$dir/$_[0]")) }; my $class_dev = first(glob_("$dir/tty/tty*")); my $device = $class_dev && basename($class_dev); my $modalias = $get->('modalias'); my $driver = get_sysfs_field_from_link($dir, 'driver'); #- fallback on modalias result #- but only if the module isn't loaded yet (else, it would already be binded) #- this prevents from guessing the wrong driver for multi-function devices my $module = $modalias && first(modalias::get_modules($modalias)); $driver ||= !member($module, modules::loaded_modules()) && $module; { description => join(' ', grep { $_ } map { $get->("prod_id$_") } 1 .. 4), driver => $driver, if_($modalias, modalias => $modalias), if_($device, device => $device), bus => 'PCMCIA', sysfs_device => $dir, }; } all($dev_dir); } sub dmi_probe() { state $dmi_probe; if (arch() !~ /86/) { return []; } $dmi_probe ||= $> ? [] : [ c::dmi_probe() ]; @$dmi_probe; } # pcmcia_probe provides field "device", used in network.pm sub probeall() { return if $::noauto; pci_probe(), usb_probe(), firewire_probe(), pcmcia_probe(), dmi_probe(), getInputDevices_and_usb(); } sub probeall_update_cache() { return if $::noauto; @pci = pci_probe__real(), @usb = usb_probe__real(), firewire_probe(), pcmcia_probe(), dmi_probe(); } sub matching_desc__regexp { my ($regexp) = @_; grep { $_->{description} =~ /$regexp/i } probeall(); } sub matching_driver__regexp { my ($regexp) = @_; grep { $_->{driver} =~ /$regexp/i } probeall(); } sub matching_driver { my (@list) = @_; grep { member($_->{driver}, @list) } probeall(); } sub probe_name { my ($name) = @_; map { $_->{driver} =~ /^$name:(.*)/ } probeall(); } sub probe_unique_name { my ($name) = @_; my @l = uniq(probe_name($name)); if (@l > 1) { log::l("oops, more than one $name from probe: ", join(' ', @l)); } $l[0]; } sub stringlist { my ($b_verbose) = @_; map { my $ids = $b_verbose || $_->{description} eq '(null)' ? sprintf("vendor:%04x device:%04x", $_->{vendor}, $_->{id}) : ''; my $subids = $_->{subid} && $_->{subid} != 0xffff ? sprintf("subv:%04x subd:%04x", $_->{subvendor}, $_->{subid}) : ''; sprintf("%-16s: %s%s%s", $_->{driver} || 'unknown', $_->{description}, $_->{media_type} ? sprintf(" [%s]", $_->{media_type}) : '', $ids || $subids ? " ($ids" . ($ids && $subids && " ") . "$subids)" : '', ); } probeall(); } sub tryOpen($) { my $F; sysopen($F, devices::make($_[0]), c::O_NONBLOCK()) && $F; } sub tryWrite($) { my $F; sysopen($F, devices::make($_[0]), 1 | c::O_NONBLOCK()) && $F; } my @dmesg; sub syslog() { if (-r "/tmp/syslog") { map { /<\d+>(.*)/ } cat_("/tmp/syslog"); } else { @dmesg = `/bin/dmesg` if !@dmesg; @dmesg; } } sub get_mac_model() { my $mac_model = cat_("/proc/device-tree/model") || die "Cannot open /proc/device-tree/model"; log::l("Mac model: $mac_model"); $mac_model; } sub get_mac_generation() { cat_('/proc/cpuinfo') =~ /^pmac-generation\s*:\s*(.*)/m ? $1 : "Unknown Generation"; } sub hasSMP() { return if $::testing; (any { /NR_CPUS limit of 1 reached/ } syslog()) || (any { /^processor\s*:\s*(\d+)/ && $1 > 0 } cat_('/proc/cpuinfo')) || any { /\bProcessor #(\d+)\s+(\S*)/ && $1 > 0 && $2 ne 'invalid' } syslog(); } sub hasPCMCIA() { $::o->{pcmcia} } my (@dmis, $dmidecode_already_runned); # we return a list b/c several DMIs have the same name: sub dmidecode() { return @dmis if $dmidecode_already_runned; return if $>; my ($ver, @l) = arch() =~ /86/ ? run_program::get_stdout('dmidecode') : (); my $tab = "\t"; my ($major, $minor) = $ver =~ /(\d+)\.(\d+)/; if ($major > 2 || $major == 2 && $minor > 7) { #- new dmidecode output is less indented $tab = ''; #- drop header shift @l while @l && $l[0] ne "\n"; } foreach (@l) { next if /TRUNCATED/; if (/^$tab\t(.*)/) { $dmis[-1]{string} .= "$1\n"; $dmis[-1]{$1} = $2 if /^$tab\t(.*): (.*)$/; } elsif (my ($s) = /^$tab(.*)/) { next if $s =~ /^$/ || $s =~ /\bDMI type \d+/; $s =~ s/ Information$//; push @dmis, { name => $s }; } } $dmidecode_already_runned = 1; @dmis; } sub dmidecode_category { my ($cat) = @_; my @l = grep { $_->{name} eq $cat } dmidecode(); wantarray() ? @l : $l[0] || {}; } #- size in MB sub dmi_detect_memory() { my @l1 = map { $_->{'Enabled Size'} =~ /(\d+) MB/ && $1 } dmidecode_category('Memory Module'); my @l2 = map { $_->{'Form Factor'} =~ /^(SIMM|SIP|DIP|DIMM|FB-DIMM|RIMM|SODIMM|SRIMM)$/ && ($_->{Size} =~ /(\d+) MB/ && $1 || $_->{Size} =~ /(\d+) kB/ && $1 * 1024); } dmidecode_category('Memory Device'); max(sum(@l1), sum(@l2)); } sub computer_info() { my $Chassis = dmidecode_category('Chassis')->{Type} =~ /(\S+)/ && $1; my $date = dmidecode_category('BIOS')->{'Release Date'} || ''; my $BIOS_Year = $date =~ m!(\d{4})! && $1 || $date =~ m!\d\d/\d\d/(\d\d)! && "20$1"; +{ isLaptop => member($Chassis, 'Portable', 'Laptop', 'Notebook', 'Hand Held', 'Sub Notebook', 'Docking Station'), isServer => member($Chassis, 'Pizza Box', 'Main Server Chassis', 'Rack Mount Chassis', 'Blade'), if_($BIOS_Year, BIOS_Year => $BIOS_Year), }; } #- try to detect a laptop, we assume pcmcia service is an indication of a laptop or #- the following regexp to match graphics card apparently only used for such systems. sub isLaptop() { arch() =~ /ppc/ ? get_mac_model() =~ /Book/ : computer_info()->{isLaptop} || glob_("/sys/bus/acpi/devices/PNP0C0D:*") #- ACPI lid button || (matching_desc__regexp('C&T.*655[45]\d') || matching_desc__regexp('C&T.*68554') || matching_desc__regexp('Neomagic.*Magic(Media|Graph)') || matching_desc__regexp('ViRGE.MX') || matching_desc__regexp('S3.*Savage.*[IM]X') || matching_desc__regexp('Intel Corporation\|Mobile') || matching_desc__regexp('\bATI\b.*(Mobility|\bLT\b)')) || (any { $_->{'model name'} =~ /\b(mobile|C7-M)\b/i } getCPUs()) || probe_unique_name("Type") eq 'laptop' #- ipw2100/2200/3945 are Mini-PCI (Express) adapters || (any { member($_->{driver}, qw(ipw2100 ipw2200 ipw3945)) } pci_probe()); } sub isServer() { computer_info()->{isServer} || (any { $_->{Type} =~ /ECC/ } dmidecode_category('Memory Module')) || dmidecode_category('System Information')->{Manufacturer} =~ /Supermicro/i || dmidecode_category('System Information')->{'Product Name'} =~ /NetServer|Proliant|PowerEdge|eServer|IBM System x|ThinkServer/i || matching_desc__regexp('LSI Logic.*SCSI') || matching_desc__regexp('MegaRAID') || matching_desc__regexp('NetServer') || (any { $_->{'model name'} =~ /(Xeon|Opteron)/i } getCPUs()); } sub isHyperv() { dmidecode_category('System')->{Manufacturer} =~ /Microsoft Corporation/i && dmidecode_category('System')->{'Product Name'} =~ /Virtual Machine/i; } sub BIGMEM() { arch() !~ /x86_64|ia64/ && $> == 0 && dmi_detect_memory() > 4 * 1024; } sub is_i586() { return 0 if arch() !~ /86/; my $cpuinfo = cat_('/proc/cpuinfo'); $cpuinfo =~ /^cpu family\s*:\s*(\d+)/m && $1 < 6 || $cpuinfo =~ /^model name\s*:\s*Transmeta.* TM5800/m || # mdvbz#37866 !has_cpu_flag('cmov'); } sub is_mips_lemote() { to_bool(cat_('/proc/cpuinfo') =~ /lemote/); } sub is_mips_ict() { to_bool(cat_('/proc/cpuinfo') =~ /ict/); } sub is_mips_gdium() { to_bool(cat_('/proc/cpuinfo') =~ /gdium/); } sub is_mips_st_ls2f() { to_bool(cat_('/proc/cpuinfo') =~ /st-ls2f/); } sub is_arm_openrd_client() { to_bool(cat_('/proc/cpuinfo') =~ /OpenRD Client/); } sub is_arm_versatile() { to_bool(cat_('/proc/cpuinfo') =~ /ARM-Versatile/); } sub is_arm_efikamix() { to_bool(cat_('/proc/cpuinfo') =~ /Efika MX/); } sub is_xbox() { any { $_->{vendor} == 0x10de && $_->{id} == 0x02a5 } pci_probe(); } sub is_virtualbox() { any { $_->{driver} eq 'vboxadd' } detect_devices::pci_probe(); } sub is_vmware() { any { $_->{driver} =~ /Card:VMware/ } detect_devices::pci_probe(); } sub is_netbook_nettop() { my @cpus = getCPUs(); (any { $_->{'model name'} =~ /(\bIntel\(R\) Atom\(TM\)\B)/i } @cpus) || (any { $_->{'model name'} =~ /(\bIntel\(R\) Celeron\(R\) M processor\b|\bVIA C7-M Processor\b|\bGeode\(TM\)\B)/i && $_->{'cpu MHz'} < 1500 } @cpus); } sub has_low_resources() { availableRamMB() < 100 || arch() =~ /i.86/ && ix86_cpu_frequency() < 350; } sub need_light_desktop() { has_low_resources() || is_netbook_nettop(); } sub has_cpu_flag { my ($flag) = @_; cat_('/proc/cpuinfo') =~ /^flags.*\b$flag\b/m; } sub matching_types() { +{ mips_lemote => is_mips_lemote(), mips_ict => is_mips_ict(), mips_st_ls2f => is_mips_st_ls2f(), laptop => isLaptop(), hyperv => isHyperv(), 'numpad' => hasNumpad(), 'touchpad' => hasTouchpad(), '64bit' => to_bool(arch() =~ /64/), wireless => to_bool(get_wireless_interface() || probe_category('network/wireless')), }; } sub hasCPUMicrocode() { state $hasCPUMicrocode; if (!defined $hasCPUMicrocode) { $hasCPUMicrocode = to_bool(find { 'microcode' } modules::loaded_modules()); } return $hasCPUMicrocode; } sub hasCPUFreq() { require cpufreq; to_bool(cpufreq::get_modules()) || cat_('/proc/cpuinfo') =~ /AuthenticAMD/ && arch() =~ /x86_64/ || cat_('/proc/cpuinfo') =~ /model name.*Intel\(R\) Core\(TM\)2 CPU/; } sub hasWacom() { find { $_->{vendor} == 0x056a || $_->{driver} =~ /wacom/ } usb_probe() } sub hasTouchpad() { any { $_->{Synaptics} || $_->{ALPS} || $_->{Elantech} } getInputDevices() } sub hasNumpad() { any { $_->{Numpad} } getInputDevices() } sub usbWacom() { grep { $_->{vendor} eq '056a' } getInputDevices() } sub usbKeyboards() { grep { $_->{media_type} =~ /\|Keyboard/ } usb_probe() } sub usbStorage() { grep { $_->{media_type} =~ /Mass Storage\|/ } usb_probe() } sub has_mesh() { find { /mesh/ } all_files_rec("/proc/device-tree") } sub has_53c94() { find { /53c94/ } all_files_rec("/proc/device-tree") } sub usbKeyboard2country_code { my ($usb_kbd) = @_; my ($F, $tmp); # FIXME: usbfs is dead! we should poke somewhere in /sys/ !!!! sysopen($F, sprintf("/proc/bus/usb/%03d/%03d", $usb_kbd->{pci_bus}, $usb_kbd->{pci_device}), 0) and sysseek $F, 0x28, 0 and sysread $F, $tmp, 1 and unpack("C", $tmp); } sub probeSerialDevices() { require list_modules; require modules; modules::append_to_modules_loaded_at_startup_for_all_kernels(modules::load_category($::o->{modules_conf}, 'various/serial')); foreach (0..3) { #- make sure the device are created before probing, devices::make("/dev/ttyS$_"); #- and make sure the device is a real terminal (major is 4). int((stat "/dev/ttyS$_")[6]/256) == 4 or $serialprobe{"/dev/ttyS$_"} = undef; } #- for device already probed, we can safely (assuming device are #- not moved during install :-) #- include /dev/mouse device if using an X server. mkdir_p("/var/lock"); -l "/dev/mouse" and $serialprobe{"/dev/" . readlink "/dev/mouse"} = undef; foreach (keys %serialprobe) { m|^/dev/(.*)| and touch "/var/lock/LCK..$1" } print STDERR "Please wait while probing serial ports...\n"; #- start probing all serial ports... really faster than before ... #- ... but still take some time :-) my %current; foreach (run_program::get_stdout('serial_probe')) { if (/^\s*$/) { $serialprobe{$current{DEVICE}} = { %current } if $current{DEVICE}; %current = (); } elsif (/^([^=]+)=(.*?)\s*$/) { $current{$1} = $2; } } foreach (values %serialprobe) { $_->{DESCRIPTION} =~ /modem/i and $_->{CLASS} = 'MODEM'; #- hack to make sure a modem is detected. $_->{DESCRIPTION} =~ /olitec/i and $_->{CLASS} = 'MODEM'; #- hack to make sure such modem gets detected. log::l("probed $_->{DESCRIPTION} of class $_->{CLASS} on device $_->{DEVICE}"); } } sub probeSerial($) { $serialprobe{$_[0]} } sub hasModem($) { $serialprobe{$_[0]} && $serialprobe{$_[0]}{CLASS} eq 'MODEM' && $serialprobe{$_[0]}{DESCRIPTION}; } sub hasMousePS2 { my $t; sysread(tryOpen($_[0]) || return, $t, 256) != 1 || $t ne "\xFE"; } sub probeall_unavailable_modules() { map { my $driver = $_->{driver}; $driver !~ /:/ && !member($driver, 'hub', 'unknown', 'amd64_agp') && !modules::module_is_available($driver) ? $driver : @{[]}; } probeall(); } sub probeall_dkms_modules() { my @unavailable_modules = probeall_unavailable_modules() or return; require modalias; my $dkms_modules = modalias::parse_file_modules($::prefix . "/usr/share/ldetect-lst/dkms-modules.alias"); intersection([ keys(%$dkms_modules) ], \@unavailable_modules); } sub usb_description2removable { local ($_) = @_; return 'camera' if /\bcamera\b/i; return 'memory_card' if /\bmemory\s?stick\b/i || /\bcompact\s?flash\b/i || /\bsmart\s?media\b/i; return 'memory_card' if /DiskOnKey/i || /IBM-DMDM/i; return 'zip' if /\bzip\s?(100|250|750)/i; return 'floppy' if /\bLS-?120\b/i; return; } sub usb2removable { my ($e) = @_; $e->{usb_driver} or return; if ($e->{usb_driver} =~ /Removable:(.*)/) { return $1; } elsif (my $name = usb_description2removable($e->{usb_description})) { return $name; } undef; } sub suggest_mount_point { my ($e) = @_; my $name = $e->{media_type}; if (member($e->{media_type}, 'hd', 'fd')) { if (exists $e->{usb_driver}) { $name = usb2removable($e) || 'removable'; } elsif (isZipDrive($e)) { $name = 'zip'; } elsif ($e->{media_type} eq 'fd') { $name = 'floppy'; } else { log::l("suggest_mount_point: do not know what to with hd $e->{device}"); } } $name; } 1; #- Local Variables: #- mode:cperl #- tab-width:8 #- End: