session_begin(); if (!empty($config['feed_http_auth']) && request_var('auth', '') == 'http') { phpbb_http_login(array( 'auth_message' => 'Feed', 'viewonline' => request_var('viewonline', true), )); } $auth->acl($user->data); $user->setup(); // Initial var setup $forum_id = request_var('f', 0); $topic_id = request_var('t', 0); $mode = request_var('mode', ''); // We do not use a template, therefore we simply define the global template variables here $global_vars = $item_vars = array(); $feed_updated_time = 0; // Generate params array for use in append_sid() to correctly link back to this page $params = false; if ($forum_id || $topic_id || $mode) { $params = array( 'f' => ($forum_id) ? $forum_id : NULL, 't' => ($topic_id) ? $topic_id : NULL, 'mode' => ($mode) ? $mode : NULL, ); } // This boards URL $board_url = generate_board_url(); // Get correct feed object $feed = phpbb_feed_factory::init($mode, $forum_id, $topic_id); // No feed found if ($feed === false) { trigger_error('NO_FEED'); } // Open Feed $feed->open(); // Iterate through items while ($row = $feed->get_item()) { // BBCode options to correctly disable urls, smilies, bbcode... if ($feed->get('options') === NULL) { // Allow all combinations $options = 7; if ($feed->get('enable_bbcode') !== NULL && $feed->get('enable_smilies') !== NULL && $feed->get('enable_magic_url') !== NULL) { $options = (($row[$feed->get('enable_bbcode')]) ? OPTION_FLAG_BBCODE : 0) + (($row[$feed->get('enable_smilies')]) ? OPTION_FLAG_SMILIES : 0) + (($row[$feed->get('enable_magic_url')]) ? OPTION_FLAG_LINKS : 0); } } else { $options = $row[$feed->get('options')]; } $title = (isset($row[$feed->get('title')]) && $row[$feed->get('title')] !== '') ? $row[$feed->get('title')] : ((isset($row[$feed->get('title2')])) ? $row[$feed->get('title2')] : ''); $published = ($feed->get('published') !== NULL) ? (int) $row[$feed->get('published')] : 0; $updated = ($feed->get('updated') !== NULL) ? (int) $row[$feed->get('updated')] : 0; $item_row = array( 'author' => ($feed->get('creator') !== NULL) ? $row[$feed->get('creator')] : '', 'published' => ($published > 0) ? feed_format_date($published) : '', 'updated' => ($updated > 0) ? feed_format_date($updated) : '', 'link' => '', 'title' => censor_text($title), 'category' => ($config['feed_item_statistics'] && !empty($row['forum_id'])) ? $board_url . '/viewforum.' . $phpEx . '?f=' . $row['forum_id'] : '', 'category_name' => ($config['feed_item_statistics'] && isset($row['forum_name'])) ? $row['forum_name'] : '', 'description' => censor_text(feed_generate_content($row[$feed->get('text')], $row[$feed->get('bbcode_uid')], $row[$feed->get('bitfield')], $options)), 'statistics' => '', ); // Adjust items, fill link, etc. $feed->adjust_item($item_row, $row); $item_vars[] = $item_row; $feed_updated_time = max($feed_updated_time, $published, $updated); } // If we do not have any items at all, sending the current time is better than sending no time. if (!$feed_updated_time) { $feed_updated_time = time(); } // Some default assignments // FEED_IMAGE is not used (atom) $global_vars = array_merge($global_vars, array( 'FEED_IMAGE' => '', 'SELF_LINK' => feed_append_sid('/feed.' . $phpEx, $params), 'FEED_LINK' => $board_url . '/index.' . $phpEx, 'FEED_TITLE' => $config['sitename'], 'FEED_SUBTITLE' => $config['site_desc'], 'FEED_UPDATED' => feed_format_date($feed_updated_time), 'FEED_LANG' => $user->lang['USER_LANG'], 'FEED_AUTHOR' => $config['sitename'], )); $feed->close(); // Output page // gzip_compression if ($config['gzip_compress']) { if (@extension_loaded('zlib') && !headers_sent()) { ob_start('ob_gzhandler'); } } // IF debug extra is enabled and admin want to "explain" the page we need to set other headers... if (defined('DEBUG_EXTRA') && request_var('explain', 0) && $auth->acl_get('a_')) { header('Content-type: text/html; charset=UTF-8'); header('Cache-Control: private, no-cache="set-cookie"'); header('Expires: 0'); header('Pragma: no-cache'); $mtime = explode(' ', microtime()); $totaltime = $mtime[0] + $mtime[1] - $starttime; if (method_exists($db, 'sql_report')) { $db->sql_report('display'); } garbage_collection(); exit_handler(); } header("Content-Type: application/atom+xml; charset=UTF-8"); header("Last-Modified: " . gmdate('D, d M Y H:i:s', $feed_updated_time) . ' GMT'); if (!empty($user->data['is_bot'])) { // Let reverse proxies know we detected a bot. header('X-PHPBB-IS-BOT: yes'); } echo '' . "\n"; echo '' . "\n"; echo '' . "\n\n"; echo (!empty($global_vars['FEED_TITLE'])) ? '' . $global_vars['FEED_TITLE'] . '' . "\n" : ''; echo (!empty($global_vars['FEED_SUBTITLE'])) ? '' . $global_vars['FEED_SUBTITLE'] . '' . "\n" : ''; echo (!empty($global_vars['FEED_LINK'])) ? '' . "\n" : ''; echo '' . $global_vars['FEED_UPDATED'] . '' . "\n\n"; echo '' . "\n"; echo '' . $global_vars['SELF_LINK'] . '' . "\n"; foreach ($item_vars as $row) { echo '' . "\n"; if (!empty($row['author'])) { echo '' . "\n"; } echo '' . ((!empty($row['updated'])) ? $row['updated'] : $row['published']) . '' . "\n"; if (!empty($row['published'])) { echo '' . $row['published'] . '' . "\n"; } echo '' . $row['link'] . '' . "\n"; echo '' . "\n"; echo '<![CDATA[' . $row['title'] . ']]>' . "\n\n"; if (!empty($row['category']) && isset($row['category_name']) && $row['category_name'] !== '') { echo '' . "\n"; } echo '' . $user->lang['STATISTICS'] . ': ' . $row['statistics'] . '

'; } echo '
' . "\n" . ']]>
' . "\n"; echo '
' . "\n"; } echo '
'; garbage_collection(); exit_handler(); /** * Run links through append_sid(), prepend generate_board_url() and remove session id **/ function feed_append_sid($url, $params) { global $board_url; return append_sid($board_url . $url, $params, true, ''); } /** * Generate ISO 8601 date string (RFC 3339) **/ function feed_format_date($time) { static $zone_offset; static $offset_string; if (empty($offset_string)) { global $user; $zone_offset = (int) $user->timezone + (int) $user->dst; $sign = ($zone_offset < 0) ? '-' : '+'; $time_offset = abs($zone_offset); $offset_seconds = $time_offset % 3600; $offset_minutes = $offset_seconds / 60; $offset_hours = ($time_offset - $offset_seconds) / 3600; $offset_string = sprintf("%s%02d:%02d", $sign, $offset_hours, $offset_minutes); } return gmdate("Y-m-d\TH:i:s", $time + $zone_offset) . $offset_string; } /** * Generate text content **/ function feed_generate_content($content, $uid, $bitfield, $options) { global $user, $config, $phpbb_root_path, $phpEx, $board_url; if (empty($content)) { return ''; } // Prepare some bbcodes for better parsing $content = preg_replace("#\[quote(=".*?")?:$uid\]\s*(.*?)\s*\[/quote:$uid\]#si", "[quote$1:$uid]
$2
[/quote:$uid]", $content); $content = generate_text_for_display($content, $uid, $bitfield, $options); // Add newlines $content = str_replace('
', '
' . "\n", $content); // Convert smiley Relative paths to Absolute path, Windows style $content = str_replace($phpbb_root_path . $config['smilies_path'], $board_url . '/' . $config['smilies_path'], $content); // Remove "Select all" link and mouse events $content = str_replace('' . $user->lang['SELECT_ALL_CODE'] . '', '', $content); $content = preg_replace('#(onkeypress|onclick)="(.*?)"#si', '', $content); // Firefox does not support CSS for feeds, though // Remove font sizes // $content = preg_replace('#([^>]+)#iU', '\1', $content); // Make text strong :P // $content = preg_replace('#(.*?)#iU', '\1', $content); // Italic // $content = preg_replace('#([^<]+)#iU', '\1', $content); // Underline // $content = preg_replace('#([^<]+)#iU', '\1', $content); // Remove embed Windows Media Streams $content = preg_replace( '#<\!--\[if \!IE\]>-->([^[]+)<\!--#si', '', $content); // Do not use < and >, because we want to retain code contained in [code][/code] // Remove embed and objects $content = preg_replace( '#<(object|embed)(.*?) (value|src)=(.*?) ([^[]+)(object|embed)>#si',' $1 ',$content); // Remove some specials html tag, because somewhere there are a mod to allow html tags ;) $content = preg_replace( '#<(script|iframe)([^[]+)\1>#siU', ' $1 ', $content); // Remove Comments from inline attachments [ia] $content = preg_replace('#
(.*?)(.*?)(.*?)
#si','$4',$content); // Replace some entities with their unicode counterpart $entities = array( ' ' => "\xC2\xA0", '•' => "\xE2\x80\xA2", '·' => "\xC2\xB7", '©' => "\xC2\xA9", ); $content = str_replace(array_keys($entities), array_values($entities), $content); // Remove CDATA blocks. ;) $content = preg_replace('#\<\!\[CDATA\[(.*?)\]\]\>#s', '', $content); // Other control characters $content = preg_replace('#(?:[\x00-\x1F\x7F]+|(?:\xC2[\x80-\x9F])+)#', '', $content); return $content; } /** * Factory class to return correct object * @package phpBB3 */ class phpbb_feed_factory { /** * Return correct object for specified mode * * @param string $mode The feeds mode. * @param int $forum_id Forum id specified by the script if forum feed provided. * @param int $topic_id Topic id specified by the script if topic feed provided. * * @return object Returns correct feeds object for specified mode. */ function init($mode, $forum_id, $topic_id) { global $config; switch ($mode) { case 'forums': if (!$config['feed_overall_forums']) { return false; } return new phpbb_feed_forums(); break; case 'topics': case 'topics_new': if (!$config['feed_topics_new']) { return false; } return new phpbb_feed_topics(); break; case 'topics_active': if (!$config['feed_topics_active']) { return false; } return new phpbb_feed_topics_active(); break; case 'news': global $db; // Get at least one news forum $sql = 'SELECT forum_id FROM ' . FORUMS_TABLE . ' WHERE ' . $db->sql_bit_and('forum_options', FORUM_OPTION_FEED_NEWS, '<> 0'); $result = $db->sql_query_limit($sql, 1, 0, 600); $s_feed_news = (int) $db->sql_fetchfield('forum_id'); $db->sql_freeresult($result); if (!$s_feed_news) { return false; } return new phpbb_feed_news(); break; default: if ($topic_id && $config['feed_topic']) { return new phpbb_feed_topic($topic_id); } else if ($forum_id && $config['feed_forum']) { return new phpbb_feed_forum($forum_id); } else if ($config['feed_overall']) { return new phpbb_feed_overall(); } return false; break; } } } /** * Base class with some generic functions and settings. * * @package phpBB3 */ class phpbb_feed_base { /** * SQL Query to be executed to get feed items */ var $sql = array(); /** * Keys specified for retrieval of title, content, etc. */ var $keys = array(); /** * Number of items to fetch. Usually overwritten by $config['feed_something'] */ var $num_items = 15; /** * Separator for title elements to separate items (for example forum / topic) */ var $separator = "\xE2\x80\xA2"; // • /** * Separator for the statistics row (Posted by, post date, replies, etc.) */ var $separator_stats = "\xE2\x80\x94"; // — /** * Constructor */ function phpbb_feed_base() { global $config; $this->set_keys(); // Allow num_items to be string if (is_string($this->num_items)) { $this->num_items = (int) $config[$this->num_items]; // A precaution if (!$this->num_items) { $this->num_items = 10; } } } /** * Set keys. */ function set_keys() { } /** * Open feed */ function open() { } /** * Close feed */ function close() { global $db; if (!empty($this->result)) { $db->sql_freeresult($this->result); } } /** * Set key */ function set($key, $value) { $this->keys[$key] = $value; } /** * Get key */ function get($key) { return (isset($this->keys[$key])) ? $this->keys[$key] : NULL; } function get_readable_forums() { global $auth; static $forum_ids; if (!isset($forum_ids)) { $forum_ids = array_keys($auth->acl_getf('f_read', true)); } return $forum_ids; } function get_moderator_approve_forums() { global $auth; static $forum_ids; if (!isset($forum_ids)) { $forum_ids = array_keys($auth->acl_getf('m_approve', true)); } return $forum_ids; } function is_moderator_approve_forum($forum_id) { static $forum_ids; if (!isset($forum_ids)) { $forum_ids = array_flip($this->get_moderator_approve_forums()); } if (!$forum_id) { // Global announcement, your a moderator in any forum than it's okay. return (!empty($forum_ids)) ? true : false; } return (isset($forum_ids[$forum_id])) ? true : false; } function get_excluded_forums() { global $db, $cache; static $forum_ids; // Matches acp/acp_board.php $cache_name = 'feed_excluded_forum_ids'; if (!isset($forum_ids) && ($forum_ids = $cache->get('_' . $cache_name)) === false) { $sql = 'SELECT forum_id FROM ' . FORUMS_TABLE . ' WHERE ' . $db->sql_bit_and('forum_options', FORUM_OPTION_FEED_EXCLUDE, '<> 0'); $result = $db->sql_query($sql); $forum_ids = array(); while ($forum_id = (int) $db->sql_fetchfield('forum_id')) { $forum_ids[$forum_id] = $forum_id; } $db->sql_freeresult($result); $cache->put('_' . $cache_name, $forum_ids); } return $forum_ids; } function is_excluded_forum($forum_id) { $forum_ids = $this->get_excluded_forums(); return isset($forum_ids[$forum_id]) ? true : false; } function get_passworded_forums() { global $user; return $user->get_passworded_forums(); } function get_item() { global $db, $cache; static $result; if (!isset($result)) { if (!$this->get_sql()) { return false; } // Query database $sql = $db->sql_build_query('SELECT', $this->sql); $result = $db->sql_query_limit($sql, $this->num_items); } return $db->sql_fetchrow($result); } function user_viewprofile($row) { global $phpEx, $user; $author_id = (int) $row[$this->get('author_id')]; if ($author_id == ANONYMOUS) { // Since we cannot link to a profile, we just return GUEST // instead of $row['username'] return $user->lang['GUEST']; } return '' . $row[$this->get('creator')] . ''; } } /** * Abstract class for post based feeds * * @package phpBB3 */ class phpbb_feed_post_base extends phpbb_feed_base { var $num_items = 'feed_limit_post'; function set_keys() { $this->set('title', 'post_subject'); $this->set('title2', 'topic_title'); $this->set('author_id', 'user_id'); $this->set('creator', 'username'); $this->set('published', 'post_time'); $this->set('updated', 'post_edit_time'); $this->set('text', 'post_text'); $this->set('bitfield', 'bbcode_bitfield'); $this->set('bbcode_uid','bbcode_uid'); $this->set('enable_bbcode', 'enable_bbcode'); $this->set('enable_smilies', 'enable_smilies'); $this->set('enable_magic_url', 'enable_magic_url'); } function adjust_item(&$item_row, &$row) { global $phpEx, $config, $user; $item_row['link'] = feed_append_sid('/viewtopic.' . $phpEx, "t={$row['topic_id']}&p={$row['post_id']}#p{$row['post_id']}"); if ($config['feed_item_statistics']) { $item_row['statistics'] = $user->lang['POSTED'] . ' ' . $user->lang['POST_BY_AUTHOR'] . ' ' . $this->user_viewprofile($row) . ' ' . $this->separator_stats . ' ' . $user->format_date($row[$this->get('published')]) . (($this->is_moderator_approve_forum($row['forum_id']) && !$row['post_approved']) ? ' ' . $this->separator_stats . ' ' . $user->lang['POST_UNAPPROVED'] : ''); } } } /** * Abstract class for topic based feeds * * @package phpBB3 */ class phpbb_feed_topic_base extends phpbb_feed_base { var $num_items = 'feed_limit_topic'; function set_keys() { $this->set('title', 'topic_title'); $this->set('title2', 'forum_name'); $this->set('author_id', 'topic_poster'); $this->set('creator', 'topic_first_poster_name'); $this->set('published', 'post_time'); $this->set('updated', 'post_edit_time'); $this->set('text', 'post_text'); $this->set('bitfield', 'bbcode_bitfield'); $this->set('bbcode_uid','bbcode_uid'); $this->set('enable_bbcode', 'enable_bbcode'); $this->set('enable_smilies', 'enable_smilies'); $this->set('enable_magic_url', 'enable_magic_url'); } function adjust_item(&$item_row, &$row) { global $phpEx, $config, $user; $item_row['link'] = feed_append_sid('/viewtopic.' . $phpEx, 't=' . $row['topic_id'] . '&p=' . $row['post_id'] . '#p' . $row['post_id']); if ($config['feed_item_statistics']) { $item_row['statistics'] = $user->lang['POSTED'] . ' ' . $user->lang['POST_BY_AUTHOR'] . ' ' . $this->user_viewprofile($row) . ' ' . $this->separator_stats . ' ' . $user->format_date($row[$this->get('published')]) . ' ' . $this->separator_stats . ' ' . $user->lang['REPLIES'] . ' ' . (($this->is_moderator_approve_forum($row['forum_id'])) ? $row['topic_replies_real'] : $row['topic_replies']) . ' ' . $this->separator_stats . ' ' . $user->lang['VIEWS'] . ' ' . $row['topic_views'] . (($this->is_moderator_approve_forum($row['forum_id']) && ($row['topic_replies_real'] != $row['topic_replies'])) ? ' ' . $this->separator_stats . ' ' . $user->lang['POSTS_UNAPPROVED'] : ''); } } } /** * Board wide feed (aka overall feed) * * This will give you the newest {$this->num_items} posts * from the whole board. * * @package phpBB3 */ class phpbb_feed_overall extends phpbb_feed_post_base { function get_sql() { global $auth, $db; $forum_ids = array_diff($this->get_readable_forums(), $this->get_excluded_forums(), $this->get_passworded_forums()); if (empty($forum_ids)) { return false; } // m_approve forums $fid_m_approve = $this->get_moderator_approve_forums(); $sql_m_approve = (!empty($fid_m_approve)) ? 'OR ' . $db->sql_in_set('forum_id', $fid_m_approve) : ''; // Determine topics with recent activity $sql = 'SELECT topic_id, topic_last_post_time FROM ' . TOPICS_TABLE . ' WHERE ' . $db->sql_in_set('forum_id', $forum_ids) . ' AND topic_moved_id = 0 AND (topic_approved = 1 ' . $sql_m_approve . ') ORDER BY topic_last_post_time DESC'; $result = $db->sql_query_limit($sql, $this->num_items); $topic_ids = array(); $min_post_time = 0; while ($row = $db->sql_fetchrow()) { $topic_ids[] = (int) $row['topic_id']; $min_post_time = (int) $row['topic_last_post_time']; } $db->sql_freeresult($result); if (empty($topic_ids)) { return false; } // Get the actual data $this->sql = array( 'SELECT' => 'f.forum_id, f.forum_name, ' . 'p.post_id, p.topic_id, p.post_time, p.post_edit_time, p.post_approved, p.post_subject, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url, ' . 'u.username, u.user_id', 'FROM' => array( USERS_TABLE => 'u', POSTS_TABLE => 'p', ), 'LEFT_JOIN' => array( array( 'FROM' => array(FORUMS_TABLE => 'f'), 'ON' => 'f.forum_id = p.forum_id', ), ), 'WHERE' => $db->sql_in_set('p.topic_id', $topic_ids) . ' AND (p.post_approved = 1 ' . str_replace('forum_id', 'p.forum_id', $sql_m_approve) . ') AND p.post_time >= ' . $min_post_time . ' AND u.user_id = p.poster_id', 'ORDER_BY' => 'p.post_time DESC', ); return true; } function adjust_item(&$item_row, &$row) { parent::adjust_item($item_row, $row); $item_row['title'] = (isset($row['forum_name']) && $row['forum_name'] !== '') ? $row['forum_name'] . ' ' . $this->separator . ' ' . $item_row['title'] : $item_row['title']; } } /** * Forum feed * * This will give you the last {$this->num_items} posts made * within a specific forum. * * @package phpBB3 */ class phpbb_feed_forum extends phpbb_feed_post_base { var $forum_id = 0; var $forum_data = array(); function phpbb_feed_forum($forum_id) { parent::phpbb_feed_base(); $this->forum_id = (int) $forum_id; } function open() { global $db, $auth; // Check if forum exists $sql = 'SELECT forum_id, forum_name, forum_password, forum_type, forum_options FROM ' . FORUMS_TABLE . ' WHERE forum_id = ' . $this->forum_id; $result = $db->sql_query($sql); $this->forum_data = $db->sql_fetchrow($result); $db->sql_freeresult($result); if (empty($this->forum_data)) { trigger_error('NO_FORUM'); } // Forum needs to be postable if ($this->forum_data['forum_type'] != FORUM_POST) { trigger_error('NO_FEED'); } // Make sure forum is not excluded from feed if (phpbb_optionget(FORUM_OPTION_FEED_EXCLUDE, $this->forum_data['forum_options'])) { trigger_error('NO_FEED'); } // Make sure we can read this forum if (!$auth->acl_get('f_read', $this->forum_id)) { trigger_error('SORRY_AUTH_READ'); } // Make sure forum is not passworded or user is authed if ($this->forum_data['forum_password']) { $forum_ids_passworded = $this->get_passworded_forums(); if (isset($forum_ids_passworded[$this->forum_id])) { trigger_error('SORRY_AUTH_READ'); } unset($forum_ids_passworded); } } function get_sql() { global $auth, $db; $m_approve = ($auth->acl_get('m_approve', $this->forum_id)) ? true : false; // Determine topics with recent activity $sql = 'SELECT topic_id, topic_last_post_time FROM ' . TOPICS_TABLE . ' WHERE forum_id = ' . $this->forum_id . ' AND topic_moved_id = 0 ' . ((!$m_approve) ? 'AND topic_approved = 1' : '') . ' ORDER BY topic_last_post_time DESC'; $result = $db->sql_query_limit($sql, $this->num_items); $topic_ids = array(); $min_post_time = 0; while ($row = $db->sql_fetchrow()) { $topic_ids[] = (int) $row['topic_id']; $min_post_time = (int) $row['topic_last_post_time']; } $db->sql_freeresult($result); if (empty($topic_ids)) { return false; } $this->sql = array( 'SELECT' => 'p.post_id, p.topic_id, p.post_time, p.post_edit_time, p.post_approved, p.post_subject, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url, ' . 'u.username, u.user_id', 'FROM' => array( POSTS_TABLE => 'p', USERS_TABLE => 'u', ), 'WHERE' => $db->sql_in_set('p.topic_id', $topic_ids) . ' ' . ((!$m_approve) ? 'AND p.post_approved = 1' : '') . ' AND p.post_time >= ' . $min_post_time . ' AND p.poster_id = u.user_id', 'ORDER_BY' => 'p.post_time DESC', ); return true; } function adjust_item(&$item_row, &$row) { parent::adjust_item($item_row, $row); $item_row['title'] = (isset($row['forum_name']) && $row['forum_name'] !== '') ? $row['forum_name'] . ' ' . $this->separator . ' ' . $item_row['title'] : $item_row['title']; } function get_item() { return ($row = parent::get_item()) ? array_merge($this->forum_data, $row) : $row; } } /** * Topic feed for a specific topic * * This will give you the last {$this->num_items} posts made within this topic. * * @package phpBB3 */ class phpbb_feed_topic extends phpbb_feed_post_base { var $topic_id = 0; var $forum_id = 0; var $topic_data = array(); function phpbb_feed_topic($topic_id) { parent::phpbb_feed_base(); $this->topic_id = (int) $topic_id; } function open() { global $auth, $db, $user; $sql = 'SELECT f.forum_options, f.forum_password, t.topic_id, t.forum_id, t.topic_approved, t.topic_title, t.topic_time, t.topic_views, t.topic_replies, t.topic_type FROM ' . TOPICS_TABLE . ' t LEFT JOIN ' . FORUMS_TABLE . ' f ON (f.forum_id = t.forum_id) WHERE t.topic_id = ' . $this->topic_id; $result = $db->sql_query($sql); $this->topic_data = $db->sql_fetchrow($result); $db->sql_freeresult($result); if (empty($this->topic_data)) { trigger_error('NO_TOPIC'); } $this->forum_id = (int) $this->topic_data['forum_id']; // Make sure topic is either approved or user authed if (!$this->topic_data['topic_approved'] && !$auth->acl_get('m_approve', $this->forum_id)) { trigger_error('SORRY_AUTH_READ'); } // Make sure forum is not excluded from feed if (phpbb_optionget(FORUM_OPTION_FEED_EXCLUDE, $this->topic_data['forum_options'])) { trigger_error('NO_FEED'); } // Make sure we can read this forum if (!$auth->acl_get('f_read', $this->forum_id)) { trigger_error('SORRY_AUTH_READ'); } // Make sure forum is not passworded or user is authed if ($this->topic_data['forum_password']) { $forum_ids_passworded = $this->get_passworded_forums(); if (isset($forum_ids_passworded[$this->forum_id])) { trigger_error('SORRY_AUTH_READ'); } unset($forum_ids_passworded); } } function get_sql() { global $auth, $db; $this->sql = array( 'SELECT' => 'p.post_id, p.post_time, p.post_edit_time, p.post_approved, p.post_subject, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url, ' . 'u.username, u.user_id', 'FROM' => array( POSTS_TABLE => 'p', USERS_TABLE => 'u', ), 'WHERE' => 'p.topic_id = ' . $this->topic_id . ' ' . ($this->forum_id && !$auth->acl_get('m_approve', $this->forum_id) ? 'AND p.post_approved = 1' : '') . ' AND p.poster_id = u.user_id', 'ORDER_BY' => 'p.post_time DESC', ); return true; } function get_item() { return ($row = parent::get_item()) ? array_merge($this->topic_data, $row) : $row; } } /** * 'All Forums' feed * * This will give you a list of all postable forums where feeds are enabled * including forum description, topic stats and post stats * * @package phpBB3 */ class phpbb_feed_forums extends phpbb_feed_base { var $num_items = 0; function set_keys() { $this->set('title', 'forum_name'); $this->set('text', 'forum_desc'); $this->set('bitfield', 'forum_desc_bitfield'); $this->set('bbcode_uid','forum_desc_uid'); $this->set('updated', 'forum_last_post_time'); $this->set('options', 'forum_desc_options'); } function get_sql() { global $auth, $db; $in_fid_ary = array_diff($this->get_readable_forums(), $this->get_excluded_forums()); if (empty($in_fid_ary)) { return false; } // Build SQL Query $this->sql = array( 'SELECT' => 'f.forum_id, f.left_id, f.forum_name, f.forum_last_post_time, f.forum_desc, f.forum_desc_bitfield, f.forum_desc_uid, f.forum_desc_options, f.forum_topics, f.forum_posts', 'FROM' => array(FORUMS_TABLE => 'f'), 'WHERE' => 'f.forum_type = ' . FORUM_POST . ' AND ' . $db->sql_in_set('f.forum_id', $in_fid_ary), 'ORDER_BY' => 'f.left_id ASC', ); return true; } function adjust_item(&$item_row, &$row) { global $phpEx, $config; $item_row['link'] = feed_append_sid('/viewforum.' . $phpEx, 'f=' . $row['forum_id']); if ($config['feed_item_statistics']) { global $user; $item_row['statistics'] = $user->lang('TOTAL_TOPICS', (int) $row['forum_topics']) . ' ' . $this->separator_stats . ' ' . $user->lang('TOTAL_POSTS_COUNT', (int) $row['forum_posts']); } } } /** * News feed * * This will give you {$this->num_items} first posts * of all topics in the selected news forums. * * @package phpBB3 */ class phpbb_feed_news extends phpbb_feed_topic_base { function get_news_forums() { global $db, $cache; static $forum_ids; // Matches acp/acp_board.php $cache_name = 'feed_news_forum_ids'; if (!isset($forum_ids) && ($forum_ids = $cache->get('_' . $cache_name)) === false) { $sql = 'SELECT forum_id FROM ' . FORUMS_TABLE . ' WHERE ' . $db->sql_bit_and('forum_options', FORUM_OPTION_FEED_NEWS, '<> 0'); $result = $db->sql_query($sql); $forum_ids = array(); while ($forum_id = (int) $db->sql_fetchfield('forum_id')) { $forum_ids[$forum_id] = $forum_id; } $db->sql_freeresult($result); $cache->put('_' . $cache_name, $forum_ids); } return $forum_ids; } function get_sql() { global $auth, $config, $db; // Determine forum ids $in_fid_ary = array_intersect($this->get_news_forums(), $this->get_readable_forums()); if (empty($in_fid_ary)) { return false; } $in_fid_ary = array_diff($in_fid_ary, $this->get_passworded_forums()); if (empty($in_fid_ary)) { return false; } // We really have to get the post ids first! $sql = 'SELECT topic_first_post_id, topic_time FROM ' . TOPICS_TABLE . ' WHERE ' . $db->sql_in_set('forum_id', $in_fid_ary) . ' AND topic_moved_id = 0 AND topic_approved = 1 ORDER BY topic_time DESC'; $result = $db->sql_query_limit($sql, $this->num_items); $post_ids = array(); while ($row = $db->sql_fetchrow($result)) { $post_ids[] = (int) $row['topic_first_post_id']; } $db->sql_freeresult($result); if (empty($post_ids)) { return false; } $this->sql = array( 'SELECT' => 'f.forum_id, f.forum_name, t.topic_id, t.topic_title, t.topic_poster, t.topic_first_poster_name, t.topic_replies, t.topic_replies_real, t.topic_views, t.topic_time, t.topic_last_post_time, p.post_id, p.post_time, p.post_edit_time, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url', 'FROM' => array( TOPICS_TABLE => 't', POSTS_TABLE => 'p', ), 'LEFT_JOIN' => array( array( 'FROM' => array(FORUMS_TABLE => 'f'), 'ON' => 'p.forum_id = f.forum_id', ), ), 'WHERE' => 'p.topic_id = t.topic_id AND ' . $db->sql_in_set('p.post_id', $post_ids), 'ORDER_BY' => 'p.post_time DESC', ); return true; } } /** * New Topics feed * * This will give you the last {$this->num_items} created topics * including the first post. * * @package phpBB3 */ class phpbb_feed_topics extends phpbb_feed_topic_base { function get_sql() { global $db, $config; $forum_ids_read = $this->get_readable_forums(); if (empty($forum_ids_read)) { return false; } $in_fid_ary = array_diff($forum_ids_read, $this->get_excluded_forums(), $this->get_passworded_forums()); if (empty($in_fid_ary)) { return false; } // We really have to get the post ids first! $sql = 'SELECT topic_first_post_id, topic_time FROM ' . TOPICS_TABLE . ' WHERE ' . $db->sql_in_set('forum_id', $in_fid_ary) . ' AND topic_moved_id = 0 AND topic_approved = 1 ORDER BY topic_time DESC'; $result = $db->sql_query_limit($sql, $this->num_items); $post_ids = array(); while ($row = $db->sql_fetchrow($result)) { $post_ids[] = (int) $row['topic_first_post_id']; } $db->sql_freeresult($result); if (empty($post_ids)) { return false; } $this->sql = array( 'SELECT' => 'f.forum_id, f.forum_name, t.topic_id, t.topic_title, t.topic_poster, t.topic_first_poster_name, t.topic_replies, t.topic_replies_real, t.topic_views, t.topic_time, t.topic_last_post_time, p.post_id, p.post_time, p.post_edit_time, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url', 'FROM' => array( TOPICS_TABLE => 't', POSTS_TABLE => 'p', ), 'LEFT_JOIN' => array( array( 'FROM' => array(FORUMS_TABLE => 'f'), 'ON' => 'p.forum_id = f.forum_id', ), ), 'WHERE' => 'p.topic_id = t.topic_id AND ' . $db->sql_in_set('p.post_id', $post_ids), 'ORDER_BY' => 'p.post_time DESC', ); return true; } function adjust_item(&$item_row, &$row) { parent::adjust_item($item_row, $row); $item_row['title'] = (isset($row['forum_name']) && $row['forum_name'] !== '') ? $row['forum_name'] . ' ' . $this->separator . ' ' . $item_row['title'] : $item_row['title']; } } /** * Active Topics feed * * This will give you the last {$this->num_items} topics * with replies made withing the last {$this->sort_days} days * including the last post. * * @package phpBB3 */ class phpbb_feed_topics_active extends phpbb_feed_topic_base { var $sort_days = 7; function set_keys() { parent::set_keys(); $this->set('author_id', 'topic_last_poster_id'); $this->set('creator', 'topic_last_poster_name'); } function get_sql() { global $db, $config; $forum_ids_read = $this->get_readable_forums(); if (empty($forum_ids_read)) { return false; } $in_fid_ary = array_intersect($forum_ids_read, $this->get_forum_ids()); $in_fid_ary = array_diff($in_fid_ary, $this->get_passworded_forums()); if (empty($in_fid_ary)) { return false; } // Search for topics in last X days $last_post_time_sql = ($this->sort_days) ? ' AND topic_last_post_time > ' . (time() - ($this->sort_days * 24 * 3600)) : ''; // We really have to get the post ids first! $sql = 'SELECT topic_last_post_id, topic_last_post_time FROM ' . TOPICS_TABLE . ' WHERE ' . $db->sql_in_set('forum_id', $in_fid_ary) . ' AND topic_moved_id = 0 AND topic_approved = 1 ' . $last_post_time_sql . ' ORDER BY topic_last_post_time DESC'; $result = $db->sql_query_limit($sql, $this->num_items); $post_ids = array(); while ($row = $db->sql_fetchrow($result)) { $post_ids[] = (int) $row['topic_last_post_id']; } $db->sql_freeresult($result); if (empty($post_ids)) { return false; } $this->sql = array( 'SELECT' => 'f.forum_id, f.forum_name, t.topic_id, t.topic_title, t.topic_replies, t.topic_replies_real, t.topic_views, t.topic_last_poster_id, t.topic_last_poster_name, t.topic_last_post_time, p.post_id, p.post_time, p.post_edit_time, p.post_text, p.bbcode_bitfield, p.bbcode_uid, p.enable_bbcode, p.enable_smilies, p.enable_magic_url', 'FROM' => array( TOPICS_TABLE => 't', POSTS_TABLE => 'p', ), 'LEFT_JOIN' => array( array( 'FROM' => array(FORUMS_TABLE => 'f'), 'ON' => 'p.forum_id = f.forum_id', ), ), 'WHERE' => 'p.topic_id = t.topic_id AND ' . $db->sql_in_set('p.post_id', $post_ids), 'ORDER_BY' => 'p.post_time DESC', ); return true; } function get_forum_ids() { global $db, $cache; static $forum_ids; $cache_name = 'feed_topic_active_forum_ids'; if (!isset($forum_ids) && ($forum_ids = $cache->get('_' . $cache_name)) === false) { $sql = 'SELECT forum_id FROM ' . FORUMS_TABLE . ' WHERE forum_type = ' . FORUM_POST . ' AND ' . $db->sql_bit_and('forum_options', FORUM_OPTION_FEED_EXCLUDE, '= 0') . ' AND ' . $db->sql_bit_and('forum_flags', log(FORUM_FLAG_ACTIVE_TOPICS, 2), '<> 0'); $result = $db->sql_query($sql); $forum_ids = array(); while ($forum_id = (int) $db->sql_fetchfield('forum_id')) { $forum_ids[$forum_id] = $forum_id; } $db->sql_freeresult($result); $cache->put('_' . $cache_name, $forum_ids, 180); } return $forum_ids; } function adjust_item(&$item_row, &$row) { parent::adjust_item($item_row, $row); $item_row['title'] = (isset($row['forum_name']) && $row['forum_name'] !== '') ? $row['forum_name'] . ' ' . $this->separator . ' ' . $item_row['title'] : $item_row['title']; } } ='#n914'>914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
/* probe serial port for PnP/Legacy devices
 *
 * Copyright 1999 Red Hat, Inc.
 *
 * This software may be freely redistributed under the terms of the GNU
 * public license.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */


#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <libgen.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>

#include <linux/serial.h>
#include "serial.h"

/* character strings ARE null-terminated in the following structure    */
/* these elements are marked with a (string) in the comment            */
/* If PnP device sent 6 bit data stream, we've xlated by a 0x20 offset */
/* When computing checksum, must remove this offset                    */
struct pnp_com_id {
    unsigned char xlate_6bit;      /* does this contain xlated data */
    unsigned char other_id[17];    /* backward compatibility with pre-PNP */
    unsigned char other_len;       /* length of the other_id */
    unsigned char pnp_rev[2];      /* PnP revision bytes */
    unsigned char pnp_rev_str[8];  /* PnP revision (string version) */
    unsigned char eisa_id[4];      /* EISA Mfr identifier (string) */
    unsigned char product_id[5];   /* Mfr determined product ID (string) */
    unsigned char serial_number[9];/* Optional dev serial number (string) */
    unsigned char class_name[33];  /* Optional PnP Class name (string) */
    unsigned char driver_id[42];   /* Optional compat device IDs (string) */
    unsigned char user_name[42];   /* Optional verbose product descr (string)*/
    unsigned char checksum[2];     /* Optional checksum */
};

/* there are two possible bytes to signify the start of a PnP ID string */
#define BeginPnP1 0x28
#define BeginPnP2 0x08

/* Likewise, two possible stop bytes */
#define EndPnP1   0x29
#define EndPnP2   0x09

/* these chars indicate extensions to the base dev id exist */
#define ExtendPnP1 0x5c
#define ExtendPnP2 0x3c

#define PNP_COM_MAXLEN 256

/* results from initiating hardware probe of a hardware device */
#define PNP_COM_FATAL      1       /* system error, check errno  */
#define PNP_COM_FAIL       2       /* probe ok, but found nothing */
#define PNP_COM_OK         3       /* probe ok, we found it      */

/* types of devices we might find */
/* if PNP_COM_PNPDEV is NOT set, its a legacy device */
#define PNP_COM_MOUSE      1       /* its a mouse */
#define PNP_COM_MODEM      2       /* its a modem */
#define PNP_COM_OTHER      4       /* device is there, cant tell what kind */
#define PNP_COM_NOEXIST    8       /* no device seen */
#define PNP_COM_PNPDEV     512     /* its a PNP device */

/* level of debugging output */
/* current any value > 0 dumps all available debugging output */
static int debug_level=0;

static void serialFreeDevice(struct serialDevice *dev) {
	if (dev->pnpmfr) free(dev->pnpmfr);
	if (dev->pnpmodel) free(dev->pnpmodel);
	if (dev->pnpcompat) free(dev->pnpcompat);
	if (dev->pnpdesc) free(dev->pnpdesc);
        freeDevice((struct device *)dev);
}

static void serialWriteDevice(FILE *file, struct serialDevice *dev)
{
	writeDevice(file, (struct device *) dev);
	if (dev->pnpmfr)
	  fprintf(file,"pnpmfr: %s\n",dev->pnpmfr);
	if (dev->pnpmodel)
	  fprintf(file,"pnpmodel: %s\n",dev->pnpmodel);
	if (dev->pnpcompat)
	  fprintf(file,"pnpcompat: %s\n",dev->pnpcompat);
	if (dev->pnpdesc)
	  fprintf(file,"pnpdesc: %s\n",dev->pnpdesc);
}

static int serialCompareDevice( struct serialDevice *dev1, struct serialDevice *dev2)
{
	int x;
	
	x = compareDevice((struct device *)dev1, (struct device *)dev2);
	if (x && x!=2) return x;
	if (dev1->pnpmfr && dev2->pnpmfr && strcmp(dev1->pnpmfr,dev2->pnpmfr))
	  return 1;
	if ((!dev1->pnpmfr || !dev2->pnpmfr) && (dev1->pnpmfr != dev2->pnpmfr))
	  return 1;
	if (dev1->pnpmodel && dev2->pnpmodel && strcmp(dev1->pnpmodel,dev2->pnpmodel))
	  return 1;
	if ((!dev1->pnpmodel || !dev2->pnpmodel) && (dev1->pnpmodel != dev2->pnpmodel))
	  return 1;
	if (dev1->pnpcompat && dev2->pnpcompat && strcmp(dev1->pnpcompat,dev2->pnpcompat))
	  return 1;
	if ((!dev1->pnpcompat || !dev2->pnpcompat) && (dev1->pnpcompat != dev2->pnpcompat))
	  return 1;
	if (dev1->pnpdesc && dev2->pnpdesc && strcmp(dev1->pnpdesc,dev2->pnpdesc))
	  return 1;
	if ((!dev1->pnpdesc || !dev2->pnpdesc) && (dev1->pnpdesc != dev2->pnpdesc))
	  return 1;
	return x;
}


struct serialDevice * serialNewDevice(struct serialDevice *dev) {
        struct serialDevice *ret;
        
        ret = malloc(sizeof(struct serialDevice));
        memset(ret,'\0',sizeof(struct serialDevice));
        ret=(struct serialDevice *)newDevice((struct device *)dev,(struct device *)ret);
        ret->bus = BUS_SERIAL;
        ret->newDevice = serialNewDevice;
        ret->freeDevice = serialFreeDevice;
	ret->writeDevice = serialWriteDevice;
	ret->compareDevice = serialCompareDevice;
	if (dev && dev->bus == BUS_SERIAL) {
		if (dev->pnpmfr)
		  ret->pnpmfr=strdup(dev->pnpmfr);
		if (dev->pnpmodel)
		  ret->pnpmodel=strdup(dev->pnpmodel);
		if (dev->pnpcompat)
		  ret->pnpcompat=strdup(dev->pnpcompat);
		if (dev->pnpdesc)
		  ret->pnpdesc=strdup(dev->pnpdesc);
	}
        return ret;
}

/* UNUSED */
void print_status_lines( int fd ) {
    int modem_lines;
    
   ioctl(fd, TIOCMGET, &modem_lines);
    
   printf("DTR : %s\n",(modem_lines & TIOCM_DTR ? "On" : "Off"));
   printf("RTS : %s\n",(modem_lines & TIOCM_RTS ? "On" : "Off"));
   printf("CTS : %s\n",(modem_lines & TIOCM_CTS ? "On" : "Off"));
   printf("DSR : %s\n",(modem_lines & TIOCM_DSR ? "On" : "Off"));
   printf("CD  : %s\n",(modem_lines & TIOCM_CD  ? "On" : "Off"));
   printf("RI  : %s\n",(modem_lines & TIOCM_RI  ? "On" : "Off"));
    
}


/* UNUSED except in debug */
/* outputs data in a hex table, 8 values per row */
void print_hex_data( unsigned char *data, int len ) {
        int i, j, pos;
    
        if (len == 0) {
	            printf("No data to print.\n");
	            return;
	}
    
        pos = 0;
        for (i=0; i< len; i+=8) {
	            printf("0x%.4x ", i);
	            for (j=i; j < len && j < i+8; j++) {
			            printf("0x%.2x ",data[pos++]);
		    }
	            printf("\n");
	}
}


/*
 * wait_input - wait until there is data available on fd,
 * for the length of time specified by *timo (indefinite
 * if timo is NULL).
 */

int wait_for_input (int fd, struct timeval *timo) {
    fd_set ready;
    int n;
    
    FD_ZERO(&ready);
    FD_SET(fd, &ready);

    n = select(fd+1, &ready, NULL, &ready, timo);
    return n;
}

/* UNUSED */
/* read characters into the buffer buf, until one of: */
/*      char_timeout expired before next character arrives */
/*      total_timeout expires                             */
/*      maxlen characters are retrieved                   */
/*                                                        */
/* returns < 0 if it fails                                */
/* otherwise the # of characters received is returned     */
/* char_timeout is in microseconds (millionths of a sec)  */
/* total_timeout is in seconds                            */
int timed_serial_read(int fd, int char_timeout, int total_timeout,
		      unsigned char *buf, int maxlen ) {

    int done, pos, starttime, temp;
    struct timeval timo;
    unsigned char intbuf[2];
    
    /* start reading */
    done = 0;
    pos  = 0;
    starttime=time(NULL);
    memset(buf, 0, maxlen);
    while (!done) {
	timo.tv_sec=0;
	timo.tv_usec=char_timeout;
	if (wait_for_input(fd, &timo) > 0) {
	    temp = read( fd, intbuf, 1 );
	    if (temp < 0) {
		if (errno != EAGAIN)
		    return -1;
	    } else {
		buf[pos++] = intbuf[0];
		buf[pos] = 0;
	    }
	} else
	    done = 1;

	/* shouldnt run more than 5 seconds */
	if (time(NULL)-starttime > total_timeout )
	    done = 1;

	if (pos > maxlen)
	    done = 1;
    }
    return pos;
}
    

int open_serial_port( char *port ) {
    int fd;

    fd = open( port, O_RDWR | O_NONBLOCK);
    if (fd < 0)
	return -1;

    /* reset file so it is no longer in non-blocking mode */
    if (fcntl(fd, F_SETFL, 0) < 0) {
	close(fd);
	return -1;
    }
	
    return fd;
}

/* <0 means ioctl error occurred */    
int get_serial_lines( int fd ) {
    int modem_lines;
    
    ioctl(fd, TIOCMGET, &modem_lines);
    return modem_lines;
}

/* <0 means ioctl error occurred */    
int set_serial_lines( int fd, int modem_lines ) {
    return ioctl(fd, TIOCMSET, &modem_lines);
}

/* set serial port to 1200 baud, 'nbits' bits, 1 stop, no parity */
int setup_serial_port( int fd, int nbits, struct termios *attr ) {
	
    attr->c_iflag = IGNBRK | IGNPAR;
    attr->c_cflag = 0;
    attr->c_cflag &= ~(CSIZE | CSTOPB | PARENB | PARODD | PARENB);
    attr->c_cflag |=  CREAD | CLOCAL; /*| CRTSCTS ; */
    if (nbits == 7)
	attr->c_cflag |= CS7 | CSTOPB;
    else
	attr->c_cflag |= CS8;
    attr->c_oflag = 0;
    attr->c_lflag = 0;

    attr->c_cc[VMIN] = 1;
    attr->c_cc[VTIME] = 5;

    cfsetospeed( attr, B1200);
    cfsetispeed( attr, B1200);
    return tcsetattr(fd, TCSANOW, attr);
}

/* Initialize the serial port to a known state *before* probing. This is
 * apparently required for some Logitech mice, who will stubbornly refuse
 * to respond to PnP probes after they've been opened by gpm or XFree.
 */

int init_port(int fd) {
	struct termios attr;
	
	if (tcgetattr(fd,&attr))
	  return 1;
	
	cfsetospeed(&attr, B2400);
	cfsetispeed(&attr, B2400);
	attr.c_iflag = IXON | ICRNL;
	attr.c_cflag = CLOCAL | HUPCL | CREAD | B9600 | CS8;
	attr.c_oflag = 0;
	attr.c_lflag = 0;
	return tcsetattr(fd, TCSANOW, &attr);
}


/* Request for PnP info from serial device                      */
/* See page 6 of the pnpcom doc from Microsoft                  */
/* Return code tells us what happened                           */
/*                                                              */
/* PNP_COM_FATAL      - error, errno has reason                 */
/* PNP_COM_OK         - probe initiated successfully            */
/* PNP_COM_FAIL       - DSR never came on - try alterntives     */
/*                          means (ATI9?) to get PnP string     */
int init_pnp_com_seq1( int fd ) {
    int modem_lines;
    int temp;
    int dsr_status;
    int rc = PNP_COM_OK;
    struct termios portattr;

    if (init_port(fd))
	  return PNP_COM_FATAL;

    modem_lines = get_serial_lines(fd);

    /* turn off RTS */
    modem_lines &= ~TIOCM_RTS;
    set_serial_lines(fd, modem_lines);

    /* wait 200ms for DSR=1 */
    usleep(200000);

    dsr_status = get_serial_lines(fd) & TIOCM_DSR;
    /* see if we got DSR coming up */

    if (!dsr_status) {
	/* turn DTR and RTS back on and try alternative methods */
	modem_lines |= TIOCM_DTR | TIOCM_RTS;
	set_serial_lines(fd, modem_lines);
	rc = PNP_COM_OK;
    }

    /* COM port Setup, 1st phase */
    /* now we set port to be 1200 baud, 7 bits, no parity, 1 stop bit */
    temp = tcgetattr(fd, &portattr);
    if (temp < 0) 
	return PNP_COM_FATAL;
    /* goto 1200 baud, etc etc as PnP requires */
    temp = setup_serial_port( fd, 7, &portattr );
    if (temp < 0) 
	return PNP_COM_FATAL;

    /* we drop DTR and RTS */
    modem_lines &= ~( TIOCM_RTS | TIOCM_DTR);
    set_serial_lines(fd, modem_lines);
    usleep(200000);

    /* bring DTR back up */
    modem_lines |= TIOCM_DTR;
    set_serial_lines(fd, modem_lines);
    usleep(200000);

    /* now entering next phase */
    modem_lines |= TIOCM_RTS;
    set_serial_lines(fd, modem_lines);
    usleep(200000);

    return rc;
}


/* Request for PnP info from serial device                      */
/* Uses ATI9 code, may not do anything but return 'ERROR'       */
/* Return code tells us what happened                           */
/*                                                              */
/* PNP_COM_FATAL      - error, errno has reason                 */
/* PNP_COM_OK         - probe initiated successfully            */
/* PNP_COM_FAIL       - DSR never came on - try alterntives     */
/*                          means (ATI9?) to get PnP string     */
int init_pnp_com_ati9( int fd ) {
    int modem_lines;
    int temp;
    int done;
    int respindex;
    int starttime;
    unsigned char resp[100], buf[2];
    struct timeval timo;
    struct termios portattr;

    modem_lines = get_serial_lines(fd);

    /* turn off RTS */
    modem_lines &= ~TIOCM_RTS;
    set_serial_lines(fd, modem_lines);

    /* wait 200ms for DSR=1 */
    usleep(200000);

    /* now we set port to be 1200 baud, 8 bits, no parity, 1 stop bit */
    temp = tcgetattr(fd, &portattr);
    if (temp < 0) {
	modem_lines |= TIOCM_DTR | TIOCM_RTS;
	set_serial_lines(fd, modem_lines);
	return PNP_COM_FATAL;
    }

    /* goto 1200 baud, 8 bits */
    temp = setup_serial_port( fd, 8, &portattr );
    if (temp < 0) {
	modem_lines |= TIOCM_DTR | TIOCM_RTS;
	set_serial_lines(fd, modem_lines);
	return PNP_COM_FATAL;
    }

    /* turn on DTR and RTS */
    modem_lines = get_serial_lines(fd);
    modem_lines |= TIOCM_RTS | TIOCM_DTR;
    set_serial_lines(fd, modem_lines);
    usleep(200000);

    /* send the 'AT' command */
    if (debug_level > 0)
	printf("Sending ATI9 command to modem\n");
    
    write(fd, "ATI9\r", 5);
    
    /* start reading - read the AT command back */
    done     = 0;
    respindex= 0;
    starttime=time(NULL);
    memset(resp, 0, sizeof(resp));
    while (!done) {
	timo.tv_sec=0;
	timo.tv_usec=250000;
	if (wait_for_input(fd, &timo) > 0) {
	    temp = read( fd, buf, 1 );
	    if (temp < 0) {
		if (errno != EAGAIN)
		    return PNP_COM_FATAL;
	    } else {
		resp[respindex++] = buf[0];
		resp[respindex] = 0;
	    }
	} else
	    done = 1;

	/* shouldnt run more than 5 seconds */
	if (time(NULL)-starttime > 5 )
	    done = 1;

	if (respindex > 6)
	    done = 1;

	if (strstr(resp, "ATI9\r"))
	    done = 1;

	if (debug_level > 0)
	    printf("ATI9 probe ->%d \"%s\"\n",respindex, resp);
    }
    
    /* see if we saw the 'OK' response */
    if (strstr(resp, "("))
	return PNP_COM_OK;
    else
	return PNP_COM_FAIL;
    
    return PNP_COM_OK;
}

/* See if this is a legacy mouse device                         */
/* Only called if the PnP probe above failed                    */
/* We turn off the mouse via RS232 lines, then turn it on       */
/* If it spits out an 'M' character (at 1200 baud, 7N1)         */
/* it could be a mouse.                                         */
/*                                                              */
/* Return code tells us what happened                           */
/*                                                              */
/* PNP_COM_FATAL     - error, errno has reason                  */
/* PNP_COM_OK        - probe saw 'M'                            */
/* PNP_COM_FAIL      - Never saw the 'M' response               */

int find_legacy_mouse( int fd ) {
    int modem_lines;
    int temp;
    int done;
    int starttime;
    unsigned char resp[2];
    struct timeval timo;
    struct termios portattr;

    /* now we set port to be 1200 baud, 7 bits, no parity, 1 stop bit */
    temp = tcgetattr(fd, &portattr);
    if (temp < 0) 
	return PNP_COM_FATAL;

    /* goto 1200 baud, etc etc*/
    temp = setup_serial_port( fd, 7, &portattr );
    if (temp < 0) 
	return PNP_COM_FATAL;

    /* we drop DTR and RTS */
    modem_lines = get_serial_lines(fd);
    modem_lines &= ~( TIOCM_RTS | TIOCM_DTR);
    set_serial_lines(fd, modem_lines);
    usleep(200000);

    /* bring them DTR back up */
    modem_lines |= TIOCM_DTR | TIOCM_RTS;
    set_serial_lines(fd, modem_lines);

    /* start reading - after first character we quit */
    done     = 0;
    starttime=time(NULL);
    while (!done) {
	timo.tv_sec=0;
	timo.tv_usec=250000;
	if (wait_for_input(fd, &timo) > 0) {
	    temp = read( fd, resp, 1 );
	    if (temp < 0) {
		if (errno != EAGAIN)
		    return PNP_COM_FATAL;
	    } else {
		done = 1;
	    }
	} else
	    done = 1;


	/* shouldnt run more than 2 seconds */
	if (time(NULL)-starttime > 2 )
	    done = 1;
    }
    if (*resp == 'M') 
	return PNP_COM_OK;
    else
	return PNP_COM_FAIL;
}

/* See if this is a legacy modem device                         */
/* Only called if the PnP probe above failed                    */
/* We send a '!AT' and see if we get an 'OK' back               */
/*                                                              */
/* Return code tells us what happened                           */
/*                                                              */
/* PNP_COM_FATAL     - error, errno has reason                  */
/* PNP_COM_OK        - probe saw 'OK'                           */
/* PNP_COM_FAIL      - Never saw the 'OK' response              */
int find_legacy_modem( int fd ) {
    int modem_lines;
    int temp;
    int done;
    int respindex;
    int starttime;
    unsigned char resp[10], buf[2];
    struct timeval timo;
    struct termios portattr;

    /* now we set port to be 1200 baud, 8 bits, no parity, 1 stop bit */
    temp = tcgetattr(fd, &portattr);
    if (temp < 0) 
	return PNP_COM_FATAL;

    /* goto 1200 baud, 8 bits */
    temp = setup_serial_port( fd, 8, &portattr );
    if (temp < 0) 
	return PNP_COM_FATAL;

    /* turn on DTR and RTS */
    modem_lines = get_serial_lines(fd);
    modem_lines |= TIOCM_RTS | TIOCM_DTR;
    set_serial_lines(fd, modem_lines);
    usleep(200000);

    /* send the 'AT' command */
    if (debug_level > 0)
	printf("Sending AT command to modem\n");
    
    write(fd, "AT\r", 3);
    
    /* start reading - we'll get AT command back first, then modem response */
    done     = 0;
    respindex= 0;
    starttime=time(NULL);
    memset(resp, 0, sizeof(resp));
    while (!done) {
	timo.tv_sec=0;
	timo.tv_usec=250000;
	if (wait_for_input(fd, &timo) > 0) {
	    temp = read( fd, buf, 1 );
	    if (temp < 0) {
		if (errno != EAGAIN)
		    return PNP_COM_FATAL;
	    } else {
		resp[respindex++] = buf[0];
	    }
	} else
	    done = 1;

	/* shouldnt run more than 5 seconds */
	if (time(NULL)-starttime > 5 )
	    done = 1;

	if (respindex > 9)
	    done = 1;
    }
    
    /* see if we saw the 'OK' response */
    if (strstr(resp, "OK"))
	return PNP_COM_OK;
    else
	return PNP_COM_FAIL;
}

/* retrieve the PnP ID string */
/* timeout after 3 seconds   */
/* should probably set a 200 msec timeout per char, as spec says */
/* if no char received, we're done                              */
int read_pnp_string( int fd, unsigned char *pnp_string, int *pnp_len, int pnp_stringbuf_size ) {
    int     pnp_index;
    int     temp, done, counter;
    int     seen_start;
    time_t  starttime;
    struct timeval timo;
    unsigned char buf[80];
    unsigned char end_char;
    
    /* see if we have any input waiting */
    pnp_index  =0;
    seen_start = 0;
    done       = 0;
    end_char   = 0;
    starttime=time(NULL);
    while (!done) {
	timo.tv_sec=0;
	timo.tv_usec=250000;
	if (wait_for_input(fd, &timo) > 0) {
	    temp = read( fd, buf, 1 );
	    if (temp < 0) {
		if (errno != EAGAIN)
		    return PNP_COM_FATAL;
	    } else {
		for (counter=0; counter < temp; counter++) {
		    pnp_string[pnp_index++] = buf[counter];
		    if (seen_start) {
			if (buf[counter] == end_char) {
			    done=1;
			    break;
			}
		    } else {
			if (buf[counter] == BeginPnP1) {
			    seen_start = 1;
			    end_char   = EndPnP1;
			} else if (buf[counter] == BeginPnP2) {
			    seen_start = 1;
			    end_char   = EndPnP2;
			}
		    }
		}
	    }
	} else
	    done = 1;
	
	/* shouldnt run more than 4 seconds */
	if (time(NULL)-starttime > 4 )
	    done = 1;

	if (pnp_index >= pnp_stringbuf_size)
	    done = 1;
    }
    pnp_string[pnp_index] = 0;
   *pnp_len=pnp_index;
    return 0;
}

/* UNUSED */
/* simple little helper function */
void xlate_memcpy( void *dest, void *src, int len, int xlate_flag ) {
  unsigned char *d, *s;
  int i;

  for (i=0,d=dest,s=src; i<len; i++, d++, s++) 
   *d = (*s) + ((xlate_flag) ? 0x20 : 0 );
}   

/* parse the PnP ID string into components */
int parse_pnp_string( unsigned char *pnp_id_string, int pnp_len,
		     struct pnp_com_id *pnp_id ) {
    unsigned char *p1, *p2;
    unsigned char *start;
    unsigned char *end;
    unsigned char *curpos;
    unsigned char *endfield;
    unsigned char *temppos;
    unsigned char *pnp_string;
    unsigned char end_char;

    int no_more_extensions=0;
    int stage;
    int len;
    unsigned short int checksum;
    char hex_checksum[5];

    char extension_delims[] = {EndPnP1, EndPnP2, ExtendPnP1, ExtendPnP2, 0};
    char end_delims[] = {EndPnP1, EndPnP2, 0};

    /* clear out pnp_id */
    memset(pnp_id, 0, sizeof(*pnp_id));

    /* copy pnp_string to temp space */
    pnp_string = alloca(pnp_len+1);
    memcpy(pnp_string, pnp_id_string, pnp_len+1);
    
    /* first find the start of the PnP part of string */
    p1 = memchr( pnp_string, BeginPnP1, pnp_len );
    p2 = memchr( pnp_string, BeginPnP2, pnp_len );

    /* use the one which points nearest to start of the string */
    /* and is actually defined                                */
    if ( p1 && p2 ) {
	start = (p1 < p2) ? p1 : p2;
    } else if (p1)
	start = p1;
    else if (p2)
	start = p2;
    else
	start = NULL;

    /* if no start then we're done */
    if (!start)
	return -1;
    
    /* the length of the initial part cannot be more than 17 bytes */
    if ((start - pnp_string) > 17)
	return -1;

    /* setup end character we are looking for based on the start character */
    if (start == p2) {
      pnp_id->xlate_6bit = 1;
      end_char = EndPnP2;
      /* we need to xlate data in PnP fields */
      /* remember to skip the revision fields (bytes 1 and 2 after start) */
      temppos=start;
      while (1) {
	  if (*temppos == EndPnP2) {
	     *temppos += 0x20;
	      break;
	  } else if (temppos != start+1 && temppos != start+2 )
	     *temppos += 0x20;
	  
	  temppos++;
      }	      
    } else {
      pnp_id->xlate_6bit = 0;
      end_char = EndPnP1;
    }
    
    /* move everything before the start of the PnP block */
    memcpy(pnp_id->other_id, pnp_string, start-pnp_string);
    pnp_id->other_len = start - pnp_string;

    /* now we get the PnP fields - all were zero'd out above */
    curpos = start+1;
    memcpy(pnp_id->pnp_rev,curpos,2);       curpos += 2;
    memcpy(pnp_id->eisa_id,curpos,3);       curpos += 3;
    memcpy(pnp_id->product_id,curpos,4);    curpos += 4;
    /* now we see if have extension fields */
    no_more_extensions = 0;
    stage = 0;
    while (!no_more_extensions) {
	if (*curpos == ExtendPnP1 || *curpos == ExtendPnP2) {
	    curpos++;
	    endfield = strpbrk(curpos, extension_delims);
	    if (!endfield)
		return -1;
	    /* if we reached the end of all PnP data, back off */
	    /* cause there is a checksum at the end of extension data */
	    if (*endfield == EndPnP1 || *endfield == EndPnP2)
		endfield -= 2;
	} else
	    break;

	len = endfield - curpos;
	switch (stage) {
	  case 0:
	    if (len != 8 && len != 0 )
		return -1;
	    
	    memcpy(pnp_id->serial_number,curpos,len);
	    curpos += len;
	    break;

	  case 1:
	    if (len > 33)
		return -1;
	    memcpy(pnp_id->class_name, curpos, len);
	    curpos = endfield;
	    break;

	  case 2:
	    if (len > 41)
		return -1;
	    memcpy(pnp_id->driver_id, curpos, len);
	    curpos = endfield;
	    break;

	  case 3:
	    if (len > 41)
		return -1;
	    memcpy(pnp_id->user_name, curpos, len);
	    curpos = endfield;
	    break;
	}
	stage++;
    }

    /* now find the end of all PnP data */
    end = strpbrk(curpos, end_delims);
    if (!end)
	return -1;
    
    /* if we had any extensions, we expect an checksum */
    if (stage != 0) {
	/* copy checksum into struct */
	memcpy(pnp_id->checksum, curpos, 2);
	
	/* compute the checksum as the sum of all PnP bytes, excluding */
	/* the two byte checksum. */
	checksum = 0;
	for (temppos=start; temppos <= end; temppos++) {
	    /* skip checksum in calculation */
	    if (temppos == (end-2) || temppos == (end-1))
		continue;
	    /* dont xlate the revision at start */
	    if (temppos != (start+1) && temppos != (start+2))
		checksum += *temppos - ((pnp_id->xlate_6bit) ? 0x20 : 0);
	    else
		checksum += *temppos;
	}
	sprintf(hex_checksum, "%.2X", checksum & 0xff);
	if (strncmp(hex_checksum, pnp_id->checksum, 2))
	    return -1;
    }

    /* checksum was ok, so we're done */
    return 0;
}

/* UNUSED except for debugging */
void print_pnp_id( struct pnp_com_id id ) {
    int i;
    int extensions_exist;
    int revision_temp;

    if (id.other_len != 0) {
	printf("Detected non-PnP data stream at start.\n");
	printf("  Length   = 0x%x\n",id.other_len);
	printf("  Contents =");
	for (i=0; i<id.other_len; i++)
	    printf(" 0x%x",id.other_id[i]);
	printf("\n");
    } else
	printf("Non-PnP data stream not detected at start.\n");


    /* parse PnP revision bytes into a string values (eg. "1.00") */
    revision_temp = ((id.pnp_rev[0]&0x3f) << 6)+(id.pnp_rev[1]&0x3f);
    sprintf(id.pnp_rev_str, "%d.%d",revision_temp/100,revision_temp % 100);
    
    printf("\nPnP Required fields:\n");
    printf("    Revision       = %s\n",id.pnp_rev_str);
    printf("    Manufacturer   = %s\n",id.eisa_id);
    printf("    Product ID     = %s\n",id.product_id);

    extensions_exist = id.serial_number[0] || id.class_name[0] ||
                       id.driver_id[0]     || id.user_name[0];

    if (extensions_exist) {
	printf("\nPnP extension field(s) exist:\n");
	if (id.serial_number[0])
	    printf("    Serial Number   = %s\n",id.serial_number);
	if (id.class_name[0])
	    printf("    PnP class name  = %s\n",id.class_name);
	if (id.driver_id[0])
	    printf("    PnP Compatible  = %s\n",id.driver_id);
	if (id.user_name[0])
	    printf("    PnP Description = %s\n",id.user_name);
    }
}

int attempt_pnp_retrieve(int fd, char *pnp_string, int *pnp_strlen, int pnp_stringbuf_size) {
    int pnp_probe_status;
    int tried_at_prodding;
    int give_up;
    struct pnp_com_id pnp_id;

    tried_at_prodding=0;
    give_up=0;

    while (!give_up) {
	pnp_probe_status = init_pnp_com_seq1(fd);
	if (pnp_probe_status == PNP_COM_FATAL) {
	    return(PNP_COM_FATAL);
	} else if (pnp_probe_status == PNP_COM_OK) {
	    read_pnp_string(fd, pnp_string, pnp_strlen, pnp_stringbuf_size );
	
	    if (debug_level > 0) {
		printf("\nPNP string = |%s|\n\n",pnp_string);
		print_hex_data(pnp_string, *pnp_strlen);
	    }
	    
	    if (*pnp_strlen == 1 && pnp_string[0] == 'M') /* legacy mouse */
	      return PNP_COM_OK;
	    /* see if we got anything useful, if not try at command */
	    /* to prod device into correct serial params       */
	    if (parse_pnp_string( pnp_string, *pnp_strlen, &pnp_id )<0)
		if (!tried_at_prodding) {
		    write(fd, "AT\r", 3);
		    tried_at_prodding=1;
		} else
		    give_up = 1;
	    else
		return PNP_COM_OK;
	} else
	    give_up = 1;
    }

    /* try sending a ATI9 code to the modem to see if we get PnP id back */
    init_pnp_com_ati9(fd);
    read_pnp_string(fd, pnp_string, pnp_strlen, pnp_stringbuf_size );
    if (parse_pnp_string( pnp_string, *pnp_strlen, &pnp_id )<0) {
	*pnp_strlen = 0;
	pnp_string[0] = 0;
	return PNP_COM_FAIL;
    } else
	return PNP_COM_OK;
}

struct device *serialProbe(enum deviceClass probeClass, int probeFlags,
			   struct device *devlist) {
    int fd;
    int temp;
    int pnp_strlen;
    int devicetype=-1;
    unsigned char pnp_string[100];
    char port[20];
    struct termios origattr;
    struct pnp_com_id pnp_id;
    struct serialDevice *serdev;
    struct stat sb;
    int maj, twelve=12;
    int console=-1;
    int stdin_line=-1;
    struct serial_struct si;
	
    if (probeFlags & PROBE_SAFE) return devlist;

    /* Are we on a serial console? */
    fstat(0,&sb);
    maj = major(sb.st_rdev);
    if (maj != 4 && (maj < 136 || maj > 143)) {
	    if (ioctl (0, TIOCLINUX, &twelve) < 0) {
		    if (ioctl (0, TIOCGSERIAL, &si) >= 0) {
			    if (si.line > 0) {
				    stdin_line = 1 << si.line;
			    } else {
				    stdin_line = 0;
			    }
		    } else stdin_line = 0;
	    }
    }
	
    fd=open("/dev/console",O_RDWR);
    if (fd != -1) {
	    fstat(fd,&sb);
	    maj = major(sb.st_rdev);
	    if (maj != 4 && (maj < 136 || maj > 143)) {
		    if (ioctl (fd, TIOCLINUX, &twelve) < 0) {
			#ifdef __powerpc__
			// we could have gotten an error for another reason - like EINVAL
			// skipping ttyS0 on PPC - which is where most modems reside
			if (errno == ENOTTY) {
			#endif
			    if (ioctl (fd, TIOCGSERIAL, &si) >= 0) {
				    if (si.line > 0) {
					    console = 1 << si.line;
				    } else {
					    console = 0;
				    }
			    } else console = 0;
			#ifdef __powerpc__
			}
			#endif 
		    }
	    }
	    close(fd);
    }

	
    if (
	(probeClass == CLASS_UNSPEC) ||
	(probeClass == CLASS_OTHER) ||
	(probeClass == CLASS_MOUSE) ||
	(probeClass == CLASS_MODEM) ||
	(probeClass == CLASS_PRINTER)
	) {
	int x;
	
	for (x=0; x<=3 ; x++) {
	    struct stat sbuf;
	    char lockfile[32];
	    if (x==console || x==stdin_line) continue;
	    snprintf(port,20,"/dev/ttyS%d",x);

	    /* Make sure it's not in use */
	    snprintf(lockfile,32,"/var/lock/LCK..ttyS%d",x);
	    if (!stat(lockfile,&sbuf)) 
		 continue;
	    memset(lockfile,'\0',32);
	    if (readlink("/dev/modem",lockfile,32)>0) {
		    if (!strcmp(basename(port),basename(lockfile))) {
			    snprintf(lockfile,32,"/var/lock/LCK..modem");
			    if (!stat(lockfile,&sbuf))
			      continue;
		    }
	    }
	    
	    if ((fd=open_serial_port(port)) < 0) {
		    continue;
	    }
	    /* save the current state of the port */
	    temp = tcgetattr(fd, &origattr);
	    if (temp < 0) {
		    close(fd);
		    continue;
	    }

	    /* try twiddling RS232 control lines and see if it talks to us */
	    devicetype=-1;
	    pnp_strlen = 0;
	    attempt_pnp_retrieve( fd, pnp_string, &pnp_strlen, sizeof(pnp_string) - 1 );
	
	    /* see if we found any PnP signature */
	    if (pnp_strlen != 0) {
		if (*pnp_string == 'M') { /* Legacy mouse */
			if (probeClass == CLASS_MOUSE || probeClass == CLASS_UNSPEC) {
				serdev = serialNewDevice(NULL);
				serdev->class=CLASS_MOUSE;
				serdev->device=strdup(port+5);
				serdev->desc=strdup("Generic Serial Mouse");
				serdev->driver=strdup("generic");
				if (devlist)
				  serdev->next = devlist;
				devlist = (struct device *)serdev;
				if (probeFlags & PROBE_ONE) {
					tcsetattr(fd, TCSANOW, &origattr);
					tcflush(fd, TCIOFLUSH);
					close(fd);
					return devlist;
				}
			}
			tcsetattr(fd, TCSANOW, &origattr);
			close(fd);
			continue;
		}
		/* fill in the PnP com structure */
		if (parse_pnp_string( pnp_string, pnp_strlen, &pnp_id )<0) {
			goto endprobe;
		} else {
		    char *foo;
		    int len;

		    if (debug_level > 0) {
			printf("PnP ID string for serial device on port %s\n",port);
			print_pnp_id( pnp_id );
		    }
		    serdev = serialNewDevice(NULL);
		    if (pnp_id.user_name[0]) {
			    serdev->pnpdesc = strdup(pnp_id.user_name);
			len = strlen(pnp_id.eisa_id)+strlen(pnp_id.product_id)+strlen(pnp_id.user_name)+3;
			foo = malloc(len);
			snprintf(foo,len,"%s|%s %s",pnp_id.eisa_id,pnp_id.product_id,pnp_id.user_name);
		    } else {
			len = strlen(pnp_id.eisa_id)+strlen(pnp_id.product_id)+3;
			foo = malloc(len);
			snprintf(foo,len,"%s|%s",pnp_id.eisa_id,pnp_id.product_id);
		    }
		    serdev->desc=strdup(foo);
		    serdev->device=strdup(port+5);
		    serdev->driver=strdup("ignore");
			serdev->pnpmfr = strdup(pnp_id.eisa_id);
			serdev->pnpmodel = strdup(pnp_id.product_id);
			
		    free(foo);
		    foo=pnp_id.product_id;
		    if (pnp_id.driver_id) {
			if (strstr(pnp_id.driver_id,"PNP"))
			  foo = strstr(pnp_id.driver_id,"PNP")+3;
			    serdev->pnpcompat = strdup(pnp_id.driver_id);
		    }
		    if (!strncmp(foo, "0F", 2))
		      serdev->class = CLASS_MOUSE;
		    else if (!strncmp(foo, "C", 1))
		      serdev->class = CLASS_MODEM;
		    else if (!strncmp(pnp_id.class_name, "Modem", 5))
		      serdev->class = CLASS_MODEM;
		    else
		      serdev->class = CLASS_OTHER;
		    if (serdev->class == probeClass || probeClass == CLASS_UNSPEC) {
		      if (devlist)
			serdev->next = devlist;
		      devlist = (struct device *)serdev;
		      if (probeFlags & PROBE_ONE) {
			tcsetattr(fd, TCSANOW, &origattr);
			tcflush(fd, TCIOFLUSH);
			close(fd);
			return devlist;
		      }
		    } else {
		      serdev->freeDevice(serdev);
		    }
		    goto endprobe;
		}
	    } else {
		/* try to find a legacy device */

		temp = find_legacy_mouse(fd);
		if (temp == PNP_COM_FATAL) {
			goto endprobe;
		} else if (temp == PNP_COM_OK) {
			if (probeClass == CLASS_UNSPEC || probeClass == CLASS_MOUSE) {
				serdev=serialNewDevice(NULL);
				serdev->class = CLASS_MOUSE;
				serdev->device = strdup(port+5);
				serdev->driver= strdup("generic");
				serdev->desc = strdup("Generic Serial Mouse");
				if (devlist)
				  serdev->next = devlist;
				devlist = (struct device *)serdev;
				if (probeFlags & PROBE_ONE) {
					tcsetattr(fd, TCSANOW, &origattr);
					tcflush(fd, TCIOFLUSH);
					close(fd);
					return devlist;
				}
			}
			goto endprobe;
		} else {
		    if (debug_level > 0)
		      printf("Didnt see a legacy mouse, need to ATI it now.\n");

		    temp = find_legacy_modem(fd);
		    if (temp == PNP_COM_FATAL) {
			    goto endprobe;
		    } else if (temp == PNP_COM_OK) {
			if (debug_level > 0)
			  printf("\nLegacy modem signature seen.\n\n");
			if (probeClass == CLASS_UNSPEC || probeClass == CLASS_MODEM) {
				serdev=serialNewDevice(NULL);
				serdev->class = CLASS_MODEM;
				serdev->device = strdup(port+5);
				serdev->driver= strdup("ignore");
				serdev->desc = strdup("Generic Serial Modem");
				if (devlist)
				  serdev->next = devlist;
				devlist = (struct device *)serdev;
				if (probeFlags & PROBE_ONE) {
					tcsetattr(fd, TCSANOW, &origattr);
					tcflush(fd, TCIOFLUSH);
					close(fd);
					return devlist;
				}
			}
			    goto endprobe;
		    } else {
			if (debug_level > 0)
			  printf("Didnt see a legacy modem, game over.\n");
		    }
		}
	    }
endprobe:
	    tcsetattr(fd, TCSANOW, &origattr);
	    tcflush(fd, TCIOFLUSH);
	    close(fd);
	}
    }
    return devlist;
}