code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* PR rtl-optimization/14692 */ void assert_failed (void); void eidecpos_1 (unsigned char *pos, long n) { int i; for (i = 0; i < n; i++) { const unsigned char *dc_ptr1 = pos; pos--; if (dc_ptr1 - pos == 1) assert_failed (); } }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/gcc.c-torture/compile/pr14692.c
C
gpl-2.0
272
<?php namespace Guzzle\Service\Resource; use Guzzle\Common\Exception\InvalidArgumentException; use Guzzle\Service\Command\CommandInterface; /** * Factory that utilizes multiple factories for creating iterators */ class CompositeResourceIteratorFactory implements ResourceIteratorFactoryInterface { /** @var array Array of factories */ protected $factories; /** @param array $factories Array of factories used to instantiate iterators */ public function __construct(array $factories) { $this->factories = $factories; } public function build(CommandInterface $command, array $options = array()) { if (!($factory = $this->getFactory($command))) { throw new InvalidArgumentException('Iterator was not found for ' . $command->getName()); } return $factory->build($command, $options); } public function canBuild(CommandInterface $command) { return $this->getFactory($command) !== false; } /** * Add a factory to the composite factory * * @param ResourceIteratorFactoryInterface $factory Factory to add * * @return self */ public function addFactory(ResourceIteratorFactoryInterface $factory) { $this->factories[] = $factory; return $this; } /** * Get the factory that matches the command object * * @param CommandInterface $command Command retrieving the iterator for * * @return ResourceIteratorFactoryInterface|bool */ protected function getFactory(CommandInterface $command) { foreach ($this->factories as $factory) { if ($factory->canBuild($command)) { return $factory; } } return false; } }
tokenly/tokenly-cms
www/resources/aws/Guzzle/Service/Resource/CompositeResourceIteratorFactory.php
PHP
gpl-2.0
1,775
jQuery( function( $ ) { pm.bind( 'googlePlusSignInMessage', function( message ) { if ( 'undefined' != typeof message.error) GooglePlusMessageHandler.error( message.error ); else if ( 'undefined' != typeof message.success && 'undefined' != typeof message.result ) GooglePlusMessageHandler.success( message.result ); else GooglePlusMessageHandler.unknownMessage( message ); } ); var GooglePlusMessageHandler = { outputContainer: '#result', success: function( result ) { $.post( './admin-ajax.php', { action: 'save_gplus_profile_data', name: result.name, url: result.url, profile_image: result.profile_image, id: result.id, state: result.state }, function() { $( GooglePlusMessageHandler.outputContainer ).text( GPlusL10n.connected ); window.location.href = 'options-general.php?page=sharing&r=' + Math.round( Math.random()*100000 ) + '#gplus'; } ); }, error: function( error ) { if ( 'unknown' == error ) { $( GooglePlusMessageHandler.outputContainer ).text( GPlusL10n.unknownError ); } else if ( 'access_denied' == error ) { $( GooglePlusMessageHandler.outputContainer ).text( GPlusL10n.accessDenied ); } else { $( GooglePlusMessageHandler.outputContainer ).text( error ); } }, unknownMessage: function( message ) { console.log( 'DEBUG: An unknown message was passed via postMessage:' ); console.log( message ); GooglePlusMessageHandler.error( 'unknown' ); }, }; $( '#disconnect-gplus' ).click( function() { var ays = confirm( 'Are you sure you want to disconnect your Google+ profile? If you have any Publicize accounts connected to this profile they will also be disconnected.' ); if ( ! ays ) { return false; } } ); } );
evantill/gssb
www.apelsohiebarat.net/migration_jekyll/gssb-construction-jekyll-bootstrap/public/assets/wp-content/plugins/jetpack/modules/gplus-authorship/admin/listener.js
JavaScript
gpl-2.0
1,770
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace DoctrineModuleTest\Validator\Adapter; use stdClass; use PHPUnit_Framework_TestCase as BaseTestCase; use DoctrineModule\Validator\NoObjectExists; /** * Tests for the NoObjectExists tests * * @license MIT * @link http://www.doctrine-project.org/ * @author Marco Pivetta <[email protected]> */ class NoObjectExistsTest extends BaseTestCase { public function testCanValidateWithNoAvailableObjectInRepository() { $repository = $this->getMock('Doctrine\Common\Persistence\ObjectRepository'); $repository ->expects($this->once()) ->method('findOneBy') ->will($this->returnValue(null)); $validator = new NoObjectExists(array('object_repository' => $repository, 'fields' => 'matchKey')); $this->assertTrue($validator->isValid('matchValue')); } public function testCannotValidateWithAvailableObjectInRepository() { $repository = $this->getMock('Doctrine\Common\Persistence\ObjectRepository'); $repository ->expects($this->once()) ->method('findOneBy') ->will($this->returnValue(new stdClass())); $validator = new NoObjectExists(array('object_repository' => $repository, 'fields' => 'matchKey')); $this->assertFalse($validator->isValid('matchValue')); } }
hieuit7/freewifi
web/vendor/doctrine/doctrine-module/tests/DoctrineModuleTest/Validator/NoObjectExistsTest.php
PHP
gpl-2.0
2,324
#ifndef DEC_PCI_H #define DEC_PCI_H #include "qemu-common.h" PCIBus *pci_dec_21154_init(PCIBus *parent_bus, int devfn); #endif
KernelAnalysisPlatform/KlareDbg
tracers/qemu/decaf/hw/dec_pci.h
C
gpl-3.0
130
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Mail * @subpackage Storage * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $ */ /** * @category Zend * @package Zend_Mail * @subpackage Storage * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_Mail_Storage_Abstract implements Countable, ArrayAccess, SeekableIterator { /** * class capabilities with default values * @var array */ protected $_has = array('uniqueid' => true, 'delete' => false, 'create' => false, 'top' => false, 'fetchPart' => true, 'flags' => false); /** * current iteration position * @var int */ protected $_iterationPos = 0; /** * maximum iteration position (= message count) * @var null|int */ protected $_iterationMax = null; /** * used message class, change it in an extened class to extend the returned message class * @var string */ protected $_messageClass = 'Zend_Mail_Message'; /** * Getter for has-properties. The standard has properties * are: hasFolder, hasUniqueid, hasDelete, hasCreate, hasTop * * The valid values for the has-properties are: * - true if a feature is supported * - false if a feature is not supported * - null is it's not yet known or it can't be know if a feature is supported * * @param string $var property name * @return bool supported or not * @throws Zend_Mail_Storage_Exception */ public function __get($var) { if (strpos($var, 'has') === 0) { $var = strtolower(substr($var, 3)); return isset($this->_has[$var]) ? $this->_has[$var] : null; } /** * @see Zend_Mail_Storage_Exception */ require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception($var . ' not found'); } /** * Get a full list of features supported by the specific mail lib and the server * * @return array list of features as array(featurename => true|false[|null]) */ public function getCapabilities() { return $this->_has; } /** * Count messages messages in current box/folder * * @return int number of messages * @throws Zend_Mail_Storage_Exception */ abstract public function countMessages(); /** * Get a list of messages with number and size * * @param int $id number of message * @return int|array size of given message of list with all messages as array(num => size) */ abstract public function getSize($id = 0); /** * Get a message with headers and body * * @param int $id number of message * @return Zend_Mail_Message */ abstract public function getMessage($id); /** * Get raw header of message or part * * @param int $id number of message * @param null|array|string $part path to part or null for messsage header * @param int $topLines include this many lines with header (after an empty line) * @return string raw header */ abstract public function getRawHeader($id, $part = null, $topLines = 0); /** * Get raw content of message or part * * @param int $id number of message * @param null|array|string $part path to part or null for messsage content * @return string raw content */ abstract public function getRawContent($id, $part = null); /** * Create instance with parameters * * @param array $params mail reader specific parameters * @throws Zend_Mail_Storage_Exception */ abstract public function __construct($params); /** * Destructor calls close() and therefore closes the resource. */ public function __destruct() { $this->close(); } /** * Close resource for mail lib. If you need to control, when the resource * is closed. Otherwise the destructor would call this. * * @return null */ abstract public function close(); /** * Keep the resource alive. * * @return null */ abstract public function noop(); /** * delete a message from current box/folder * * @return null */ abstract public function removeMessage($id); /** * get unique id for one or all messages * * if storage does not support unique ids it's the same as the message number * * @param int|null $id message number * @return array|string message number for given message or all messages as array * @throws Zend_Mail_Storage_Exception */ abstract public function getUniqueId($id = null); /** * get a message number from a unique id * * I.e. if you have a webmailer that supports deleting messages you should use unique ids * as parameter and use this method to translate it to message number right before calling removeMessage() * * @param string $id unique id * @return int message number * @throws Zend_Mail_Storage_Exception */ abstract public function getNumberByUniqueId($id); // interface implementations follows /** * Countable::count() * * @return int */ public function count() { return $this->countMessages(); } /** * ArrayAccess::offsetExists() * * @param int $id * @return boolean */ public function offsetExists($id) { try { if ($this->getMessage($id)) { return true; } } catch(Zend_Mail_Storage_Exception $e) {} return false; } /** * ArrayAccess::offsetGet() * * @param int $id * @return Zend_Mail_Message message object */ public function offsetGet($id) { return $this->getMessage($id); } /** * ArrayAccess::offsetSet() * * @param id $id * @param mixed $value * @throws Zend_Mail_Storage_Exception * @return void */ public function offsetSet($id, $value) { /** * @see Zend_Mail_Storage_Exception */ require_once 'Zend/Mail/Storage/Exception.php'; throw new Zend_Mail_Storage_Exception('cannot write mail messages via array access'); } /** * ArrayAccess::offsetUnset() * * @param int $id * @return boolean success */ public function offsetUnset($id) { return $this->removeMessage($id); } /** * Iterator::rewind() * * Rewind always gets the new count from the storage. Thus if you use * the interfaces and your scripts take long you should use reset() * from time to time. * * @return void */ public function rewind() { $this->_iterationMax = $this->countMessages(); $this->_iterationPos = 1; } /** * Iterator::current() * * @return Zend_Mail_Message current message */ public function current() { return $this->getMessage($this->_iterationPos); } /** * Iterator::key() * * @return int id of current position */ public function key() { return $this->_iterationPos; } /** * Iterator::next() * * @return void */ public function next() { ++$this->_iterationPos; } /** * Iterator::valid() * * @return boolean */ public function valid() { if ($this->_iterationMax === null) { $this->_iterationMax = $this->countMessages(); } return $this->_iterationPos && $this->_iterationPos <= $this->_iterationMax; } /** * SeekableIterator::seek() * * @param int $pos * @return void * @throws OutOfBoundsException */ public function seek($pos) { if ($this->_iterationMax === null) { $this->_iterationMax = $this->countMessages(); } if ($pos > $this->_iterationMax) { throw new OutOfBoundsException('this position does not exist'); } $this->_iterationPos = $pos; } }
Arcavias/arcavias-demo
zendlib/Zend/Mail/Storage/Abstract.php
PHP
lgpl-3.0
9,314
<?php namespace Drupal\Core\Database\Driver\mysql\Install; use Drupal\Core\Database\Install\Tasks as InstallTasks; use Drupal\Core\Database\Database; use Drupal\Core\Database\Driver\mysql\Connection; use Drupal\Core\Database\DatabaseNotFoundException; /** * Specifies installation tasks for MySQL and equivalent databases. */ class Tasks extends InstallTasks { /** * Minimum required MySQLnd version. */ const MYSQLND_MINIMUM_VERSION = '5.0.9'; /** * Minimum required libmysqlclient version. */ const LIBMYSQLCLIENT_MINIMUM_VERSION = '5.5.3'; /** * The PDO driver name for MySQL and equivalent databases. * * @var string */ protected $pdoDriver = 'mysql'; /** * Constructs a \Drupal\Core\Database\Driver\mysql\Install\Tasks object. */ public function __construct() { $this->tasks[] = [ 'arguments' => [], 'function' => 'ensureInnoDbAvailable', ]; } /** * {@inheritdoc} */ public function name() { return t('MySQL, MariaDB, Percona Server, or equivalent'); } /** * {@inheritdoc} */ public function minimumVersion() { return '5.5.3'; } /** * {@inheritdoc} */ protected function connect() { try { // This doesn't actually test the connection. db_set_active(); // Now actually do a check. try { Database::getConnection(); } catch (\Exception $e) { // Detect utf8mb4 incompability. if ($e->getCode() == Connection::UNSUPPORTED_CHARSET || ($e->getCode() == Connection::SQLSTATE_SYNTAX_ERROR && $e->errorInfo[1] == Connection::UNKNOWN_CHARSET)) { $this->fail(t('Your MySQL server and PHP MySQL driver must support utf8mb4 character encoding. Make sure to use a database system that supports this (such as MySQL/MariaDB/Percona 5.5.3 and up), and that the utf8mb4 character set is compiled in. See the <a href=":documentation" target="_blank">MySQL documentation</a> for more information.', [':documentation' => 'https://dev.mysql.com/doc/refman/5.0/en/cannot-initialize-character-set.html'])); $info = Database::getConnectionInfo(); $info_copy = $info; // Set a flag to fall back to utf8. Note: this flag should only be // used here and is for internal use only. $info_copy['default']['_dsn_utf8_fallback'] = TRUE; // In order to change the Database::$databaseInfo array, we need to // remove the active connection, then re-add it with the new info. Database::removeConnection('default'); Database::addConnectionInfo('default', 'default', $info_copy['default']); // Connect with the new database info, using the utf8 character set so // that we can run the checkEngineVersion test. Database::getConnection(); // Revert to the old settings. Database::removeConnection('default'); Database::addConnectionInfo('default', 'default', $info['default']); } else { // Rethrow the exception. throw $e; } } $this->pass('Drupal can CONNECT to the database ok.'); } catch (\Exception $e) { // Attempt to create the database if it is not found. if ($e->getCode() == Connection::DATABASE_NOT_FOUND) { // Remove the database string from connection info. $connection_info = Database::getConnectionInfo(); $database = $connection_info['default']['database']; unset($connection_info['default']['database']); // In order to change the Database::$databaseInfo array, need to remove // the active connection, then re-add it with the new info. Database::removeConnection('default'); Database::addConnectionInfo('default', 'default', $connection_info['default']); try { // Now, attempt the connection again; if it's successful, attempt to // create the database. Database::getConnection()->createDatabase($database); } catch (DatabaseNotFoundException $e) { // Still no dice; probably a permission issue. Raise the error to the // installer. $this->fail(t('Database %database not found. The server reports the following message when attempting to create the database: %error.', ['%database' => $database, '%error' => $e->getMessage()])); } } else { // Database connection failed for some other reason than the database // not existing. $this->fail(t('Failed to connect to your database server. The server reports the following message: %error.<ul><li>Is the database server running?</li><li>Does the database exist or does the database user have sufficient privileges to create the database?</li><li>Have you entered the correct database name?</li><li>Have you entered the correct username and password?</li><li>Have you entered the correct database hostname?</li></ul>', ['%error' => $e->getMessage()])); return FALSE; } } return TRUE; } /** * {@inheritdoc} */ public function getFormOptions(array $database) { $form = parent::getFormOptions($database); if (empty($form['advanced_options']['port']['#default_value'])) { $form['advanced_options']['port']['#default_value'] = '3306'; } return $form; } /** * Ensure that InnoDB is available. */ public function ensureInnoDbAvailable() { $engines = Database::getConnection()->query('SHOW ENGINES')->fetchAllKeyed(); if (isset($engines['MyISAM']) && $engines['MyISAM'] == 'DEFAULT' && !isset($engines['InnoDB'])) { $this->fail(t('The MyISAM storage engine is not supported.')); } } /** * {@inheritdoc} */ protected function checkEngineVersion() { parent::checkEngineVersion(); // Ensure that the MySQL driver supports utf8mb4 encoding. $version = Database::getConnection()->clientVersion(); if (FALSE !== strpos($version, 'mysqlnd')) { // The mysqlnd driver supports utf8mb4 starting at version 5.0.9. $version = preg_replace('/^\D+([\d.]+).*/', '$1', $version); if (version_compare($version, self::MYSQLND_MINIMUM_VERSION, '<')) { $this->fail(t("The MySQLnd driver version %version is less than the minimum required version. Upgrade to MySQLnd version %mysqlnd_minimum_version or up, or alternatively switch mysql drivers to libmysqlclient version %libmysqlclient_minimum_version or up.", ['%version' => $version, '%mysqlnd_minimum_version' => self::MYSQLND_MINIMUM_VERSION, '%libmysqlclient_minimum_version' => self::LIBMYSQLCLIENT_MINIMUM_VERSION])); } } else { // The libmysqlclient driver supports utf8mb4 starting at version 5.5.3. if (version_compare($version, self::LIBMYSQLCLIENT_MINIMUM_VERSION, '<')) { $this->fail(t("The libmysqlclient driver version %version is less than the minimum required version. Upgrade to libmysqlclient version %libmysqlclient_minimum_version or up, or alternatively switch mysql drivers to MySQLnd version %mysqlnd_minimum_version or up.", ['%version' => $version, '%libmysqlclient_minimum_version' => self::LIBMYSQLCLIENT_MINIMUM_VERSION, '%mysqlnd_minimum_version' => self::MYSQLND_MINIMUM_VERSION])); } } } }
JeramyK/training
web/core/lib/Drupal/Core/Database/Driver/mysql/Install/Tasks.php
PHP
gpl-2.0
7,275
<?php use yii\helpers\Url as Url; class AboutCest { public function ensureThatAboutWorks(AcceptanceTester $I) { $I->amOnPage(Url::toRoute('/site/about')); $I->see('About', 'h1'); } }
johnatandante/MyPhpPicFor
yiiapp/tests/acceptance/AboutCest.php
PHP
gpl-3.0
212
YUI.add('node-load', function(Y) { /** * Extended Node interface with a basic IO API. * @module node * @submodule node-load */ /** * The default IO complete handler. * @method _ioComplete * @protected * @for Node * @param {String} code The response code. * @param {Object} response The response object. * @param {Array} args An array containing the callback and selector */ Y.Node.prototype._ioComplete = function(code, response, args) { var selector = args[0], callback = args[1], tmp, content; if (response && response.responseText) { content = response.responseText; if (selector) { tmp = Y.DOM.create(content); content = Y.Selector.query(selector, tmp); } this.setContent(content); } if (callback) { callback.call(this, code, response); } }; /** * Loads content from the given url and replaces the Node's * existing content with it. * @method load * @param {String} url The URL to load via XMLHttpRequest. * @param {String} selector An optional selector representing a subset of an HTML document to load. * @param {Function} callback An optional function to run after the content has been loaded. * of the content. * @chainable */ Y.Node.prototype.load = function(url, selector, callback) { if (typeof selector == 'function') { callback = selector; selector = null; } var config = { context: this, on: { complete: this._ioComplete }, arguments: [selector, callback] }; Y.io(url, config); return this; } }, '@VERSION@' ,{requires:['node-base', 'io-base']});
DaAwesomeP/cdnjs
ajax/libs/yui/3.4.0/node-load/node-load.js
JavaScript
mit
1,682
/* SPDX-License-Identifier: GPL-2.0-only */ /* * Copyright (C) 2004, 2007-2010, 2011-2012 Synopsys, Inc. (www.synopsys.com) */ #ifndef _ASM_ARC_ARCREGS_H #define _ASM_ARC_ARCREGS_H /* Build Configuration Registers */ #define ARC_REG_AUX_DCCM 0x18 /* DCCM Base Addr ARCv2 */ #define ARC_REG_ERP_CTRL 0x3F /* ARCv2 Error protection control */ #define ARC_REG_DCCM_BASE_BUILD 0x61 /* DCCM Base Addr ARCompact */ #define ARC_REG_CRC_BCR 0x62 #define ARC_REG_VECBASE_BCR 0x68 #define ARC_REG_PERIBASE_BCR 0x69 #define ARC_REG_FP_BCR 0x6B /* ARCompact: Single-Precision FPU */ #define ARC_REG_DPFP_BCR 0x6C /* ARCompact: Dbl Precision FPU */ #define ARC_REG_ERP_BUILD 0xc7 /* ARCv2 Error protection Build: ECC/Parity */ #define ARC_REG_FP_V2_BCR 0xc8 /* ARCv2 FPU */ #define ARC_REG_SLC_BCR 0xce #define ARC_REG_DCCM_BUILD 0x74 /* DCCM size (common) */ #define ARC_REG_AP_BCR 0x76 #define ARC_REG_ICCM_BUILD 0x78 /* ICCM size (common) */ #define ARC_REG_XY_MEM_BCR 0x79 #define ARC_REG_MAC_BCR 0x7a #define ARC_REG_MUL_BCR 0x7b #define ARC_REG_SWAP_BCR 0x7c #define ARC_REG_NORM_BCR 0x7d #define ARC_REG_MIXMAX_BCR 0x7e #define ARC_REG_BARREL_BCR 0x7f #define ARC_REG_D_UNCACH_BCR 0x6A #define ARC_REG_BPU_BCR 0xc0 #define ARC_REG_ISA_CFG_BCR 0xc1 #define ARC_REG_LPB_BUILD 0xE9 /* ARCv2 Loop Buffer Build */ #define ARC_REG_RTT_BCR 0xF2 #define ARC_REG_IRQ_BCR 0xF3 #define ARC_REG_MICRO_ARCH_BCR 0xF9 /* ARCv2 Product revision */ #define ARC_REG_SMART_BCR 0xFF #define ARC_REG_CLUSTER_BCR 0xcf #define ARC_REG_AUX_ICCM 0x208 /* ICCM Base Addr (ARCv2) */ #define ARC_REG_LPB_CTRL 0x488 /* ARCv2 Loop Buffer control */ #define ARC_REG_FPU_CTRL 0x300 #define ARC_REG_FPU_STATUS 0x301 /* Common for ARCompact and ARCv2 status register */ #define ARC_REG_STATUS32 0x0A /* status32 Bits Positions */ #define STATUS_AE_BIT 5 /* Exception active */ #define STATUS_DE_BIT 6 /* PC is in delay slot */ #define STATUS_U_BIT 7 /* User/Kernel mode */ #define STATUS_Z_BIT 11 #define STATUS_L_BIT 12 /* Loop inhibit */ /* These masks correspond to the status word(STATUS_32) bits */ #define STATUS_AE_MASK (1<<STATUS_AE_BIT) #define STATUS_DE_MASK (1<<STATUS_DE_BIT) #define STATUS_U_MASK (1<<STATUS_U_BIT) #define STATUS_Z_MASK (1<<STATUS_Z_BIT) #define STATUS_L_MASK (1<<STATUS_L_BIT) /* * ECR: Exception Cause Reg bits-n-pieces * [23:16] = Exception Vector * [15: 8] = Exception Cause Code * [ 7: 0] = Exception Parameters (for certain types only) */ #ifdef CONFIG_ISA_ARCOMPACT #define ECR_V_MEM_ERR 0x01 #define ECR_V_INSN_ERR 0x02 #define ECR_V_MACH_CHK 0x20 #define ECR_V_ITLB_MISS 0x21 #define ECR_V_DTLB_MISS 0x22 #define ECR_V_PROTV 0x23 #define ECR_V_TRAP 0x25 #else #define ECR_V_MEM_ERR 0x01 #define ECR_V_INSN_ERR 0x02 #define ECR_V_MACH_CHK 0x03 #define ECR_V_ITLB_MISS 0x04 #define ECR_V_DTLB_MISS 0x05 #define ECR_V_PROTV 0x06 #define ECR_V_TRAP 0x09 #define ECR_V_MISALIGN 0x0d #endif /* DTLB Miss and Protection Violation Cause Codes */ #define ECR_C_PROTV_INST_FETCH 0x00 #define ECR_C_PROTV_LOAD 0x01 #define ECR_C_PROTV_STORE 0x02 #define ECR_C_PROTV_XCHG 0x03 #define ECR_C_PROTV_MISALIG_DATA 0x04 #define ECR_C_BIT_PROTV_MISALIG_DATA 10 /* Machine Check Cause Code Values */ #define ECR_C_MCHK_DUP_TLB 0x01 /* DTLB Miss Exception Cause Code Values */ #define ECR_C_BIT_DTLB_LD_MISS 8 #define ECR_C_BIT_DTLB_ST_MISS 9 /* Auxiliary registers */ #define AUX_IDENTITY 4 #define AUX_EXEC_CTRL 8 #define AUX_INTR_VEC_BASE 0x25 #define AUX_VOL 0x5e /* * Floating Pt Registers * Status regs are read-only (build-time) so need not be saved/restored */ #define ARC_AUX_FP_STAT 0x300 #define ARC_AUX_DPFP_1L 0x301 #define ARC_AUX_DPFP_1H 0x302 #define ARC_AUX_DPFP_2L 0x303 #define ARC_AUX_DPFP_2H 0x304 #define ARC_AUX_DPFP_STAT 0x305 /* * DSP-related registers * Registers names must correspond to dsp_callee_regs structure fields names * for automatic offset calculation in DSP_AUX_SAVE_RESTORE macros. */ #define ARC_AUX_DSP_BUILD 0x7A #define ARC_AUX_ACC0_LO 0x580 #define ARC_AUX_ACC0_GLO 0x581 #define ARC_AUX_ACC0_HI 0x582 #define ARC_AUX_ACC0_GHI 0x583 #define ARC_AUX_DSP_BFLY0 0x598 #define ARC_AUX_DSP_CTRL 0x59F #define ARC_AUX_DSP_FFT_CTRL 0x59E #define ARC_AUX_AGU_BUILD 0xCC #define ARC_AUX_AGU_AP0 0x5C0 #define ARC_AUX_AGU_AP1 0x5C1 #define ARC_AUX_AGU_AP2 0x5C2 #define ARC_AUX_AGU_AP3 0x5C3 #define ARC_AUX_AGU_OS0 0x5D0 #define ARC_AUX_AGU_OS1 0x5D1 #define ARC_AUX_AGU_MOD0 0x5E0 #define ARC_AUX_AGU_MOD1 0x5E1 #define ARC_AUX_AGU_MOD2 0x5E2 #define ARC_AUX_AGU_MOD3 0x5E3 #ifndef __ASSEMBLY__ #include <soc/arc/aux.h> /* Helpers */ #define TO_KB(bytes) ((bytes) >> 10) #define TO_MB(bytes) (TO_KB(bytes) >> 10) #define PAGES_TO_KB(n_pages) ((n_pages) << (PAGE_SHIFT - 10)) #define PAGES_TO_MB(n_pages) (PAGES_TO_KB(n_pages) >> 10) /* *************************************************************** * Build Configuration Registers, with encoded hardware config */ struct bcr_identity { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int chip_id:16, cpu_id:8, family:8; #else unsigned int family:8, cpu_id:8, chip_id:16; #endif }; struct bcr_isa_arcv2 { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int div_rem:4, pad2:4, ldd:1, unalign:1, atomic:1, be:1, pad1:12, ver:8; #else unsigned int ver:8, pad1:12, be:1, atomic:1, unalign:1, ldd:1, pad2:4, div_rem:4; #endif }; struct bcr_uarch_build_arcv2 { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int pad:8, prod:8, maj:8, min:8; #else unsigned int min:8, maj:8, prod:8, pad:8; #endif }; struct bcr_mpy { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int pad:8, x1616:8, dsp:4, cycles:2, type:2, ver:8; #else unsigned int ver:8, type:2, cycles:2, dsp:4, x1616:8, pad:8; #endif }; struct bcr_iccm_arcompact { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int base:16, pad:5, sz:3, ver:8; #else unsigned int ver:8, sz:3, pad:5, base:16; #endif }; struct bcr_iccm_arcv2 { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int pad:8, sz11:4, sz01:4, sz10:4, sz00:4, ver:8; #else unsigned int ver:8, sz00:4, sz10:4, sz01:4, sz11:4, pad:8; #endif }; struct bcr_dccm_arcompact { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int res:21, sz:3, ver:8; #else unsigned int ver:8, sz:3, res:21; #endif }; struct bcr_dccm_arcv2 { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int pad2:12, cyc:3, pad1:1, sz1:4, sz0:4, ver:8; #else unsigned int ver:8, sz0:4, sz1:4, pad1:1, cyc:3, pad2:12; #endif }; /* ARCompact: Both SP and DP FPU BCRs have same format */ struct bcr_fp_arcompact { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int fast:1, ver:8; #else unsigned int ver:8, fast:1; #endif }; struct bcr_fp_arcv2 { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int pad2:15, dp:1, pad1:7, sp:1, ver:8; #else unsigned int ver:8, sp:1, pad1:7, dp:1, pad2:15; #endif }; struct bcr_actionpoint { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int pad:21, min:1, num:2, ver:8; #else unsigned int ver:8, num:2, min:1, pad:21; #endif }; #include <soc/arc/timers.h> struct bcr_bpu_arcompact { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int pad2:19, fam:1, pad:2, ent:2, ver:8; #else unsigned int ver:8, ent:2, pad:2, fam:1, pad2:19; #endif }; struct bcr_bpu_arcv2 { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int pad:6, fbe:2, tqe:2, ts:4, ft:1, rse:2, pte:3, bce:3, ver:8; #else unsigned int ver:8, bce:3, pte:3, rse:2, ft:1, ts:4, tqe:2, fbe:2, pad:6; #endif }; /* Error Protection Build: ECC/Parity */ struct bcr_erp { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int pad3:5, mmu:3, pad2:4, ic:3, dc:3, pad1:6, ver:8; #else unsigned int ver:8, pad1:6, dc:3, ic:3, pad2:4, mmu:3, pad3:5; #endif }; /* Error Protection Control */ struct ctl_erp { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int pad2:27, mpd:1, pad1:2, dpd:1, dpi:1; #else unsigned int dpi:1, dpd:1, pad1:2, mpd:1, pad2:27; #endif }; struct bcr_lpb { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int pad:16, entries:8, ver:8; #else unsigned int ver:8, entries:8, pad:16; #endif }; struct bcr_generic { #ifdef CONFIG_CPU_BIG_ENDIAN unsigned int info:24, ver:8; #else unsigned int ver:8, info:24; #endif }; /* ******************************************************************* * Generic structures to hold build configuration used at runtime */ struct cpuinfo_arc_mmu { unsigned int ver:4, pg_sz_k:8, s_pg_sz_m:8, pad:10, sasid:1, pae:1; unsigned int sets:12, ways:4, u_dtlb:8, u_itlb:8; }; struct cpuinfo_arc_cache { unsigned int sz_k:14, line_len:8, assoc:4, alias:1, vipt:1, pad:4; }; struct cpuinfo_arc_bpu { unsigned int ver, full, num_cache, num_pred, ret_stk; }; struct cpuinfo_arc_ccm { unsigned int base_addr, sz; }; struct cpuinfo_arc { struct cpuinfo_arc_cache icache, dcache, slc; struct cpuinfo_arc_mmu mmu; struct cpuinfo_arc_bpu bpu; struct bcr_identity core; struct bcr_isa_arcv2 isa; const char *release, *name; unsigned int vec_base; struct cpuinfo_arc_ccm iccm, dccm; struct { unsigned int swap:1, norm:1, minmax:1, barrel:1, crc:1, swape:1, pad1:2, fpu_sp:1, fpu_dp:1, dual:1, dual_enb:1, pad2:4, ap_num:4, ap_full:1, smart:1, rtt:1, pad3:1, timer0:1, timer1:1, rtc:1, gfrc:1, pad4:4; } extn; struct bcr_mpy extn_mpy; }; extern struct cpuinfo_arc cpuinfo_arc700[]; static inline int is_isa_arcv2(void) { return IS_ENABLED(CONFIG_ISA_ARCV2); } static inline int is_isa_arcompact(void) { return IS_ENABLED(CONFIG_ISA_ARCOMPACT); } #endif /* __ASEMBLY__ */ #endif /* _ASM_ARC_ARCREGS_H */
CSE3320/kernel-code
linux-5.8/arch/arc/include/asm/arcregs.h
C
gpl-2.0
9,477
/* * mem-memcpy.c * * memcpy: Simple memory copy in various ways * * Written by Hitoshi Mitake <[email protected]> */ #include <ctype.h> #include "../perf.h" #include "../util/util.h" #include "../util/parse-options.h" #include "../util/header.h" #include "bench.h" #include "mem-memcpy-arch.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <errno.h> #define K 1024 static const char *length_str = "1MB"; static const char *routine = "default"; static bool use_clock; static int clock_fd; static bool only_prefault; static bool no_prefault; static const struct option options[] = { OPT_STRING('l', "length", &length_str, "1MB", "Specify length of memory to copy. " "available unit: B, MB, GB (upper and lower)"), OPT_STRING('r', "routine", &routine, "default", "Specify routine to copy"), OPT_BOOLEAN('c', "clock", &use_clock, "Use CPU clock for measuring"), OPT_BOOLEAN('o', "only-prefault", &only_prefault, "Show only the result with page faults before memcpy()"), OPT_BOOLEAN('n', "no-prefault", &no_prefault, "Show only the result without page faults before memcpy()"), OPT_END() }; typedef void *(*memcpy_t)(void *, const void *, size_t); struct routine { const char *name; const char *desc; memcpy_t fn; }; struct routine routines[] = { { "default", "Default memcpy() provided by glibc", memcpy }, #ifdef ARCH_X86_64 #define MEMCPY_FN(fn, name, desc) { name, desc, fn }, #include "mem-memcpy-x86-64-asm-def.h" #undef MEMCPY_FN #endif { NULL, NULL, NULL } }; static const char * const bench_mem_memcpy_usage[] = { "perf bench mem memcpy <options>", NULL }; static struct perf_event_attr clock_attr = { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES }; static void init_clock(void) { clock_fd = sys_perf_event_open(&clock_attr, getpid(), -1, -1, 0); if (clock_fd < 0 && errno == ENOSYS) die("No CONFIG_PERF_EVENTS=y kernel support configured?\n"); else BUG_ON(clock_fd < 0); } static u64 get_clock(void) { int ret; u64 clk; ret = read(clock_fd, &clk, sizeof(u64)); BUG_ON(ret != sizeof(u64)); return clk; } static double timeval2double(struct timeval *ts) { return (double)ts->tv_sec + (double)ts->tv_usec / (double)1000000; } static void alloc_mem(void **dst, void **src, size_t length) { *dst = zalloc(length); if (!dst) die("memory allocation failed - maybe length is too large?\n"); *src = zalloc(length); if (!src) die("memory allocation failed - maybe length is too large?\n"); } static u64 do_memcpy_clock(memcpy_t fn, size_t len, bool prefault) { u64 clock_start = 0ULL, clock_end = 0ULL; void *src = NULL, *dst = NULL; alloc_mem(&src, &dst, len); if (prefault) fn(dst, src, len); clock_start = get_clock(); fn(dst, src, len); clock_end = get_clock(); free(src); free(dst); return clock_end - clock_start; } static double do_memcpy_gettimeofday(memcpy_t fn, size_t len, bool prefault) { struct timeval tv_start, tv_end, tv_diff; void *src = NULL, *dst = NULL; alloc_mem(&src, &dst, len); if (prefault) fn(dst, src, len); BUG_ON(gettimeofday(&tv_start, NULL)); fn(dst, src, len); BUG_ON(gettimeofday(&tv_end, NULL)); timersub(&tv_end, &tv_start, &tv_diff); free(src); free(dst); return (double)((double)len / timeval2double(&tv_diff)); } #define pf (no_prefault ? 0 : 1) #define print_bps(x) do { \ if (x < K) \ printf(" %14lf B/Sec", x); \ else if (x < K * K) \ printf(" %14lfd KB/Sec", x / K); \ else if (x < K * K * K) \ printf(" %14lf MB/Sec", x / K / K); \ else \ printf(" %14lf GB/Sec", x / K / K / K); \ } while (0) int bench_mem_memcpy(int argc, const char **argv, const char *prefix __used) { int i; size_t len; double result_bps[2]; u64 result_clock[2]; argc = parse_options(argc, argv, options, bench_mem_memcpy_usage, 0); if (use_clock) init_clock(); len = (size_t)perf_atoll((char *)length_str); result_clock[0] = result_clock[1] = 0ULL; result_bps[0] = result_bps[1] = 0.0; if ((s64)len <= 0) { fprintf(stderr, "Invalid length:%s\n", length_str); return 1; } /* same to without specifying either of prefault and no-prefault */ if (only_prefault && no_prefault) only_prefault = no_prefault = false; for (i = 0; routines[i].name; i++) { if (!strcmp(routines[i].name, routine)) break; } if (!routines[i].name) { printf("Unknown routine:%s\n", routine); printf("Available routines...\n"); for (i = 0; routines[i].name; i++) { printf("\t%s ... %s\n", routines[i].name, routines[i].desc); } return 1; } if (bench_format == BENCH_FORMAT_DEFAULT) printf("# Copying %s Bytes ...\n\n", length_str); if (!only_prefault && !no_prefault) { /* show both of results */ if (use_clock) { result_clock[0] = do_memcpy_clock(routines[i].fn, len, false); result_clock[1] = do_memcpy_clock(routines[i].fn, len, true); } else { result_bps[0] = do_memcpy_gettimeofday(routines[i].fn, len, false); result_bps[1] = do_memcpy_gettimeofday(routines[i].fn, len, true); } } else { if (use_clock) { result_clock[pf] = do_memcpy_clock(routines[i].fn, len, only_prefault); } else { result_bps[pf] = do_memcpy_gettimeofday(routines[i].fn, len, only_prefault); } } switch (bench_format) { case BENCH_FORMAT_DEFAULT: if (!only_prefault && !no_prefault) { if (use_clock) { printf(" %14lf Clock/Byte\n", (double)result_clock[0] / (double)len); printf(" %14lf Clock/Byte (with prefault)\n", (double)result_clock[1] / (double)len); } else { print_bps(result_bps[0]); printf("\n"); print_bps(result_bps[1]); printf(" (with prefault)\n"); } } else { if (use_clock) { printf(" %14lf Clock/Byte", (double)result_clock[pf] / (double)len); } else print_bps(result_bps[pf]); printf("%s\n", only_prefault ? " (with prefault)" : ""); } break; case BENCH_FORMAT_SIMPLE: if (!only_prefault && !no_prefault) { if (use_clock) { printf("%lf %lf\n", (double)result_clock[0] / (double)len, (double)result_clock[1] / (double)len); } else { printf("%lf %lf\n", result_bps[0], result_bps[1]); } } else { if (use_clock) { printf("%lf\n", (double)result_clock[pf] / (double)len); } else printf("%lf\n", result_bps[pf]); } break; default: /* reaching this means there's some disaster: */ die("unknown format: %d\n", bench_format); break; } return 0; }
JijonHyuni/HyperKernel-JB
virt/tools/perf/bench/mem-memcpy.c
C
gpl-2.0
6,612
html { background: #f1f1f1; margin: 0 20px; } body { background: #fff; color: #444; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; margin: 140px auto 25px; padding: 20px 20px 10px 20px; max-width: 700px; -webkit-font-smoothing: subpixel-antialiased; -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.13); box-shadow: 0 1px 3px rgba(0,0,0,0.13); } a { color: #0073aa; } a:hover, a:active { color: #00a0d2; } a:focus { color: #124964; -webkit-box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, .8); box-shadow: 0 0 0 1px #5b9dd9, 0 0 2px 1px rgba(30, 140, 190, .8); } .ie8 a:focus { outline: #5b9dd9 solid 1px; } h1, h2 { border-bottom: 1px solid #ddd; clear: both; color: #666; font-size: 24px; padding: 0; padding-bottom: 7px; font-weight: 400; } h3 { font-size: 16px; } p, li, dd, dt { padding-bottom: 2px; font-size: 14px; line-height: 1.5; } code, .code { font-family: Consolas, Monaco, monospace; } ul, ol, dl { padding: 5px 5px 5px 22px; } a img { border:0 } abbr { border: 0; font-variant: normal; } fieldset { border: 0; padding: 0; margin: 0; } label { cursor: pointer; } #logo { margin: 6px 0 14px 0; padding: 0 0 7px 0; border-bottom: none; text-align:center } #logo a { background-image: url(../images/w-logo-blue.png?ver=20131202); background-image: none, url(../images/wordpress-logo.svg?ver=20131107); -webkit-background-size: 84px; background-size: 84px; background-position: center top; background-repeat: no-repeat; color: #444; /* same as login.css */ height: 84px; font-size: 20px; font-weight: 400; line-height: 1.3em; margin: -130px auto 25px; padding: 0; text-decoration: none; width: 84px; text-indent: -9999px; outline: none; overflow: hidden; display: block; } #logo a:focus { -webkit-box-shadow: none; box-shadow: none; } .step { margin: 20px 0 15px; } .step, th { text-align: left; padding: 0; } .language-chooser.wp-core-ui .step .button.button-large { height: 36px; font-size: 14px; line-height: 33px; vertical-align: middle; } textarea { border: 1px solid #ddd; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .form-table { border-collapse: collapse; margin-top: 1em; width: 100%; } .form-table td { margin-bottom: 9px; padding: 10px 20px 10px 0; font-size: 14px; vertical-align: top } .form-table th { font-size: 14px; text-align: left; padding: 10px 20px 10px 0; width: 140px; vertical-align: top; } .form-table code { line-height: 18px; font-size: 14px; } .form-table p { margin: 4px 0 0 0; font-size: 11px; } .form-table input { line-height: 20px; font-size: 15px; padding: 3px 5px; border: 1px solid #ddd; -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,0.07); box-shadow: inset 0 1px 2px rgba(0,0,0,0.07); } input, submit { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; } .form-table input[type=text], .form-table input[type=email], .form-table input[type=url], .form-table input[type=password] { width: 206px; } .form-table th p { font-weight: 400; } .form-table.install-success th, .form-table.install-success td { vertical-align: middle; padding: 16px 20px 16px 0; } .form-table.install-success td p { margin: 0; font-size: 14px; } .form-table.install-success td code { margin: 0; font-size: 18px; } #error-page { margin-top: 50px; } #error-page p { font-size: 14px; line-height: 18px; margin: 25px 0 20px; } #error-page code, .code { font-family: Consolas, Monaco, monospace; } .wp-hide-pw > .dashicons { line-height: inherit; } #pass-strength-result { background-color: #eee; border: 1px solid #ddd; color: #23282d; margin: -2px 5px 5px 0px; padding: 3px 5px; text-align: center; width: 218px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; opacity: 0; } #pass-strength-result.short { background-color: #f1adad; border-color: #e35b5b; opacity: 1; } #pass-strength-result.bad { background-color: #fbc5a9; border-color: #f78b53; opacity: 1; } #pass-strength-result.good { background-color: #ffe399; border-color: #ffc733; opacity: 1; } #pass-strength-result.strong { background-color: #c1e1b9; border-color: #83c373; opacity: 1; } #pass1.short, #pass1-text.short { border-color: #e35b5b; } #pass1.bad, #pass1-text.bad { border-color: #f78b53; } #pass1.good, #pass1-text.good { border-color: #ffc733; } #pass1.strong, #pass1-text.strong { border-color: #83c373; } .pw-weak { display: none; } .message { border-left: 4px solid #dc3232; padding: .7em .6em; background-color: #fbeaea; } /* rtl:ignore */ #dbname, #uname, #pwd, #dbhost, #prefix, #user_login, #admin_email, #pass1, #pass2 { direction: ltr; } #pass1-text, .show-password #pass1 { display: none; } .show-password #pass1-text { display: inline-block; } .form-table span.description.important { font-size: 12px; } /* localization */ body.rtl, .rtl textarea, .rtl input, .rtl submit { font-family: Tahoma, sans-serif; } :lang(he-il) body.rtl, :lang(he-il) .rtl textarea, :lang(he-il) .rtl input, :lang(he-il) .rtl submit { font-family: Arial, sans-serif; } @media only screen and (max-width: 799px) { body { margin-top: 115px; } #logo a { margin: -125px auto 30px; } } @media screen and ( max-width: 782px ) { .form-table { margin-top: 0; } .form-table th, .form-table td { display: block; width: auto; vertical-align: middle; } .form-table th { padding: 20px 0 0; } .form-table td { padding: 5px 0; border: 0; margin: 0; } textarea, input { font-size: 16px; } .form-table td input[type="text"], .form-table td input[type="email"], .form-table td input[type="url"], .form-table td input[type="password"], .form-table td select, .form-table td textarea, .form-table span.description { width: 100%; font-size: 16px; line-height: 1.5; padding: 7px 10px; display: block; max-width: none; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } } body.language-chooser { max-width: 300px; } .language-chooser select { padding: 8px; width: 100%; display: block; border: 1px solid #ddd; background-color: #fff; color: #32373c; font-size: 16px; font-family: Arial, sans-serif; font-weight: 400; } .language-chooser p { text-align: right; } .screen-reader-input, .screen-reader-text { position: absolute; margin: -1px; padding: 0; height: 1px; width: 1px; overflow: hidden; clip: rect(0 0 0 0); border: 0; } .spinner { background: url(../images/spinner.gif) no-repeat; -webkit-background-size: 20px 20px; background-size: 20px 20px; visibility: hidden; opacity: 0.7; filter: alpha(opacity=70); width: 20px; height: 20px; margin: 2px 5px 0; } .step .spinner { display: inline-block; vertical-align: middle; margin-right: 15px; } .button-secondary.hide-if-no-js, .hide-if-no-js { display: none; } /** * HiDPI Displays */ @media print, (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .spinner { background-image: url(../images/spinner-2x.gif); } }
pdpfsug/wp_raga10
wp_raga10/wp-admin/css/install.css
CSS
agpl-3.0
7,403
/***************************************************************************** * * Filename: ksdazzle.c * Version: 0.1.2 * Description: Irda KingSun Dazzle USB Dongle * Status: Experimental * Author: Alex Villacís Lasso <[email protected]> * * Based on stir4200, mcs7780, kingsun-sir drivers. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * *****************************************************************************/ /* * Following is my most current (2007-07-26) understanding of how the Kingsun * 07D0:4100 dongle (sometimes known as the MA-660) is supposed to work. This * information was deduced by examining the USB traffic captured with USBSnoopy * from the WinXP driver. Feel free to update here as more of the dongle is * known. * * General: This dongle exposes one interface with two interrupt endpoints, one * IN and one OUT. In this regard, it is similar to what the Kingsun/Donshine * dongle (07c0:4200) exposes. Traffic is raw and needs to be wrapped and * unwrapped manually as in stir4200, kingsun-sir, and ks959-sir. * * Transmission: To transmit an IrDA frame, it is necessary to wrap it, then * split it into multiple segments of up to 7 bytes each, and transmit each in * sequence. It seems that sending a single big block (like kingsun-sir does) * won't work with this dongle. Each segment needs to be prefixed with a value * equal to (unsigned char)0xF8 + <number of bytes in segment>, inside a payload * of exactly 8 bytes. For example, a segment of 1 byte gets prefixed by 0xF9, * and one of 7 bytes gets prefixed by 0xFF. The bytes at the end of the * payload, not considered by the prefix, are ignored (set to 0 by this * implementation). * * Reception: To receive data, the driver must poll the dongle regularly (like * kingsun-sir.c) with interrupt URBs. If data is available, it will be returned * in payloads from 0 to 8 bytes long. When concatenated, these payloads form * a raw IrDA stream that needs to be unwrapped as in stir4200 and kingsun-sir * * Speed change: To change the speed of the dongle, the driver prepares a * control URB with the following as a setup packet: * bRequestType USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE * bRequest 0x09 * wValue 0x0200 * wIndex 0x0001 * wLength 0x0008 (length of the payload) * The payload is a 8-byte record, apparently identical to the one used in * drivers/usb/serial/cypress_m8.c to change speed: * __u32 baudSpeed; * unsigned int dataBits : 2; // 0 - 5 bits 3 - 8 bits * unsigned int : 1; * unsigned int stopBits : 1; * unsigned int parityEnable : 1; * unsigned int parityType : 1; * unsigned int : 1; * unsigned int reset : 1; * unsigned char reserved[3]; // set to 0 * * For now only SIR speeds have been observed with this dongle. Therefore, * nothing is known on what changes (if any) must be done to frame wrapping / * unwrapping for higher than SIR speeds. This driver assumes no change is * necessary and announces support for all the way to 115200 bps. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/usb.h> #include <linux/device.h> #include <linux/crc32.h> #include <asm/unaligned.h> #include <asm/byteorder.h> #include <asm/uaccess.h> #include <net/irda/irda.h> #include <net/irda/wrapper.h> #include <net/irda/crc.h> #define KSDAZZLE_VENDOR_ID 0x07d0 #define KSDAZZLE_PRODUCT_ID 0x4100 /* These are the currently known USB ids */ static struct usb_device_id dongles[] = { /* KingSun Co,Ltd IrDA/USB Bridge */ {USB_DEVICE(KSDAZZLE_VENDOR_ID, KSDAZZLE_PRODUCT_ID)}, {} }; MODULE_DEVICE_TABLE(usb, dongles); #define KINGSUN_MTT 0x07 #define KINGSUN_REQ_RECV 0x01 #define KINGSUN_REQ_SEND 0x09 #define KINGSUN_SND_FIFO_SIZE 2048 /* Max packet we can send */ #define KINGSUN_RCV_MAX 2048 /* Max transfer we can receive */ struct ksdazzle_speedparams { __le32 baudrate; /* baud rate, little endian */ __u8 flags; __u8 reserved[3]; } __packed; #define KS_DATA_5_BITS 0x00 #define KS_DATA_6_BITS 0x01 #define KS_DATA_7_BITS 0x02 #define KS_DATA_8_BITS 0x03 #define KS_STOP_BITS_1 0x00 #define KS_STOP_BITS_2 0x08 #define KS_PAR_DISABLE 0x00 #define KS_PAR_EVEN 0x10 #define KS_PAR_ODD 0x30 #define KS_RESET 0x80 #define KINGSUN_EP_IN 0 #define KINGSUN_EP_OUT 1 struct ksdazzle_cb { struct usb_device *usbdev; /* init: probe_irda */ struct net_device *netdev; /* network layer */ struct irlap_cb *irlap; /* The link layer we are binded to */ struct qos_info qos; struct urb *tx_urb; __u8 *tx_buf_clear; unsigned int tx_buf_clear_used; unsigned int tx_buf_clear_sent; __u8 tx_payload[8]; struct urb *rx_urb; __u8 *rx_buf; iobuff_t rx_unwrap_buff; struct usb_ctrlrequest *speed_setuprequest; struct urb *speed_urb; struct ksdazzle_speedparams speedparams; unsigned int new_speed; __u8 ep_in; __u8 ep_out; spinlock_t lock; int receiving; }; /* Callback transmission routine */ static void ksdazzle_speed_irq(struct urb *urb) { /* unlink, shutdown, unplug, other nasties */ if (urb->status != 0) dev_err(&urb->dev->dev, "ksdazzle_speed_irq: urb asynchronously failed - %d\n", urb->status); } /* Send a control request to change speed of the dongle */ static int ksdazzle_change_speed(struct ksdazzle_cb *kingsun, unsigned speed) { static unsigned int supported_speeds[] = { 2400, 9600, 19200, 38400, 57600, 115200, 576000, 1152000, 4000000, 0 }; int err; unsigned int i; if (kingsun->speed_setuprequest == NULL || kingsun->speed_urb == NULL) return -ENOMEM; /* Check that requested speed is among the supported ones */ for (i = 0; supported_speeds[i] && supported_speeds[i] != speed; i++) ; if (supported_speeds[i] == 0) return -EOPNOTSUPP; memset(&(kingsun->speedparams), 0, sizeof(struct ksdazzle_speedparams)); kingsun->speedparams.baudrate = cpu_to_le32(speed); kingsun->speedparams.flags = KS_DATA_8_BITS; /* speed_setuprequest pre-filled in ksdazzle_probe */ usb_fill_control_urb(kingsun->speed_urb, kingsun->usbdev, usb_sndctrlpipe(kingsun->usbdev, 0), (unsigned char *)kingsun->speed_setuprequest, &(kingsun->speedparams), sizeof(struct ksdazzle_speedparams), ksdazzle_speed_irq, kingsun); kingsun->speed_urb->status = 0; err = usb_submit_urb(kingsun->speed_urb, GFP_ATOMIC); return err; } /* Submit one fragment of an IrDA frame to the dongle */ static void ksdazzle_send_irq(struct urb *urb); static int ksdazzle_submit_tx_fragment(struct ksdazzle_cb *kingsun) { unsigned int wraplen; int ret; /* We can send at most 7 bytes of payload at a time */ wraplen = 7; if (wraplen > kingsun->tx_buf_clear_used) wraplen = kingsun->tx_buf_clear_used; /* Prepare payload prefix with used length */ memset(kingsun->tx_payload, 0, 8); kingsun->tx_payload[0] = (unsigned char)0xf8 + wraplen; memcpy(kingsun->tx_payload + 1, kingsun->tx_buf_clear, wraplen); usb_fill_int_urb(kingsun->tx_urb, kingsun->usbdev, usb_sndintpipe(kingsun->usbdev, kingsun->ep_out), kingsun->tx_payload, 8, ksdazzle_send_irq, kingsun, 1); kingsun->tx_urb->status = 0; ret = usb_submit_urb(kingsun->tx_urb, GFP_ATOMIC); /* Remember how much data was sent, in order to update at callback */ kingsun->tx_buf_clear_sent = (ret == 0) ? wraplen : 0; return ret; } /* Callback transmission routine */ static void ksdazzle_send_irq(struct urb *urb) { struct ksdazzle_cb *kingsun = urb->context; struct net_device *netdev = kingsun->netdev; int ret = 0; /* in process of stopping, just drop data */ if (!netif_running(kingsun->netdev)) { dev_err(&kingsun->usbdev->dev, "ksdazzle_send_irq: Network not running!\n"); return; } /* unlink, shutdown, unplug, other nasties */ if (urb->status != 0) { dev_err(&kingsun->usbdev->dev, "ksdazzle_send_irq: urb asynchronously failed - %d\n", urb->status); return; } if (kingsun->tx_buf_clear_used > 0) { /* Update data remaining to be sent */ if (kingsun->tx_buf_clear_sent < kingsun->tx_buf_clear_used) { memmove(kingsun->tx_buf_clear, kingsun->tx_buf_clear + kingsun->tx_buf_clear_sent, kingsun->tx_buf_clear_used - kingsun->tx_buf_clear_sent); } kingsun->tx_buf_clear_used -= kingsun->tx_buf_clear_sent; kingsun->tx_buf_clear_sent = 0; if (kingsun->tx_buf_clear_used > 0) { /* There is more data to be sent */ if ((ret = ksdazzle_submit_tx_fragment(kingsun)) != 0) { dev_err(&kingsun->usbdev->dev, "ksdazzle_send_irq: failed tx_urb submit: %d\n", ret); switch (ret) { case -ENODEV: case -EPIPE: break; default: netdev->stats.tx_errors++; netif_start_queue(netdev); } } } else { /* All data sent, send next speed && wake network queue */ if (kingsun->new_speed != -1 && cpu_to_le32(kingsun->new_speed) != kingsun->speedparams.baudrate) ksdazzle_change_speed(kingsun, kingsun->new_speed); netif_wake_queue(netdev); } } } /* * Called from net/core when new frame is available. */ static netdev_tx_t ksdazzle_hard_xmit(struct sk_buff *skb, struct net_device *netdev) { struct ksdazzle_cb *kingsun; unsigned int wraplen; int ret = 0; netif_stop_queue(netdev); /* the IRDA wrapping routines don't deal with non linear skb */ SKB_LINEAR_ASSERT(skb); kingsun = netdev_priv(netdev); spin_lock(&kingsun->lock); kingsun->new_speed = irda_get_next_speed(skb); /* Append data to the end of whatever data remains to be transmitted */ wraplen = async_wrap_skb(skb, kingsun->tx_buf_clear, KINGSUN_SND_FIFO_SIZE); kingsun->tx_buf_clear_used = wraplen; if ((ret = ksdazzle_submit_tx_fragment(kingsun)) != 0) { dev_err(&kingsun->usbdev->dev, "ksdazzle_hard_xmit: failed tx_urb submit: %d\n", ret); switch (ret) { case -ENODEV: case -EPIPE: break; default: netdev->stats.tx_errors++; netif_start_queue(netdev); } } else { netdev->stats.tx_packets++; netdev->stats.tx_bytes += skb->len; } dev_kfree_skb(skb); spin_unlock(&kingsun->lock); return NETDEV_TX_OK; } /* Receive callback function */ static void ksdazzle_rcv_irq(struct urb *urb) { struct ksdazzle_cb *kingsun = urb->context; struct net_device *netdev = kingsun->netdev; /* in process of stopping, just drop data */ if (!netif_running(netdev)) { kingsun->receiving = 0; return; } /* unlink, shutdown, unplug, other nasties */ if (urb->status != 0) { dev_err(&kingsun->usbdev->dev, "ksdazzle_rcv_irq: urb asynchronously failed - %d\n", urb->status); kingsun->receiving = 0; return; } if (urb->actual_length > 0) { __u8 *bytes = urb->transfer_buffer; unsigned int i; for (i = 0; i < urb->actual_length; i++) { async_unwrap_char(netdev, &netdev->stats, &kingsun->rx_unwrap_buff, bytes[i]); } kingsun->receiving = (kingsun->rx_unwrap_buff.state != OUTSIDE_FRAME) ? 1 : 0; } /* This urb has already been filled in ksdazzle_net_open. It is assumed that urb keeps the pointer to the payload buffer. */ urb->status = 0; usb_submit_urb(urb, GFP_ATOMIC); } /* * Function ksdazzle_net_open (dev) * * Network device is taken up. Usually this is done by "ifconfig irda0 up" */ static int ksdazzle_net_open(struct net_device *netdev) { struct ksdazzle_cb *kingsun = netdev_priv(netdev); int err = -ENOMEM; char hwname[16]; /* At this point, urbs are NULL, and skb is NULL (see ksdazzle_probe) */ kingsun->receiving = 0; /* Initialize for SIR to copy data directly into skb. */ kingsun->rx_unwrap_buff.in_frame = FALSE; kingsun->rx_unwrap_buff.state = OUTSIDE_FRAME; kingsun->rx_unwrap_buff.truesize = IRDA_SKB_MAX_MTU; kingsun->rx_unwrap_buff.skb = dev_alloc_skb(IRDA_SKB_MAX_MTU); if (!kingsun->rx_unwrap_buff.skb) goto free_mem; skb_reserve(kingsun->rx_unwrap_buff.skb, 1); kingsun->rx_unwrap_buff.head = kingsun->rx_unwrap_buff.skb->data; kingsun->rx_urb = usb_alloc_urb(0, GFP_KERNEL); if (!kingsun->rx_urb) goto free_mem; kingsun->tx_urb = usb_alloc_urb(0, GFP_KERNEL); if (!kingsun->tx_urb) goto free_mem; kingsun->speed_urb = usb_alloc_urb(0, GFP_KERNEL); if (!kingsun->speed_urb) goto free_mem; /* Initialize speed for dongle */ kingsun->new_speed = 9600; err = ksdazzle_change_speed(kingsun, 9600); if (err < 0) goto free_mem; /* * Now that everything should be initialized properly, * Open new IrLAP layer instance to take care of us... */ sprintf(hwname, "usb#%d", kingsun->usbdev->devnum); kingsun->irlap = irlap_open(netdev, &kingsun->qos, hwname); if (!kingsun->irlap) { err = -ENOMEM; dev_err(&kingsun->usbdev->dev, "irlap_open failed\n"); goto free_mem; } /* Start reception. */ usb_fill_int_urb(kingsun->rx_urb, kingsun->usbdev, usb_rcvintpipe(kingsun->usbdev, kingsun->ep_in), kingsun->rx_buf, KINGSUN_RCV_MAX, ksdazzle_rcv_irq, kingsun, 1); kingsun->rx_urb->status = 0; err = usb_submit_urb(kingsun->rx_urb, GFP_KERNEL); if (err) { dev_err(&kingsun->usbdev->dev, "first urb-submit failed: %d\n", err); goto close_irlap; } netif_start_queue(netdev); /* Situation at this point: - all work buffers allocated - urbs allocated and ready to fill - max rx packet known (in max_rx) - unwrap state machine initialized, in state outside of any frame - receive request in progress - IrLAP layer started, about to hand over packets to send */ return 0; close_irlap: irlap_close(kingsun->irlap); free_mem: usb_free_urb(kingsun->speed_urb); kingsun->speed_urb = NULL; usb_free_urb(kingsun->tx_urb); kingsun->tx_urb = NULL; usb_free_urb(kingsun->rx_urb); kingsun->rx_urb = NULL; if (kingsun->rx_unwrap_buff.skb) { kfree_skb(kingsun->rx_unwrap_buff.skb); kingsun->rx_unwrap_buff.skb = NULL; kingsun->rx_unwrap_buff.head = NULL; } return err; } /* * Function ksdazzle_net_close (dev) * * Network device is taken down. Usually this is done by * "ifconfig irda0 down" */ static int ksdazzle_net_close(struct net_device *netdev) { struct ksdazzle_cb *kingsun = netdev_priv(netdev); /* Stop transmit processing */ netif_stop_queue(netdev); /* Mop up receive && transmit urb's */ usb_kill_urb(kingsun->tx_urb); usb_free_urb(kingsun->tx_urb); kingsun->tx_urb = NULL; usb_kill_urb(kingsun->speed_urb); usb_free_urb(kingsun->speed_urb); kingsun->speed_urb = NULL; usb_kill_urb(kingsun->rx_urb); usb_free_urb(kingsun->rx_urb); kingsun->rx_urb = NULL; kfree_skb(kingsun->rx_unwrap_buff.skb); kingsun->rx_unwrap_buff.skb = NULL; kingsun->rx_unwrap_buff.head = NULL; kingsun->rx_unwrap_buff.in_frame = FALSE; kingsun->rx_unwrap_buff.state = OUTSIDE_FRAME; kingsun->receiving = 0; /* Stop and remove instance of IrLAP */ irlap_close(kingsun->irlap); kingsun->irlap = NULL; return 0; } /* * IOCTLs : Extra out-of-band network commands... */ static int ksdazzle_net_ioctl(struct net_device *netdev, struct ifreq *rq, int cmd) { struct if_irda_req *irq = (struct if_irda_req *)rq; struct ksdazzle_cb *kingsun = netdev_priv(netdev); int ret = 0; switch (cmd) { case SIOCSBANDWIDTH: /* Set bandwidth */ if (!capable(CAP_NET_ADMIN)) return -EPERM; /* Check if the device is still there */ if (netif_device_present(kingsun->netdev)) return ksdazzle_change_speed(kingsun, irq->ifr_baudrate); break; case SIOCSMEDIABUSY: /* Set media busy */ if (!capable(CAP_NET_ADMIN)) return -EPERM; /* Check if the IrDA stack is still there */ if (netif_running(kingsun->netdev)) irda_device_set_media_busy(kingsun->netdev, TRUE); break; case SIOCGRECEIVING: /* Only approximately true */ irq->ifr_receiving = kingsun->receiving; break; default: ret = -EOPNOTSUPP; } return ret; } static const struct net_device_ops ksdazzle_ops = { .ndo_start_xmit = ksdazzle_hard_xmit, .ndo_open = ksdazzle_net_open, .ndo_stop = ksdazzle_net_close, .ndo_do_ioctl = ksdazzle_net_ioctl, }; /* * This routine is called by the USB subsystem for each new device * in the system. We need to check if the device is ours, and in * this case start handling it. */ static int ksdazzle_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_host_interface *interface; struct usb_endpoint_descriptor *endpoint; struct usb_device *dev = interface_to_usbdev(intf); struct ksdazzle_cb *kingsun = NULL; struct net_device *net = NULL; int ret = -ENOMEM; int pipe, maxp_in, maxp_out; __u8 ep_in; __u8 ep_out; /* Check that there really are two interrupt endpoints. Check based on the one in drivers/usb/input/usbmouse.c */ interface = intf->cur_altsetting; if (interface->desc.bNumEndpoints != 2) { dev_err(&intf->dev, "ksdazzle: expected 2 endpoints, found %d\n", interface->desc.bNumEndpoints); return -ENODEV; } endpoint = &interface->endpoint[KINGSUN_EP_IN].desc; if (!usb_endpoint_is_int_in(endpoint)) { dev_err(&intf->dev, "ksdazzle: endpoint 0 is not interrupt IN\n"); return -ENODEV; } ep_in = endpoint->bEndpointAddress; pipe = usb_rcvintpipe(dev, ep_in); maxp_in = usb_maxpacket(dev, pipe, usb_pipeout(pipe)); if (maxp_in > 255 || maxp_in <= 1) { dev_err(&intf->dev, "ksdazzle: endpoint 0 has max packet size %d not in range [2..255]\n", maxp_in); return -ENODEV; } endpoint = &interface->endpoint[KINGSUN_EP_OUT].desc; if (!usb_endpoint_is_int_out(endpoint)) { dev_err(&intf->dev, "ksdazzle: endpoint 1 is not interrupt OUT\n"); return -ENODEV; } ep_out = endpoint->bEndpointAddress; pipe = usb_sndintpipe(dev, ep_out); maxp_out = usb_maxpacket(dev, pipe, usb_pipeout(pipe)); /* Allocate network device container. */ net = alloc_irdadev(sizeof(*kingsun)); if (!net) goto err_out1; SET_NETDEV_DEV(net, &intf->dev); kingsun = netdev_priv(net); kingsun->netdev = net; kingsun->usbdev = dev; kingsun->ep_in = ep_in; kingsun->ep_out = ep_out; kingsun->irlap = NULL; kingsun->tx_urb = NULL; kingsun->tx_buf_clear = NULL; kingsun->tx_buf_clear_used = 0; kingsun->tx_buf_clear_sent = 0; kingsun->rx_urb = NULL; kingsun->rx_buf = NULL; kingsun->rx_unwrap_buff.in_frame = FALSE; kingsun->rx_unwrap_buff.state = OUTSIDE_FRAME; kingsun->rx_unwrap_buff.skb = NULL; kingsun->receiving = 0; spin_lock_init(&kingsun->lock); kingsun->speed_setuprequest = NULL; kingsun->speed_urb = NULL; kingsun->speedparams.baudrate = 0; /* Allocate input buffer */ kingsun->rx_buf = kmalloc(KINGSUN_RCV_MAX, GFP_KERNEL); if (!kingsun->rx_buf) goto free_mem; /* Allocate output buffer */ kingsun->tx_buf_clear = kmalloc(KINGSUN_SND_FIFO_SIZE, GFP_KERNEL); if (!kingsun->tx_buf_clear) goto free_mem; /* Allocate and initialize speed setup packet */ kingsun->speed_setuprequest = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL); if (!kingsun->speed_setuprequest) goto free_mem; kingsun->speed_setuprequest->bRequestType = USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE; kingsun->speed_setuprequest->bRequest = KINGSUN_REQ_SEND; kingsun->speed_setuprequest->wValue = cpu_to_le16(0x0200); kingsun->speed_setuprequest->wIndex = cpu_to_le16(0x0001); kingsun->speed_setuprequest->wLength = cpu_to_le16(sizeof(struct ksdazzle_speedparams)); printk(KERN_INFO "KingSun/Dazzle IRDA/USB found at address %d, " "Vendor: %x, Product: %x\n", dev->devnum, le16_to_cpu(dev->descriptor.idVendor), le16_to_cpu(dev->descriptor.idProduct)); /* Initialize QoS for this device */ irda_init_max_qos_capabilies(&kingsun->qos); /* Baud rates known to be supported. Please uncomment if devices (other than a SonyEriccson K300 phone) can be shown to support higher speeds with this dongle. */ kingsun->qos.baud_rate.bits = IR_2400 | IR_9600 | IR_19200 | IR_38400 | IR_57600 | IR_115200; kingsun->qos.min_turn_time.bits &= KINGSUN_MTT; irda_qos_bits_to_value(&kingsun->qos); /* Override the network functions we need to use */ net->netdev_ops = &ksdazzle_ops; ret = register_netdev(net); if (ret != 0) goto free_mem; dev_info(&net->dev, "IrDA: Registered KingSun/Dazzle device %s\n", net->name); usb_set_intfdata(intf, kingsun); /* Situation at this point: - all work buffers allocated - setup requests pre-filled - urbs not allocated, set to NULL - max rx packet known (is KINGSUN_FIFO_SIZE) - unwrap state machine (partially) initialized, but skb == NULL */ return 0; free_mem: kfree(kingsun->speed_setuprequest); kfree(kingsun->tx_buf_clear); kfree(kingsun->rx_buf); free_netdev(net); err_out1: return ret; } /* * The current device is removed, the USB layer tell us to shut it down... */ static void ksdazzle_disconnect(struct usb_interface *intf) { struct ksdazzle_cb *kingsun = usb_get_intfdata(intf); if (!kingsun) return; unregister_netdev(kingsun->netdev); /* Mop up receive && transmit urb's */ usb_kill_urb(kingsun->speed_urb); usb_free_urb(kingsun->speed_urb); kingsun->speed_urb = NULL; usb_kill_urb(kingsun->tx_urb); usb_free_urb(kingsun->tx_urb); kingsun->tx_urb = NULL; usb_kill_urb(kingsun->rx_urb); usb_free_urb(kingsun->rx_urb); kingsun->rx_urb = NULL; kfree(kingsun->speed_setuprequest); kfree(kingsun->tx_buf_clear); kfree(kingsun->rx_buf); free_netdev(kingsun->netdev); usb_set_intfdata(intf, NULL); } #ifdef CONFIG_PM /* USB suspend, so power off the transmitter/receiver */ static int ksdazzle_suspend(struct usb_interface *intf, pm_message_t message) { struct ksdazzle_cb *kingsun = usb_get_intfdata(intf); netif_device_detach(kingsun->netdev); if (kingsun->speed_urb != NULL) usb_kill_urb(kingsun->speed_urb); if (kingsun->tx_urb != NULL) usb_kill_urb(kingsun->tx_urb); if (kingsun->rx_urb != NULL) usb_kill_urb(kingsun->rx_urb); return 0; } /* Coming out of suspend, so reset hardware */ static int ksdazzle_resume(struct usb_interface *intf) { struct ksdazzle_cb *kingsun = usb_get_intfdata(intf); if (kingsun->rx_urb != NULL) { /* Setup request already filled in ksdazzle_probe */ usb_submit_urb(kingsun->rx_urb, GFP_KERNEL); } netif_device_attach(kingsun->netdev); return 0; } #endif /* * USB device callbacks */ static struct usb_driver irda_driver = { .name = "ksdazzle-sir", .probe = ksdazzle_probe, .disconnect = ksdazzle_disconnect, .id_table = dongles, #ifdef CONFIG_PM .suspend = ksdazzle_suspend, .resume = ksdazzle_resume, #endif }; module_usb_driver(irda_driver); MODULE_AUTHOR("Alex Villacís Lasso <[email protected]>"); MODULE_DESCRIPTION("IrDA-USB Dongle Driver for KingSun Dazzle"); MODULE_LICENSE("GPL");
AiJiaZone/linux-4.0
virt/drivers/net/irda/ksdazzle-sir.c
C
gpl-2.0
23,404
/* * Misc utility routines for WL and Apps * This header file housing the define and function prototype use by * both the wl driver, tools & Apps. * * Copyright (C) 1999-2011, Broadcom Corporation * * Unless you and Broadcom execute a separate written software license * agreement governing use of this software, this software is licensed to you * under the terms of the GNU General Public License version 2 (the "GPL"), * available at http://www.broadcom.com/licenses/GPLv2.php, with the * following added to such license: * * As a special exception, the copyright holders of this software give you * permission to link this software with independent modules, and to copy and * distribute the resulting executable under terms of your choice, provided that * you also meet, for each linked independent module, the terms and conditions of * the license of that module. An independent module is a module which is not * derived from this software. The special exception does not apply to any * modifications of the software. * * Notwithstanding the above, under no circumstances may you combine this * software in any way with any other Broadcom software provided under a license * other than the GPL, without Broadcom's express prior written consent. * * $Id: bcmwifi.h 277737 2011-08-16 17:54:59Z $ */ #ifndef _bcmwifi_h_ #define _bcmwifi_h_ typedef uint16 chanspec_t; #define CH_UPPER_SB 0x01 #define CH_LOWER_SB 0x02 #define CH_EWA_VALID 0x04 #define CH_20MHZ_APART 4 #define CH_10MHZ_APART 2 #define CH_5MHZ_APART 1 #define CH_MAX_2G_CHANNEL 14 #define WLC_MAX_2G_CHANNEL CH_MAX_2G_CHANNEL #define MAXCHANNEL 224 #define WL_CHANSPEC_CHAN_MASK 0x00ff #define WL_CHANSPEC_CHAN_SHIFT 0 #define WL_CHANSPEC_CTL_SB_MASK 0x0300 #define WL_CHANSPEC_CTL_SB_SHIFT 8 #define WL_CHANSPEC_CTL_SB_LOWER 0x0100 #define WL_CHANSPEC_CTL_SB_UPPER 0x0200 #define WL_CHANSPEC_CTL_SB_NONE 0x0300 #define WL_CHANSPEC_BW_MASK 0x0C00 #define WL_CHANSPEC_BW_SHIFT 10 #define WL_CHANSPEC_BW_10 0x0400 #define WL_CHANSPEC_BW_20 0x0800 #define WL_CHANSPEC_BW_40 0x0C00 #define WL_CHANSPEC_BAND_MASK 0xf000 #define WL_CHANSPEC_BAND_SHIFT 12 #define WL_CHANSPEC_BAND_5G 0x1000 #define WL_CHANSPEC_BAND_2G 0x2000 #define INVCHANSPEC 255 #define WF_CHAN_FACTOR_2_4_G 4814 #define WF_CHAN_FACTOR_5_G 10000 #define WF_CHAN_FACTOR_4_G 8000 #define LOWER_20_SB(channel) (((channel) > CH_10MHZ_APART) ? ((channel) - CH_10MHZ_APART) : 0) #define UPPER_20_SB(channel) (((channel) < (MAXCHANNEL - CH_10MHZ_APART)) ? \ ((channel) + CH_10MHZ_APART) : 0) #define CHSPEC_WLCBANDUNIT(chspec) (CHSPEC_IS5G(chspec) ? BAND_5G_INDEX : BAND_2G_INDEX) #define CH20MHZ_CHSPEC(channel) (chanspec_t)((chanspec_t)(channel) | WL_CHANSPEC_BW_20 | \ WL_CHANSPEC_CTL_SB_NONE | (((channel) <= CH_MAX_2G_CHANNEL) ? \ WL_CHANSPEC_BAND_2G : WL_CHANSPEC_BAND_5G)) #define NEXT_20MHZ_CHAN(channel) (((channel) < (MAXCHANNEL - CH_20MHZ_APART)) ? \ ((channel) + CH_20MHZ_APART) : 0) #define CH40MHZ_CHSPEC(channel, ctlsb) (chanspec_t) \ ((channel) | (ctlsb) | WL_CHANSPEC_BW_40 | \ ((channel) <= CH_MAX_2G_CHANNEL ? WL_CHANSPEC_BAND_2G : \ WL_CHANSPEC_BAND_5G)) #define CHSPEC_CHANNEL(chspec) ((uint8)((chspec) & WL_CHANSPEC_CHAN_MASK)) #define CHSPEC_BAND(chspec) ((chspec) & WL_CHANSPEC_BAND_MASK) #define CHSPEC_CTL_SB(chspec) (chspec & WL_CHANSPEC_CTL_SB_MASK) #define CHSPEC_BW(chspec) (chspec & WL_CHANSPEC_BW_MASK) #ifdef WL11N_20MHZONLY #define CHSPEC_IS10(chspec) 0 #define CHSPEC_IS20(chspec) 1 #ifndef CHSPEC_IS40 #define CHSPEC_IS40(chspec) 0 #endif #else #define CHSPEC_IS10(chspec) (((chspec) & WL_CHANSPEC_BW_MASK) == WL_CHANSPEC_BW_10) #define CHSPEC_IS20(chspec) (((chspec) & WL_CHANSPEC_BW_MASK) == WL_CHANSPEC_BW_20) #ifndef CHSPEC_IS40 #define CHSPEC_IS40(chspec) (((chspec) & WL_CHANSPEC_BW_MASK) == WL_CHANSPEC_BW_40) #endif #endif #define CHSPEC_IS20_UNCOND(chspec) (((chspec) & WL_CHANSPEC_BW_MASK) == WL_CHANSPEC_BW_20) #define CHSPEC_IS5G(chspec) (((chspec) & WL_CHANSPEC_BAND_MASK) == WL_CHANSPEC_BAND_5G) #define CHSPEC_IS2G(chspec) (((chspec) & WL_CHANSPEC_BAND_MASK) == WL_CHANSPEC_BAND_2G) #define CHSPEC_SB_NONE(chspec) (((chspec) & WL_CHANSPEC_CTL_SB_MASK) == WL_CHANSPEC_CTL_SB_NONE) #define CHSPEC_SB_UPPER(chspec) (((chspec) & WL_CHANSPEC_CTL_SB_MASK) == WL_CHANSPEC_CTL_SB_UPPER) #define CHSPEC_SB_LOWER(chspec) (((chspec) & WL_CHANSPEC_CTL_SB_MASK) == WL_CHANSPEC_CTL_SB_LOWER) #define CHSPEC_CTL_CHAN(chspec) ((CHSPEC_SB_LOWER(chspec)) ? \ (LOWER_20_SB(((chspec) & WL_CHANSPEC_CHAN_MASK))) : \ (UPPER_20_SB(((chspec) & WL_CHANSPEC_CHAN_MASK)))) #define CHSPEC2WLC_BAND(chspec) (CHSPEC_IS5G(chspec) ? WLC_BAND_5G : WLC_BAND_2G) #define CHANSPEC_STR_LEN 8 #define WLC_MAXRATE 108 #define WLC_RATE_1M 2 #define WLC_RATE_2M 4 #define WLC_RATE_5M5 11 #define WLC_RATE_11M 22 #define WLC_RATE_6M 12 #define WLC_RATE_9M 18 #define WLC_RATE_12M 24 #define WLC_RATE_18M 36 #define WLC_RATE_24M 48 #define WLC_RATE_36M 72 #define WLC_RATE_48M 96 #define WLC_RATE_54M 108 #define WLC_2G_25MHZ_OFFSET 5 extern char * wf_chspec_ntoa(chanspec_t chspec, char *buf); extern chanspec_t wf_chspec_aton(char *a); extern bool wf_chspec_malformed(chanspec_t chanspec); extern uint8 wf_chspec_ctlchan(chanspec_t chspec); extern chanspec_t wf_chspec_ctlchspec(chanspec_t chspec); extern int wf_mhz2channel(uint freq, uint start_factor); extern int wf_channel2mhz(uint channel, uint start_factor); #endif
JijonHyuni/HyperKernel-JB
virt/drivers/net/wireless/bcmdhd/include/bcmwifi.h
C
gpl-2.0
5,569
/* Copyright (c) 2007, 2013 The Linux Foundation. All rights reserved. * Copyright (C) 2007 Google Incorporated * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/file.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/major.h> #include <linux/slab.h> #include <linux/types.h> #include <linux/uaccess.h> #include <linux/sched.h> #include <linux/mutex.h> #include <linux/sync.h> #include <linux/sw_sync.h> #include "linux/proc_fs.h" #include <linux/delay.h> #include "mdss_fb.h" #include "mdp3_ppp.h" #include "mdp3_hwio.h" #include "mdp3.h" #define MDP_IS_IMGTYPE_BAD(x) ((x) >= MDP_IMGTYPE_LIMIT) #define MDP_RELEASE_BW_TIMEOUT 50 #define MDP_BLIT_CLK_RATE 200000000 #define MDP_PPP_MAX_BPP 4 #define MDP_PPP_DYNAMIC_FACTOR 3 #define MDP_PPP_MAX_READ_WRITE 3 #define ENABLE_SOLID_FILL 0x2 #define DISABLE_SOLID_FILL 0x0 static const bool valid_fmt[MDP_IMGTYPE_LIMIT] = { [MDP_RGB_565] = true, [MDP_BGR_565] = true, [MDP_RGB_888] = true, [MDP_BGR_888] = true, [MDP_BGRA_8888] = true, [MDP_RGBA_8888] = true, [MDP_ARGB_8888] = true, [MDP_XRGB_8888] = true, [MDP_RGBX_8888] = true, [MDP_Y_CRCB_H2V2] = true, [MDP_Y_CBCR_H2V2] = true, [MDP_Y_CBCR_H2V2_ADRENO] = true, [MDP_Y_CBCR_H2V2_VENUS] = true, [MDP_YCRYCB_H2V1] = true, [MDP_Y_CBCR_H2V1] = true, [MDP_Y_CRCB_H2V1] = true, [MDP_BGRX_8888] = true, }; #define MAX_LIST_WINDOW 16 #define MDP3_PPP_MAX_LIST_REQ 8 struct blit_req_list { int count; struct mdp_blit_req req_list[MAX_LIST_WINDOW]; struct mdp3_img_data src_data[MAX_LIST_WINDOW]; struct mdp3_img_data dst_data[MAX_LIST_WINDOW]; struct sync_fence *acq_fen[MDP_MAX_FENCE_FD]; u32 acq_fen_cnt; int cur_rel_fen_fd; struct sync_pt *cur_rel_sync_pt; struct sync_fence *cur_rel_fence; struct sync_fence *last_rel_fence; }; struct blit_req_queue { struct blit_req_list req[MDP3_PPP_MAX_LIST_REQ]; int count; int push_idx; int pop_idx; }; struct ppp_status { int busy; bool wait_for_pop; spinlock_t ppp_lock; struct completion ppp_comp; struct completion pop_q_comp; struct mutex req_mutex; /* Protect request queue */ struct mutex config_ppp_mutex; /* Only one client configure register */ struct msm_fb_data_type *mfd; struct work_struct blit_work; struct blit_req_queue req_q; struct sw_sync_timeline *timeline; int timeline_value; struct timer_list free_bw_timer; struct work_struct free_bw_work; bool bw_on; }; static struct ppp_status *ppp_stat; int ppp_get_bpp(uint32_t format, uint32_t fb_format) { int bpp = -EINVAL; if (format == MDP_FB_FORMAT) format = fb_format; bpp = ppp_bpp(format); if (bpp <= 0) pr_err("%s incorrect format %d\n", __func__, format); return bpp; } int mdp3_ppp_get_img(struct mdp_img *img, struct mdp_blit_req *req, struct mdp3_img_data *data) { struct msmfb_data fb_data; uint32_t stride; int bpp = ppp_bpp(img->format); if (bpp <= 0) { pr_err("%s incorrect format %d\n", __func__, img->format); return -EINVAL; } fb_data.flags = img->priv; fb_data.memory_id = img->memory_id; fb_data.offset = 0; stride = img->width * bpp; data->padding = 16 * stride; return mdp3_get_img(&fb_data, data, MDP3_CLIENT_PPP); } /* Check format */ int mdp3_ppp_verify_fmt(struct mdp_blit_req *req) { if (MDP_IS_IMGTYPE_BAD(req->src.format) || MDP_IS_IMGTYPE_BAD(req->dst.format)) { pr_err("%s: Color format out of range\n", __func__); return -EINVAL; } if (!valid_fmt[req->src.format] || !valid_fmt[req->dst.format]) { pr_err("%s: Color format not supported\n", __func__); return -EINVAL; } return 0; } /* Check resolution */ int mdp3_ppp_verify_res(struct mdp_blit_req *req) { if ((req->src.width == 0) || (req->src.height == 0) || (req->src_rect.w == 0) || (req->src_rect.h == 0) || (req->dst.width == 0) || (req->dst.height == 0) || (req->dst_rect.w == 0) || (req->dst_rect.h == 0)) { pr_err("%s: Height/width can't be 0\n", __func__); return -EINVAL; } if (((req->src_rect.x + req->src_rect.w) > req->src.width) || ((req->src_rect.y + req->src_rect.h) > req->src.height)) { pr_err("%s: src roi larger than boundary\n", __func__); return -EINVAL; } if (((req->dst_rect.x + req->dst_rect.w) > req->dst.width) || ((req->dst_rect.y + req->dst_rect.h) > req->dst.height)) { pr_err("%s: dst roi larger than boundary\n", __func__); return -EINVAL; } return 0; } /* scaling range check */ int mdp3_ppp_verify_scale(struct mdp_blit_req *req) { u32 src_width, src_height, dst_width, dst_height; src_width = req->src_rect.w; src_height = req->src_rect.h; if (req->flags & MDP_ROT_90) { dst_width = req->dst_rect.h; dst_height = req->dst_rect.w; } else { dst_width = req->dst_rect.w; dst_height = req->dst_rect.h; } switch (req->dst.format) { case MDP_Y_CRCB_H2V2: case MDP_Y_CBCR_H2V2: src_width = (src_width / 2) * 2; src_height = (src_height / 2) * 2; dst_width = (dst_width / 2) * 2; dst_height = (dst_height / 2) * 2; break; case MDP_Y_CRCB_H2V1: case MDP_Y_CBCR_H2V1: case MDP_YCRYCB_H2V1: src_width = (src_width / 2) * 2; dst_width = (dst_width / 2) * 2; break; default: break; } if (((MDP_SCALE_Q_FACTOR * dst_width) / src_width > MDP_MAX_X_SCALE_FACTOR) || ((MDP_SCALE_Q_FACTOR * dst_width) / src_width < MDP_MIN_X_SCALE_FACTOR)) { pr_err("%s: x req scale factor beyond capability\n", __func__); return -EINVAL; } if (((MDP_SCALE_Q_FACTOR * dst_height) / src_height > MDP_MAX_Y_SCALE_FACTOR) || ((MDP_SCALE_Q_FACTOR * dst_height) / src_height < MDP_MIN_Y_SCALE_FACTOR)) { pr_err("%s: y req scale factor beyond capability\n", __func__); return -EINVAL; } return 0; } /* operation check */ int mdp3_ppp_verify_op(struct mdp_blit_req *req) { if (req->flags & MDP_DEINTERLACE) { pr_err("\n%s(): deinterlace not supported", __func__); return -EINVAL; } if (req->flags & MDP_SHARPENING) { pr_err("\n%s(): sharpening not supported", __func__); return -EINVAL; } return 0; } int mdp3_ppp_verify_req(struct mdp_blit_req *req) { int rc; if (req == NULL) { pr_err("%s: req == null\n", __func__); return -EINVAL; } rc = mdp3_ppp_verify_fmt(req); rc |= mdp3_ppp_verify_res(req); rc |= mdp3_ppp_verify_scale(req); rc |= mdp3_ppp_verify_op(req); return rc; } int mdp3_ppp_pipe_wait(void) { int ret = 1; int wait; unsigned long flag; /* * wait 5 secs for operation to complete before declaring * the MDP hung */ spin_lock_irqsave(&ppp_stat->ppp_lock, flag); wait = ppp_stat->busy; spin_unlock_irqrestore(&ppp_stat->ppp_lock, flag); if (wait) { ret = wait_for_completion_interruptible_timeout( &ppp_stat->ppp_comp, 5 * HZ); if (!ret) pr_err("%s: Timed out waiting for the MDP.\n", __func__); } return ret; } uint32_t mdp3_calc_tpval(struct ppp_img_desc *img, uint32_t old_tp) { uint32_t tpVal; uint8_t plane_tp; tpVal = 0; if ((img->color_fmt == MDP_RGB_565) || (img->color_fmt == MDP_BGR_565)) { /* transparent color conversion into 24 bpp */ plane_tp = (uint8_t) ((old_tp & 0xF800) >> 11); tpVal |= ((plane_tp << 3) | ((plane_tp & 0x1C) >> 2)) << 16; plane_tp = (uint8_t) (old_tp & 0x1F); tpVal |= ((plane_tp << 3) | ((plane_tp & 0x1C) >> 2)) << 8; plane_tp = (uint8_t) ((old_tp & 0x7E0) >> 5); tpVal |= ((plane_tp << 2) | ((plane_tp & 0x30) >> 4)); } else { /* 24bit RGB to RBG conversion */ tpVal = (old_tp & 0xFF00) >> 8; tpVal |= (old_tp & 0xFF) << 8; tpVal |= (old_tp & 0xFF0000); } return tpVal; } static void mdp3_ppp_intr_handler(int type, void *arg) { spin_lock(&ppp_stat->ppp_lock); ppp_stat->busy = false; spin_unlock(&ppp_stat->ppp_lock); complete(&ppp_stat->ppp_comp); mdp3_irq_disable_nosync(type); } static int mdp3_ppp_callback_setup(void) { int rc; struct mdp3_intr_cb ppp_done_cb = { .cb = mdp3_ppp_intr_handler, .data = NULL, }; rc = mdp3_set_intr_callback(MDP3_PPP_DONE, &ppp_done_cb); return rc; } void mdp3_ppp_kickoff(void) { unsigned long flag; mdp3_irq_enable(MDP3_PPP_DONE); init_completion(&ppp_stat->ppp_comp); spin_lock_irqsave(&ppp_stat->ppp_lock, flag); ppp_stat->busy = true; spin_unlock_irqrestore(&ppp_stat->ppp_lock, flag); ppp_enable(); mdp3_ppp_pipe_wait(); } int mdp3_ppp_turnon(struct msm_fb_data_type *mfd, int on_off) { struct mdss_panel_info *panel_info = mfd->panel_info; uint64_t ab = 0, ib = 0; int rate = 0; int rc; if (on_off) { rate = MDP_BLIT_CLK_RATE; ab = panel_info->xres * panel_info->yres * panel_info->mipi.frame_rate * MDP_PPP_MAX_BPP * MDP_PPP_DYNAMIC_FACTOR * MDP_PPP_MAX_READ_WRITE; ib = (ab * 3) / 2; } mdp3_clk_set_rate(MDP3_CLK_CORE, rate, MDP3_CLIENT_PPP); rc = mdp3_clk_enable(on_off, 0); if (rc < 0) { pr_err("%s: mdp3_clk_enable failed\n", __func__); return rc; } rc = mdp3_bus_scale_set_quota(MDP3_CLIENT_PPP, ab, ib); if (rc < 0) { mdp3_clk_enable(!on_off, 0); pr_err("%s: scale_set_quota failed\n", __func__); return rc; } ppp_stat->bw_on = on_off; return 0; } void mdp3_start_ppp(struct ppp_blit_op *blit_op) { /* Wait for the pipe to clear */ do { } while (mdp3_ppp_pipe_wait() <= 0); config_ppp_op_mode(blit_op); if (blit_op->solid_fill) { MDP3_REG_WRITE(0x10138, 0x10000000); MDP3_REG_WRITE(0x1014c, 0xffffffff); MDP3_REG_WRITE(0x101b8, 0); MDP3_REG_WRITE(0x101bc, 0); MDP3_REG_WRITE(0x1013c, 0); MDP3_REG_WRITE(0x10140, 0); MDP3_REG_WRITE(0x10144, 0); MDP3_REG_WRITE(0x10148, 0); MDP3_REG_WRITE(MDP3_TFETCH_FILL_COLOR, blit_op->solid_fill_color); MDP3_REG_WRITE(MDP3_TFETCH_SOLID_FILL, ENABLE_SOLID_FILL); } else { MDP3_REG_WRITE(MDP3_TFETCH_SOLID_FILL, DISABLE_SOLID_FILL); } mdp3_ppp_kickoff(); } static int solid_fill_workaround(struct mdp_blit_req *req, struct ppp_blit_op *blit_op) { /* Make width 2 when there is a solid fill of width 1, and make sure width does not become zero while trying to avoid odd width */ if (blit_op->dst.roi.width == 1) { if (req->dst_rect.x + 2 > req->dst.width) { pr_err("%s: Unable to handle solid fill of width 1", __func__); return -EINVAL; } blit_op->dst.roi.width = 2; } if (blit_op->src.roi.width == 1) { if (req->src_rect.x + 2 > req->src.width) { pr_err("%s: Unable to handle solid fill of width 1", __func__); return -EINVAL; } blit_op->src.roi.width = 2; } /* Avoid odd width, as it could hang ppp during solid fill */ blit_op->dst.roi.width = (blit_op->dst.roi.width / 2) * 2; blit_op->src.roi.width = (blit_op->src.roi.width / 2) * 2; /* Avoid RGBA format, as it could hang ppp during solid fill */ if (blit_op->src.color_fmt == MDP_RGBA_8888) blit_op->src.color_fmt = MDP_RGBX_8888; if (blit_op->dst.color_fmt == MDP_RGBA_8888) blit_op->dst.color_fmt = MDP_RGBX_8888; return 0; } static int mdp3_ppp_process_req(struct ppp_blit_op *blit_op, struct mdp_blit_req *req, struct mdp3_img_data *src_data, struct mdp3_img_data *dst_data) { unsigned long srcp0_start, srcp0_len, dst_start, dst_len; uint32_t dst_width, dst_height; int ret = 0; srcp0_start = (unsigned long) src_data->addr; srcp0_len = (unsigned long) src_data->len; dst_start = (unsigned long) dst_data->addr; dst_len = (unsigned long) dst_data->len; blit_op->dst.prop.width = req->dst.width; blit_op->dst.prop.height = req->dst.height; blit_op->dst.color_fmt = req->dst.format; blit_op->dst.p0 = (void *) dst_start; blit_op->dst.p0 += req->dst.offset; blit_op->dst.roi.x = req->dst_rect.x; blit_op->dst.roi.y = req->dst_rect.y; blit_op->dst.roi.width = req->dst_rect.w; blit_op->dst.roi.height = req->dst_rect.h; blit_op->src.roi.x = req->src_rect.x; blit_op->src.roi.y = req->src_rect.y; blit_op->src.roi.width = req->src_rect.w; blit_op->src.roi.height = req->src_rect.h; blit_op->src.prop.width = req->src.width; blit_op->src.color_fmt = req->src.format; blit_op->src.p0 = (void *) (srcp0_start + req->src.offset); if (blit_op->src.color_fmt == MDP_Y_CBCR_H2V2_ADRENO) blit_op->src.p1 = (void *) ((uint32_t) blit_op->src.p0 + ALIGN((ALIGN(req->src.width, 32) * ALIGN(req->src.height, 32)), 4096)); else if (blit_op->src.color_fmt == MDP_Y_CBCR_H2V2_VENUS) blit_op->src.p1 = (void *) ((uint32_t) blit_op->src.p0 + ALIGN((ALIGN(req->src.width, 128) * ALIGN(req->src.height, 32)), 4096)); else blit_op->src.p1 = (void *) ((uint32_t) blit_op->src.p0 + req->src.width * req->src.height); if (req->flags & MDP_IS_FG) blit_op->mdp_op |= MDPOP_LAYER_IS_FG; /* blending check */ if (req->transp_mask != MDP_TRANSP_NOP) { blit_op->mdp_op |= MDPOP_TRANSP; blit_op->blend.trans_color = mdp3_calc_tpval(&blit_op->src, req->transp_mask); } else { blit_op->blend.trans_color = 0; } req->alpha &= 0xff; if (req->alpha < MDP_ALPHA_NOP) { blit_op->mdp_op |= MDPOP_ALPHAB; blit_op->blend.const_alpha = req->alpha; } else { blit_op->blend.const_alpha = 0xff; } /* rotation check */ if (req->flags & MDP_FLIP_LR) blit_op->mdp_op |= MDPOP_LR; if (req->flags & MDP_FLIP_UD) blit_op->mdp_op |= MDPOP_UD; if (req->flags & MDP_ROT_90) blit_op->mdp_op |= MDPOP_ROT90; if (req->flags & MDP_DITHER) blit_op->mdp_op |= MDPOP_DITHER; if (req->flags & MDP_BLEND_FG_PREMULT) blit_op->mdp_op |= MDPOP_FG_PM_ALPHA; /* scale check */ if (req->flags & MDP_ROT_90) { dst_width = req->dst_rect.h; dst_height = req->dst_rect.w; } else { dst_width = req->dst_rect.w; dst_height = req->dst_rect.h; } if ((blit_op->src.roi.width != dst_width) || (blit_op->src.roi.height != dst_height)) blit_op->mdp_op |= MDPOP_ASCALE; if (req->flags & MDP_BLUR) blit_op->mdp_op |= MDPOP_ASCALE | MDPOP_BLUR; if (req->flags & MDP_SOLID_FILL) { ret = solid_fill_workaround(req, blit_op); if (ret) return ret; blit_op->solid_fill_color = (req->const_color.g & 0xFF)| (req->const_color.r & 0xFF) << 8 | (req->const_color.b & 0xFF) << 16 | (req->const_color.alpha & 0xFF) << 24; blit_op->solid_fill = true; } else { blit_op->solid_fill = false; } return ret; } static void mdp3_ppp_tile_workaround(struct ppp_blit_op *blit_op, struct mdp_blit_req *req) { int dst_h, src_w, i; uint32_t mdp_op = blit_op->mdp_op; void *src_p0 = blit_op->src.p0; void *src_p1 = blit_op->src.p1; void *dst_p0 = blit_op->dst.p0; src_w = req->src_rect.w; dst_h = blit_op->dst.roi.height; /* bg tile fetching HW workaround */ for (i = 0; i < (req->dst_rect.h / 16); i++) { /* this tile size */ blit_op->dst.roi.height = 16; blit_op->src.roi.width = (16 * req->src_rect.w) / req->dst_rect.h; /* if it's out of scale range... */ if (((MDP_SCALE_Q_FACTOR * blit_op->dst.roi.height) / blit_op->src.roi.width) > MDP_MAX_X_SCALE_FACTOR) blit_op->src.roi.width = (MDP_SCALE_Q_FACTOR * blit_op->dst.roi.height) / MDP_MAX_X_SCALE_FACTOR; else if (((MDP_SCALE_Q_FACTOR * blit_op->dst.roi.height) / blit_op->src.roi.width) < MDP_MIN_X_SCALE_FACTOR) blit_op->src.roi.width = (MDP_SCALE_Q_FACTOR * blit_op->dst.roi.height) / MDP_MIN_X_SCALE_FACTOR; mdp3_start_ppp(blit_op); /* next tile location */ blit_op->dst.roi.y += 16; blit_op->src.roi.x += blit_op->src.roi.width; /* this is for a remainder update */ dst_h -= 16; src_w -= blit_op->src.roi.width; /* restore parameters that may have been overwritten */ blit_op->mdp_op = mdp_op; blit_op->src.p0 = src_p0; blit_op->src.p1 = src_p1; blit_op->dst.p0 = dst_p0; } if ((dst_h < 0) || (src_w < 0)) pr_err ("msm_fb: mdp_blt_ex() unexpected result! line:%d\n", __LINE__); /* remainder update */ if ((dst_h > 0) && (src_w > 0)) { u32 tmp_v; blit_op->dst.roi.height = dst_h; blit_op->src.roi.width = src_w; if (((MDP_SCALE_Q_FACTOR * blit_op->dst.roi.height) / blit_op->src.roi.width) > MDP_MAX_X_SCALE_FACTOR) { tmp_v = (MDP_SCALE_Q_FACTOR * blit_op->dst.roi.height) / MDP_MAX_X_SCALE_FACTOR + ((MDP_SCALE_Q_FACTOR * blit_op->dst.roi.height) % MDP_MAX_X_SCALE_FACTOR ? 1 : 0); /* move x location as roi width gets bigger */ blit_op->src.roi.x -= tmp_v - blit_op->src.roi.width; blit_op->src.roi.width = tmp_v; } else if (((MDP_SCALE_Q_FACTOR * blit_op->dst.roi.height) / blit_op->src.roi.width) < MDP_MIN_X_SCALE_FACTOR) { tmp_v = (MDP_SCALE_Q_FACTOR * blit_op->dst.roi.height) / MDP_MIN_X_SCALE_FACTOR + ((MDP_SCALE_Q_FACTOR * blit_op->dst.roi.height) % MDP_MIN_X_SCALE_FACTOR ? 1 : 0); /* * we don't move x location for continuity of * source image */ blit_op->src.roi.width = tmp_v; } mdp3_start_ppp(blit_op); } } static int mdp3_ppp_blit(struct msm_fb_data_type *mfd, struct mdp_blit_req *req, struct mdp3_img_data *src_data, struct mdp3_img_data *dst_data) { struct ppp_blit_op blit_op; int ret = 0; memset(&blit_op, 0, sizeof(blit_op)); if (req->dst.format == MDP_FB_FORMAT) req->dst.format = mfd->fb_imgType; if (req->src.format == MDP_FB_FORMAT) req->src.format = mfd->fb_imgType; if (mdp3_ppp_verify_req(req)) { pr_err("%s: invalid image!\n", __func__); return -EINVAL; } ret = mdp3_ppp_process_req(&blit_op, req, src_data, dst_data); if (ret) { pr_err("%s: Failed to process the blit request", __func__); return ret; } if (((blit_op.mdp_op & (MDPOP_TRANSP | MDPOP_ALPHAB)) || (req->src.format == MDP_ARGB_8888) || (req->src.format == MDP_BGRA_8888) || (req->src.format == MDP_RGBA_8888)) && (blit_op.mdp_op & MDPOP_ROT90) && (req->dst_rect.w <= 16)) { mdp3_ppp_tile_workaround(&blit_op, req); } else { mdp3_start_ppp(&blit_op); } return 0; } static int mdp3_ppp_blit_workaround(struct msm_fb_data_type *mfd, struct mdp_blit_req *req, unsigned int remainder, struct mdp3_img_data *src_data, struct mdp3_img_data *dst_data) { int ret; struct mdp_blit_req splitreq; int s_x_0, s_x_1, s_w_0, s_w_1, s_y_0, s_y_1, s_h_0, s_h_1; int d_x_0, d_x_1, d_w_0, d_w_1, d_y_0, d_y_1, d_h_0, d_h_1; /* make new request as provide by user */ splitreq = *req; /* break dest roi at width*/ d_y_0 = d_y_1 = req->dst_rect.y; d_h_0 = d_h_1 = req->dst_rect.h; d_x_0 = req->dst_rect.x; if (remainder == 14 || remainder == 6) d_w_1 = req->dst_rect.w / 2; else d_w_1 = (req->dst_rect.w - 1) / 2 - 1; d_w_0 = req->dst_rect.w - d_w_1; d_x_1 = d_x_0 + d_w_0; /* blit first region */ if (((splitreq.flags & 0x07) == 0x07) || ((splitreq.flags & 0x07) == 0x05) || ((splitreq.flags & 0x07) == 0x02) || ((splitreq.flags & 0x07) == 0x0)) { if (splitreq.flags & MDP_ROT_90) { s_x_0 = s_x_1 = req->src_rect.x; s_w_0 = s_w_1 = req->src_rect.w; s_y_0 = req->src_rect.y; s_h_1 = (req->src_rect.h * d_w_1) / req->dst_rect.w; s_h_0 = req->src_rect.h - s_h_1; s_y_1 = s_y_0 + s_h_0; if (d_w_1 >= 8 * s_h_1) { s_h_1++; s_y_1--; } } else { s_y_0 = s_y_1 = req->src_rect.y; s_h_0 = s_h_1 = req->src_rect.h; s_x_0 = req->src_rect.x; s_w_1 = (req->src_rect.w * d_w_1) / req->dst_rect.w; s_w_0 = req->src_rect.w - s_w_1; s_x_1 = s_x_0 + s_w_0; if (d_w_1 >= 8 * s_w_1) { s_w_1++; s_x_1--; } } splitreq.src_rect.h = s_h_0; splitreq.src_rect.y = s_y_0; splitreq.dst_rect.h = d_h_0; splitreq.dst_rect.y = d_y_0; splitreq.src_rect.x = s_x_0; splitreq.src_rect.w = s_w_0; splitreq.dst_rect.x = d_x_0; splitreq.dst_rect.w = d_w_0; } else { if (splitreq.flags & MDP_ROT_90) { s_x_0 = s_x_1 = req->src_rect.x; s_w_0 = s_w_1 = req->src_rect.w; s_y_0 = req->src_rect.y; s_h_1 = (req->src_rect.h * d_w_0) / req->dst_rect.w; s_h_0 = req->src_rect.h - s_h_1; s_y_1 = s_y_0 + s_h_0; if (d_w_0 >= 8 * s_h_1) { s_h_1++; s_y_1--; } } else { s_y_0 = s_y_1 = req->src_rect.y; s_h_0 = s_h_1 = req->src_rect.h; s_x_0 = req->src_rect.x; s_w_1 = (req->src_rect.w * d_w_0) / req->dst_rect.w; s_w_0 = req->src_rect.w - s_w_1; s_x_1 = s_x_0 + s_w_0; if (d_w_0 >= 8 * s_w_1) { s_w_1++; s_x_1--; } } splitreq.src_rect.h = s_h_0; splitreq.src_rect.y = s_y_0; splitreq.dst_rect.h = d_h_1; splitreq.dst_rect.y = d_y_1; splitreq.src_rect.x = s_x_0; splitreq.src_rect.w = s_w_0; splitreq.dst_rect.x = d_x_1; splitreq.dst_rect.w = d_w_1; } /* No need to split in height */ ret = mdp3_ppp_blit(mfd, &splitreq, src_data, dst_data); if (ret) return ret; /* blit second region */ if (((splitreq.flags & 0x07) == 0x07) || ((splitreq.flags & 0x07) == 0x05) || ((splitreq.flags & 0x07) == 0x02) || ((splitreq.flags & 0x07) == 0x0)) { splitreq.src_rect.h = s_h_1; splitreq.src_rect.y = s_y_1; splitreq.dst_rect.h = d_h_1; splitreq.dst_rect.y = d_y_1; splitreq.src_rect.x = s_x_1; splitreq.src_rect.w = s_w_1; splitreq.dst_rect.x = d_x_1; splitreq.dst_rect.w = d_w_1; } else { splitreq.src_rect.h = s_h_1; splitreq.src_rect.y = s_y_1; splitreq.dst_rect.h = d_h_0; splitreq.dst_rect.y = d_y_0; splitreq.src_rect.x = s_x_1; splitreq.src_rect.w = s_w_1; splitreq.dst_rect.x = d_x_0; splitreq.dst_rect.w = d_w_0; } /* No need to split in height ... just width */ return mdp3_ppp_blit(mfd, &splitreq, src_data, dst_data); } int mdp3_ppp_start_blit(struct msm_fb_data_type *mfd, struct mdp_blit_req *req, struct mdp3_img_data *src_data, struct mdp3_img_data *dst_data) { int ret; unsigned int remainder = 0, is_bpp_4 = 0; if (unlikely(req->src_rect.h == 0 || req->src_rect.w == 0)) { pr_err("mdp_ppp: src img of zero size!\n"); return -EINVAL; } if (unlikely(req->dst_rect.h == 0 || req->dst_rect.w == 0)) return 0; if (req->flags & MDP_ROT_90) { if (((req->dst_rect.h == 1) && ((req->src_rect.w != 1) || (req->dst_rect.w != req->src_rect.h))) || ((req->dst_rect.w == 1) && ((req->src_rect.h != 1) || (req->dst_rect.h != req->src_rect.w)))) { pr_err("mdp_ppp: error scaling when size is 1!\n"); return -EINVAL; } } else { if (((req->dst_rect.w == 1) && ((req->src_rect.w != 1) || (req->dst_rect.h != req->src_rect.h))) || ((req->dst_rect.h == 1) && ((req->src_rect.h != 1) || (req->dst_rect.w != req->src_rect.w)))) { pr_err("mdp_ppp: error scaling when size is 1!\n"); return -EINVAL; } } /* MDP width split workaround */ remainder = (req->dst_rect.w) % 16; ret = ppp_get_bpp(req->dst.format, mfd->fb_imgType); if (ret <= 0) { pr_err("mdp_ppp: incorrect bpp!\n"); return -EINVAL; } is_bpp_4 = (ret == 4) ? 1 : 0; if ((is_bpp_4 && (remainder == 6 || remainder == 14)) && !(req->flags & MDP_SOLID_FILL)) ret = mdp3_ppp_blit_workaround(mfd, req, remainder, src_data, dst_data); else ret = mdp3_ppp_blit(mfd, req, src_data, dst_data); return ret; } void mdp3_ppp_wait_for_fence(struct blit_req_list *req) { int i, ret = 0; /* buf sync */ for (i = 0; i < req->acq_fen_cnt; i++) { ret = sync_fence_wait(req->acq_fen[i], WAIT_FENCE_FINAL_TIMEOUT); if (ret < 0) { pr_err("%s: sync_fence_wait failed! ret = %x\n", __func__, ret); break; } sync_fence_put(req->acq_fen[i]); } if (ret < 0) { while (i < req->acq_fen_cnt) { sync_fence_put(req->acq_fen[i]); i++; } } req->acq_fen_cnt = 0; } void mdp3_ppp_signal_timeline(struct blit_req_list *req) { sw_sync_timeline_inc(ppp_stat->timeline, 1); req->last_rel_fence = req->cur_rel_fence; req->cur_rel_fence = 0; } static void mdp3_ppp_deinit_buf_sync(struct blit_req_list *req) { int i; put_unused_fd(req->cur_rel_fen_fd); sync_fence_put(req->cur_rel_fence); req->cur_rel_fence = NULL; req->cur_rel_fen_fd = 0; ppp_stat->timeline_value--; for (i = 0; i < req->acq_fen_cnt; i++) sync_fence_put(req->acq_fen[i]); req->acq_fen_cnt = 0; } static int mdp3_ppp_handle_buf_sync(struct blit_req_list *req, struct mdp_buf_sync *buf_sync) { int i, fence_cnt = 0, ret = 0; int acq_fen_fd[MDP_MAX_FENCE_FD]; struct sync_fence *fence; if ((buf_sync->acq_fen_fd_cnt > MDP_MAX_FENCE_FD) || (ppp_stat->timeline == NULL)) return -EINVAL; if (buf_sync->acq_fen_fd_cnt) ret = copy_from_user(acq_fen_fd, buf_sync->acq_fen_fd, buf_sync->acq_fen_fd_cnt * sizeof(int)); if (ret) { pr_err("%s: copy_from_user failed\n", __func__); return ret; } for (i = 0; i < buf_sync->acq_fen_fd_cnt; i++) { fence = sync_fence_fdget(acq_fen_fd[i]); if (fence == NULL) { pr_info("%s: null fence! i=%d fd=%d\n", __func__, i, acq_fen_fd[i]); ret = -EINVAL; break; } req->acq_fen[i] = fence; } fence_cnt = i; if (ret) goto buf_sync_err_1; req->acq_fen_cnt = fence_cnt; if (buf_sync->flags & MDP_BUF_SYNC_FLAG_WAIT) mdp3_ppp_wait_for_fence(req); req->cur_rel_sync_pt = sw_sync_pt_create(ppp_stat->timeline, ppp_stat->timeline_value++); if (req->cur_rel_sync_pt == NULL) { pr_err("%s: cannot create sync point\n", __func__); ret = -ENOMEM; goto buf_sync_err_2; } /* create fence */ req->cur_rel_fence = sync_fence_create("ppp-fence", req->cur_rel_sync_pt); if (req->cur_rel_fence == NULL) { sync_pt_free(req->cur_rel_sync_pt); req->cur_rel_sync_pt = NULL; pr_err("%s: cannot create fence\n", __func__); ret = -ENOMEM; goto buf_sync_err_2; } /* create fd */ return ret; buf_sync_err_2: ppp_stat->timeline_value--; buf_sync_err_1: for (i = 0; i < fence_cnt; i++) sync_fence_put(req->acq_fen[i]); req->acq_fen_cnt = 0; return ret; } void mdp3_ppp_req_push(struct blit_req_queue *req_q, struct blit_req_list *req) { int idx = req_q->push_idx; req_q->req[idx] = *req; req_q->count++; req_q->push_idx = (req_q->push_idx + 1) % MDP3_PPP_MAX_LIST_REQ; } struct blit_req_list *mdp3_ppp_next_req(struct blit_req_queue *req_q) { struct blit_req_list *req; if (req_q->count == 0) return NULL; req = &req_q->req[req_q->pop_idx]; return req; } void mdp3_ppp_req_pop(struct blit_req_queue *req_q) { req_q->count--; req_q->pop_idx = (req_q->pop_idx + 1) % MDP3_PPP_MAX_LIST_REQ; } void mdp3_free_fw_timer_func(unsigned long arg) { schedule_work(&ppp_stat->free_bw_work); } static void mdp3_free_bw_wq_handler(struct work_struct *work) { struct msm_fb_data_type *mfd = ppp_stat->mfd; int rc; mutex_lock(&ppp_stat->config_ppp_mutex); if (ppp_stat->bw_on) { mdp3_ppp_turnon(mfd, 0); rc = mdp3_iommu_disable(MDP3_CLIENT_PPP); if (rc < 0) WARN(1, "Unable to disable ppp iommu\n"); } mutex_unlock(&ppp_stat->config_ppp_mutex); } static void mdp3_ppp_blit_wq_handler(struct work_struct *work) { struct msm_fb_data_type *mfd = ppp_stat->mfd; struct blit_req_list *req; int i, rc = 0; mutex_lock(&ppp_stat->config_ppp_mutex); req = mdp3_ppp_next_req(&ppp_stat->req_q); if (!req) { mutex_unlock(&ppp_stat->config_ppp_mutex); return; } if (!ppp_stat->bw_on) { rc = mdp3_iommu_enable(MDP3_CLIENT_PPP); if (rc < 0) { mutex_unlock(&ppp_stat->config_ppp_mutex); pr_err("%s: mdp3_iommu_enable failed\n", __func__); return; } mdp3_ppp_turnon(mfd, 1); if (rc < 0) { mdp3_iommu_disable(MDP3_CLIENT_PPP); mutex_unlock(&ppp_stat->config_ppp_mutex); pr_err("%s: Enable ppp resources failed\n", __func__); return; } } while (req) { mdp3_ppp_wait_for_fence(req); for (i = 0; i < req->count; i++) { if (!(req->req_list[i].flags & MDP_NO_BLIT)) { /* Do the actual blit. */ if (!rc) { rc = mdp3_ppp_start_blit(mfd, &(req->req_list[i]), &req->src_data[i], &req->dst_data[i]); } mdp3_put_img(&req->src_data[i], MDP3_CLIENT_PPP); mdp3_put_img(&req->dst_data[i], MDP3_CLIENT_PPP); } } /* Signal to release fence */ mutex_lock(&ppp_stat->req_mutex); mdp3_ppp_signal_timeline(req); mdp3_ppp_req_pop(&ppp_stat->req_q); req = mdp3_ppp_next_req(&ppp_stat->req_q); if (ppp_stat->wait_for_pop) complete(&ppp_stat->pop_q_comp); mutex_unlock(&ppp_stat->req_mutex); } mod_timer(&ppp_stat->free_bw_timer, jiffies + msecs_to_jiffies(MDP_RELEASE_BW_TIMEOUT)); mutex_unlock(&ppp_stat->config_ppp_mutex); } int mdp3_ppp_parse_req(void __user *p, struct mdp_async_blit_req_list *req_list_header, int async) { struct blit_req_list *req; struct blit_req_queue *req_q = &ppp_stat->req_q; struct sync_fence *fence = NULL; int count, rc, idx, i; count = req_list_header->count; mutex_lock(&ppp_stat->req_mutex); while (req_q->count >= MDP3_PPP_MAX_LIST_REQ) { ppp_stat->wait_for_pop = true; mutex_unlock(&ppp_stat->req_mutex); rc = wait_for_completion_interruptible_timeout( &ppp_stat->pop_q_comp, 5 * HZ); if (rc == 0) { /* This will only occur if there is serious problem */ pr_err("%s: timeout exiting queuing request\n", __func__); return -EBUSY; } mutex_lock(&ppp_stat->req_mutex); ppp_stat->wait_for_pop = false; } idx = req_q->push_idx; req = &req_q->req[idx]; if (copy_from_user(&req->req_list, p, sizeof(struct mdp_blit_req) * count)) { mutex_unlock(&ppp_stat->req_mutex); return -EFAULT; } rc = mdp3_ppp_handle_buf_sync(req, &req_list_header->sync); if (rc < 0) { pr_err("%s: Failed create sync point\n", __func__); mutex_unlock(&ppp_stat->req_mutex); return rc; } req->count = count; /* We need to grab ion handle while running in client thread */ for (i = 0; i < count; i++) { rc = mdp3_ppp_get_img(&req->req_list[i].src, &req->req_list[i], &req->src_data[i]); if (rc < 0 || req->src_data[i].len == 0) { pr_err("mdp_ppp: couldn't retrieve src img from mem\n"); goto parse_err_1; } rc = mdp3_ppp_get_img(&req->req_list[i].dst, &req->req_list[i], &req->dst_data[i]); if (rc < 0 || req->dst_data[i].len == 0) { mdp3_put_img(&req->src_data[i], MDP3_CLIENT_PPP); pr_err("mdp_ppp: couldn't retrieve dest img from mem\n"); goto parse_err_1; } } if (async) { req->cur_rel_fen_fd = get_unused_fd_flags(0); if (req->cur_rel_fen_fd < 0) { pr_err("%s: get_unused_fd_flags failed\n", __func__); rc = -ENOMEM; goto parse_err_1; } sync_fence_install(req->cur_rel_fence, req->cur_rel_fen_fd); rc = copy_to_user(req_list_header->sync.rel_fen_fd, &req->cur_rel_fen_fd, sizeof(int)); if (rc) { pr_err("%s:copy_to_user failed\n", __func__); goto parse_err_2; } } else { fence = req->cur_rel_fence; } mdp3_ppp_req_push(req_q, req); mutex_unlock(&ppp_stat->req_mutex); schedule_work(&ppp_stat->blit_work); if (!async) { /* wait for release fence */ rc = sync_fence_wait(fence, 5 * MSEC_PER_SEC); if (rc < 0) pr_err("%s: sync blit! rc = %x\n", __func__, rc); sync_fence_put(fence); fence = NULL; } return 0; parse_err_2: put_unused_fd(req->cur_rel_fen_fd); parse_err_1: for (i--; i >= 0; i--) { mdp3_put_img(&req->src_data[i], MDP3_CLIENT_PPP); mdp3_put_img(&req->dst_data[i], MDP3_CLIENT_PPP); } mdp3_ppp_deinit_buf_sync(req); mutex_unlock(&ppp_stat->req_mutex); return rc; } int mdp3_ppp_res_init(struct msm_fb_data_type *mfd) { const char timeline_name[] = "mdp3_ppp"; ppp_stat = kzalloc(sizeof(struct ppp_status), GFP_KERNEL); if (!ppp_stat) { pr_err("%s: kmalloc failed\n", __func__); return -ENOMEM; } /*Setup sync_pt timeline for ppp*/ ppp_stat->timeline = sw_sync_timeline_create(timeline_name); if (ppp_stat->timeline == NULL) { pr_err("%s: cannot create time line\n", __func__); return -ENOMEM; } else { ppp_stat->timeline_value = 1; } INIT_WORK(&ppp_stat->blit_work, mdp3_ppp_blit_wq_handler); INIT_WORK(&ppp_stat->free_bw_work, mdp3_free_bw_wq_handler); init_completion(&ppp_stat->pop_q_comp); spin_lock_init(&ppp_stat->ppp_lock); mutex_init(&ppp_stat->req_mutex); mutex_init(&ppp_stat->config_ppp_mutex); init_timer(&ppp_stat->free_bw_timer); ppp_stat->free_bw_timer.function = mdp3_free_fw_timer_func; ppp_stat->free_bw_timer.data = 0; ppp_stat->busy = false; ppp_stat->mfd = mfd; mdp3_ppp_callback_setup(); return 0; }
danialbehzadi/Nokia-RM-1013-2.0.0.11
kernel/drivers/video/msm/mdss/mdp3_ppp.c
C
gpl-3.0
32,129
/* IEEE-1284 operations for parport. * * This file is for generic IEEE 1284 operations. The idea is that * they are used by the low-level drivers. If they have a special way * of doing something, they can provide their own routines (and put * the function pointers in port->ops); if not, they can just use these * as a fallback. * * Note: Make no assumptions about hardware or architecture in this file! * * Author: Tim Waugh <[email protected]> * Fixed AUTOFD polarity in ecp_forward_to_reverse(). Fred Barnes, 1999 * Software emulated EPP fixes, Fred Barnes, 04/2001. */ #include <linux/module.h> #include <linux/parport.h> #include <linux/delay.h> #include <linux/sched.h> #include <asm/uaccess.h> #undef DEBUG /* undef me for production */ #ifdef CONFIG_LP_CONSOLE #undef DEBUG /* Don't want a garbled console */ #endif #ifdef DEBUG #define DPRINTK(stuff...) printk (stuff) #else #define DPRINTK(stuff...) #endif /*** * * One-way data transfer functions. * * ***/ /* Compatibility mode. */ size_t parport_ieee1284_write_compat (struct parport *port, const void *buffer, size_t len, int flags) { int no_irq = 1; ssize_t count = 0; const unsigned char *addr = buffer; unsigned char byte; struct pardevice *dev = port->physport->cad; unsigned char ctl = (PARPORT_CONTROL_SELECT | PARPORT_CONTROL_INIT); if (port->irq != PARPORT_IRQ_NONE) { parport_enable_irq (port); no_irq = 0; } port->physport->ieee1284.phase = IEEE1284_PH_FWD_DATA; parport_write_control (port, ctl); parport_data_forward (port); while (count < len) { unsigned long expire = jiffies + dev->timeout; long wait = msecs_to_jiffies(10); unsigned char mask = (PARPORT_STATUS_ERROR | PARPORT_STATUS_BUSY); unsigned char val = (PARPORT_STATUS_ERROR | PARPORT_STATUS_BUSY); /* Wait until the peripheral's ready */ do { /* Is the peripheral ready yet? */ if (!parport_wait_peripheral (port, mask, val)) /* Skip the loop */ goto ready; /* Is the peripheral upset? */ if ((parport_read_status (port) & (PARPORT_STATUS_PAPEROUT | PARPORT_STATUS_SELECT | PARPORT_STATUS_ERROR)) != (PARPORT_STATUS_SELECT | PARPORT_STATUS_ERROR)) /* If nFault is asserted (i.e. no * error) and PAPEROUT and SELECT are * just red herrings, give the driver * a chance to check it's happy with * that before continuing. */ goto stop; /* Have we run out of time? */ if (!time_before (jiffies, expire)) break; /* Yield the port for a while. If this is the first time around the loop, don't let go of the port. This way, we find out if we have our interrupt handler called. */ if (count && no_irq) { parport_release (dev); schedule_timeout_interruptible(wait); parport_claim_or_block (dev); } else /* We must have the device claimed here */ parport_wait_event (port, wait); /* Is there a signal pending? */ if (signal_pending (current)) break; /* Wait longer next time. */ wait *= 2; } while (time_before (jiffies, expire)); if (signal_pending (current)) break; DPRINTK (KERN_DEBUG "%s: Timed out\n", port->name); break; ready: /* Write the character to the data lines. */ byte = *addr++; parport_write_data (port, byte); udelay (1); /* Pulse strobe. */ parport_write_control (port, ctl | PARPORT_CONTROL_STROBE); udelay (1); /* strobe */ parport_write_control (port, ctl); udelay (1); /* hold */ /* Assume the peripheral received it. */ count++; /* Let another process run if it needs to. */ if (time_before (jiffies, expire)) if (!parport_yield_blocking (dev) && need_resched()) schedule (); } stop: port->physport->ieee1284.phase = IEEE1284_PH_FWD_IDLE; return count; } /* Nibble mode. */ size_t parport_ieee1284_read_nibble (struct parport *port, void *buffer, size_t len, int flags) { #ifndef CONFIG_PARPORT_1284 return 0; #else unsigned char *buf = buffer; int i; unsigned char byte = 0; len *= 2; /* in nibbles */ for (i=0; i < len; i++) { unsigned char nibble; /* Does the error line indicate end of data? */ if (((i & 1) == 0) && (parport_read_status(port) & PARPORT_STATUS_ERROR)) { goto end_of_data; } /* Event 7: Set nAutoFd low. */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD, PARPORT_CONTROL_AUTOFD); /* Event 9: nAck goes low. */ port->ieee1284.phase = IEEE1284_PH_REV_DATA; if (parport_wait_peripheral (port, PARPORT_STATUS_ACK, 0)) { /* Timeout -- no more data? */ DPRINTK (KERN_DEBUG "%s: Nibble timeout at event 9 (%d bytes)\n", port->name, i/2); parport_frob_control (port, PARPORT_CONTROL_AUTOFD, 0); break; } /* Read a nibble. */ nibble = parport_read_status (port) >> 3; nibble &= ~8; if ((nibble & 0x10) == 0) nibble |= 8; nibble &= 0xf; /* Event 10: Set nAutoFd high. */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD, 0); /* Event 11: nAck goes high. */ if (parport_wait_peripheral (port, PARPORT_STATUS_ACK, PARPORT_STATUS_ACK)) { /* Timeout -- no more data? */ DPRINTK (KERN_DEBUG "%s: Nibble timeout at event 11\n", port->name); break; } if (i & 1) { /* Second nibble */ byte |= nibble << 4; *buf++ = byte; } else byte = nibble; } if (i == len) { /* Read the last nibble without checking data avail. */ if (parport_read_status (port) & PARPORT_STATUS_ERROR) { end_of_data: DPRINTK (KERN_DEBUG "%s: No more nibble data (%d bytes)\n", port->name, i/2); /* Go to reverse idle phase. */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD, PARPORT_CONTROL_AUTOFD); port->physport->ieee1284.phase = IEEE1284_PH_REV_IDLE; } else port->physport->ieee1284.phase = IEEE1284_PH_HBUSY_DAVAIL; } return i/2; #endif /* IEEE1284 support */ } /* Byte mode. */ size_t parport_ieee1284_read_byte (struct parport *port, void *buffer, size_t len, int flags) { #ifndef CONFIG_PARPORT_1284 return 0; #else unsigned char *buf = buffer; ssize_t count = 0; for (count = 0; count < len; count++) { unsigned char byte; /* Data available? */ if (parport_read_status (port) & PARPORT_STATUS_ERROR) { goto end_of_data; } /* Event 14: Place data bus in high impedance state. */ parport_data_reverse (port); /* Event 7: Set nAutoFd low. */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD, PARPORT_CONTROL_AUTOFD); /* Event 9: nAck goes low. */ port->physport->ieee1284.phase = IEEE1284_PH_REV_DATA; if (parport_wait_peripheral (port, PARPORT_STATUS_ACK, 0)) { /* Timeout -- no more data? */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD, 0); DPRINTK (KERN_DEBUG "%s: Byte timeout at event 9\n", port->name); break; } byte = parport_read_data (port); *buf++ = byte; /* Event 10: Set nAutoFd high */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD, 0); /* Event 11: nAck goes high. */ if (parport_wait_peripheral (port, PARPORT_STATUS_ACK, PARPORT_STATUS_ACK)) { /* Timeout -- no more data? */ DPRINTK (KERN_DEBUG "%s: Byte timeout at event 11\n", port->name); break; } /* Event 16: Set nStrobe low. */ parport_frob_control (port, PARPORT_CONTROL_STROBE, PARPORT_CONTROL_STROBE); udelay (5); /* Event 17: Set nStrobe high. */ parport_frob_control (port, PARPORT_CONTROL_STROBE, 0); } if (count == len) { /* Read the last byte without checking data avail. */ if (parport_read_status (port) & PARPORT_STATUS_ERROR) { end_of_data: DPRINTK (KERN_DEBUG "%s: No more byte data (%Zd bytes)\n", port->name, count); /* Go to reverse idle phase. */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD, PARPORT_CONTROL_AUTOFD); port->physport->ieee1284.phase = IEEE1284_PH_REV_IDLE; } else port->physport->ieee1284.phase = IEEE1284_PH_HBUSY_DAVAIL; } return count; #endif /* IEEE1284 support */ } /*** * * ECP Functions. * * ***/ #ifdef CONFIG_PARPORT_1284 static inline int ecp_forward_to_reverse (struct parport *port) { int retval; /* Event 38: Set nAutoFd low */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD, PARPORT_CONTROL_AUTOFD); parport_data_reverse (port); udelay (5); /* Event 39: Set nInit low to initiate bus reversal */ parport_frob_control (port, PARPORT_CONTROL_INIT, 0); /* Event 40: PError goes low */ retval = parport_wait_peripheral (port, PARPORT_STATUS_PAPEROUT, 0); if (!retval) { DPRINTK (KERN_DEBUG "%s: ECP direction: reverse\n", port->name); port->ieee1284.phase = IEEE1284_PH_REV_IDLE; } else { DPRINTK (KERN_DEBUG "%s: ECP direction: failed to reverse\n", port->name); port->ieee1284.phase = IEEE1284_PH_ECP_DIR_UNKNOWN; } return retval; } static inline int ecp_reverse_to_forward (struct parport *port) { int retval; /* Event 47: Set nInit high */ parport_frob_control (port, PARPORT_CONTROL_INIT | PARPORT_CONTROL_AUTOFD, PARPORT_CONTROL_INIT | PARPORT_CONTROL_AUTOFD); /* Event 49: PError goes high */ retval = parport_wait_peripheral (port, PARPORT_STATUS_PAPEROUT, PARPORT_STATUS_PAPEROUT); if (!retval) { parport_data_forward (port); DPRINTK (KERN_DEBUG "%s: ECP direction: forward\n", port->name); port->ieee1284.phase = IEEE1284_PH_FWD_IDLE; } else { DPRINTK (KERN_DEBUG "%s: ECP direction: failed to switch forward\n", port->name); port->ieee1284.phase = IEEE1284_PH_ECP_DIR_UNKNOWN; } return retval; } #endif /* IEEE1284 support */ /* ECP mode, forward channel, data. */ size_t parport_ieee1284_ecp_write_data (struct parport *port, const void *buffer, size_t len, int flags) { #ifndef CONFIG_PARPORT_1284 return 0; #else const unsigned char *buf = buffer; size_t written; int retry; port = port->physport; if (port->ieee1284.phase != IEEE1284_PH_FWD_IDLE) if (ecp_reverse_to_forward (port)) return 0; port->ieee1284.phase = IEEE1284_PH_FWD_DATA; /* HostAck high (data, not command) */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD | PARPORT_CONTROL_STROBE | PARPORT_CONTROL_INIT, PARPORT_CONTROL_INIT); for (written = 0; written < len; written++, buf++) { unsigned long expire = jiffies + port->cad->timeout; unsigned char byte; byte = *buf; try_again: parport_write_data (port, byte); parport_frob_control (port, PARPORT_CONTROL_STROBE, PARPORT_CONTROL_STROBE); udelay (5); for (retry = 0; retry < 100; retry++) { if (!parport_wait_peripheral (port, PARPORT_STATUS_BUSY, 0)) goto success; if (signal_pending (current)) { parport_frob_control (port, PARPORT_CONTROL_STROBE, 0); break; } } /* Time for Host Transfer Recovery (page 41 of IEEE1284) */ DPRINTK (KERN_DEBUG "%s: ECP transfer stalled!\n", port->name); parport_frob_control (port, PARPORT_CONTROL_INIT, PARPORT_CONTROL_INIT); udelay (50); if (parport_read_status (port) & PARPORT_STATUS_PAPEROUT) { /* It's buggered. */ parport_frob_control (port, PARPORT_CONTROL_INIT, 0); break; } parport_frob_control (port, PARPORT_CONTROL_INIT, 0); udelay (50); if (!(parport_read_status (port) & PARPORT_STATUS_PAPEROUT)) break; DPRINTK (KERN_DEBUG "%s: Host transfer recovered\n", port->name); if (time_after_eq (jiffies, expire)) break; goto try_again; success: parport_frob_control (port, PARPORT_CONTROL_STROBE, 0); udelay (5); if (parport_wait_peripheral (port, PARPORT_STATUS_BUSY, PARPORT_STATUS_BUSY)) /* Peripheral hasn't accepted the data. */ break; } port->ieee1284.phase = IEEE1284_PH_FWD_IDLE; return written; #endif /* IEEE1284 support */ } /* ECP mode, reverse channel, data. */ size_t parport_ieee1284_ecp_read_data (struct parport *port, void *buffer, size_t len, int flags) { #ifndef CONFIG_PARPORT_1284 return 0; #else struct pardevice *dev = port->cad; unsigned char *buf = buffer; int rle_count = 0; /* shut gcc up */ unsigned char ctl; int rle = 0; ssize_t count = 0; port = port->physport; if (port->ieee1284.phase != IEEE1284_PH_REV_IDLE) if (ecp_forward_to_reverse (port)) return 0; port->ieee1284.phase = IEEE1284_PH_REV_DATA; /* Set HostAck low to start accepting data. */ ctl = parport_read_control (port); ctl &= ~(PARPORT_CONTROL_STROBE | PARPORT_CONTROL_INIT | PARPORT_CONTROL_AUTOFD); parport_write_control (port, ctl | PARPORT_CONTROL_AUTOFD); while (count < len) { unsigned long expire = jiffies + dev->timeout; unsigned char byte; int command; /* Event 43: Peripheral sets nAck low. It can take as long as it wants. */ while (parport_wait_peripheral (port, PARPORT_STATUS_ACK, 0)) { /* The peripheral hasn't given us data in 35ms. If we have data to give back to the caller, do it now. */ if (count) goto out; /* If we've used up all the time we were allowed, give up altogether. */ if (!time_before (jiffies, expire)) goto out; /* Yield the port for a while. */ if (count && dev->port->irq != PARPORT_IRQ_NONE) { parport_release (dev); schedule_timeout_interruptible(msecs_to_jiffies(40)); parport_claim_or_block (dev); } else /* We must have the device claimed here. */ parport_wait_event (port, msecs_to_jiffies(40)); /* Is there a signal pending? */ if (signal_pending (current)) goto out; } /* Is this a command? */ if (rle) /* The last byte was a run-length count, so this can't be as well. */ command = 0; else command = (parport_read_status (port) & PARPORT_STATUS_BUSY) ? 1 : 0; /* Read the data. */ byte = parport_read_data (port); /* If this is a channel command, rather than an RLE command or a normal data byte, don't accept it. */ if (command) { if (byte & 0x80) { DPRINTK (KERN_DEBUG "%s: stopping short at " "channel command (%02x)\n", port->name, byte); goto out; } else if (port->ieee1284.mode != IEEE1284_MODE_ECPRLE) DPRINTK (KERN_DEBUG "%s: device illegally " "using RLE; accepting anyway\n", port->name); rle_count = byte + 1; /* Are we allowed to read that many bytes? */ if (rle_count > (len - count)) { DPRINTK (KERN_DEBUG "%s: leaving %d RLE bytes " "for next time\n", port->name, rle_count); break; } rle = 1; } /* Event 44: Set HostAck high, acknowledging handshake. */ parport_write_control (port, ctl); /* Event 45: The peripheral has 35ms to set nAck high. */ if (parport_wait_peripheral (port, PARPORT_STATUS_ACK, PARPORT_STATUS_ACK)) { /* It's gone wrong. Return what data we have to the caller. */ DPRINTK (KERN_DEBUG "ECP read timed out at 45\n"); if (command) printk (KERN_WARNING "%s: command ignored (%02x)\n", port->name, byte); break; } /* Event 46: Set HostAck low and accept the data. */ parport_write_control (port, ctl | PARPORT_CONTROL_AUTOFD); /* If we just read a run-length count, fetch the data. */ if (command) continue; /* If this is the byte after a run-length count, decompress. */ if (rle) { rle = 0; memset (buf, byte, rle_count); buf += rle_count; count += rle_count; DPRINTK (KERN_DEBUG "%s: decompressed to %d bytes\n", port->name, rle_count); } else { /* Normal data byte. */ *buf = byte; buf++, count++; } } out: port->ieee1284.phase = IEEE1284_PH_REV_IDLE; return count; #endif /* IEEE1284 support */ } /* ECP mode, forward channel, commands. */ size_t parport_ieee1284_ecp_write_addr (struct parport *port, const void *buffer, size_t len, int flags) { #ifndef CONFIG_PARPORT_1284 return 0; #else const unsigned char *buf = buffer; size_t written; int retry; port = port->physport; if (port->ieee1284.phase != IEEE1284_PH_FWD_IDLE) if (ecp_reverse_to_forward (port)) return 0; port->ieee1284.phase = IEEE1284_PH_FWD_DATA; /* HostAck low (command, not data) */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD | PARPORT_CONTROL_STROBE | PARPORT_CONTROL_INIT, PARPORT_CONTROL_AUTOFD | PARPORT_CONTROL_INIT); for (written = 0; written < len; written++, buf++) { unsigned long expire = jiffies + port->cad->timeout; unsigned char byte; byte = *buf; try_again: parport_write_data (port, byte); parport_frob_control (port, PARPORT_CONTROL_STROBE, PARPORT_CONTROL_STROBE); udelay (5); for (retry = 0; retry < 100; retry++) { if (!parport_wait_peripheral (port, PARPORT_STATUS_BUSY, 0)) goto success; if (signal_pending (current)) { parport_frob_control (port, PARPORT_CONTROL_STROBE, 0); break; } } /* Time for Host Transfer Recovery (page 41 of IEEE1284) */ DPRINTK (KERN_DEBUG "%s: ECP transfer stalled!\n", port->name); parport_frob_control (port, PARPORT_CONTROL_INIT, PARPORT_CONTROL_INIT); udelay (50); if (parport_read_status (port) & PARPORT_STATUS_PAPEROUT) { /* It's buggered. */ parport_frob_control (port, PARPORT_CONTROL_INIT, 0); break; } parport_frob_control (port, PARPORT_CONTROL_INIT, 0); udelay (50); if (!(parport_read_status (port) & PARPORT_STATUS_PAPEROUT)) break; DPRINTK (KERN_DEBUG "%s: Host transfer recovered\n", port->name); if (time_after_eq (jiffies, expire)) break; goto try_again; success: parport_frob_control (port, PARPORT_CONTROL_STROBE, 0); udelay (5); if (parport_wait_peripheral (port, PARPORT_STATUS_BUSY, PARPORT_STATUS_BUSY)) /* Peripheral hasn't accepted the data. */ break; } port->ieee1284.phase = IEEE1284_PH_FWD_IDLE; return written; #endif /* IEEE1284 support */ } /*** * * EPP functions. * * ***/ /* EPP mode, forward channel, data. */ size_t parport_ieee1284_epp_write_data (struct parport *port, const void *buffer, size_t len, int flags) { unsigned char *bp = (unsigned char *) buffer; size_t ret = 0; /* set EPP idle state (just to make sure) with strobe low */ parport_frob_control (port, PARPORT_CONTROL_STROBE | PARPORT_CONTROL_AUTOFD | PARPORT_CONTROL_SELECT | PARPORT_CONTROL_INIT, PARPORT_CONTROL_STROBE | PARPORT_CONTROL_INIT); port->ops->data_forward (port); for (; len > 0; len--, bp++) { /* Event 62: Write data and set autofd low */ parport_write_data (port, *bp); parport_frob_control (port, PARPORT_CONTROL_AUTOFD, PARPORT_CONTROL_AUTOFD); /* Event 58: wait for busy (nWait) to go high */ if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY, 0, 10)) break; /* Event 63: set nAutoFd (nDStrb) high */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD, 0); /* Event 60: wait for busy (nWait) to go low */ if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY, PARPORT_STATUS_BUSY, 5)) break; ret++; } /* Event 61: set strobe (nWrite) high */ parport_frob_control (port, PARPORT_CONTROL_STROBE, 0); return ret; } /* EPP mode, reverse channel, data. */ size_t parport_ieee1284_epp_read_data (struct parport *port, void *buffer, size_t len, int flags) { unsigned char *bp = (unsigned char *) buffer; unsigned ret = 0; /* set EPP idle state (just to make sure) with strobe high */ parport_frob_control (port, PARPORT_CONTROL_STROBE | PARPORT_CONTROL_AUTOFD | PARPORT_CONTROL_SELECT | PARPORT_CONTROL_INIT, PARPORT_CONTROL_INIT); port->ops->data_reverse (port); for (; len > 0; len--, bp++) { /* Event 67: set nAutoFd (nDStrb) low */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD, PARPORT_CONTROL_AUTOFD); /* Event 58: wait for Busy to go high */ if (parport_wait_peripheral (port, PARPORT_STATUS_BUSY, 0)) { break; } *bp = parport_read_data (port); /* Event 63: set nAutoFd (nDStrb) high */ parport_frob_control (port, PARPORT_CONTROL_AUTOFD, 0); /* Event 60: wait for Busy to go low */ if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY, PARPORT_STATUS_BUSY, 5)) { break; } ret++; } port->ops->data_forward (port); return ret; } /* EPP mode, forward channel, addresses. */ size_t parport_ieee1284_epp_write_addr (struct parport *port, const void *buffer, size_t len, int flags) { unsigned char *bp = (unsigned char *) buffer; size_t ret = 0; /* set EPP idle state (just to make sure) with strobe low */ parport_frob_control (port, PARPORT_CONTROL_STROBE | PARPORT_CONTROL_AUTOFD | PARPORT_CONTROL_SELECT | PARPORT_CONTROL_INIT, PARPORT_CONTROL_STROBE | PARPORT_CONTROL_INIT); port->ops->data_forward (port); for (; len > 0; len--, bp++) { /* Event 56: Write data and set nAStrb low. */ parport_write_data (port, *bp); parport_frob_control (port, PARPORT_CONTROL_SELECT, PARPORT_CONTROL_SELECT); /* Event 58: wait for busy (nWait) to go high */ if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY, 0, 10)) break; /* Event 59: set nAStrb high */ parport_frob_control (port, PARPORT_CONTROL_SELECT, 0); /* Event 60: wait for busy (nWait) to go low */ if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY, PARPORT_STATUS_BUSY, 5)) break; ret++; } /* Event 61: set strobe (nWrite) high */ parport_frob_control (port, PARPORT_CONTROL_STROBE, 0); return ret; } /* EPP mode, reverse channel, addresses. */ size_t parport_ieee1284_epp_read_addr (struct parport *port, void *buffer, size_t len, int flags) { unsigned char *bp = (unsigned char *) buffer; unsigned ret = 0; /* Set EPP idle state (just to make sure) with strobe high */ parport_frob_control (port, PARPORT_CONTROL_STROBE | PARPORT_CONTROL_AUTOFD | PARPORT_CONTROL_SELECT | PARPORT_CONTROL_INIT, PARPORT_CONTROL_INIT); port->ops->data_reverse (port); for (; len > 0; len--, bp++) { /* Event 64: set nSelectIn (nAStrb) low */ parport_frob_control (port, PARPORT_CONTROL_SELECT, PARPORT_CONTROL_SELECT); /* Event 58: wait for Busy to go high */ if (parport_wait_peripheral (port, PARPORT_STATUS_BUSY, 0)) { break; } *bp = parport_read_data (port); /* Event 59: set nSelectIn (nAStrb) high */ parport_frob_control (port, PARPORT_CONTROL_SELECT, 0); /* Event 60: wait for Busy to go low */ if (parport_poll_peripheral (port, PARPORT_STATUS_BUSY, PARPORT_STATUS_BUSY, 5)) break; ret++; } port->ops->data_forward (port); return ret; } EXPORT_SYMBOL(parport_ieee1284_ecp_write_data); EXPORT_SYMBOL(parport_ieee1284_ecp_read_data); EXPORT_SYMBOL(parport_ieee1284_ecp_write_addr); EXPORT_SYMBOL(parport_ieee1284_write_compat); EXPORT_SYMBOL(parport_ieee1284_read_nibble); EXPORT_SYMBOL(parport_ieee1284_read_byte); EXPORT_SYMBOL(parport_ieee1284_epp_write_data); EXPORT_SYMBOL(parport_ieee1284_epp_read_data); EXPORT_SYMBOL(parport_ieee1284_epp_write_addr); EXPORT_SYMBOL(parport_ieee1284_epp_read_addr);
talnoah/android_kernel_htc_dlx
virt/drivers/parport/ieee1284_ops.c
C
gpl-2.0
23,800
.mm-menu .mm-listview.mm-multiline>li>a,.mm-menu .mm-listview.mm-multiline>li>span,.mm-menu .mm-listview>li.mm-multiline>a,.mm-menu .mm-listview>li.mm-multiline>span,.mm-menu.mm-multiline .mm-listview>li>a,.mm-menu.mm-multiline .mm-listview>li>span{text-overflow:clip;white-space:normal}
JugglerX/figurit-drupal
web/libraries/mmenu/jquery.mmenu/extensions/multiline/jquery.mmenu.multiline.css
CSS
gpl-2.0
287
# CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 2.8 # Relative path conversion top directories. SET(CMAKE_RELATIVE_PATH_TOP_SOURCE "/home/ares/Developer/speed-dream-2.0/speed") SET(CMAKE_RELATIVE_PATH_TOP_BINARY "/home/ares/Developer/speed-dream-2.0/speed") # Force unix paths in dependencies. SET(CMAKE_FORCE_UNIX_PATHS 1) # The C and CXX include file regular expressions for this directory. SET(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$") SET(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$") SET(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN}) SET(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN})
xy008areshsu/speed-dreams-2
src/tools/xmlversion/CMakeFiles/CMakeDirectoryInformation.cmake
CMake
gpl-2.0
659
/* Package l7policies provides information and interaction with L7Policies and Rules of the LBaaS v2 extension for the OpenStack Networking service. Example to Create a L7Policy createOpts := l7policies.CreateOpts{ Name: "redirect-example.com", ListenerID: "023f2e34-7806-443b-bfae-16c324569a3d", Action: l7policies.ActionRedirectToURL, RedirectURL: "http://www.example.com", } l7policy, err := l7policies.Create(lbClient, createOpts).Extract() if err != nil { panic(err) } Example to List L7Policies listOpts := l7policies.ListOpts{ ListenerID: "c79a4468-d788-410c-bf79-9a8ef6354852", } allPages, err := l7policies.List(lbClient, listOpts).AllPages() if err != nil { panic(err) } allL7Policies, err := l7policies.ExtractL7Policies(allPages) if err != nil { panic(err) } for _, l7policy := range allL7Policies { fmt.Printf("%+v\n", l7policy) } Example to Get a L7Policy l7policy, err := l7policies.Get(lbClient, "023f2e34-7806-443b-bfae-16c324569a3d").Extract() if err != nil { panic(err) } Example to Delete a L7Policy l7policyID := "d67d56a6-4a86-4688-a282-f46444705c64" err := l7policies.Delete(lbClient, l7policyID).ExtractErr() if err != nil { panic(err) } Example to Update a L7Policy l7policyID := "d67d56a6-4a86-4688-a282-f46444705c64" name := "new-name" updateOpts := l7policies.UpdateOpts{ Name: &name, } l7policy, err := l7policies.Update(lbClient, l7policyID, updateOpts).Extract() if err != nil { panic(err) } Example to Create a Rule l7policyID := "d67d56a6-4a86-4688-a282-f46444705c64" createOpts := l7policies.CreateRuleOpts{ RuleType: l7policies.TypePath, CompareType: l7policies.CompareTypeRegex, Value: "/images*", } rule, err := l7policies.CreateRule(lbClient, l7policyID, createOpts).Extract() if err != nil { panic(err) } Example to List L7 Rules l7policyID := "d67d56a6-4a86-4688-a282-f46444705c64" listOpts := l7policies.ListRulesOpts{ RuleType: l7policies.TypePath, } allPages, err := l7policies.ListRules(lbClient, l7policyID, listOpts).AllPages() if err != nil { panic(err) } allRules, err := l7policies.ExtractRules(allPages) if err != nil { panic(err) } for _, rule := allRules { fmt.Printf("%+v\n", rule) } Example to Get a l7 rule l7rule, err := l7policies.GetRule(lbClient, "023f2e34-7806-443b-bfae-16c324569a3d", "53ad8ab8-40fa-11e8-a508-00224d6b7bc1").Extract() if err != nil { panic(err) } Example to Delete a l7 rule l7policyID := "d67d56a6-4a86-4688-a282-f46444705c64" ruleID := "64dba99f-8af8-4200-8882-e32a0660f23e" err := l7policies.DeleteRule(lbClient, l7policyID, ruleID).ExtractErr() if err != nil { panic(err) } Example to Update a Rule l7policyID := "d67d56a6-4a86-4688-a282-f46444705c64" ruleID := "64dba99f-8af8-4200-8882-e32a0660f23e" updateOpts := l7policies.UpdateRuleOpts{ RuleType: l7policies.TypePath, CompareType: l7policies.CompareTypeRegex, Value: "/images/special*", } rule, err := l7policies.UpdateRule(lbClient, l7policyID, ruleID, updateOpts).Extract() if err != nil { panic(err) } */ package l7policies
kubernetes/autoscaler
vertical-pod-autoscaler/e2e/vendor/github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/lbaas_v2/l7policies/doc.go
GO
apache-2.0
3,130
/* The industrial I/O core * * Copyright (c) 2008 Jonathan Cameron * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. */ #ifndef _INDUSTRIAL_IO_H_ #define _INDUSTRIAL_IO_H_ #include <linux/device.h> #include <linux/cdev.h> #include <linux/iio/types.h> #include <linux/of.h> /* IIO TODO LIST */ /* * Provide means of adjusting timer accuracy. * Currently assumes nano seconds. */ enum iio_chan_info_enum { IIO_CHAN_INFO_RAW = 0, IIO_CHAN_INFO_PROCESSED, IIO_CHAN_INFO_SCALE, IIO_CHAN_INFO_OFFSET, IIO_CHAN_INFO_CALIBSCALE, IIO_CHAN_INFO_CALIBBIAS, IIO_CHAN_INFO_PEAK, IIO_CHAN_INFO_PEAK_SCALE, IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW, IIO_CHAN_INFO_AVERAGE_RAW, IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY, IIO_CHAN_INFO_HIGH_PASS_FILTER_3DB_FREQUENCY, IIO_CHAN_INFO_SAMP_FREQ, IIO_CHAN_INFO_FREQUENCY, IIO_CHAN_INFO_PHASE, IIO_CHAN_INFO_HARDWAREGAIN, IIO_CHAN_INFO_HYSTERESIS, IIO_CHAN_INFO_INT_TIME, IIO_CHAN_INFO_ENABLE, IIO_CHAN_INFO_CALIBHEIGHT, IIO_CHAN_INFO_CALIBWEIGHT, IIO_CHAN_INFO_DEBOUNCE_COUNT, IIO_CHAN_INFO_DEBOUNCE_TIME, IIO_CHAN_INFO_CALIBEMISSIVITY, IIO_CHAN_INFO_OVERSAMPLING_RATIO, }; enum iio_shared_by { IIO_SEPARATE, IIO_SHARED_BY_TYPE, IIO_SHARED_BY_DIR, IIO_SHARED_BY_ALL }; enum iio_endian { IIO_CPU, IIO_BE, IIO_LE, }; struct iio_chan_spec; struct iio_dev; /** * struct iio_chan_spec_ext_info - Extended channel info attribute * @name: Info attribute name * @shared: Whether this attribute is shared between all channels. * @read: Read callback for this info attribute, may be NULL. * @write: Write callback for this info attribute, may be NULL. * @private: Data private to the driver. */ struct iio_chan_spec_ext_info { const char *name; enum iio_shared_by shared; ssize_t (*read)(struct iio_dev *, uintptr_t private, struct iio_chan_spec const *, char *buf); ssize_t (*write)(struct iio_dev *, uintptr_t private, struct iio_chan_spec const *, const char *buf, size_t len); uintptr_t private; }; /** * struct iio_enum - Enum channel info attribute * @items: An array of strings. * @num_items: Length of the item array. * @set: Set callback function, may be NULL. * @get: Get callback function, may be NULL. * * The iio_enum struct can be used to implement enum style channel attributes. * Enum style attributes are those which have a set of strings which map to * unsigned integer values. The IIO enum helper code takes care of mapping * between value and string as well as generating a "_available" file which * contains a list of all available items. The set callback will be called when * the attribute is updated. The last parameter is the index to the newly * activated item. The get callback will be used to query the currently active * item and is supposed to return the index for it. */ struct iio_enum { const char * const *items; unsigned int num_items; int (*set)(struct iio_dev *, const struct iio_chan_spec *, unsigned int); int (*get)(struct iio_dev *, const struct iio_chan_spec *); }; ssize_t iio_enum_available_read(struct iio_dev *indio_dev, uintptr_t priv, const struct iio_chan_spec *chan, char *buf); ssize_t iio_enum_read(struct iio_dev *indio_dev, uintptr_t priv, const struct iio_chan_spec *chan, char *buf); ssize_t iio_enum_write(struct iio_dev *indio_dev, uintptr_t priv, const struct iio_chan_spec *chan, const char *buf, size_t len); /** * IIO_ENUM() - Initialize enum extended channel attribute * @_name: Attribute name * @_shared: Whether the attribute is shared between all channels * @_e: Pointer to an iio_enum struct * * This should usually be used together with IIO_ENUM_AVAILABLE() */ #define IIO_ENUM(_name, _shared, _e) \ { \ .name = (_name), \ .shared = (_shared), \ .read = iio_enum_read, \ .write = iio_enum_write, \ .private = (uintptr_t)(_e), \ } /** * IIO_ENUM_AVAILABLE() - Initialize enum available extended channel attribute * @_name: Attribute name ("_available" will be appended to the name) * @_e: Pointer to an iio_enum struct * * Creates a read only attribute which lists all the available enum items in a * space separated list. This should usually be used together with IIO_ENUM() */ #define IIO_ENUM_AVAILABLE(_name, _e) \ { \ .name = (_name "_available"), \ .shared = IIO_SHARED_BY_TYPE, \ .read = iio_enum_available_read, \ .private = (uintptr_t)(_e), \ } /** * struct iio_event_spec - specification for a channel event * @type: Type of the event * @dir: Direction of the event * @mask_separate: Bit mask of enum iio_event_info values. Attributes * set in this mask will be registered per channel. * @mask_shared_by_type: Bit mask of enum iio_event_info values. Attributes * set in this mask will be shared by channel type. * @mask_shared_by_dir: Bit mask of enum iio_event_info values. Attributes * set in this mask will be shared by channel type and * direction. * @mask_shared_by_all: Bit mask of enum iio_event_info values. Attributes * set in this mask will be shared by all channels. */ struct iio_event_spec { enum iio_event_type type; enum iio_event_direction dir; unsigned long mask_separate; unsigned long mask_shared_by_type; unsigned long mask_shared_by_dir; unsigned long mask_shared_by_all; }; /** * struct iio_chan_spec - specification of a single channel * @type: What type of measurement is the channel making. * @channel: What number do we wish to assign the channel. * @channel2: If there is a second number for a differential * channel then this is it. If modified is set then the * value here specifies the modifier. * @address: Driver specific identifier. * @scan_index: Monotonic index to give ordering in scans when read * from a buffer. * @scan_type: Sign: 's' or 'u' to specify signed or unsigned * realbits: Number of valid bits of data * storage_bits: Realbits + padding * shift: Shift right by this before masking out * realbits. * endianness: little or big endian * repeat: Number of times real/storage bits * repeats. When the repeat element is * more than 1, then the type element in * sysfs will show a repeat value. * Otherwise, the number of repetitions is * omitted. * @info_mask_separate: What information is to be exported that is specific to * this channel. * @info_mask_shared_by_type: What information is to be exported that is shared * by all channels of the same type. * @info_mask_shared_by_dir: What information is to be exported that is shared * by all channels of the same direction. * @info_mask_shared_by_all: What information is to be exported that is shared * by all channels. * @event_spec: Array of events which should be registered for this * channel. * @num_event_specs: Size of the event_spec array. * @ext_info: Array of extended info attributes for this channel. * The array is NULL terminated, the last element should * have its name field set to NULL. * @extend_name: Allows labeling of channel attributes with an * informative name. Note this has no effect codes etc, * unlike modifiers. * @datasheet_name: A name used in in-kernel mapping of channels. It should * correspond to the first name that the channel is referred * to by in the datasheet (e.g. IND), or the nearest * possible compound name (e.g. IND-INC). * @modified: Does a modifier apply to this channel. What these are * depends on the channel type. Modifier is set in * channel2. Examples are IIO_MOD_X for axial sensors about * the 'x' axis. * @indexed: Specify the channel has a numerical index. If not, * the channel index number will be suppressed for sysfs * attributes but not for event codes. * @output: Channel is output. * @differential: Channel is differential. */ struct iio_chan_spec { enum iio_chan_type type; int channel; int channel2; unsigned long address; int scan_index; struct { char sign; u8 realbits; u8 storagebits; u8 shift; u8 repeat; enum iio_endian endianness; } scan_type; long info_mask_separate; long info_mask_shared_by_type; long info_mask_shared_by_dir; long info_mask_shared_by_all; const struct iio_event_spec *event_spec; unsigned int num_event_specs; const struct iio_chan_spec_ext_info *ext_info; const char *extend_name; const char *datasheet_name; unsigned modified:1; unsigned indexed:1; unsigned output:1; unsigned differential:1; }; /** * iio_channel_has_info() - Checks whether a channel supports a info attribute * @chan: The channel to be queried * @type: Type of the info attribute to be checked * * Returns true if the channels supports reporting values for the given info * attribute type, false otherwise. */ static inline bool iio_channel_has_info(const struct iio_chan_spec *chan, enum iio_chan_info_enum type) { return (chan->info_mask_separate & BIT(type)) | (chan->info_mask_shared_by_type & BIT(type)) | (chan->info_mask_shared_by_dir & BIT(type)) | (chan->info_mask_shared_by_all & BIT(type)); } #define IIO_CHAN_SOFT_TIMESTAMP(_si) { \ .type = IIO_TIMESTAMP, \ .channel = -1, \ .scan_index = _si, \ .scan_type = { \ .sign = 's', \ .realbits = 64, \ .storagebits = 64, \ }, \ } /** * iio_get_time_ns() - utility function to get a time stamp for events etc **/ static inline s64 iio_get_time_ns(void) { return ktime_get_real_ns(); } /* Device operating modes */ #define INDIO_DIRECT_MODE 0x01 #define INDIO_BUFFER_TRIGGERED 0x02 #define INDIO_BUFFER_SOFTWARE 0x04 #define INDIO_BUFFER_HARDWARE 0x08 #define INDIO_ALL_BUFFER_MODES \ (INDIO_BUFFER_TRIGGERED | INDIO_BUFFER_HARDWARE | INDIO_BUFFER_SOFTWARE) #define INDIO_MAX_RAW_ELEMENTS 4 struct iio_trigger; /* forward declaration */ struct iio_dev; /** * struct iio_info - constant information about device * @driver_module: module structure used to ensure correct * ownership of chrdevs etc * @event_attrs: event control attributes * @attrs: general purpose device attributes * @read_raw: function to request a value from the device. * mask specifies which value. Note 0 means a reading of * the channel in question. Return value will specify the * type of value returned by the device. val and val2 will * contain the elements making up the returned value. * @read_raw_multi: function to return values from the device. * mask specifies which value. Note 0 means a reading of * the channel in question. Return value will specify the * type of value returned by the device. vals pointer * contain the elements making up the returned value. * max_len specifies maximum number of elements * vals pointer can contain. val_len is used to return * length of valid elements in vals. * @write_raw: function to write a value to the device. * Parameters are the same as for read_raw. * @write_raw_get_fmt: callback function to query the expected * format/precision. If not set by the driver, write_raw * returns IIO_VAL_INT_PLUS_MICRO. * @read_event_config: find out if the event is enabled. * @write_event_config: set if the event is enabled. * @read_event_value: read a configuration value associated with the event. * @write_event_value: write a configuration value for the event. * @validate_trigger: function to validate the trigger when the * current trigger gets changed. * @update_scan_mode: function to configure device and scan buffer when * channels have changed * @debugfs_reg_access: function to read or write register value of device * @of_xlate: function pointer to obtain channel specifier index. * When #iio-cells is greater than '0', the driver could * provide a custom of_xlate function that reads the * *args* and returns the appropriate index in registered * IIO channels array. * @hwfifo_set_watermark: function pointer to set the current hardware * fifo watermark level; see hwfifo_* entries in * Documentation/ABI/testing/sysfs-bus-iio for details on * how the hardware fifo operates * @hwfifo_flush_to_buffer: function pointer to flush the samples stored * in the hardware fifo to the device buffer. The driver * should not flush more than count samples. The function * must return the number of samples flushed, 0 if no * samples were flushed or a negative integer if no samples * were flushed and there was an error. **/ struct iio_info { struct module *driver_module; struct attribute_group *event_attrs; const struct attribute_group *attrs; int (*read_raw)(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int *val, int *val2, long mask); int (*read_raw_multi)(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int max_len, int *vals, int *val_len, long mask); int (*write_raw)(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int val, int val2, long mask); int (*write_raw_get_fmt)(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, long mask); int (*read_event_config)(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir); int (*write_event_config)(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir, int state); int (*read_event_value)(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir, enum iio_event_info info, int *val, int *val2); int (*write_event_value)(struct iio_dev *indio_dev, const struct iio_chan_spec *chan, enum iio_event_type type, enum iio_event_direction dir, enum iio_event_info info, int val, int val2); int (*validate_trigger)(struct iio_dev *indio_dev, struct iio_trigger *trig); int (*update_scan_mode)(struct iio_dev *indio_dev, const unsigned long *scan_mask); int (*debugfs_reg_access)(struct iio_dev *indio_dev, unsigned reg, unsigned writeval, unsigned *readval); int (*of_xlate)(struct iio_dev *indio_dev, const struct of_phandle_args *iiospec); int (*hwfifo_set_watermark)(struct iio_dev *indio_dev, unsigned val); int (*hwfifo_flush_to_buffer)(struct iio_dev *indio_dev, unsigned count); }; /** * struct iio_buffer_setup_ops - buffer setup related callbacks * @preenable: [DRIVER] function to run prior to marking buffer enabled * @postenable: [DRIVER] function to run after marking buffer enabled * @predisable: [DRIVER] function to run prior to marking buffer * disabled * @postdisable: [DRIVER] function to run after marking buffer disabled * @validate_scan_mask: [DRIVER] function callback to check whether a given * scan mask is valid for the device. */ struct iio_buffer_setup_ops { int (*preenable)(struct iio_dev *); int (*postenable)(struct iio_dev *); int (*predisable)(struct iio_dev *); int (*postdisable)(struct iio_dev *); bool (*validate_scan_mask)(struct iio_dev *indio_dev, const unsigned long *scan_mask); }; /** * struct iio_dev - industrial I/O device * @id: [INTERN] used to identify device internally * @modes: [DRIVER] operating modes supported by device * @currentmode: [DRIVER] current operating mode * @dev: [DRIVER] device structure, should be assigned a parent * and owner * @event_interface: [INTERN] event chrdevs associated with interrupt lines * @buffer: [DRIVER] any buffer present * @buffer_list: [INTERN] list of all buffers currently attached * @scan_bytes: [INTERN] num bytes captured to be fed to buffer demux * @mlock: [INTERN] lock used to prevent simultaneous device state * changes * @available_scan_masks: [DRIVER] optional array of allowed bitmasks * @masklength: [INTERN] the length of the mask established from * channels * @active_scan_mask: [INTERN] union of all scan masks requested by buffers * @scan_timestamp: [INTERN] set if any buffers have requested timestamp * @scan_index_timestamp:[INTERN] cache of the index to the timestamp * @trig: [INTERN] current device trigger (buffer modes) * @pollfunc: [DRIVER] function run on trigger being received * @channels: [DRIVER] channel specification structure table * @num_channels: [DRIVER] number of channels specified in @channels. * @channel_attr_list: [INTERN] keep track of automatically created channel * attributes * @chan_attr_group: [INTERN] group for all attrs in base directory * @name: [DRIVER] name of the device. * @info: [DRIVER] callbacks and constant info from driver * @info_exist_lock: [INTERN] lock to prevent use during removal * @setup_ops: [DRIVER] callbacks to call before and after buffer * enable/disable * @chrdev: [INTERN] associated character device * @groups: [INTERN] attribute groups * @groupcounter: [INTERN] index of next attribute group * @flags: [INTERN] file ops related flags including busy flag. * @debugfs_dentry: [INTERN] device specific debugfs dentry. * @cached_reg_addr: [INTERN] cached register address for debugfs reads. */ struct iio_dev { int id; int modes; int currentmode; struct device dev; struct iio_event_interface *event_interface; struct iio_buffer *buffer; struct list_head buffer_list; int scan_bytes; struct mutex mlock; const unsigned long *available_scan_masks; unsigned masklength; const unsigned long *active_scan_mask; bool scan_timestamp; unsigned scan_index_timestamp; struct iio_trigger *trig; struct iio_poll_func *pollfunc; struct iio_chan_spec const *channels; int num_channels; struct list_head channel_attr_list; struct attribute_group chan_attr_group; const char *name; const struct iio_info *info; struct mutex info_exist_lock; const struct iio_buffer_setup_ops *setup_ops; struct cdev chrdev; #define IIO_MAX_GROUPS 6 const struct attribute_group *groups[IIO_MAX_GROUPS + 1]; int groupcounter; unsigned long flags; #if defined(CONFIG_DEBUG_FS) struct dentry *debugfs_dentry; unsigned cached_reg_addr; #endif }; const struct iio_chan_spec *iio_find_channel_from_si(struct iio_dev *indio_dev, int si); int iio_device_register(struct iio_dev *indio_dev); void iio_device_unregister(struct iio_dev *indio_dev); int devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev); void devm_iio_device_unregister(struct device *dev, struct iio_dev *indio_dev); int iio_push_event(struct iio_dev *indio_dev, u64 ev_code, s64 timestamp); extern struct bus_type iio_bus_type; /** * iio_device_put() - reference counted deallocation of struct device * @indio_dev: IIO device structure containing the device **/ static inline void iio_device_put(struct iio_dev *indio_dev) { if (indio_dev) put_device(&indio_dev->dev); } /** * dev_to_iio_dev() - Get IIO device struct from a device struct * @dev: The device embedded in the IIO device * * Note: The device must be a IIO device, otherwise the result is undefined. */ static inline struct iio_dev *dev_to_iio_dev(struct device *dev) { return container_of(dev, struct iio_dev, dev); } /** * iio_device_get() - increment reference count for the device * @indio_dev: IIO device structure * * Returns: The passed IIO device **/ static inline struct iio_dev *iio_device_get(struct iio_dev *indio_dev) { return indio_dev ? dev_to_iio_dev(get_device(&indio_dev->dev)) : NULL; } /** * iio_device_set_drvdata() - Set device driver data * @indio_dev: IIO device structure * @data: Driver specific data * * Allows to attach an arbitrary pointer to an IIO device, which can later be * retrieved by iio_device_get_drvdata(). */ static inline void iio_device_set_drvdata(struct iio_dev *indio_dev, void *data) { dev_set_drvdata(&indio_dev->dev, data); } /** * iio_device_get_drvdata() - Get device driver data * @indio_dev: IIO device structure * * Returns the data previously set with iio_device_set_drvdata() */ static inline void *iio_device_get_drvdata(struct iio_dev *indio_dev) { return dev_get_drvdata(&indio_dev->dev); } /* Can we make this smaller? */ #define IIO_ALIGN L1_CACHE_BYTES struct iio_dev *iio_device_alloc(int sizeof_priv); static inline void *iio_priv(const struct iio_dev *indio_dev) { return (char *)indio_dev + ALIGN(sizeof(struct iio_dev), IIO_ALIGN); } static inline struct iio_dev *iio_priv_to_dev(void *priv) { return (struct iio_dev *)((char *)priv - ALIGN(sizeof(struct iio_dev), IIO_ALIGN)); } void iio_device_free(struct iio_dev *indio_dev); struct iio_dev *devm_iio_device_alloc(struct device *dev, int sizeof_priv); void devm_iio_device_free(struct device *dev, struct iio_dev *indio_dev); struct iio_trigger *devm_iio_trigger_alloc(struct device *dev, const char *fmt, ...); void devm_iio_trigger_free(struct device *dev, struct iio_trigger *iio_trig); /** * iio_buffer_enabled() - helper function to test if the buffer is enabled * @indio_dev: IIO device structure for device **/ static inline bool iio_buffer_enabled(struct iio_dev *indio_dev) { return indio_dev->currentmode & (INDIO_BUFFER_TRIGGERED | INDIO_BUFFER_HARDWARE | INDIO_BUFFER_SOFTWARE); } /** * iio_get_debugfs_dentry() - helper function to get the debugfs_dentry * @indio_dev: IIO device structure for device **/ #if defined(CONFIG_DEBUG_FS) static inline struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev) { return indio_dev->debugfs_dentry; } #else static inline struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev) { return NULL; } #endif int iio_str_to_fixpoint(const char *str, int fract_mult, int *integer, int *fract); /** * IIO_DEGREE_TO_RAD() - Convert degree to rad * @deg: A value in degree * * Returns the given value converted from degree to rad */ #define IIO_DEGREE_TO_RAD(deg) (((deg) * 314159ULL + 9000000ULL) / 18000000ULL) /** * IIO_RAD_TO_DEGREE() - Convert rad to degree * @rad: A value in rad * * Returns the given value converted from rad to degree */ #define IIO_RAD_TO_DEGREE(rad) \ (((rad) * 18000000ULL + 314159ULL / 2) / 314159ULL) /** * IIO_G_TO_M_S_2() - Convert g to meter / second**2 * @g: A value in g * * Returns the given value converted from g to meter / second**2 */ #define IIO_G_TO_M_S_2(g) ((g) * 980665ULL / 100000ULL) /** * IIO_M_S_2_TO_G() - Convert meter / second**2 to g * @ms2: A value in meter / second**2 * * Returns the given value converted from meter / second**2 to g */ #define IIO_M_S_2_TO_G(ms2) (((ms2) * 100000ULL + 980665ULL / 2) / 980665ULL) #endif /* _INDUSTRIAL_IO_H_ */
publicloudapp/csrutil
linux-4.3/include/linux/iio/iio.h
C
mit
22,791
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved using System; using System.Collections.ObjectModel; using System.Runtime.InteropServices; using System.Text; #if !WINRT_NOT_PRESENT using Windows.Data.Xml.Dom; #endif namespace NotificationsExtensions { internal sealed class NotificationContentText : INotificationContentText { internal NotificationContentText() { } public string Text { get { return m_Text; } set { m_Text = value; } } public string Lang { get { return m_Lang; } set { m_Lang = value; } } private string m_Text; private string m_Lang; } internal sealed class NotificationContentImage : INotificationContentImage { internal NotificationContentImage() { } public string Src { get { return m_Src; } set { m_Src = value; } } public string Alt { get { return m_Alt; } set { m_Alt = value; } } public bool AddImageQuery { get { if (m_AddImageQueryNullable == null || m_AddImageQueryNullable.Value == false) { return false; } else { return true; } } set { m_AddImageQueryNullable = value; } } public bool? AddImageQueryNullable { get { return m_AddImageQueryNullable; } set { m_AddImageQueryNullable = value; } } private string m_Src; private string m_Alt; private bool? m_AddImageQueryNullable; } internal static class Util { public const int NOTIFICATION_CONTENT_VERSION = 1; public static string HttpEncode(string value) { return value.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;"); } } /// <summary> /// Base class for the notification content creation helper classes. /// </summary> #if !WINRT_NOT_PRESENT internal abstract class NotificationBase #else abstract partial class NotificationBase #endif { protected NotificationBase(string templateName, string fallbackName, int imageCount, int textCount) { m_TemplateName = templateName; m_FallbackName = fallbackName; m_Images = new NotificationContentImage[imageCount]; for (int i = 0; i < m_Images.Length; i++) { m_Images[i] = new NotificationContentImage(); } m_TextFields = new INotificationContentText[textCount]; for (int i = 0; i < m_TextFields.Length; i++) { m_TextFields[i] = new NotificationContentText(); } } public bool StrictValidation { get { return m_StrictValidation; } set { m_StrictValidation = value; } } public abstract string GetContent(); public override string ToString() { return GetContent(); } #if !WINRT_NOT_PRESENT public XmlDocument GetXml() { XmlDocument xml = new XmlDocument(); xml.LoadXml(GetContent()); return xml; } #endif /// <summary> /// Retrieves the list of images that can be manipulated on the notification content. /// </summary> public INotificationContentImage[] Images { get { return m_Images; } } /// <summary> /// Retrieves the list of text fields that can be manipulated on the notification content. /// </summary> public INotificationContentText[] TextFields { get { return m_TextFields; } } /// <summary> /// The base Uri path that should be used for all image references in the notification. /// </summary> public string BaseUri { get { return m_BaseUri; } set { if (this.StrictValidation && !String.IsNullOrEmpty(value)) { Uri uri; try { uri = new Uri(value); } catch (Exception e) { throw new ArgumentException("Invalid URI. Use a valid URI or turn off StrictValidation", e); } if (!(uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) || uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) || uri.Scheme.Equals("ms-appx", StringComparison.OrdinalIgnoreCase) || (uri.Scheme.Equals("ms-appdata", StringComparison.OrdinalIgnoreCase) && (String.IsNullOrEmpty(uri.Authority)) // check to make sure the Uri isn't ms-appdata://foo/local && (uri.AbsolutePath.StartsWith("/local/") || uri.AbsolutePath.StartsWith("local/"))))) // both ms-appdata:local/ and ms-appdata:/local/ are valid { throw new ArgumentException("The BaseUri must begin with http://, https://, ms-appx:///, or ms-appdata:///local/.", "value"); } } m_BaseUri = value; } } public string Lang { get { return m_Lang; } set { m_Lang = value; } } public bool AddImageQuery { get { if (m_AddImageQueryNullable == null || m_AddImageQueryNullable.Value == false) { return false; } else { return true; } } set { m_AddImageQueryNullable = value; } } public bool? AddImageQueryNullable { get { return m_AddImageQueryNullable; } set { m_AddImageQueryNullable = value; } } protected string SerializeProperties(string globalLang, string globalBaseUri, bool globalAddImageQuery) { globalLang = (globalLang != null) ? globalLang : String.Empty; globalBaseUri = String.IsNullOrWhiteSpace(globalBaseUri) ? null : globalBaseUri; StringBuilder builder = new StringBuilder(String.Empty); for (int i = 0; i < m_Images.Length; i++) { if (!String.IsNullOrEmpty(m_Images[i].Src)) { string escapedSrc = Util.HttpEncode(m_Images[i].Src); if (!String.IsNullOrWhiteSpace(m_Images[i].Alt)) { string escapedAlt = Util.HttpEncode(m_Images[i].Alt); if (m_Images[i].AddImageQueryNullable == null || m_Images[i].AddImageQueryNullable == globalAddImageQuery) { builder.AppendFormat("<image id='{0}' src='{1}' alt='{2}'/>", i + 1, escapedSrc, escapedAlt); } else { builder.AppendFormat("<image addImageQuery='{0}' id='{1}' src='{2}' alt='{3}'/>", m_Images[i].AddImageQuery.ToString().ToLowerInvariant(), i + 1, escapedSrc, escapedAlt); } } else { if (m_Images[i].AddImageQueryNullable == null || m_Images[i].AddImageQueryNullable == globalAddImageQuery) { builder.AppendFormat("<image id='{0}' src='{1}'/>", i + 1, escapedSrc); } else { builder.AppendFormat("<image addImageQuery='{0}' id='{1}' src='{2}'/>", m_Images[i].AddImageQuery.ToString().ToLowerInvariant(), i + 1, escapedSrc); } } } } for (int i = 0; i < m_TextFields.Length; i++) { if (!String.IsNullOrWhiteSpace(m_TextFields[i].Text)) { string escapedValue = Util.HttpEncode(m_TextFields[i].Text); if (!String.IsNullOrWhiteSpace(m_TextFields[i].Lang) && !m_TextFields[i].Lang.Equals(globalLang)) { string escapedLang = Util.HttpEncode(m_TextFields[i].Lang); builder.AppendFormat("<text id='{0}' lang='{1}'>{2}</text>", i + 1, escapedLang, escapedValue); } else { builder.AppendFormat("<text id='{0}'>{1}</text>", i + 1, escapedValue); } } } return builder.ToString(); } public string TemplateName { get { return m_TemplateName; } } public string FallbackName { get { return m_FallbackName; } } private bool m_StrictValidation = true; private NotificationContentImage[] m_Images; private INotificationContentText[] m_TextFields; private string m_Lang; private string m_BaseUri; private string m_TemplateName; private string m_FallbackName; private bool? m_AddImageQueryNullable; } /// <summary> /// Exception returned when invalid notification content is provided. /// </summary> internal sealed class NotificationContentValidationException : COMException { public NotificationContentValidationException(string message) : base(message, unchecked((int)0x80070057)) { } } }
gisfromscratch/windowsappsamples
Secondary tiles sample/C#/NotificationsExtensions/Common.cs
C#
apache-2.0
10,217
/** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @main yui @submodule yui-base **/ /*jshint eqeqeq: false*/ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. This is the constructor for all YUI instances. This is a self-instantiable factory function, meaning you don't need to precede it with the `new` operator. You can invoke it directly like this: YUI().use('*', function (Y) { // Y is a new YUI instance. }); But it also works like this: var Y = YUI(); The `YUI` constructor accepts an optional config object, like this: YUI({ debug: true, combine: false }).use('node', function (Y) { // Y.Node is ready to use. }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. If a global `YUI` object is already defined, the existing YUI object will not be overwritten, to ensure that defined namespaces are preserved. Each YUI instance has full custom event support, but only if the event system is available. @class YUI @uses EventTarget @constructor @global @param {Object} [config]* Zero or more optional configuration objects. Config values are stored in the `Y.config` property. See the <a href="config.html">Config</a> docs for the list of supported properties. **/ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** Master configuration that might span multiple contexts in a non- browser environment. It is applied first to all instances in all contexts. @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} GlobalConfig @global @static **/ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** Page-level config applied to all YUI instances created on the current page. This is applied after `YUI.GlobalConfig` and before any instance-level configuration. @example // Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} YUI_config @global **/ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', /* These CSS class names can't be generated by getClassName since it is not available at the time they are being used. */ DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleReady = function() { YUI.Env.DOMReady = true; if (hasWin) { remove(doc, 'DOMContentLoaded', handleReady); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader, lCore = [ 'loader-base' ], G_ENV = YUI.Env, mods = G_ENV.mods; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } if (mods && mods.loader) { lCore = [].concat(lCore, YUI.Env.loaderExtras); } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore)); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.5.0'; // dev time hack for cdn test } proto = { /** Applies a new configuration object to the config of this YUI instance. This will merge new group/module definitions, and will also update the loader cache if necessary. Updating `Y.config` directly will not update the cache. @method applyConfig @param {Object} o the configuration object. @since 3.2.0 **/ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** Old way to apply a config to this instance (calls `applyConfig` under the hood). @private @method _config @param {Object} o The config to apply **/ _config: function(o) { this.applyConfig(o); }, /** Initializes this YUI instance. @private @method _init **/ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** The version number of this YUI instance. This value is typically updated by a script when a YUI release is built, so it may not reflect the correct version number when YUI is run from the development source tree. @property {String} version **/ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get', 'features', 'intl-base', 'yui-log', 'yui-later', 'loader-base', 'loader-rollup', 'loader-yui3'], loaderExtras: ['loader-rollup', 'loader-yui3'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _exported: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(yui). // 1. Look in the test string for "yui" or // "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_yui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js". // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b( after a word break find either the string // yui(?:-\w+)? "yui" optionally followed by a -, then more characters // ) and store the yui-* string in \2 // \/\2 then comes a / followed by the yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path }; } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/[^a-z0-9_]+/g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win, global: Function('return this')() }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; if (doc.body) { doc.body.appendChild(YUI.Env.cssStampEl); } else { docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } } else if (doc && doc.getElementById(CSS_STAMP_EL) && !YUI.Env.cssStampEl) { YUI.Env.cssStampEl = doc.getElementById(CSS_STAMP_EL); } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** Finishes the instance setup. Attaches whatever YUI modules were defined at the time that this instance was created. @method _setup @private **/ _setup: function() { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } }, /** Executes the named method on the specified YUI instance if that method is whitelisted. @method applyTo @param {String} id YUI instance id. @param {String} method Name of the method to execute. For example: 'Object.keys'. @param {Array} args Arguments to apply to the method. @return {Mixed} Return value from the applied method, or `null` if the specified instance was not found or the method was not whitelisted. **/ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m && m.apply(instance, args); } return null; }, /** Registers a YUI module and makes it available for use in a `YUI().use()` call or as a dependency for other modules. The easiest way to create a first-class YUI module is to use <a href="http://yui.github.com/shifter/">Shifter</a>, the YUI component build tool. Shifter will automatically wrap your module code in a `YUI.add()` call along with any configuration info required for the module. @example YUI.add('davglass', function (Y) { Y.davglass = function () { }; }, '3.4.0', { requires: ['harley-davidson', 'mt-dew'] }); @method add @param {String} name Module name. @param {Function} fn Function containing module code. This function will be executed whenever the module is attached to a specific YUI instance. @param {YUI} fn.Y The YUI instance to which this module is attached. @param {String} fn.name Name of the module @param {String} version Module version number. This is currently used only for informational purposes, and is not used internally by YUI. @param {Object} [config] Module config. @param {Array} [config.requires] Array of other module names that must be attached before this module can be attached. @param {Array} [config.optional] Array of optional module names that should be attached before this module is attached if they've already been loaded. If the `loadOptional` YUI option is `true`, optional modules that have not yet been loaded will be loaded just as if they were hard requirements. @param {Array} [config.use] Array of module names that are included within or otherwise provided by this module, and which should be attached automatically when this module is attached. This makes it possible to create "virtual rollup" modules that simply attach a collection of other modules or submodules. @return {YUI} This YUI instance. **/ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, //Instance hash so we don't apply it to the same instance twice applied = {}, loader, inst, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { inst = instances[i]; if (!applied[inst.id]) { applied[inst.id] = true; loader = inst.Env._loader; if (loader) { if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) { loader.addModule(details, name); } } } } } return this; }, /** Executes the callback function associated with each required module, attaching the module to this YUI instance. @method _attach @param {Array} r The array of modules to attach @param {Boolean} [moot=false] If `true`, don't throw a warning if the module is not attached. @private **/ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, cache = YUI.Env._renderedMods, loader = Y.Env._loader, done = Y.Env._attached, exported = Y.Env._exported, len = r.length, loader, def, go, c = [], modArgs, esCompat, reqlen, __exports__, __imports__; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { for (j in loader.conditions[name]) { if (loader.conditions[name].hasOwnProperty(j)) { def = loader.conditions[name][j]; go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } } } } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name] && !mod) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } /* If it's a temp module, we need to redo it's requirements if it's already loaded since it may have been loaded by another instance and it's dependencies might have been redefined inside the fetched file. */ if (loader && cache && cache[name] && cache[name].temp) { loader.getRequires(cache[name]); req = []; for (j in loader.moduleInfo[name].expanded_map) { if (loader.moduleInfo[name].expanded_map.hasOwnProperty(j)) { req.push(j); } } Y._attach(req); } details = mod.details; req = details.requires; esCompat = details.es; use = details.use; after = details.after; //Force Intl load if there is a language (Loader logic) @todo fix this shit if (details.lang) { req = req || []; req.unshift('intl'); } if (req) { reqlen = req.length; for (j = 0; j < reqlen; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { modArgs = [Y, name]; if (esCompat) { __imports__ = {}; __exports__ = {}; // passing `exports` and `imports` onto the module function modArgs.push(__imports__, __exports__); if (req) { reqlen = req.length; for (j = 0; j < reqlen; j++) { __imports__[req[j]] = exported.hasOwnProperty(req[j]) ? exported[req[j]] : Y; } } } if (Y.config.throwFail) { __exports__ = mod.fn.apply(mod, modArgs); } else { try { __exports__ = mod.fn.apply(mod, modArgs); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } if (esCompat) { // store the `exports` in case others `es` modules requires it exported[name] = __exports__; } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** Delays the `use` callback until another event has taken place such as `window.onload`, `domready`, `contentready`, or `available`. @private @method _delayCallback @param {Function} cb The original `use` callback. @param {String|Object} until Either an event name ('load', 'domready', etc.) or an object containing event/args keys for contentready/available. @return {Function} **/ _delayCallback: function(cb, until) { var Y = this, mod = ['event-base']; until = (Y.Lang.isObject(until) ? until : { event: until }); if (until.event === 'load') { mod.push('event-synthetic'); } return function() { var args = arguments; Y._use(mod, function() { Y.on(until.event, function() { args[1].delayUntil = until.event; cb.apply(Y, args); }, until.args); }); }; }, /** Attaches one or more modules to this YUI instance. When this is executed, the requirements of the desired modules are analyzed, and one of several things can happen: * All required modules have already been loaded, and just need to be attached to this YUI instance. In this case, the `use()` callback will be executed synchronously after the modules are attached. * One or more modules have not yet been loaded, or the Get utility is not available, or the `bootstrap` config option is `false`. In this case, a warning is issued indicating that modules are missing, but all available modules will still be attached and the `use()` callback will be executed synchronously. * One or more modules are missing and the Loader is not available but the Get utility is, and `bootstrap` is not `false`. In this case, the Get utility will be used to load the Loader, and we will then proceed to the following state: * One or more modules are missing and the Loader is available. In this case, the Loader will be used to resolve the dependency tree for the missing modules and load them and their dependencies. When the Loader is finished loading modules, the `use()` callback will be executed asynchronously. @example // Loads and attaches dd and its dependencies. YUI().use('dd', function (Y) { // ... }); // Loads and attaches dd and node as well as all of their dependencies. YUI().use(['dd', 'node'], function (Y) { // ... }); // Attaches all modules that have already been loaded. YUI().use('*', function (Y) { // ... }); // Attaches a gallery module. YUI().use('gallery-yql', function (Y) { // ... }); // Attaches a YUI 2in3 module. YUI().use('yui2-datatable', function (Y) { // ... }); @method use @param {String|Array} modules* One or more module names to attach. @param {Function} [callback] Callback function to be executed once all specified modules and their dependencies have been attached. @param {YUI} callback.Y The YUI instance created for this sandbox. @param {Object} callback.status Object containing `success`, `msg` and `data` properties. @chainable **/ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); if (Y.config.delayUntil) { callback = Y._delayCallback(callback, Y.config.delayUntil); } } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** Handles Loader notifications about attachment/load errors. @method _notify @param {Function} callback Callback to pass to `Y.config.loadErrorFn`. @param {Object} response Response returned from Loader. @param {Array} args Arguments passed from Loader. @private **/ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { if (this.Env._missed && this.Env._missed.length) { response.msg = 'Missing modules: ' + this.Env._missed.join(); response.success = false; } if (this.config.throwFail) { callback(this, response); } else { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } } }, /** Called from the `use` method queue to ensure that only one set of loading logic is performed at a time. @method _use @param {String} args* One or more modules to attach. @param {Function} [callback] Function to call once all required modules have been attached. @private **/ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], i, r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = [], name, len, m, req, use; if (!names.length) { return; } if (aliases) { len = names.length; for (i = 0; i < len; i++) { if (aliases[names[i]] && !mods[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } len = names.length; for (i = 0; i < len; i++) { name = names[i]; if (!skip) { r.push(name); } // only attach a module once if (used[name]) { continue; } m = mods[name]; req = null; use = null; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } } }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if ([].concat(missing).sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { args = []; for (i in mods) { if (mods.hasOwnProperty(i)) { args.push(i); } } ret = Y._attach(args); if (ret) { handleLoader(); } return Y; } if ((mods.loader || mods['loader-base']) && !Y.Loader) { Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]); } // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } process(args); len = missing.length; if (len) { missing = YArray.dedupe(missing); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(missing); loader.insert(null, (fetchCSS) ? null : 'js'); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Utility method for safely creating namespaces if they don't already exist. May be called statically on the YUI global object or as a method on a YUI instance. When called statically, a namespace will be created on the YUI global object: // Create `YUI.your.namespace.here` as nested objects, preserving any // objects that already exist instead of overwriting them. YUI.namespace('your.namespace.here'); When called as a method on a YUI instance, a namespace will be created on that instance: // Creates `Y.property.package`. Y.namespace('property.package'); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place and will not be overwritten. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", that token is discarded. This is legacy behavior for backwards compatibility with YUI 2. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace('really.long.nested.namespace'); Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function. @method namespace @param {String} namespace* One or more namespaces to create. @return {Object} Reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** Reports an error. The reporting mechanism is controlled by the `throwFail` configuration attribute. If `throwFail` is falsy, the message is logged. If `throwFail` is truthy, a JS exception is thrown. If an `errorFn` is specified in the config it must return `true` to indicate that the exception was handled and keep it from being thrown. @method error @param {String} msg Error message. @param {Error|String} [e] JavaScript error object or an error string. @param {String} [src] Source of the error (such as the name of the module in which the error occurred). @chainable **/ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (!ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** Generates an id string that is unique among all YUI instances in this execution context. @method guid @param {String} [pre] Prefix. @return {String} Unique id. **/ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** Returns a unique id associated with the given object and (if *readOnly* is falsy) stamps the object with that id so it can be identified in the future. Stamping an object involves adding a `_yuid` property to it that contains the object's id. One exception to this is that in Internet Explorer, DOM nodes have a `uniqueID` property that contains a browser-generated unique id, which will be used instead of a YUI-generated id when available. @method stamp @param {Object} o Object to stamp. @param {Boolean} readOnly If truthy and the given object has not already been stamped, the object will not be modified and `null` will be returned. @return {String} Object's unique id, or `null` if *readOnly* was truthy and the given object was not already stamped. **/ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** Destroys this YUI instance. @method destroy @since 3.3.0 **/ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** Safe `instanceof` wrapper that works around a memory leak in IE when the object being tested is `window` or `document`. Unless you are testing objects that may be `window` or `document`, you should use the native `instanceof` operator instead of this method. @method instanceOf @param {Object} o Object to check. @param {Object} type Class to check against. @since 3.3.0 **/ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } /** Applies a configuration to all YUI instances in this execution context. The main use case for this method is in "mashups" where several third-party scripts need to write to a global YUI config, but cannot share a single centrally-managed config object. This way they can all call `YUI.applyConfig({})` instead of overwriting the single global config. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function (Y) { // Module davglass will be available here. }); @method applyConfig @param {Object} o Configuration object to apply. @static @since 3.5.0 **/ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // set up the environment YUI._init(); if (hasWin) { add(doc, 'DOMContentLoaded', handleReady); // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleReady(); handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; /** * Set a method to be called when `Get.script` is called in Node.js * `Get` will open the file, then pass it's content and it's path * to this method before attaching it. Commonly used for code coverage * instrumentation. <strong>Calling this multiple times will only * attach the last hook method</strong>. This method is only * available in Node.js. * @method setLoadHook * @static * @param {Function} fn The function to set * @param {String} fn.data The content of the file * @param {String} fn.path The file path of the file */ YUI.setLoadHook = function(fn) { YUI._getLoadHook = fn; }; /** * Load hook for `Y.Get.script` in Node.js, see `YUI.setLoadHook` * @method _getLoadHook * @private * @param {String} data The content of the file * @param {String} path The file path of the file */ YUI._getLoadHook = null; } YUI.Env[VERSION] = {}; }()); /** Config object that contains all of the configuration options for this `YUI` instance. This object is supplied by the implementer when instantiating YUI. Some properties have default values if they are not supplied by the implementer. This object should not be updated directly because some values are cached. Use `applyConfig()` to update the config object on a YUI instance that has already been configured. @class config @static **/ /** If `true` (the default), YUI will "bootstrap" the YUI Loader and module metadata if they're needed to load additional dependencies and aren't already available. Setting this to `false` will prevent YUI from automatically loading the Loader and module metadata, so you will need to manually ensure that they're available or handle dependency resolution yourself. @property {Boolean} bootstrap @default true **/ /** @property {Object} aliases **/ /** A hash of module group definitions. For each group you can specify a list of modules and the base path and combo spec to use when dynamically loading the modules. @example groups: { yui2: { // specify whether or not this group has a combo service combine: true, // The comboSeperator to use with this group's combo handler comboSep: ';', // The maxURLLength for this server maxURLLength: 500, // the base path for non-combo paths base: 'http://yui.yahooapis.com/2.8.0r4/build/', // the path to the combo service comboBase: 'http://yui.yahooapis.com/combo?', // a fragment to prepend to the path attribute when // when building combo urls root: '2.8.0r4/build/', // the module definitions modules: { yui2_yde: { path: "yahoo-dom-event/yahoo-dom-event.js" }, yui2_anim: { path: "animation/animation.js", requires: ['yui2_yde'] } } } } @property {Object} groups **/ /** Path to the Loader JS file, relative to the `base` path. This is used to dynamically bootstrap the Loader when it's needed and isn't yet available. @property {String} loaderPath @default "loader/loader-min.js" **/ /** If `true`, YUI will attempt to load CSS dependencies and skins. Set this to `false` to prevent YUI from loading any CSS, or set it to the string `"force"` to force CSS dependencies to be loaded even if their associated JS modules are already loaded. @property {Boolean|String} fetchCSS @default true **/ /** Default gallery version used to build gallery module urls. @property {String} gallery @since 3.1.0 **/ /** Default YUI 2 version used to build YUI 2 module urls. This is used for intrinsic YUI 2 support via the 2in3 project. Also see the `2in3` config for pulling different revisions of the wrapped YUI 2 modules. @property {String} yui2 @default "2.9.0" @since 3.1.0 **/ /** Revision number of YUI 2in3 modules that should be used when loading YUI 2in3. @property {String} 2in3 @default "4" @since 3.1.0 **/ /** Alternate console log function that should be used in environments without a supported native console. This function is executed with the YUI instance as its `this` object. @property {Function} logFn @since 3.1.0 **/ /** The minimum log level to log messages for. Log levels are defined incrementally. Messages greater than or equal to the level specified will be shown. All others will be discarded. The order of log levels in increasing priority is: debug info warn error @property {String} logLevel @default 'debug' @since 3.10.0 **/ /** Callback to execute when `Y.error()` is called. It receives the error message and a JavaScript error object if one was provided. This function is executed with the YUI instance as its `this` object. Returning `true` from this function will prevent an exception from being thrown. @property {Function} errorFn @param {String} errorFn.msg Error message @param {Object} [errorFn.err] Error object (if one was provided). @since 3.2.0 **/ /** A callback to execute when Loader fails to load one or more resources. This could be because of a script load failure. It could also be because a module fails to register itself when the `requireRegistration` config is `true`. If this function is defined, the `use()` callback will only be called when the loader succeeds. Otherwise, `use()` will always executes unless there was a JavaScript error when attaching a module. @property {Function} loadErrorFn @since 3.3.0 **/ /** If `true`, Loader will expect all loaded scripts to be first-class YUI modules that register themselves with the YUI global, and will trigger a failure if a loaded script does not register a YUI module. @property {Boolean} requireRegistration @default false @since 3.3.0 **/ /** Cache serviced use() requests. @property {Boolean} cacheUse @default true @since 3.3.0 @deprecated No longer used. **/ /** Whether or not YUI should use native ES5 functionality when available for features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will always use its own fallback implementations instead of relying on ES5 functionality, even when ES5 functionality is available. @property {Boolean} useNativeES5 @default true @since 3.5.0 **/ /** * Leverage native JSON stringify if the browser has a native * implementation. In general, this is a good idea. See the Known Issues * section in the JSON user guide for caveats. The default value is true * for browsers with native JSON support. * * @property useNativeJSONStringify * @type Boolean * @default true * @since 3.8.0 */ /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeJSONParse * @type Boolean * @default true * @since 3.8.0 */ /** Delay the `use` callback until a specific event has passed (`load`, `domready`, `contentready` or `available`) @property {Object|String} delayUntil @since 3.6.0 @example You can use `load` or `domready` strings by default: YUI({ delayUntil: 'domready' }, function (Y) { // This will not execute until 'domeready' occurs. }); Or you can delay until a node is available (with `available` or `contentready`): YUI({ delayUntil: { event: 'available', args : '#foo' } }, function (Y) { // This will not execute until a node matching the selector "#foo" is // available in the DOM. }); **/ YUI.add('yui-base', function (Y, NAME) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, WHITESPACE = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF", WHITESPACE_CLASS = "[\x09-\x0D\x20\xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]+", TRIM_LEFT_REGEX = new RegExp("^" + WHITESPACE_CLASS), TRIM_RIGHT_REGEX = new RegExp(WHITESPACE_CLASS + "$"), TRIMREGEX = new RegExp(TRIM_LEFT_REGEX.source + "|" + TRIM_RIGHT_REGEX.source, "g"), NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided value is a regexp. * @method isRegExp * @static * @param value The value or object to test. * @return {boolean} true if value is a regexp. */ L.isRegExp = function(value) { return L.type(value) === 'regexp'; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * Performs `{placeholder}` substitution on a string. The object passed as the * second parameter provides values to replace the `{placeholder}`s. * `{placeholder}` token names must match property names of the object. For example, * *`var greeting = Y.Lang.sub("Hello, {who}!", { who: "World" });` * * `{placeholder}` tokens that are undefined on the object map will be left * in tact (leaving unsightly `{placeholder}`'s in the output string). * * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = L._isNative(STRING_PROTO.trim) && !WHITESPACE.trim() ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = L._isNative(STRING_PROTO.trimLeft) && !WHITESPACE.trimLeft() ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(TRIM_LEFT_REGEX, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = L._isNative(STRING_PROTO.trimRight) && !WHITESPACE.trimRight() ? function (s) { return s.trimRight(); } : function (s) { return s.replace(TRIM_RIGHT_REGEX, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @method type @param o the item to test. @return {string} the detected type. @static **/ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; /*jshint expr: true*/ startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with arrays consisting entirely of strings or entirely of numbers, whereas `unique` may be used with other value types (but is slower). Using `dedupe()` with values other than strings or numbers, or with arrays containing a mix of strings and numbers, may result in unexpected behavior. @method dedupe @param {String[]|Number[]} array Array of strings or numbers to dedupe. @return {Array} Copy of _array_ containing no duplicate values. @static @since 3.4.0 **/ YArray.dedupe = Lang._isNative(Object.create) ? function (array) { var hash = Object.create(null), results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hash[item]) { hash[item] = 1; results.push(item); } } return results; } : function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or scrollTo/document (window. From DOM.isWindow test which we can't use here), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !(obj.scrollTo && obj.document) && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { /*jshint expr: true*/ cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); /*jshint eqeqeq: false*/ if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var i = 0, len = arguments.length, result = {}, key, obj; for (; i < len; ++i) { obj = arguments[i]; for (key in obj) { if (hasOwn.call(obj, key)) { result[key] = obj[key]; } } } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = Lang._isNative(Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type Boolean * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50 and Android 2.3.x. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available and non-buggy. The Opera 11.50 and Android 2.3.x versions of * `Object.keys()` have an inconsistency as they consider `prototype` to be * enumerable, so a non-native shim is used to rectify the difference. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = Lang._isNative(Object.keys) && !hasProtoEnumBug ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { for (key in obj) { if (owns(obj, key)) { keys.push(key); } } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(Object(obj)).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ === 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * PhantomJS version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property phantomjs * @type float */ phantomjs: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type Boolean * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0, /** * Window8/IE10 Application host environment * @property winjs * @type Boolean * @static */ winjs: !!((typeof Windows !== "undefined") && Windows.System), /** * Are touch/msPointer events available on this device * @property touchEnabled * @type Boolean * @static */ touchEnabled: false }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; if (/PhantomJS/.test(ua)) { m = ua.match(/PhantomJS\/([^\s]*)/); if (m && m[1]) { o.phantomjs = numberify(m[1]); } } // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.os = 'ios'; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)\)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/OPR\/(\d+\.\d+)/); if (m && m[1]) { // Opera 15+ with Blink (pretends to be both Chrome and Safari) o.opera = numberify(m[1]); } else { m = ua.match(/(Chrome|CrMo|CriOS)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) if (/Opera/.test(ua)) { m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE ([^;]*)|Trident.*; rv:([0-9.]+)/); if (m && (m[1] || m[2])) { o.ie = numberify(m[1] || m[2]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); if (/Mobile|Tablet/.test(ua)) { o.mobile = "ffos"; } } } } } } } //Check for known properties to tell if touch events are enabled on this device or if //the number of MSPointer touchpoints on this device is greater than 0. if (win && nav && !(o.chrome && o.chrome < 6)) { o.touchEnabled = (("ontouchstart" in win) || (("msMaxTouchPoints" in nav) && (nav.msMaxTouchPoints > 0))); } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process === 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = numberify(process.versions.node); } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); /** Performs a simple comparison between two version numbers, accounting for standard versioning logic such as the fact that "535.8" is a lower version than "535.24", even though a simple numerical comparison would indicate that it's greater. Also accounts for cases such as "1.1" vs. "1.1.0", which are considered equivalent. Returns -1 if version _a_ is lower than version _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. Versions may be numbers or strings containing numbers and dots. For example, both `535` and `"535.8.10"` are acceptable. A version string containing non-numeric characters, like `"535.8.beta"`, may produce unexpected results. @method compareVersions @param {Number|String} a First version number to compare. @param {Number|String} b Second version number to compare. @return -1 if _a_ is lower than _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. **/ Y.UA.compareVersions = function (a, b) { var aPart, aParts, bPart, bParts, i, len; if (a === b) { return 0; } aParts = (a + '').split('.'); bParts = (b + '').split('.'); for (i = 0, len = Math.max(aParts.length, bParts.length); i < len; ++i) { aPart = parseInt(aParts[i], 10); bPart = parseInt(bParts[i], 10); /*jshint expr: true*/ isNaN(aPart) && (aPart = 0); isNaN(bPart) && (bPart = 0); if (aPart < bPart) { return -1; } if (aPart > bPart) { return 1; } } return 0; }; YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "anim-shape-transform": ["anim-shape"], "app": ["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","model-sync-local","router","view","view-node-map"], "attribute": ["attribute-base","attribute-complex"], "attribute-events": ["attribute-observable"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "axes": ["axis-numeric","axis-category","axis-time","axis-stacked"], "axes-base": ["axis-numeric-base","axis-category-base","axis-time-base","axis-stacked-base"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "charts": ["charts-base"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "color": ["color-base","color-hsl","color-harmony"], "controller": ["router"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatype": ["datatype-date","datatype-number","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format","datatype-date-math"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange","event-tap"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "template": ["template-base","template-micro"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"] }; }, '@VERSION@', { "use": [ "yui-base", "get", "features", "intl-base", "yui-log", "yui-later", "loader-base", "loader-rollup", "loader-yui3" ] }); YUI.add('get', function (Y, NAME) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { } else { } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { } else { } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { } else { } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes // IE10 doesn't return true for the MDN feature test, so setting it explicitly, // because it is async by default, and allows you to disable async by setting it to false async: (doc && doc.createElement('script').async === true) || (ua.ie >= 10), // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+ cssFail: ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ( (!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0 ) && !(ua.chrome && ua.chrome <= 18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera || (ua.ie && ua.ie >= 10)) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; options._onFinish = Get._onTransactionFinish; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _onTransactionFinish : function() { Get._pending = null; Get._next(); }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(item.callback); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._reqsWaiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. @since 3.5.0 @property {Object[]} errors @property {String} errors.error Error message. @property {Object} errors.request Request object related to the error. **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._reqsWaiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } self._reqsWaiting = requests.length; for (i = 0, len = requests.length; i < len; ++i) { req = requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } if (options._onFinish) { options._onFinish(); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && (ua.ie < 9 || (document.documentMode && document.documentMode < 9))) { // Script on IE < 9, and IE 9+ when in IE 8 or older modes, including quirks mode. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. if (ua.ie >= 10) { // We currently need to introduce a timeout for IE10, since it // calls onerror/onload synchronously for 304s - messing up existing // program flow. // Remove this block if the following bug gets fixed by GA /*jshint maxlen: 1500 */ // https://connect.microsoft.com/IE/feedback/details/763871/dynamically-loaded-scripts-with-304s-responses-interrupt-the-currently-executing-js-thread-onload node.onerror = function() { setTimeout(onError, 0); }; node.onload = function() { setTimeout(onLoad, 0); }; } else { node.onerror = onError; node.onload = onLoad; } // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._reqsWaiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._reqsWaiting -= 1; this._next(); } }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('intl-base', function (Y, NAME) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 2, warn: 4, error: 8 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", "debug". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, minlevel, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } // Determine the current minlevel as defined in configuration Y.config.logLevel = Y.config.logLevel || 'debug'; minlevel = LEVELS[Y.config.logLevel.toLowerCase()]; if (cat in LEVELS && LEVELS[cat] < minlevel) { // Skip this message if the we don't meet the defined minlevel bail = 1; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", "debug". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-later', function (Y, NAME) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {Number} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('loader-base', function (Y, NAME) { /** * The YUI loader core * @module loader * @submodule loader-base */ (function() { var VERSION = Y.version, BUILD = '/build/', ROOT = VERSION + '/', CDN_BASE = Y.Env.base, GALLERY_VERSION = 'gallery-2013.12.12-21-06', TNT = '2in3', TNT_VERSION = '4', YUI2_VERSION = '2.9.0', COMBO_BASE = CDN_BASE + 'combo?', META = { version: VERSION, root: ROOT, base: Y.Env.base, comboBase: COMBO_BASE, skin: { defaultSkin: 'sam', base: 'assets/skins/', path: 'skin.css', after: [ 'cssreset', 'cssfonts', 'cssgrids', 'cssbase', 'cssreset-context', 'cssfonts-context' ] }, groups: {}, patterns: {} }, groups = META.groups, yui2Update = function(tnt, yui2, config) { var root = TNT + '.' + (tnt || TNT_VERSION) + '/' + (yui2 || YUI2_VERSION) + BUILD, base = (config && config.base) ? config.base : CDN_BASE, combo = (config && config.comboBase) ? config.comboBase : COMBO_BASE; groups.yui2.base = base + root; groups.yui2.root = root; groups.yui2.comboBase = combo; }, galleryUpdate = function(tag, config) { var root = (tag || GALLERY_VERSION) + BUILD, base = (config && config.base) ? config.base : CDN_BASE, combo = (config && config.comboBase) ? config.comboBase : COMBO_BASE; groups.gallery.base = base + root; groups.gallery.root = root; groups.gallery.comboBase = combo; }; groups[VERSION] = {}; groups.gallery = { ext: false, combine: true, comboBase: COMBO_BASE, update: galleryUpdate, patterns: { 'gallery-': {}, 'lang/gallery-': {}, 'gallerycss-': { type: 'css' } } }; groups.yui2 = { combine: true, ext: false, comboBase: COMBO_BASE, update: yui2Update, patterns: { 'yui2-': { configFn: function(me) { if (/-skin|reset|fonts|grids|base/.test(me.name)) { me.type = 'css'; me.path = me.path.replace(/\.js/, '.css'); // this makes skins in builds earlier than // 2.6.0 work as long as combine is false me.path = me.path.replace(/\/yui2-skin/, '/assets/skins/sam/yui2-skin'); } } } } }; galleryUpdate(); yui2Update(); if (YUI.Env[VERSION]) { Y.mix(META, YUI.Env[VERSION], false, [ 'modules', 'groups', 'skin' ], 0, true); } YUI.Env[VERSION] = META; }()); /*jslint forin: true, maxlen: 350 */ /** * Loader dynamically loads script and css files. It includes the dependency * information for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It can also load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * @module loader * @main loader * @submodule loader-base */ var NOT_FOUND = {}, NO_REQUIREMENTS = [], MAX_URL_LENGTH = 1024, GLOBAL_ENV = YUI.Env, GLOBAL_LOADED = GLOBAL_ENV._loaded, CSS = 'css', JS = 'js', INTL = 'intl', DEFAULT_SKIN = 'sam', VERSION = Y.version, ROOT_LANG = '', YObject = Y.Object, oeach = YObject.each, yArray = Y.Array, _queue = GLOBAL_ENV._loaderQueue, META = GLOBAL_ENV[VERSION], SKIN_PREFIX = 'skin-', L = Y.Lang, ON_PAGE = GLOBAL_ENV.mods, modulekey, _path = function(dir, file, type, nomin) { var path = dir + '/' + file; if (!nomin) { path += '-min'; } path += '.' + (type || CSS); return path; }; if (!YUI.Env._cssLoaded) { YUI.Env._cssLoaded = {}; } /** * The component metadata is stored in Y.Env.meta. * Part of the loader module. * @property meta * @for YUI */ Y.Env.meta = META; /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. You can also specify an external, custom combo service to host * your modules as well. var Y = YUI(); var loader = new Y.Loader({ filter: 'debug', base: '../../', root: 'build/', combine: true, require: ['node', 'dd', 'console'] }); var out = loader.resolve(true); * @constructor * @class Loader * @param {Object} config an optional set of configuration options. * @param {String} config.base The base dir which to fetch this module from * @param {String} config.comboBase The Combo service base path. Ex: `http://yui.yahooapis.com/combo?` * @param {String} config.root The root path to prepend to module names for the combo service. Ex: `2.5.2/build/` * @param {String|Object} config.filter A filter to apply to result urls. <a href="#property_filter">See filter property</a> * @param {Object} config.filters Per-component filter specification. If specified for a given component, this overrides the filter config. * @param {Boolean} config.combine Use a combo service to reduce the number of http connections required to load your dependencies * @param {Boolean} [config.async=true] Fetch files in async * @param {Array} config.ignore: A list of modules that should never be dynamically loaded * @param {Array} config.force A list of modules that should always be loaded when required, even if already present on the page * @param {HTMLElement|String} config.insertBefore Node or id for a node that should be used as the insertion point for new nodes * @param {Object} config.jsAttributes Object literal containing attributes to add to script nodes * @param {Object} config.cssAttributes Object literal containing attributes to add to link nodes * @param {Number} config.timeout The number of milliseconds before a timeout occurs when dynamically loading nodes. If not set, there is no timeout * @param {Object} config.context Execution context for all callbacks * @param {Function} config.onSuccess Callback for the 'success' event * @param {Function} config.onFailure Callback for the 'failure' event * @param {Function} config.onCSS Callback for the 'CSSComplete' event. When loading YUI components with CSS the CSS is loaded first, then the script. This provides a moment you can tie into to improve the presentation of the page while the script is loading. * @param {Function} config.onTimeout Callback for the 'timeout' event * @param {Function} config.onProgress Callback executed each time a script or css file is loaded * @param {Object} config.modules A list of module definitions. See <a href="#method_addModule">Loader.addModule</a> for the supported module metadata * @param {Object} config.groups A list of group definitions. Each group can contain specific definitions for `base`, `comboBase`, `combine`, and accepts a list of `modules`. * @param {String} config.2in3 The version of the YUI 2 in 3 wrapper to use. The intrinsic support for YUI 2 modules in YUI 3 relies on versions of the YUI 2 components inside YUI 3 module wrappers. These wrappers change over time to accomodate the issues that arise from running YUI 2 in a YUI 3 sandbox. * @param {String} config.yui2 When using the 2in3 project, you can select the version of YUI 2 to use. Valid values are `2.2.2`, `2.3.1`, `2.4.1`, `2.5.2`, `2.6.0`, `2.7.0`, `2.8.0`, `2.8.1` and `2.9.0` [default] -- plus all versions of YUI 2 going forward. */ Y.Loader = function(o) { var self = this; //Catch no config passed. o = o || {}; modulekey = META.md5; /** * Internal callback to handle multiple internal insert() calls * so that css is inserted prior to js * @property _internalCallback * @private */ // self._internalCallback = null; /** * Callback that will be executed when the loader is finished * with an insert * @method onSuccess * @type function */ // self.onSuccess = null; /** * Callback that will be executed if there is a failure * @method onFailure * @type function */ // self.onFailure = null; /** * Callback for the 'CSSComplete' event. When loading YUI components * with CSS the CSS is loaded first, then the script. This provides * a moment you can tie into to improve the presentation of the page * while the script is loading. * @method onCSS * @type function */ // self.onCSS = null; /** * Callback executed each time a script or css file is loaded * @method onProgress * @type function */ // self.onProgress = null; /** * Callback that will be executed if a timeout occurs * @method onTimeout * @type function */ // self.onTimeout = null; /** * The execution context for all callbacks * @property context * @default {YUI} the YUI instance */ self.context = Y; /** * Data that is passed to all callbacks * @property data */ // self.data = null; /** * Node reference or id where new nodes should be inserted before * @property insertBefore * @type string|HTMLElement */ // self.insertBefore = null; /** * The charset attribute for inserted nodes * @property charset * @type string * @deprecated , use cssAttributes or jsAttributes. */ // self.charset = null; /** * An object literal containing attributes to add to link nodes * @property cssAttributes * @type object */ // self.cssAttributes = null; /** * An object literal containing attributes to add to script nodes * @property jsAttributes * @type object */ // self.jsAttributes = null; /** * The base directory. * @property base * @type string * @default http://yui.yahooapis.com/[YUI VERSION]/build/ */ self.base = Y.Env.meta.base + Y.Env.meta.root; /** * Base path for the combo service * @property comboBase * @type string * @default http://yui.yahooapis.com/combo? */ self.comboBase = Y.Env.meta.comboBase; /* * Base path for language packs. */ // self.langBase = Y.Env.meta.langBase; // self.lang = ""; /** * If configured, the loader will attempt to use the combo * service for YUI resources and configured external resources. * @property combine * @type boolean * @default true if a base dir isn't in the config */ self.combine = o.base && (o.base.indexOf(self.comboBase.substr(0, 20)) > -1); /** * The default seperator to use between files in a combo URL * @property comboSep * @type {String} * @default Ampersand */ self.comboSep = '&'; /** * Max url length for combo urls. The default is 1024. This is the URL * limit for the Yahoo! hosted combo servers. If consuming * a different combo service that has a different URL limit * it is possible to override this default by supplying * the maxURLLength config option. The config option will * only take effect if lower than the default. * * @property maxURLLength * @type int */ self.maxURLLength = MAX_URL_LENGTH; /** * Ignore modules registered on the YUI global * @property ignoreRegistered * @default false */ self.ignoreRegistered = o.ignoreRegistered; /** * Root path to prepend to module path for the combo * service * @property root * @type string * @default [YUI VERSION]/build/ */ self.root = Y.Env.meta.root; /** * Timeout value in milliseconds. If set, self value will be used by * the get utility. the timeout event will fire if * a timeout occurs. * @property timeout * @type int */ self.timeout = 0; /** * A list of modules that should not be loaded, even if * they turn up in the dependency tree * @property ignore * @type string[] */ // self.ignore = null; /** * A list of modules that should always be loaded, even * if they have already been inserted into the page. * @property force * @type string[] */ // self.force = null; self.forceMap = {}; /** * Should we allow rollups * @property allowRollup * @type boolean * @default false */ self.allowRollup = false; /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js). * </dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * * myFilter: { * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * } * * @property filter * @type string| {searchExp: string, replaceStr: string} */ // self.filter = null; /** * per-component filter specification. If specified for a given * component, this overrides the filter config. * @property filters * @type object */ self.filters = {}; /** * The list of requested modules * @property required * @type {string: boolean} */ self.required = {}; /** * If a module name is predefined when requested, it is checked againsts * the patterns provided in this property. If there is a match, the * module is added with the default configuration. * * At the moment only supporting module prefixes, but anticipate * supporting at least regular expressions. * @property patterns * @type Object */ // self.patterns = Y.merge(Y.Env.meta.patterns); self.patterns = {}; /** * The library metadata * @property moduleInfo */ // self.moduleInfo = Y.merge(Y.Env.meta.moduleInfo); self.moduleInfo = {}; self.groups = Y.merge(Y.Env.meta.groups); /** * Provides the information used to skin the skinnable components. * The following skin definition would result in 'skin1' and 'skin2' * being loaded for calendar (if calendar was requested), and * 'sam' for all other skinnable components: * * skin: { * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. ex: * // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/ * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * calendar: ['skin1', 'skin2'] * } * } * @property skin * @type {Object} */ self.skin = Y.merge(Y.Env.meta.skin); /* * Map of conditional modules * @since 3.2.0 */ self.conditions = {}; // map of modules with a hash of modules that meet the requirement // self.provides = {}; self.config = o; self._internal = true; self._populateCache(); /** * Set when beginning to compute the dependency tree. * Composed of what YUI reports to be loaded combined * with what has been loaded by any instance on the page * with the version number specified in the metadata. * @property loaded * @type {string: boolean} */ self.loaded = GLOBAL_LOADED[VERSION]; /** * Should Loader fetch scripts in `async`, defaults to `true` * @property async */ self.async = true; self._inspectPage(); self._internal = false; self._config(o); self.forceMap = (self.force) ? Y.Array.hash(self.force) : {}; self.testresults = null; if (Y.config.tests) { self.testresults = Y.config.tests; } /** * List of rollup files found in the library metadata * @property rollups */ // self.rollups = null; /** * Whether or not to load optional dependencies for * the requested modules * @property loadOptional * @type boolean * @default false */ // self.loadOptional = false; /** * All of the derived dependencies in sorted order, which * will be populated when either calculate() or insert() * is called * @property sorted * @type string[] */ self.sorted = []; /* * A list of modules to attach to the YUI instance when complete. * If not supplied, the sorted list of dependencies are applied. * @property attaching */ // self.attaching = null; /** * Flag to indicate the dependency tree needs to be recomputed * if insert is called again. * @property dirty * @type boolean * @default true */ self.dirty = true; /** * List of modules inserted by the utility * @property inserted * @type {string: boolean} */ self.inserted = {}; /** * List of skipped modules during insert() because the module * was not defined * @property skipped */ self.skipped = {}; // Y.on('yui:load', self.loadNext, self); self.tested = {}; /* * Cached sorted calculate results * @property results * @since 3.2.0 */ //self.results = {}; if (self.ignoreRegistered) { //Clear inpage already processed modules. self._resetModules(); } }; Y.Loader.prototype = { /** * Checks the cache for modules and conditions, if they do not exist * process the default metadata and populate the local moduleInfo hash. * @method _populateCache * @private */ _populateCache: function() { var self = this, defaults = META.modules, cache = GLOBAL_ENV._renderedMods, i; if (cache && !self.ignoreRegistered) { for (i in cache) { if (cache.hasOwnProperty(i)) { self.moduleInfo[i] = Y.merge(cache[i]); } } cache = GLOBAL_ENV._conditions; for (i in cache) { if (cache.hasOwnProperty(i)) { self.conditions[i] = Y.merge(cache[i]); } } } else { for (i in defaults) { if (defaults.hasOwnProperty(i)) { self.addModule(defaults[i], i); } } } }, /** * Reset modules in the module cache to a pre-processed state so additional * computations with a different skin or language will work as expected. * @method _resetModules * @private */ _resetModules: function() { var self = this, i, o, mod, name, details; for (i in self.moduleInfo) { if (self.moduleInfo.hasOwnProperty(i)) { mod = self.moduleInfo[i]; name = mod.name; details = (YUI.Env.mods[name] ? YUI.Env.mods[name].details : null); if (details) { self.moduleInfo[name]._reset = true; self.moduleInfo[name].requires = details.requires || []; self.moduleInfo[name].optional = details.optional || []; self.moduleInfo[name].supersedes = details.supercedes || []; } if (mod.defaults) { for (o in mod.defaults) { if (mod.defaults.hasOwnProperty(o)) { if (mod[o]) { mod[o] = mod.defaults[o]; } } } } delete mod.langCache; delete mod.skinCache; if (mod.skinnable) { self._addSkin(self.skin.defaultSkin, mod.name); } } } }, /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** * Default filters for raw and debug * @property FILTER_DEFS * @type Object * @final * @protected */ FILTER_DEFS: { RAW: { 'searchExp': '-min\\.js', 'replaceStr': '.js' }, DEBUG: { 'searchExp': '-min\\.js', 'replaceStr': '-debug.js' }, COVERAGE: { 'searchExp': '-min\\.js', 'replaceStr': '-coverage.js' } }, /* * Check the pages meta-data and cache the result. * @method _inspectPage * @private */ _inspectPage: function() { var self = this, v, m, req, mr, i; //Inspect the page for CSS only modules and mark them as loaded. for (i in self.moduleInfo) { if (self.moduleInfo.hasOwnProperty(i)) { v = self.moduleInfo[i]; if (v.type && v.type === CSS) { if (self.isCSSLoaded(v.name)) { self.loaded[i] = true; } } } } for (i in ON_PAGE) { if (ON_PAGE.hasOwnProperty(i)) { v = ON_PAGE[i]; if (v.details) { m = self.moduleInfo[v.name]; req = v.details.requires; mr = m && m.requires; if (m) { if (!m._inspected && req && mr.length !== req.length) { // console.log('deleting ' + m.name); delete m.expanded; } } else { m = self.addModule(v.details, i); } m._inspected = true; } } } }, /* * returns true if b is not loaded, and is required directly or by means of modules it supersedes. * @private * @method _requires * @param {String} mod1 The first module to compare * @param {String} mod2 The second module to compare */ _requires: function(mod1, mod2) { var i, rm, after_map, s, info = this.moduleInfo, m = info[mod1], other = info[mod2]; if (!m || !other) { return false; } rm = m.expanded_map; after_map = m.after_map; // check if this module should be sorted after the other // do this first to short circut circular deps if (after_map && (mod2 in after_map)) { return true; } after_map = other.after_map; // and vis-versa if (after_map && (mod1 in after_map)) { return false; } // check if this module requires one the other supersedes s = info[mod2] && info[mod2].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod1, s[i])) { return true; } } } s = info[mod1] && info[mod1].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod2, s[i])) { return false; } } } // check if this module requires the other directly // if (r && yArray.indexOf(r, mod2) > -1) { if (rm && (mod2 in rm)) { return true; } // external css files should be sorted below yui css if (m.ext && m.type === CSS && !other.ext && other.type === CSS) { return true; } return false; }, /** * Apply a new config to the Loader instance * @method _config * @private * @param {Object} o The new configuration */ _config: function(o) { var i, j, val, a, f, group, groupName, self = this, mods = [], mod; // apply config values if (o) { for (i in o) { if (o.hasOwnProperty(i)) { val = o[i]; //TODO This should be a case if (i === 'require') { self.require(val); } else if (i === 'skin') { //If the config.skin is a string, format to the expected object if (typeof val === 'string') { self.skin.defaultSkin = o.skin; val = { defaultSkin: val }; } Y.mix(self.skin, val, true); } else if (i === 'groups') { for (j in val) { if (val.hasOwnProperty(j)) { groupName = j; group = val[j]; self.addGroup(group, groupName); if (group.aliases) { for (a in group.aliases) { if (group.aliases.hasOwnProperty(a)) { self.addAlias(group.aliases[a], a); } } } } } } else if (i === 'modules') { // add a hash of module definitions for (j in val) { if (val.hasOwnProperty(j)) { self.addModule(val[j], j); } } } else if (i === 'aliases') { for (j in val) { if (val.hasOwnProperty(j)) { self.addAlias(val[j], j); } } } else if (i === 'gallery') { if (this.groups.gallery.update) { this.groups.gallery.update(val, o); } } else if (i === 'yui2' || i === '2in3') { if (this.groups.yui2.update) { this.groups.yui2.update(o['2in3'], o.yui2, o); } } else { self[i] = val; } } } } // fix filter f = self.filter; if (L.isString(f)) { f = f.toUpperCase(); self.filterName = f; self.filter = self.FILTER_DEFS[f]; if (f === 'DEBUG') { self.require('yui-log', 'dump'); } } if (self.filterName && self.coverage) { if (self.filterName === 'COVERAGE' && L.isArray(self.coverage) && self.coverage.length) { for (i = 0; i < self.coverage.length; i++) { mod = self.coverage[i]; if (self.moduleInfo[mod] && self.moduleInfo[mod].use) { mods = [].concat(mods, self.moduleInfo[mod].use); } else { mods.push(mod); } } self.filters = self.filters || {}; Y.Array.each(mods, function(mod) { self.filters[mod] = self.FILTER_DEFS.COVERAGE; }); self.filterName = 'RAW'; self.filter = self.FILTER_DEFS[self.filterName]; } } }, /** * Returns the skin module name for the specified skin name. If a * module name is supplied, the returned skin module name is * specific to the module passed in. * @method formatSkin * @param {string} skin the name of the skin. * @param {string} mod optional: the name of a module to skin. * @return {string} the full skin module name. */ formatSkin: function(skin, mod) { var s = SKIN_PREFIX + skin; if (mod) { s = s + '-' + mod; } return s; }, /** * Adds the skin def to the module info * @method _addSkin * @param {string} skin the name of the skin. * @param {string} mod the name of the module. * @param {string} parent parent module if this is a skin of a * submodule or plugin. * @return {string} the module name for the skin. * @private */ _addSkin: function(skin, mod, parent) { var mdef, pkg, name, nmod, info = this.moduleInfo, sinf = this.skin, ext = info[mod] && info[mod].ext; // Add a module definition for the module-specific skin css if (mod) { name = this.formatSkin(skin, mod); if (!info[name]) { mdef = info[mod]; pkg = mdef.pkg || mod; nmod = { skin: true, name: name, group: mdef.group, type: 'css', after: sinf.after, path: (parent || pkg) + '/' + sinf.base + skin + '/' + mod + '.css', ext: ext }; if (mdef.base) { nmod.base = mdef.base; } if (mdef.configFn) { nmod.configFn = mdef.configFn; } this.addModule(nmod, name); } } return name; }, /** * Adds an alias module to the system * @method addAlias * @param {Array} use An array of modules that makes up this alias * @param {String} name The name of the alias * @example * var loader = new Y.Loader({}); * loader.addAlias([ 'node', 'yql' ], 'davglass'); * loader.require(['davglass']); * var out = loader.resolve(true); * * //out.js will contain Node and YQL modules */ addAlias: function(use, name) { YUI.Env.aliases[name] = use; this.addModule({ name: name, use: use }); }, /** * Add a new module group * @method addGroup * @param {Object} config An object containing the group configuration data * @param {String} config.name required, the group name * @param {String} config.base The base directory for this module group * @param {String} config.root The root path to add to each combo resource path * @param {Boolean} config.combine Should the request be combined * @param {String} config.comboBase Combo service base path * @param {Object} config.modules The group of modules * @param {String} name the group name. * @example * var loader = new Y.Loader({}); * loader.addGroup({ * name: 'davglass', * combine: true, * comboBase: '/combo?', * root: '', * modules: { * //Module List here * } * }, 'davglass'); */ addGroup: function(o, name) { var mods = o.modules, self = this, i, v; name = name || o.name; o.name = name; self.groups[name] = o; if (o.patterns) { for (i in o.patterns) { if (o.patterns.hasOwnProperty(i)) { o.patterns[i].group = name; self.patterns[i] = o.patterns[i]; } } } if (mods) { for (i in mods) { if (mods.hasOwnProperty(i)) { v = mods[i]; if (typeof v === 'string') { v = { name: i, fullpath: v }; } v.group = name; self.addModule(v, i); } } } }, /** * Add a new module to the component metadata. * @method addModule * @param {Object} config An object containing the module data. * @param {String} config.name Required, the component name * @param {String} config.type Required, the component type (js or css) * @param {String} config.path Required, the path to the script from `base` * @param {Array} config.requires Array of modules required by this component * @param {Array} [config.optional] Array of optional modules for this component * @param {Array} [config.supersedes] Array of the modules this component replaces * @param {Array} [config.after] Array of modules the components which, if present, should be sorted above this one * @param {Object} [config.after_map] Faster alternative to 'after' -- supply a hash instead of an array * @param {Number} [config.rollup] The number of superseded modules required for automatic rollup * @param {String} [config.fullpath] If `fullpath` is specified, this is used instead of the configured `base + path` * @param {Boolean} [config.skinnable] Flag to determine if skin assets should automatically be pulled in * @param {Object} [config.submodules] Hash of submodules * @param {String} [config.group] The group the module belongs to -- this is set automatically when it is added as part of a group configuration. * @param {Array} [config.lang] Array of BCP 47 language tags of languages for which this module has localized resource bundles, e.g., `["en-GB", "zh-Hans-CN"]` * @param {Object} [config.condition] Specifies that the module should be loaded automatically if a condition is met. This is an object with up to four fields: * @param {String} [config.condition.trigger] The name of a module that can trigger the auto-load * @param {Function} [config.condition.test] A function that returns true when the module is to be loaded. * @param {String} [config.condition.ua] The UA name of <a href="UA.html">Y.UA</a> object that returns true when the module is to be loaded. e.g., `"ie"`, `"nodejs"`. * @param {String} [config.condition.when] Specifies the load order of the conditional module * with regard to the position of the trigger module. * This should be one of three values: `before`, `after`, or `instead`. The default is `after`. * @param {Object} [config.testresults] A hash of test results from `Y.Features.all()` * @param {Function} [config.configFn] A function to exectute when configuring this module * @param {Object} config.configFn.mod The module config, modifying this object will modify it's config. Returning false will delete the module's config. * @param {String} [name] The module name, required if not in the module data. * @return {Object} the module definition or null if the object passed in did not provide all required attributes. */ addModule: function(o, name) { name = name || o.name; if (typeof o === 'string') { o = { name: name, fullpath: o }; } var subs, i, l, t, sup, s, smod, plugins, plug, j, langs, packName, supName, flatSup, flatLang, lang, ret, overrides, skinname, when, g, p, conditions = this.conditions, trigger; //Only merge this data if the temp flag is set //from an earlier pass from a pattern or else //an override module (YUI_config) can not be used to //replace a default module. if (this.moduleInfo[name] && this.moduleInfo[name].temp) { //This catches temp modules loaded via a pattern // The module will be added twice, once from the pattern and // Once from the actual add call, this ensures that properties // that were added to the module the first time around (group: gallery) // are also added the second time around too. o = Y.merge(this.moduleInfo[name], o); } o.name = name; if (!o || !o.name) { return null; } if (!o.type) { //Always assume it's javascript unless the CSS pattern is matched. o.type = JS; p = o.path || o.fullpath; if (p && this.REGEX_CSS.test(p)) { o.type = CSS; } } if (!o.path && !o.fullpath) { o.path = _path(name, name, o.type); } o.supersedes = o.supersedes || o.use; o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true; // Handle submodule logic subs = o.submodules; this.moduleInfo[name] = o; o.requires = o.requires || []; /* Only allowing the cascade of requires information, since optional and supersedes are far more fine grained than a blanket requires is. */ if (this.requires) { for (i = 0; i < this.requires.length; i++) { o.requires.push(this.requires[i]); } } if (o.group && this.groups && this.groups[o.group]) { g = this.groups[o.group]; if (g.requires) { for (i = 0; i < g.requires.length; i++) { o.requires.push(g.requires[i]); } } } if (!o.defaults) { o.defaults = { requires: o.requires ? [].concat(o.requires) : null, supersedes: o.supersedes ? [].concat(o.supersedes) : null, optional: o.optional ? [].concat(o.optional) : null }; } if (o.skinnable && o.ext && o.temp) { skinname = this._addSkin(this.skin.defaultSkin, name); o.requires.unshift(skinname); } if (o.requires.length) { o.requires = this.filterRequires(o.requires) || []; } if (!o.langPack && o.lang) { langs = yArray(o.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } } } if (subs) { sup = o.supersedes || []; l = 0; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; s.path = s.path || _path(name, i, o.type); s.pkg = name; s.group = o.group; if (s.supersedes) { sup = sup.concat(s.supersedes); } smod = this.addModule(s, i); sup.push(i); if (smod.skinnable) { o.skinnable = true; overrides = this.skin.overrides; if (overrides && overrides[i]) { for (j = 0; j < overrides[i].length; j++) { skinname = this._addSkin(overrides[i][j], i, name); sup.push(skinname); } } skinname = this._addSkin(this.skin.defaultSkin, i, name); sup.push(skinname); } // looks like we are expected to work out the metadata // for the parent module language packs from what is // specified in the child modules. if (s.lang && s.lang.length) { langs = yArray(s.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); supName = this.getLangPackName(lang, i); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } flatSup = flatSup || yArray.hash(smod.supersedes); if (!(supName in flatSup)) { smod.supersedes.push(supName); } o.lang = o.lang || []; flatLang = flatLang || yArray.hash(o.lang); if (!(lang in flatLang)) { o.lang.push(lang); } // Add rollup file, need to add to supersedes list too // default packages packName = this.getLangPackName(ROOT_LANG, name); supName = this.getLangPackName(ROOT_LANG, i); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } if (!(supName in flatSup)) { smod.supersedes.push(supName); } // Add rollup file, need to add to supersedes list too } } l++; } } //o.supersedes = YObject.keys(yArray.hash(sup)); o.supersedes = yArray.dedupe(sup); if (this.allowRollup) { o.rollup = (l < 4) ? l : Math.min(l - 1, 4); } } plugins = o.plugins; if (plugins) { for (i in plugins) { if (plugins.hasOwnProperty(i)) { plug = plugins[i]; plug.pkg = name; plug.path = plug.path || _path(name, i, o.type); plug.requires = plug.requires || []; plug.group = o.group; this.addModule(plug, i); if (o.skinnable) { this._addSkin(this.skin.defaultSkin, i, name); } } } } if (o.condition) { t = o.condition.trigger; if (YUI.Env.aliases[t]) { t = YUI.Env.aliases[t]; } if (!Y.Lang.isArray(t)) { t = [t]; } for (i = 0; i < t.length; i++) { trigger = t[i]; when = o.condition.when; conditions[trigger] = conditions[trigger] || {}; conditions[trigger][name] = o.condition; // the 'when' attribute can be 'before', 'after', or 'instead' // the default is after. if (when && when !== 'after') { if (when === 'instead') { // replace the trigger o.supersedes = o.supersedes || []; o.supersedes.push(trigger); } // before the trigger // the trigger requires the conditional mod, // so it should appear before the conditional // mod if we do not intersede. } else { // after the trigger o.after = o.after || []; o.after.push(trigger); } } } if (o.supersedes) { o.supersedes = this.filterRequires(o.supersedes); } if (o.after) { o.after = this.filterRequires(o.after); o.after_map = yArray.hash(o.after); } // this.dirty = true; if (o.configFn) { ret = o.configFn(o); if (ret === false) { delete this.moduleInfo[name]; delete GLOBAL_ENV._renderedMods[name]; o = null; } } //Add to global cache if (o) { if (!GLOBAL_ENV._renderedMods) { GLOBAL_ENV._renderedMods = {}; } GLOBAL_ENV._renderedMods[name] = Y.mix(GLOBAL_ENV._renderedMods[name] || {}, o); GLOBAL_ENV._conditions = conditions; } return o; }, /** * Add a requirement for one or more module * @method require * @param {string[] | string*} what the modules to load. */ require: function(what) { var a = (typeof what === 'string') ? yArray(arguments) : what; this.dirty = true; this.required = Y.merge(this.required, yArray.hash(this.filterRequires(a))); this._explodeRollups(); }, /** * Grab all the items that were asked for, check to see if the Loader * meta-data contains a "use" array. If it doesm remove the asked item and replace it with * the content of the "use". * This will make asking for: "dd" * Actually ask for: "dd-ddm-base,dd-ddm,dd-ddm-drop,dd-drag,dd-proxy,dd-constrain,dd-drop,dd-scroll,dd-drop-plugin" * @private * @method _explodeRollups */ _explodeRollups: function() { var self = this, m, m2, i, a, v, len, len2, r = self.required; if (!self.allowRollup) { for (i in r) { if (r.hasOwnProperty(i)) { m = self.getModule(i); if (m && m.use) { len = m.use.length; for (a = 0; a < len; a++) { m2 = self.getModule(m.use[a]); if (m2 && m2.use) { len2 = m2.use.length; for (v = 0; v < len2; v++) { r[m2.use[v]] = true; } } else { r[m.use[a]] = true; } } } } } self.required = r; } }, /** * Explodes the required array to remove aliases and replace them with real modules * @method filterRequires * @param {Array} r The original requires array * @return {Array} The new array of exploded requirements */ filterRequires: function(r) { if (r) { if (!Y.Lang.isArray(r)) { r = [r]; } r = Y.Array(r); var c = [], i, mod, o, m; for (i = 0; i < r.length; i++) { mod = this.getModule(r[i]); if (mod && mod.use) { for (o = 0; o < mod.use.length; o++) { //Must walk the other modules in case a module is a rollup of rollups (datatype) m = this.getModule(mod.use[o]); if (m && m.use && (m.name !== mod.name)) { c = Y.Array.dedupe([].concat(c, this.filterRequires(m.use))); } else { c.push(mod.use[o]); } } } else { c.push(r[i]); } } r = c; } return r; }, /** * Returns an object containing properties for all modules required * in order to load the requested module * @method getRequires * @param {object} mod The module definition from moduleInfo. * @return {array} the expanded requirement list. */ getRequires: function(mod) { if (!mod) { //console.log('returning no reqs for ' + mod.name); return NO_REQUIREMENTS; } if (mod._parsed) { //console.log('returning requires for ' + mod.name, mod.requires); return mod.expanded || NO_REQUIREMENTS; } //TODO add modue cache here out of scope.. var i, m, j, add, packName, lang, testresults = this.testresults, name = mod.name, cond, adddef = ON_PAGE[name] && ON_PAGE[name].details, d, go, def, r, old_mod, o, skinmod, skindef, skinpar, skinname, intl = mod.lang || mod.intl, info = this.moduleInfo, ftests = Y.Features && Y.Features.tests.load, hash, reparse; // console.log(name); // pattern match leaves module stub that needs to be filled out if (mod.temp && adddef) { old_mod = mod; mod = this.addModule(adddef, name); mod.group = old_mod.group; mod.pkg = old_mod.pkg; delete mod.expanded; } // console.log('cache: ' + mod.langCache + ' == ' + this.lang); //If a skin or a lang is different, reparse.. reparse = !((!this.lang || mod.langCache === this.lang) && (mod.skinCache === this.skin.defaultSkin)); if (mod.expanded && !reparse) { return mod.expanded; } d = []; hash = {}; r = this.filterRequires(mod.requires); if (mod.lang) { //If a module has a lang attribute, auto add the intl requirement. d.unshift('intl'); r.unshift('intl'); intl = true; } o = this.filterRequires(mod.optional); mod._parsed = true; mod.langCache = this.lang; mod.skinCache = this.skin.defaultSkin; for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { d.push(r[i]); hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } // get the requirements from superseded modules, if any r = this.filterRequires(mod.supersedes); if (r) { for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { // if this module has submodules, the requirements list is // expanded to include the submodules. This is so we can // prevent dups when a submodule is already loaded and the // parent is requested. if (mod.submodules) { d.push(r[i]); } hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } if (o && this.loadOptional) { for (i = 0; i < o.length; i++) { if (!hash[o[i]]) { d.push(o[i]); hash[o[i]] = true; m = info[o[i]]; if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } cond = this.conditions[name]; if (cond) { //Set the module to not parsed since we have conditionals and this could change the dependency tree. mod._parsed = false; if (testresults && ftests) { oeach(testresults, function(result, id) { var condmod = ftests[id].name; if (!hash[condmod] && ftests[id].trigger === name) { if (result && ftests[id]) { hash[condmod] = true; d.push(condmod); } } }); } else { for (i in cond) { if (cond.hasOwnProperty(i)) { if (!hash[i]) { def = cond[i]; //first see if they've specfied a ua check //then see if they've got a test fn & if it returns true //otherwise just having a condition block is enough go = def && ((!def.ua && !def.test) || (def.ua && Y.UA[def.ua]) || (def.test && def.test(Y, r))); if (go) { hash[i] = true; d.push(i); m = this.getModule(i); if (m) { add = this.getRequires(m); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } } } } // Create skin modules if (mod.skinnable) { skindef = this.skin.overrides; for (i in YUI.Env.aliases) { if (YUI.Env.aliases.hasOwnProperty(i)) { if (Y.Array.indexOf(YUI.Env.aliases[i], name) > -1) { skinpar = i; } } } if (skindef && (skindef[name] || (skinpar && skindef[skinpar]))) { skinname = name; if (skindef[skinpar]) { skinname = skinpar; } for (i = 0; i < skindef[skinname].length; i++) { skinmod = this._addSkin(skindef[skinname][i], name); if (!this.isCSSLoaded(skinmod, this._boot)) { d.push(skinmod); } } } else { skinmod = this._addSkin(this.skin.defaultSkin, name); if (!this.isCSSLoaded(skinmod, this._boot)) { d.push(skinmod); } } } mod._parsed = false; if (intl) { if (mod.lang && !mod.langPack && Y.Intl) { lang = Y.Intl.lookupBestLang(this.lang || ROOT_LANG, mod.lang); packName = this.getLangPackName(lang, name); if (packName) { d.unshift(packName); } } d.unshift(INTL); } mod.expanded_map = yArray.hash(d); mod.expanded = YObject.keys(mod.expanded_map); return mod.expanded; }, /** * Check to see if named css module is already loaded on the page * @method isCSSLoaded * @param {String} name The name of the css file * @return Boolean */ isCSSLoaded: function(name, skip) { //TODO - Make this call a batching call with name being an array if (!name || !YUI.Env.cssStampEl || (!skip && this.ignoreRegistered)) { return false; } var el = YUI.Env.cssStampEl, ret = false, mod = YUI.Env._cssLoaded[name], style = el.currentStyle; //IE if (mod !== undefined) { return mod; } //Add the classname to the element el.className = name; if (!style) { style = Y.config.doc.defaultView.getComputedStyle(el, null); } if (style && style.display === 'none') { ret = true; } el.className = ''; //Reset the classname to '' YUI.Env._cssLoaded[name] = ret; return ret; }, /** * Returns a hash of module names the supplied module satisfies. * @method getProvides * @param {string} name The name of the module. * @return {object} what this module provides. */ getProvides: function(name) { var m = this.getModule(name), o, s; // supmap = this.provides; if (!m) { return NOT_FOUND; } if (m && !m.provides) { o = {}; s = m.supersedes; if (s) { yArray.each(s, function(v) { Y.mix(o, this.getProvides(v)); }, this); } o[name] = true; m.provides = o; } return m.provides; }, /** * Calculates the dependency tree, the result is stored in the sorted * property. * @method calculate * @param {object} o optional options object. * @param {string} type optional argument to prune modules. */ calculate: function(o, type) { if (o || type || this.dirty) { if (o) { this._config(o); } if (!this._init) { this._setup(); } this._explode(); if (this.allowRollup) { this._rollup(); } else { this._explodeRollups(); } this._reduce(); this._sort(); } }, /** * Creates a "psuedo" package for languages provided in the lang array * @method _addLangPack * @private * @param {String} lang The language to create * @param {Object} m The module definition to create the language pack around * @param {String} packName The name of the package (e.g: lang/datatype-date-en-US) * @return {Object} The module definition */ _addLangPack: function(lang, m, packName) { var name = m.name, packPath, conf, existing = this.moduleInfo[packName]; if (!existing) { packPath = _path((m.pkg || name), packName, JS, true); conf = { path: packPath, intl: true, langPack: true, ext: m.ext, group: m.group, supersedes: [] }; if (m.root) { conf.root = m.root; } if (m.base) { conf.base = m.base; } if (m.configFn) { conf.configFn = m.configFn; } this.addModule(conf, packName); if (lang) { Y.Env.lang = Y.Env.lang || {}; Y.Env.lang[lang] = Y.Env.lang[lang] || {}; Y.Env.lang[lang][name] = true; } } return this.moduleInfo[packName]; }, /** * Investigates the current YUI configuration on the page. By default, * modules already detected will not be loaded again unless a force * option is encountered. Called by calculate() * @method _setup * @private */ _setup: function() { var info = this.moduleInfo, name, i, j, m, l, packName; for (name in info) { if (info.hasOwnProperty(name)) { m = info[name]; if (m) { // remove dups //m.requires = YObject.keys(yArray.hash(m.requires)); m.requires = yArray.dedupe(m.requires); // Create lang pack modules //if (m.lang && m.lang.length) { if (m.lang) { // Setup root package if the module has lang defined, // it needs to provide a root language pack packName = this.getLangPackName(ROOT_LANG, name); this._addLangPack(null, m, packName); } } } } //l = Y.merge(this.inserted); l = {}; // available modules if (!this.ignoreRegistered) { Y.mix(l, GLOBAL_ENV.mods); } // add the ignore list to the list of loaded packages if (this.ignore) { Y.mix(l, yArray.hash(this.ignore)); } // expand the list to include superseded modules for (j in l) { if (l.hasOwnProperty(j)) { Y.mix(l, this.getProvides(j)); } } // remove modules on the force list from the loaded list if (this.force) { for (i = 0; i < this.force.length; i++) { if (this.force[i] in l) { delete l[this.force[i]]; } } } Y.mix(this.loaded, l); this._init = true; }, /** * Builds a module name for a language pack * @method getLangPackName * @param {string} lang the language code. * @param {string} mname the module to build it for. * @return {string} the language pack module name. */ getLangPackName: function(lang, mname) { return ('lang/' + mname + ((lang) ? '_' + lang : '')); }, /** * Inspects the required modules list looking for additional * dependencies. Expands the required list to include all * required modules. Called by calculate() * @method _explode * @private */ _explode: function() { //TODO Move done out of scope var r = this.required, m, reqs, done = {}, self = this, name, expound; // the setup phase is over, all modules have been created self.dirty = false; self._explodeRollups(); r = self.required; for (name in r) { if (r.hasOwnProperty(name)) { if (!done[name]) { done[name] = true; m = self.getModule(name); if (m) { expound = m.expound; if (expound) { r[expound] = self.getModule(expound); reqs = self.getRequires(r[expound]); Y.mix(r, yArray.hash(reqs)); } reqs = self.getRequires(m); Y.mix(r, yArray.hash(reqs)); } } } } }, /** * The default method used to test a module against a pattern * @method _patternTest * @private * @param {String} mname The module being tested * @param {String} pname The pattern to match */ _patternTest: function(mname, pname) { return (mname.indexOf(pname) > -1); }, /** * Get's the loader meta data for the requested module * @method getModule * @param {String} mname The module name to get * @return {Object} The module metadata */ getModule: function(mname) { //TODO: Remove name check - it's a quick hack to fix pattern WIP if (!mname) { return null; } var p, found, pname, m = this.moduleInfo[mname], patterns = this.patterns; // check the patterns library to see if we should automatically add // the module with defaults if (!m || (m && m.ext)) { for (pname in patterns) { if (patterns.hasOwnProperty(pname)) { p = patterns[pname]; //There is no test method, create a default one that tests // the pattern against the mod name if (!p.test) { p.test = this._patternTest; } if (p.test(mname, pname)) { // use the metadata supplied for the pattern // as the module definition. found = p; break; } } } } if (!m) { if (found) { if (p.action) { p.action.call(this, mname, pname); } else { // ext true or false? m = this.addModule(Y.merge(found), mname); if (found.configFn) { m.configFn = found.configFn; } m.temp = true; } } } else { if (found && m && found.configFn && !m.configFn) { m.configFn = found.configFn; m.configFn(m); } } return m; }, // impl in rollup submodule _rollup: function() { }, /** * Remove superceded modules and loaded modules. Called by * calculate() after we have the mega list of all dependencies * @method _reduce * @return {object} the reduced dependency hash. * @private */ _reduce: function(r) { r = r || this.required; var i, j, s, m, type = this.loadType, ignore = this.ignore ? yArray.hash(this.ignore) : false; for (i in r) { if (r.hasOwnProperty(i)) { m = this.getModule(i); // remove if already loaded if (((this.loaded[i] || ON_PAGE[i]) && !this.forceMap[i] && !this.ignoreRegistered) || (type && m && m.type !== type)) { delete r[i]; } if (ignore && ignore[i]) { delete r[i]; } // remove anything this module supersedes s = m && m.supersedes; if (s) { for (j = 0; j < s.length; j++) { if (s[j] in r) { delete r[s[j]]; } } } } } return r; }, /** * Handles the queue when a module has been loaded for all cases * @method _finish * @private * @param {String} msg The message from Loader * @param {Boolean} success A boolean denoting success or failure */ _finish: function(msg, success) { _queue.running = false; var onEnd = this.onEnd; if (onEnd) { onEnd.call(this.context, { msg: msg, data: this.data, success: success }); } this._continue(); }, /** * The default Loader onSuccess handler, calls this.onSuccess with a payload * @method _onSuccess * @private */ _onSuccess: function() { var self = this, skipped = Y.merge(self.skipped), fn, failed = [], rreg = self.requireRegistration, success, msg, i, mod; for (i in skipped) { if (skipped.hasOwnProperty(i)) { delete self.inserted[i]; } } self.skipped = {}; for (i in self.inserted) { if (self.inserted.hasOwnProperty(i)) { mod = self.getModule(i); if (mod && rreg && mod.type === JS && !(i in YUI.Env.mods)) { failed.push(i); } else { Y.mix(self.loaded, self.getProvides(i)); } } } fn = self.onSuccess; msg = (failed.length) ? 'notregistered' : 'success'; success = !(failed.length); if (fn) { fn.call(self.context, { msg: msg, data: self.data, success: success, failed: failed, skipped: skipped }); } self._finish(msg, success); }, /** * The default Loader onProgress handler, calls this.onProgress with a payload * @method _onProgress * @private */ _onProgress: function(e) { var self = this, i; //set the internal cache to what just came in. if (e.data && e.data.length) { for (i = 0; i < e.data.length; i++) { e.data[i] = self.getModule(e.data[i].name); } } if (self.onProgress) { self.onProgress.call(self.context, { name: e.url, data: e.data }); } }, /** * The default Loader onFailure handler, calls this.onFailure with a payload * @method _onFailure * @private */ _onFailure: function(o) { var f = this.onFailure, msg = [], i = 0, len = o.errors.length; for (i; i < len; i++) { msg.push(o.errors[i].error); } msg = msg.join(','); if (f) { f.call(this.context, { msg: msg, data: this.data, success: false }); } this._finish(msg, false); }, /** * The default Loader onTimeout handler, calls this.onTimeout with a payload * @method _onTimeout * @param {Get.Transaction} transaction The Transaction object from `Y.Get` * @private */ _onTimeout: function(transaction) { var f = this.onTimeout; if (f) { f.call(this.context, { msg: 'timeout', data: this.data, success: false, transaction: transaction }); } }, /** * Sorts the dependency tree. The last step of calculate() * @method _sort * @private */ _sort: function() { // create an indexed list var s = YObject.keys(this.required), // loaded = this.loaded, //TODO Move this out of scope done = {}, p = 0, l, a, b, j, k, moved, doneKey; // keep going until we make a pass without moving anything for (;;) { l = s.length; moved = false; // start the loop after items that are already sorted for (j = p; j < l; j++) { // check the next module on the list to see if its // dependencies have been met a = s[j]; // check everything below current item and move if we // find a requirement for the current item for (k = j + 1; k < l; k++) { doneKey = a + s[k]; if (!done[doneKey] && this._requires(a, s[k])) { // extract the dependency so we can move it up b = s.splice(k, 1); // insert the dependency above the item that // requires it s.splice(j, 0, b[0]); // only swap two dependencies once to short circut // circular dependencies done[doneKey] = true; // keep working moved = true; break; } } // jump out of loop if we moved something if (moved) { break; // this item is sorted, move our pointer and keep going } else { p++; } } // when we make it here and moved is false, we are // finished sorting if (!moved) { break; } } this.sorted = s; }, /** * Handles the actual insertion of script/link tags * @method _insert * @private * @param {Object} source The YUI instance the request came from * @param {Object} o The metadata to include * @param {String} type JS or CSS * @param {Boolean} [skipcalc=false] Do a Loader.calculate on the meta */ _insert: function(source, o, type, skipcalc) { // restore the state at the time of the request if (source) { this._config(source); } // build the dependency list // don't include type so we can process CSS and script in // one pass when the type is not specified. var modules = this.resolve(!skipcalc), self = this, comp = 0, actions = 0, mods = {}, deps, complete; self._refetch = []; if (type) { //Filter out the opposite type and reset the array so the checks later work modules[((type === JS) ? CSS : JS)] = []; } if (!self.fetchCSS) { modules.css = []; } if (modules.js.length) { comp++; } if (modules.css.length) { comp++; } //console.log('Resolved Modules: ', modules); complete = function(d) { actions++; var errs = {}, i = 0, o = 0, u = '', fn, modName, resMods; if (d && d.errors) { for (i = 0; i < d.errors.length; i++) { if (d.errors[i].request) { u = d.errors[i].request.url; } else { u = d.errors[i]; } errs[u] = u; } } if (d && d.data && d.data.length && (d.type === 'success')) { for (i = 0; i < d.data.length; i++) { self.inserted[d.data[i].name] = true; //If the external module has a skin or a lang, reprocess it if (d.data[i].lang || d.data[i].skinnable) { delete self.inserted[d.data[i].name]; self._refetch.push(d.data[i].name); } } } if (actions === comp) { self._loading = null; if (self._refetch.length) { //Get the deps for the new meta-data and reprocess for (i = 0; i < self._refetch.length; i++) { deps = self.getRequires(self.getModule(self._refetch[i])); for (o = 0; o < deps.length; o++) { if (!self.inserted[deps[o]]) { //We wouldn't be to this point without the module being here mods[deps[o]] = deps[o]; } } } mods = Y.Object.keys(mods); if (mods.length) { self.require(mods); resMods = self.resolve(true); if (resMods.cssMods.length) { for (i=0; i < resMods.cssMods.length; i++) { modName = resMods.cssMods[i].name; delete YUI.Env._cssLoaded[modName]; if (self.isCSSLoaded(modName)) { self.inserted[modName] = true; delete self.required[modName]; } } self.sorted = []; self._sort(); } d = null; //bail self._insert(); //insert the new deps } } if (d && d.fn) { fn = d.fn; delete d.fn; fn.call(self, d); } } }; this._loading = true; if (!modules.js.length && !modules.css.length) { actions = -1; complete({ fn: self._onSuccess }); return; } if (modules.css.length) { //Load CSS first Y.Get.css(modules.css, { data: modules.cssMods, attributes: self.cssAttributes, insertBefore: self.insertBefore, charset: self.charset, timeout: self.timeout, context: self, onProgress: function(e) { self._onProgress.call(self, e); }, onTimeout: function(d) { self._onTimeout.call(self, d); }, onSuccess: function(d) { d.type = 'success'; d.fn = self._onSuccess; complete.call(self, d); }, onFailure: function(d) { d.type = 'failure'; d.fn = self._onFailure; complete.call(self, d); } }); } if (modules.js.length) { Y.Get.js(modules.js, { data: modules.jsMods, insertBefore: self.insertBefore, attributes: self.jsAttributes, charset: self.charset, timeout: self.timeout, autopurge: false, context: self, async: self.async, onProgress: function(e) { self._onProgress.call(self, e); }, onTimeout: function(d) { self._onTimeout.call(self, d); }, onSuccess: function(d) { d.type = 'success'; d.fn = self._onSuccess; complete.call(self, d); }, onFailure: function(d) { d.type = 'failure'; d.fn = self._onFailure; complete.call(self, d); } }); } }, /** * Once a loader operation is completely finished, process any additional queued items. * @method _continue * @private */ _continue: function() { if (!(_queue.running) && _queue.size() > 0) { _queue.running = true; _queue.next()(); } }, /** * inserts the requested modules and their dependencies. * <code>type</code> can be "js" or "css". Both script and * css are inserted if type is not provided. * @method insert * @param {object} o optional options object. * @param {string} type the type of dependency to insert. */ insert: function(o, type, skipsort) { var self = this, copy = Y.merge(this); delete copy.require; delete copy.dirty; _queue.add(function() { self._insert(copy, o, type, skipsort); }); this._continue(); }, /** * Executed every time a module is loaded, and if we are in a load * cycle, we attempt to load the next script. Public so that it * is possible to call this if using a method other than * Y.register to determine when scripts are fully loaded * @method loadNext * @deprecated * @param {string} mname optional the name of the module that has * been loaded (which is usually why it is time to load the next * one). */ loadNext: function() { return; }, /** * Apply filter defined for this instance to a url/path * @method _filter * @param {string} u the string to filter. * @param {string} name the name of the module, if we are processing * a single module as opposed to a combined url. * @return {string} the filtered string. * @private */ _filter: function(u, name, group) { var f = this.filter, hasFilter = name && (name in this.filters), modFilter = hasFilter && this.filters[name], groupName = group || (this.moduleInfo[name] ? this.moduleInfo[name].group : null); if (groupName && this.groups[groupName] && this.groups[groupName].filter) { modFilter = this.groups[groupName].filter; hasFilter = true; } if (u) { if (hasFilter) { f = (L.isString(modFilter)) ? this.FILTER_DEFS[modFilter.toUpperCase()] || null : modFilter; } if (f) { u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr); } } return u; }, /** * Generates the full url for a module * @method _url * @param {string} path the path fragment. * @param {String} name The name of the module * @param {String} [base=self.base] The base url to use * @return {string} the full url. * @private */ _url: function(path, name, base) { return this._filter((base || this.base || '') + path, name); }, /** * Returns an Object hash of file arrays built from `loader.sorted` or from an arbitrary list of sorted modules. * @method resolve * @param {Boolean} [calc=false] Perform a loader.calculate() before anything else * @param {Array} [s=loader.sorted] An override for the loader.sorted array * @return {Object} Object hash (js and css) of two arrays of file lists * @example This method can be used as an off-line dep calculator * * var Y = YUI(); * var loader = new Y.Loader({ * filter: 'debug', * base: '../../', * root: 'build/', * combine: true, * require: ['node', 'dd', 'console'] * }); * var out = loader.resolve(true); * */ resolve: function(calc, s) { var len, i, m, url, group, groupName, j, frag, comboSource, comboSources, mods, comboBase, base, urls, u = [], tmpBase, baseLen, resCombos = {}, self = this, comboSep, maxURLLength, inserted = (self.ignoreRegistered) ? {} : self.inserted, resolved = { js: [], jsMods: [], css: [], cssMods: [] }, type = self.loadType || 'js', addSingle; if (self.skin.overrides || self.skin.defaultSkin !== DEFAULT_SKIN || self.ignoreRegistered) { self._resetModules(); } if (calc) { self.calculate(); } s = s || self.sorted; addSingle = function(m) { if (m) { group = (m.group && self.groups[m.group]) || NOT_FOUND; //Always assume it's async if (group.async === false) { m.async = group.async; } url = (m.fullpath) ? self._filter(m.fullpath, s[i]) : self._url(m.path, s[i], group.base || m.base); if (m.attributes || m.async === false) { url = { url: url, async: m.async }; if (m.attributes) { url.attributes = m.attributes; } } resolved[m.type].push(url); resolved[m.type + 'Mods'].push(m); } else { } }; len = s.length; // the default combo base comboBase = self.comboBase; url = comboBase; comboSources = {}; for (i = 0; i < len; i++) { comboSource = comboBase; m = self.getModule(s[i]); groupName = m && m.group; group = self.groups[groupName]; if (groupName && group) { if (!group.combine || m.fullpath) { //This is not a combo module, skip it and load it singly later. addSingle(m); continue; } m.combine = true; if (group.comboBase) { comboSource = group.comboBase; } if ("root" in group && L.isValue(group.root)) { m.root = group.root; } m.comboSep = group.comboSep || self.comboSep; m.maxURLLength = group.maxURLLength || self.maxURLLength; } else { if (!self.combine) { //This is not a combo module, skip it and load it singly later. addSingle(m); continue; } } comboSources[comboSource] = comboSources[comboSource] || []; comboSources[comboSource].push(m); } for (j in comboSources) { if (comboSources.hasOwnProperty(j)) { resCombos[j] = resCombos[j] || { js: [], jsMods: [], css: [], cssMods: [] }; url = j; mods = comboSources[j]; len = mods.length; if (len) { for (i = 0; i < len; i++) { if (inserted[mods[i]]) { continue; } m = mods[i]; // Do not try to combine non-yui JS unless combo def // is found if (m && (m.combine || !m.ext)) { resCombos[j].comboSep = m.comboSep; resCombos[j].group = m.group; resCombos[j].maxURLLength = m.maxURLLength; frag = ((L.isValue(m.root)) ? m.root : self.root) + (m.path || m.fullpath); frag = self._filter(frag, m.name); resCombos[j][m.type].push(frag); resCombos[j][m.type + 'Mods'].push(m); } else { //Add them to the next process.. if (mods[i]) { addSingle(mods[i]); } } } } } } for (j in resCombos) { if (resCombos.hasOwnProperty(j)) { base = j; comboSep = resCombos[base].comboSep || self.comboSep; maxURLLength = resCombos[base].maxURLLength || self.maxURLLength; for (type in resCombos[base]) { if (type === JS || type === CSS) { urls = resCombos[base][type]; mods = resCombos[base][type + 'Mods']; len = urls.length; tmpBase = base + urls.join(comboSep); baseLen = tmpBase.length; if (maxURLLength <= base.length) { maxURLLength = MAX_URL_LENGTH; } if (len) { if (baseLen > maxURLLength) { u = []; for (s = 0; s < len; s++) { u.push(urls[s]); tmpBase = base + u.join(comboSep); if (tmpBase.length > maxURLLength) { m = u.pop(); tmpBase = base + u.join(comboSep); resolved[type].push(self._filter(tmpBase, null, resCombos[base].group)); u = []; if (m) { u.push(m); } } } if (u.length) { tmpBase = base + u.join(comboSep); resolved[type].push(self._filter(tmpBase, null, resCombos[base].group)); } } else { resolved[type].push(self._filter(tmpBase, null, resCombos[base].group)); } } resolved[type + 'Mods'] = resolved[type + 'Mods'].concat(mods); } } } } resCombos = null; return resolved; }, /** Shortcut to calculate, resolve and load all modules. var loader = new Y.Loader({ ignoreRegistered: true, modules: { mod: { path: 'mod.js' } }, requires: [ 'mod' ] }); loader.load(function() { console.log('All modules have loaded..'); }); @method load @param {Callback} cb Executed after all load operations are complete */ load: function(cb) { if (!cb) { return; } var self = this, out = self.resolve(true); self.data = out; self.onEnd = function() { cb.apply(self.context || self, arguments); }; self.insert(); } }; }, '@VERSION@', {"requires": ["get", "features"]}); YUI.add('loader-rollup', function (Y, NAME) { /** * Optional automatic rollup logic for reducing http connections * when not using a combo service. * @module loader * @submodule rollup */ /** * Look for rollup packages to determine if all of the modules a * rollup supersedes are required. If so, include the rollup to * help reduce the total number of connections required. Called * by calculate(). This is an optional feature, and requires the * appropriate submodule to function. * @method _rollup * @for Loader * @private */ Y.Loader.prototype._rollup = function() { var i, j, m, s, r = this.required, roll, info = this.moduleInfo, rolled, c, smod; // find and cache rollup modules if (this.dirty || !this.rollups) { this.rollups = {}; for (i in info) { if (info.hasOwnProperty(i)) { m = this.getModule(i); // if (m && m.rollup && m.supersedes) { if (m && m.rollup) { this.rollups[i] = m; } } } } // make as many passes as needed to pick up rollup rollups for (;;) { rolled = false; // go through the rollup candidates for (i in this.rollups) { if (this.rollups.hasOwnProperty(i)) { // there can be only one, unless forced if (!r[i] && ((!this.loaded[i]) || this.forceMap[i])) { m = this.getModule(i); s = m.supersedes || []; roll = false; // @TODO remove continue if (!m.rollup) { continue; } c = 0; // check the threshold for (j = 0; j < s.length; j++) { smod = info[s[j]]; // if the superseded module is loaded, we can't // load the rollup unless it has been forced. if (this.loaded[s[j]] && !this.forceMap[s[j]]) { roll = false; break; // increment the counter if this module is required. // if we are beyond the rollup threshold, we will // use the rollup module } else if (r[s[j]] && m.type === smod.type) { c++; roll = (c >= m.rollup); if (roll) { break; } } } if (roll) { // add the rollup r[i] = true; rolled = true; // expand the rollup's dependencies this.getRequires(m); } } } } // if we made it here w/o rolling up something, we are done if (!rolled) { break; } } }; }, '@VERSION@', {"requires": ["loader-base"]}); YUI.add('loader-yui3', function (Y, NAME) { /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ /** * YUI 3 module metadata * @module loader * @submodule loader-yui3 */ YUI.Env[Y.version].modules = YUI.Env[Y.version].modules || {}; Y.mix(YUI.Env[Y.version].modules, { "align-plugin": { "requires": [ "node-screen", "node-pluginhost" ] }, "anim": { "use": [ "anim-base", "anim-color", "anim-curve", "anim-easing", "anim-node-plugin", "anim-scroll", "anim-xy" ] }, "anim-base": { "requires": [ "base-base", "node-style" ] }, "anim-color": { "requires": [ "anim-base" ] }, "anim-curve": { "requires": [ "anim-xy" ] }, "anim-easing": { "requires": [ "anim-base" ] }, "anim-node-plugin": { "requires": [ "node-pluginhost", "anim-base" ] }, "anim-scroll": { "requires": [ "anim-base" ] }, "anim-shape": { "requires": [ "anim-base", "anim-easing", "anim-color", "matrix" ] }, "anim-shape-transform": { "use": [ "anim-shape" ] }, "anim-xy": { "requires": [ "anim-base", "node-screen" ] }, "app": { "use": [ "app-base", "app-content", "app-transitions", "lazy-model-list", "model", "model-list", "model-sync-rest", "model-sync-local", "router", "view", "view-node-map" ] }, "app-base": { "requires": [ "classnamemanager", "pjax-base", "router", "view" ] }, "app-content": { "requires": [ "app-base", "pjax-content" ] }, "app-transitions": { "requires": [ "app-base" ] }, "app-transitions-css": { "type": "css" }, "app-transitions-native": { "condition": { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }, "requires": [ "app-transitions", "app-transitions-css", "parallel", "transition" ] }, "array-extras": { "requires": [ "yui-base" ] }, "array-invoke": { "requires": [ "yui-base" ] }, "arraylist": { "requires": [ "yui-base" ] }, "arraylist-add": { "requires": [ "arraylist" ] }, "arraylist-filter": { "requires": [ "arraylist" ] }, "arraysort": { "requires": [ "yui-base" ] }, "async-queue": { "requires": [ "event-custom" ] }, "attribute": { "use": [ "attribute-base", "attribute-complex" ] }, "attribute-base": { "requires": [ "attribute-core", "attribute-observable", "attribute-extras" ] }, "attribute-complex": { "requires": [ "attribute-base" ] }, "attribute-core": { "requires": [ "oop" ] }, "attribute-events": { "use": [ "attribute-observable" ] }, "attribute-extras": { "requires": [ "oop" ] }, "attribute-observable": { "requires": [ "event-custom" ] }, "autocomplete": { "use": [ "autocomplete-base", "autocomplete-sources", "autocomplete-list", "autocomplete-plugin" ] }, "autocomplete-base": { "optional": [ "autocomplete-sources" ], "requires": [ "array-extras", "base-build", "escape", "event-valuechange", "node-base" ] }, "autocomplete-filters": { "requires": [ "array-extras", "text-wordbreak" ] }, "autocomplete-filters-accentfold": { "requires": [ "array-extras", "text-accentfold", "text-wordbreak" ] }, "autocomplete-highlighters": { "requires": [ "array-extras", "highlight-base" ] }, "autocomplete-highlighters-accentfold": { "requires": [ "array-extras", "highlight-accentfold" ] }, "autocomplete-list": { "after": [ "autocomplete-sources" ], "lang": [ "en", "es", "hu", "it" ], "requires": [ "autocomplete-base", "event-resize", "node-screen", "selector-css3", "shim-plugin", "widget", "widget-position", "widget-position-align" ], "skinnable": true }, "autocomplete-list-keys": { "condition": { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }, "requires": [ "autocomplete-list", "base-build" ] }, "autocomplete-plugin": { "requires": [ "autocomplete-list", "node-pluginhost" ] }, "autocomplete-sources": { "optional": [ "io-base", "json-parse", "jsonp", "yql" ], "requires": [ "autocomplete-base" ] }, "axes": { "use": [ "axis-numeric", "axis-category", "axis-time", "axis-stacked" ] }, "axes-base": { "use": [ "axis-numeric-base", "axis-category-base", "axis-time-base", "axis-stacked-base" ] }, "axis": { "requires": [ "dom", "widget", "widget-position", "widget-stack", "graphics", "axis-base" ] }, "axis-base": { "requires": [ "classnamemanager", "datatype-number", "datatype-date", "base", "event-custom" ] }, "axis-category": { "requires": [ "axis", "axis-category-base" ] }, "axis-category-base": { "requires": [ "axis-base" ] }, "axis-numeric": { "requires": [ "axis", "axis-numeric-base" ] }, "axis-numeric-base": { "requires": [ "axis-base" ] }, "axis-stacked": { "requires": [ "axis-numeric", "axis-stacked-base" ] }, "axis-stacked-base": { "requires": [ "axis-numeric-base" ] }, "axis-time": { "requires": [ "axis", "axis-time-base" ] }, "axis-time-base": { "requires": [ "axis-base" ] }, "base": { "use": [ "base-base", "base-pluginhost", "base-build" ] }, "base-base": { "requires": [ "attribute-base", "base-core", "base-observable" ] }, "base-build": { "requires": [ "base-base" ] }, "base-core": { "requires": [ "attribute-core" ] }, "base-observable": { "requires": [ "attribute-observable" ] }, "base-pluginhost": { "requires": [ "base-base", "pluginhost" ] }, "button": { "requires": [ "button-core", "cssbutton", "widget" ] }, "button-core": { "requires": [ "attribute-core", "classnamemanager", "node-base", "escape" ] }, "button-group": { "requires": [ "button-plugin", "cssbutton", "widget" ] }, "button-plugin": { "requires": [ "button-core", "cssbutton", "node-pluginhost" ] }, "cache": { "use": [ "cache-base", "cache-offline", "cache-plugin" ] }, "cache-base": { "requires": [ "base" ] }, "cache-offline": { "requires": [ "cache-base", "json" ] }, "cache-plugin": { "requires": [ "plugin", "cache-base" ] }, "calendar": { "requires": [ "calendar-base", "calendarnavigator" ], "skinnable": true }, "calendar-base": { "lang": [ "de", "en", "es", "es-AR", "fr", "hu", "it", "ja", "nb-NO", "nl", "pt-BR", "ru", "zh-Hans", "zh-Hans-CN", "zh-Hant", "zh-Hant-HK", "zh-HANT-TW" ], "requires": [ "widget", "datatype-date", "datatype-date-math", "cssgrids" ], "skinnable": true }, "calendarnavigator": { "requires": [ "plugin", "classnamemanager", "datatype-date", "node" ], "skinnable": true }, "charts": { "use": [ "charts-base" ] }, "charts-base": { "requires": [ "dom", "event-mouseenter", "event-touch", "graphics-group", "axes", "series-pie", "series-line", "series-marker", "series-area", "series-spline", "series-column", "series-bar", "series-areaspline", "series-combo", "series-combospline", "series-line-stacked", "series-marker-stacked", "series-area-stacked", "series-spline-stacked", "series-column-stacked", "series-bar-stacked", "series-areaspline-stacked", "series-combo-stacked", "series-combospline-stacked" ] }, "charts-legend": { "requires": [ "charts-base" ] }, "classnamemanager": { "requires": [ "yui-base" ] }, "clickable-rail": { "requires": [ "slider-base" ] }, "collection": { "use": [ "array-extras", "arraylist", "arraylist-add", "arraylist-filter", "array-invoke" ] }, "color": { "use": [ "color-base", "color-hsl", "color-harmony" ] }, "color-base": { "requires": [ "yui-base" ] }, "color-harmony": { "requires": [ "color-hsl" ] }, "color-hsl": { "requires": [ "color-base" ] }, "color-hsv": { "requires": [ "color-base" ] }, "console": { "lang": [ "en", "es", "hu", "it", "ja" ], "requires": [ "yui-log", "widget" ], "skinnable": true }, "console-filters": { "requires": [ "plugin", "console" ], "skinnable": true }, "content-editable": { "requires": [ "node-base", "editor-selection", "stylesheet", "plugin" ] }, "controller": { "use": [ "router" ] }, "cookie": { "requires": [ "yui-base" ] }, "createlink-base": { "requires": [ "editor-base" ] }, "cssbase": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssbase-context": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssbutton": { "type": "css" }, "cssfonts": { "type": "css" }, "cssfonts-context": { "type": "css" }, "cssgrids": { "optional": [ "cssnormalize" ], "type": "css" }, "cssgrids-base": { "optional": [ "cssnormalize" ], "type": "css" }, "cssgrids-responsive": { "optional": [ "cssnormalize" ], "requires": [ "cssgrids", "cssgrids-responsive-base" ], "type": "css" }, "cssgrids-units": { "optional": [ "cssnormalize" ], "requires": [ "cssgrids-base" ], "type": "css" }, "cssnormalize": { "type": "css" }, "cssnormalize-context": { "type": "css" }, "cssreset": { "type": "css" }, "cssreset-context": { "type": "css" }, "dataschema": { "use": [ "dataschema-base", "dataschema-json", "dataschema-xml", "dataschema-array", "dataschema-text" ] }, "dataschema-array": { "requires": [ "dataschema-base" ] }, "dataschema-base": { "requires": [ "base" ] }, "dataschema-json": { "requires": [ "dataschema-base", "json" ] }, "dataschema-text": { "requires": [ "dataschema-base" ] }, "dataschema-xml": { "requires": [ "dataschema-base" ] }, "datasource": { "use": [ "datasource-local", "datasource-io", "datasource-get", "datasource-function", "datasource-cache", "datasource-jsonschema", "datasource-xmlschema", "datasource-arrayschema", "datasource-textschema", "datasource-polling" ] }, "datasource-arrayschema": { "requires": [ "datasource-local", "plugin", "dataschema-array" ] }, "datasource-cache": { "requires": [ "datasource-local", "plugin", "cache-base" ] }, "datasource-function": { "requires": [ "datasource-local" ] }, "datasource-get": { "requires": [ "datasource-local", "get" ] }, "datasource-io": { "requires": [ "datasource-local", "io-base" ] }, "datasource-jsonschema": { "requires": [ "datasource-local", "plugin", "dataschema-json" ] }, "datasource-local": { "requires": [ "base" ] }, "datasource-polling": { "requires": [ "datasource-local" ] }, "datasource-textschema": { "requires": [ "datasource-local", "plugin", "dataschema-text" ] }, "datasource-xmlschema": { "requires": [ "datasource-local", "plugin", "datatype-xml", "dataschema-xml" ] }, "datatable": { "use": [ "datatable-core", "datatable-table", "datatable-head", "datatable-body", "datatable-base", "datatable-column-widths", "datatable-message", "datatable-mutable", "datatable-sort", "datatable-datasource" ] }, "datatable-base": { "requires": [ "datatable-core", "datatable-table", "datatable-head", "datatable-body", "base-build", "widget" ], "skinnable": true }, "datatable-body": { "requires": [ "datatable-core", "view", "classnamemanager" ] }, "datatable-column-widths": { "requires": [ "datatable-base" ] }, "datatable-core": { "requires": [ "escape", "model-list", "node-event-delegate" ] }, "datatable-datasource": { "requires": [ "datatable-base", "plugin", "datasource-local" ] }, "datatable-foot": { "requires": [ "datatable-core", "view" ] }, "datatable-formatters": { "requires": [ "datatable-body", "datatype-number-format", "datatype-date-format", "escape" ] }, "datatable-head": { "requires": [ "datatable-core", "view", "classnamemanager" ] }, "datatable-highlight": { "requires": [ "datatable-base", "event-hover" ], "skinnable": true }, "datatable-keynav": { "requires": [ "datatable-base" ] }, "datatable-message": { "lang": [ "en", "fr", "es", "hu", "it" ], "requires": [ "datatable-base" ], "skinnable": true }, "datatable-mutable": { "requires": [ "datatable-base" ] }, "datatable-paginator": { "lang": [ "en", "fr" ], "requires": [ "model", "view", "paginator-core", "datatable-foot", "datatable-paginator-templates" ], "skinnable": true }, "datatable-paginator-templates": { "requires": [ "template" ] }, "datatable-scroll": { "requires": [ "datatable-base", "datatable-column-widths", "dom-screen" ], "skinnable": true }, "datatable-sort": { "lang": [ "en", "fr", "es", "hu" ], "requires": [ "datatable-base" ], "skinnable": true }, "datatable-table": { "requires": [ "datatable-core", "datatable-head", "datatable-body", "view", "classnamemanager" ] }, "datatype": { "use": [ "datatype-date", "datatype-number", "datatype-xml" ] }, "datatype-date": { "use": [ "datatype-date-parse", "datatype-date-format", "datatype-date-math" ] }, "datatype-date-format": { "lang": [ "ar", "ar-JO", "ca", "ca-ES", "da", "da-DK", "de", "de-AT", "de-DE", "el", "el-GR", "en", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", "en-JO", "en-MY", "en-NZ", "en-PH", "en-SG", "en-US", "es", "es-AR", "es-BO", "es-CL", "es-CO", "es-EC", "es-ES", "es-MX", "es-PE", "es-PY", "es-US", "es-UY", "es-VE", "fi", "fi-FI", "fr", "fr-BE", "fr-CA", "fr-FR", "hi", "hi-IN", "hu", "id", "id-ID", "it", "it-IT", "ja", "ja-JP", "ko", "ko-KR", "ms", "ms-MY", "nb", "nb-NO", "nl", "nl-BE", "nl-NL", "pl", "pl-PL", "pt", "pt-BR", "ro", "ro-RO", "ru", "ru-RU", "sv", "sv-SE", "th", "th-TH", "tr", "tr-TR", "vi", "vi-VN", "zh-Hans", "zh-Hans-CN", "zh-Hant", "zh-Hant-HK", "zh-Hant-TW" ] }, "datatype-date-math": { "requires": [ "yui-base" ] }, "datatype-date-parse": {}, "datatype-number": { "use": [ "datatype-number-parse", "datatype-number-format" ] }, "datatype-number-format": {}, "datatype-number-parse": { "requires": [ "escape" ] }, "datatype-xml": { "use": [ "datatype-xml-parse", "datatype-xml-format" ] }, "datatype-xml-format": {}, "datatype-xml-parse": {}, "dd": { "use": [ "dd-ddm-base", "dd-ddm", "dd-ddm-drop", "dd-drag", "dd-proxy", "dd-constrain", "dd-drop", "dd-scroll", "dd-delegate" ] }, "dd-constrain": { "requires": [ "dd-drag" ] }, "dd-ddm": { "requires": [ "dd-ddm-base", "event-resize" ] }, "dd-ddm-base": { "requires": [ "node", "base", "yui-throttle", "classnamemanager" ] }, "dd-ddm-drop": { "requires": [ "dd-ddm" ] }, "dd-delegate": { "requires": [ "dd-drag", "dd-drop-plugin", "event-mouseenter" ] }, "dd-drag": { "requires": [ "dd-ddm-base" ] }, "dd-drop": { "requires": [ "dd-drag", "dd-ddm-drop" ] }, "dd-drop-plugin": { "requires": [ "dd-drop" ] }, "dd-gestures": { "condition": { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }, "requires": [ "dd-drag", "event-synthetic", "event-gestures" ] }, "dd-plugin": { "optional": [ "dd-constrain", "dd-proxy" ], "requires": [ "dd-drag" ] }, "dd-proxy": { "requires": [ "dd-drag" ] }, "dd-scroll": { "requires": [ "dd-drag" ] }, "dial": { "lang": [ "en", "es", "hu" ], "requires": [ "widget", "dd-drag", "event-mouseenter", "event-move", "event-key", "transition", "intl" ], "skinnable": true }, "dom": { "use": [ "dom-base", "dom-screen", "dom-style", "selector-native", "selector" ] }, "dom-base": { "requires": [ "dom-core" ] }, "dom-core": { "requires": [ "oop", "features" ] }, "dom-screen": { "requires": [ "dom-base", "dom-style" ] }, "dom-style": { "requires": [ "dom-base", "color-base" ] }, "dom-style-ie": { "condition": { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }, "requires": [ "dom-style" ] }, "dump": { "requires": [ "yui-base" ] }, "editor": { "use": [ "frame", "editor-selection", "exec-command", "editor-base", "editor-para", "editor-br", "editor-bidi", "editor-tab", "createlink-base" ] }, "editor-base": { "requires": [ "base", "frame", "node", "exec-command", "editor-selection" ] }, "editor-bidi": { "requires": [ "editor-base" ] }, "editor-br": { "requires": [ "editor-base" ] }, "editor-inline": { "requires": [ "editor-base", "content-editable" ] }, "editor-lists": { "requires": [ "editor-base" ] }, "editor-para": { "requires": [ "editor-para-base" ] }, "editor-para-base": { "requires": [ "editor-base" ] }, "editor-para-ie": { "condition": { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }, "requires": [ "editor-para-base" ] }, "editor-selection": { "requires": [ "node" ] }, "editor-tab": { "requires": [ "editor-base" ] }, "escape": { "requires": [ "yui-base" ] }, "event": { "after": [ "node-base" ], "use": [ "event-base", "event-delegate", "event-synthetic", "event-mousewheel", "event-mouseenter", "event-key", "event-focus", "event-resize", "event-hover", "event-outside", "event-touch", "event-move", "event-flick", "event-valuechange", "event-tap" ] }, "event-base": { "after": [ "node-base" ], "requires": [ "event-custom-base" ] }, "event-base-ie": { "after": [ "event-base" ], "condition": { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }, "requires": [ "node-base" ] }, "event-contextmenu": { "requires": [ "event-synthetic", "dom-screen" ] }, "event-custom": { "use": [ "event-custom-base", "event-custom-complex" ] }, "event-custom-base": { "requires": [ "oop" ] }, "event-custom-complex": { "requires": [ "event-custom-base" ] }, "event-delegate": { "requires": [ "node-base" ] }, "event-flick": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-focus": { "requires": [ "event-synthetic" ] }, "event-gestures": { "use": [ "event-flick", "event-move" ] }, "event-hover": { "requires": [ "event-mouseenter" ] }, "event-key": { "requires": [ "event-synthetic" ] }, "event-mouseenter": { "requires": [ "event-synthetic" ] }, "event-mousewheel": { "requires": [ "node-base" ] }, "event-move": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-outside": { "requires": [ "event-synthetic" ] }, "event-resize": { "requires": [ "node-base", "event-synthetic" ] }, "event-simulate": { "requires": [ "event-base" ] }, "event-synthetic": { "requires": [ "node-base", "event-custom-complex" ] }, "event-tap": { "requires": [ "node-base", "event-base", "event-touch", "event-synthetic" ] }, "event-touch": { "requires": [ "node-base" ] }, "event-valuechange": { "requires": [ "event-focus", "event-synthetic" ] }, "exec-command": { "requires": [ "frame" ] }, "features": { "requires": [ "yui-base" ] }, "file": { "requires": [ "file-flash", "file-html5" ] }, "file-flash": { "requires": [ "base" ] }, "file-html5": { "requires": [ "base" ] }, "frame": { "requires": [ "base", "node", "plugin", "selector-css3", "yui-throttle" ] }, "gesture-simulate": { "requires": [ "async-queue", "event-simulate", "node-screen" ] }, "get": { "requires": [ "yui-base" ] }, "graphics": { "requires": [ "node", "event-custom", "pluginhost", "matrix", "classnamemanager" ] }, "graphics-canvas": { "condition": { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }, "requires": [ "graphics" ] }, "graphics-canvas-default": { "condition": { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" } }, "graphics-group": { "requires": [ "graphics" ] }, "graphics-svg": { "condition": { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }, "requires": [ "graphics" ] }, "graphics-svg-default": { "condition": { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" } }, "graphics-vml": { "condition": { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }, "requires": [ "graphics" ] }, "graphics-vml-default": { "condition": { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" } }, "handlebars": { "use": [ "handlebars-compiler" ] }, "handlebars-base": { "requires": [] }, "handlebars-compiler": { "requires": [ "handlebars-base" ] }, "highlight": { "use": [ "highlight-base", "highlight-accentfold" ] }, "highlight-accentfold": { "requires": [ "highlight-base", "text-accentfold" ] }, "highlight-base": { "requires": [ "array-extras", "classnamemanager", "escape", "text-wordbreak" ] }, "history": { "use": [ "history-base", "history-hash", "history-hash-ie", "history-html5" ] }, "history-base": { "requires": [ "event-custom-complex" ] }, "history-hash": { "after": [ "history-html5" ], "requires": [ "event-synthetic", "history-base", "yui-later" ] }, "history-hash-ie": { "condition": { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }, "requires": [ "history-hash", "node-base" ] }, "history-html5": { "optional": [ "json" ], "requires": [ "event-base", "history-base", "node-base" ] }, "imageloader": { "requires": [ "base-base", "node-style", "node-screen" ] }, "intl": { "requires": [ "intl-base", "event-custom" ] }, "intl-base": { "requires": [ "yui-base" ] }, "io": { "use": [ "io-base", "io-xdr", "io-form", "io-upload-iframe", "io-queue" ] }, "io-base": { "requires": [ "event-custom-base", "querystring-stringify-simple" ] }, "io-form": { "requires": [ "io-base", "node-base" ] }, "io-nodejs": { "condition": { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }, "requires": [ "io-base" ] }, "io-queue": { "requires": [ "io-base", "queue-promote" ] }, "io-upload-iframe": { "requires": [ "io-base", "node-base" ] }, "io-xdr": { "requires": [ "io-base", "datatype-xml-parse" ] }, "json": { "use": [ "json-parse", "json-stringify" ] }, "json-parse": { "requires": [ "yui-base" ] }, "json-parse-shim": { "condition": { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }, "requires": [ "json-parse" ] }, "json-stringify": { "requires": [ "yui-base" ] }, "json-stringify-shim": { "condition": { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }, "requires": [ "json-stringify" ] }, "jsonp": { "requires": [ "get", "oop" ] }, "jsonp-url": { "requires": [ "jsonp" ] }, "lazy-model-list": { "requires": [ "model-list" ] }, "loader": { "use": [ "loader-base", "loader-rollup", "loader-yui3" ] }, "loader-base": { "requires": [ "get", "features" ] }, "loader-rollup": { "requires": [ "loader-base" ] }, "loader-yui3": { "requires": [ "loader-base" ] }, "matrix": { "requires": [ "yui-base" ] }, "model": { "requires": [ "base-build", "escape", "json-parse" ] }, "model-list": { "requires": [ "array-extras", "array-invoke", "arraylist", "base-build", "escape", "json-parse", "model" ] }, "model-sync-local": { "requires": [ "model", "json-stringify" ] }, "model-sync-rest": { "requires": [ "model", "io-base", "json-stringify" ] }, "node": { "use": [ "node-base", "node-event-delegate", "node-pluginhost", "node-screen", "node-style" ] }, "node-base": { "requires": [ "event-base", "node-core", "dom-base", "dom-style" ] }, "node-core": { "requires": [ "dom-core", "selector" ] }, "node-event-delegate": { "requires": [ "node-base", "event-delegate" ] }, "node-event-html5": { "requires": [ "node-base" ] }, "node-event-simulate": { "requires": [ "node-base", "event-simulate", "gesture-simulate" ] }, "node-flick": { "requires": [ "classnamemanager", "transition", "event-flick", "plugin" ], "skinnable": true }, "node-focusmanager": { "requires": [ "attribute", "node", "plugin", "node-event-simulate", "event-key", "event-focus" ] }, "node-load": { "requires": [ "node-base", "io-base" ] }, "node-menunav": { "requires": [ "node", "classnamemanager", "plugin", "node-focusmanager" ], "skinnable": true }, "node-pluginhost": { "requires": [ "node-base", "pluginhost" ] }, "node-screen": { "requires": [ "dom-screen", "node-base" ] }, "node-scroll-info": { "requires": [ "array-extras", "base-build", "event-resize", "node-pluginhost", "plugin", "selector" ] }, "node-style": { "requires": [ "dom-style", "node-base" ] }, "oop": { "requires": [ "yui-base" ] }, "overlay": { "requires": [ "widget", "widget-stdmod", "widget-position", "widget-position-align", "widget-stack", "widget-position-constrain" ], "skinnable": true }, "paginator": { "requires": [ "paginator-core" ] }, "paginator-core": { "requires": [ "base" ] }, "paginator-url": { "requires": [ "paginator" ] }, "panel": { "requires": [ "widget", "widget-autohide", "widget-buttons", "widget-modality", "widget-position", "widget-position-align", "widget-position-constrain", "widget-stack", "widget-stdmod" ], "skinnable": true }, "parallel": { "requires": [ "yui-base" ] }, "pjax": { "requires": [ "pjax-base", "pjax-content" ] }, "pjax-base": { "requires": [ "classnamemanager", "node-event-delegate", "router" ] }, "pjax-content": { "requires": [ "io-base", "node-base", "router" ] }, "pjax-plugin": { "requires": [ "node-pluginhost", "pjax", "plugin" ] }, "plugin": { "requires": [ "base-base" ] }, "pluginhost": { "use": [ "pluginhost-base", "pluginhost-config" ] }, "pluginhost-base": { "requires": [ "yui-base" ] }, "pluginhost-config": { "requires": [ "pluginhost-base" ] }, "promise": { "requires": [ "timers" ] }, "querystring": { "use": [ "querystring-parse", "querystring-stringify" ] }, "querystring-parse": { "requires": [ "yui-base", "array-extras" ] }, "querystring-parse-simple": { "requires": [ "yui-base" ] }, "querystring-stringify": { "requires": [ "yui-base" ] }, "querystring-stringify-simple": { "requires": [ "yui-base" ] }, "queue-promote": { "requires": [ "yui-base" ] }, "range-slider": { "requires": [ "slider-base", "slider-value-range", "clickable-rail" ] }, "recordset": { "use": [ "recordset-base", "recordset-sort", "recordset-filter", "recordset-indexer" ] }, "recordset-base": { "requires": [ "base", "arraylist" ] }, "recordset-filter": { "requires": [ "recordset-base", "array-extras", "plugin" ] }, "recordset-indexer": { "requires": [ "recordset-base", "plugin" ] }, "recordset-sort": { "requires": [ "arraysort", "recordset-base", "plugin" ] }, "resize": { "use": [ "resize-base", "resize-proxy", "resize-constrain" ] }, "resize-base": { "requires": [ "base", "widget", "event", "oop", "dd-drag", "dd-delegate", "dd-drop" ], "skinnable": true }, "resize-constrain": { "requires": [ "plugin", "resize-base" ] }, "resize-plugin": { "optional": [ "resize-constrain" ], "requires": [ "resize-base", "plugin" ] }, "resize-proxy": { "requires": [ "plugin", "resize-base" ] }, "router": { "optional": [ "querystring-parse" ], "requires": [ "array-extras", "base-build", "history" ] }, "scrollview": { "requires": [ "scrollview-base", "scrollview-scrollbars" ] }, "scrollview-base": { "requires": [ "widget", "event-gestures", "event-mousewheel", "transition" ], "skinnable": true }, "scrollview-base-ie": { "condition": { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }, "requires": [ "scrollview-base" ] }, "scrollview-list": { "requires": [ "plugin", "classnamemanager" ], "skinnable": true }, "scrollview-paginator": { "requires": [ "plugin", "classnamemanager" ] }, "scrollview-scrollbars": { "requires": [ "classnamemanager", "transition", "plugin" ], "skinnable": true }, "selector": { "requires": [ "selector-native" ] }, "selector-css2": { "condition": { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }, "requires": [ "selector-native" ] }, "selector-css3": { "requires": [ "selector-native", "selector-css2" ] }, "selector-native": { "requires": [ "dom-base" ] }, "series-area": { "requires": [ "series-cartesian", "series-fill-util" ] }, "series-area-stacked": { "requires": [ "series-stacked", "series-area" ] }, "series-areaspline": { "requires": [ "series-area", "series-curve-util" ] }, "series-areaspline-stacked": { "requires": [ "series-stacked", "series-areaspline" ] }, "series-bar": { "requires": [ "series-marker", "series-histogram-base" ] }, "series-bar-stacked": { "requires": [ "series-stacked", "series-bar" ] }, "series-base": { "requires": [ "graphics", "axis-base" ] }, "series-candlestick": { "requires": [ "series-range" ] }, "series-cartesian": { "requires": [ "series-base" ] }, "series-column": { "requires": [ "series-marker", "series-histogram-base" ] }, "series-column-stacked": { "requires": [ "series-stacked", "series-column" ] }, "series-combo": { "requires": [ "series-cartesian", "series-line-util", "series-plot-util", "series-fill-util" ] }, "series-combo-stacked": { "requires": [ "series-stacked", "series-combo" ] }, "series-combospline": { "requires": [ "series-combo", "series-curve-util" ] }, "series-combospline-stacked": { "requires": [ "series-combo-stacked", "series-curve-util" ] }, "series-curve-util": {}, "series-fill-util": {}, "series-histogram-base": { "requires": [ "series-cartesian", "series-plot-util" ] }, "series-line": { "requires": [ "series-cartesian", "series-line-util" ] }, "series-line-stacked": { "requires": [ "series-stacked", "series-line" ] }, "series-line-util": {}, "series-marker": { "requires": [ "series-cartesian", "series-plot-util" ] }, "series-marker-stacked": { "requires": [ "series-stacked", "series-marker" ] }, "series-ohlc": { "requires": [ "series-range" ] }, "series-pie": { "requires": [ "series-base", "series-plot-util" ] }, "series-plot-util": {}, "series-range": { "requires": [ "series-cartesian" ] }, "series-spline": { "requires": [ "series-line", "series-curve-util" ] }, "series-spline-stacked": { "requires": [ "series-stacked", "series-spline" ] }, "series-stacked": { "requires": [ "axis-stacked" ] }, "shim-plugin": { "requires": [ "node-style", "node-pluginhost" ] }, "slider": { "use": [ "slider-base", "slider-value-range", "clickable-rail", "range-slider" ] }, "slider-base": { "requires": [ "widget", "dd-constrain", "event-key" ], "skinnable": true }, "slider-value-range": { "requires": [ "slider-base" ] }, "sortable": { "requires": [ "dd-delegate", "dd-drop-plugin", "dd-proxy" ] }, "sortable-scroll": { "requires": [ "dd-scroll", "sortable" ] }, "stylesheet": { "requires": [ "yui-base" ] }, "substitute": { "optional": [ "dump" ], "requires": [ "yui-base" ] }, "swf": { "requires": [ "event-custom", "node", "swfdetect", "escape" ] }, "swfdetect": { "requires": [ "yui-base" ] }, "tabview": { "requires": [ "widget", "widget-parent", "widget-child", "tabview-base", "node-pluginhost", "node-focusmanager" ], "skinnable": true }, "tabview-base": { "requires": [ "node-event-delegate", "classnamemanager" ] }, "tabview-plugin": { "requires": [ "tabview-base" ] }, "template": { "use": [ "template-base", "template-micro" ] }, "template-base": { "requires": [ "yui-base" ] }, "template-micro": { "requires": [ "escape" ] }, "test": { "requires": [ "event-simulate", "event-custom", "json-stringify" ] }, "test-console": { "requires": [ "console-filters", "test", "array-extras" ], "skinnable": true }, "text": { "use": [ "text-accentfold", "text-wordbreak" ] }, "text-accentfold": { "requires": [ "array-extras", "text-data-accentfold" ] }, "text-data-accentfold": { "requires": [ "yui-base" ] }, "text-data-wordbreak": { "requires": [ "yui-base" ] }, "text-wordbreak": { "requires": [ "array-extras", "text-data-wordbreak" ] }, "timers": { "requires": [ "yui-base" ] }, "transition": { "requires": [ "node-style" ] }, "transition-timer": { "condition": { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }, "requires": [ "transition" ] }, "tree": { "requires": [ "base-build", "tree-node" ] }, "tree-labelable": { "requires": [ "tree" ] }, "tree-lazy": { "requires": [ "base-pluginhost", "plugin", "tree" ] }, "tree-node": {}, "tree-openable": { "requires": [ "tree" ] }, "tree-selectable": { "requires": [ "tree" ] }, "tree-sortable": { "requires": [ "tree" ] }, "uploader": { "requires": [ "uploader-html5", "uploader-flash" ] }, "uploader-flash": { "requires": [ "swfdetect", "escape", "widget", "base", "cssbutton", "node", "event-custom", "uploader-queue" ] }, "uploader-html5": { "requires": [ "widget", "node-event-simulate", "file-html5", "uploader-queue" ] }, "uploader-queue": { "requires": [ "base" ] }, "view": { "requires": [ "base-build", "node-event-delegate" ] }, "view-node-map": { "requires": [ "view" ] }, "widget": { "use": [ "widget-base", "widget-htmlparser", "widget-skin", "widget-uievents" ] }, "widget-anim": { "requires": [ "anim-base", "plugin", "widget" ] }, "widget-autohide": { "requires": [ "base-build", "event-key", "event-outside", "widget" ] }, "widget-base": { "requires": [ "attribute", "base-base", "base-pluginhost", "classnamemanager", "event-focus", "node-base", "node-style" ], "skinnable": true }, "widget-base-ie": { "condition": { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }, "requires": [ "widget-base" ] }, "widget-buttons": { "requires": [ "button-plugin", "cssbutton", "widget-stdmod" ] }, "widget-child": { "requires": [ "base-build", "widget" ] }, "widget-htmlparser": { "requires": [ "widget-base" ] }, "widget-modality": { "requires": [ "base-build", "event-outside", "widget" ], "skinnable": true }, "widget-parent": { "requires": [ "arraylist", "base-build", "widget" ] }, "widget-position": { "requires": [ "base-build", "node-screen", "widget" ] }, "widget-position-align": { "requires": [ "widget-position" ] }, "widget-position-constrain": { "requires": [ "widget-position" ] }, "widget-skin": { "requires": [ "widget-base" ] }, "widget-stack": { "requires": [ "base-build", "widget" ], "skinnable": true }, "widget-stdmod": { "requires": [ "base-build", "widget" ] }, "widget-uievents": { "requires": [ "node-event-delegate", "widget-base" ] }, "yql": { "requires": [ "oop" ] }, "yql-jsonp": { "condition": { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }, "requires": [ "jsonp", "jsonp-url" ] }, "yql-nodejs": { "condition": { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" } }, "yql-winjs": { "condition": { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" } }, "yui": {}, "yui-base": {}, "yui-later": { "requires": [ "yui-base" ] }, "yui-log": { "requires": [ "yui-base" ] }, "yui-throttle": { "requires": [ "yui-base" ] } }); YUI.Env[Y.version].md5 = '7becfe88413f127e331d461de8ec774c'; }, '@VERSION@', {"requires": ["loader-base"]}); YUI.add('yui', function (Y, NAME) {}, '@VERSION@', { "use": [ "yui-base", "get", "features", "intl-base", "yui-log", "yui-later", "loader-base", "loader-rollup", "loader-yui3" ] });
ProfNandaa/cdnjs
ajax/libs/yui/3.14.1/yui/yui.js
JavaScript
mit
340,583
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Mvc; use Zend\EventManager\EventManager; use Zend\EventManager\EventManagerAwareInterface; use Zend\EventManager\EventManagerInterface; use Zend\EventManager\ListenerAggregateInterface; use Zend\Mvc\ResponseSender\ConsoleResponseSender; use Zend\Mvc\ResponseSender\HttpResponseSender; use Zend\Mvc\ResponseSender\PhpEnvironmentResponseSender; use Zend\Mvc\ResponseSender\SendResponseEvent; use Zend\Mvc\ResponseSender\SimpleStreamResponseSender; use Zend\Stdlib\ResponseInterface as Response; class SendResponseListener implements EventManagerAwareInterface, ListenerAggregateInterface { /** * @var \Zend\Stdlib\CallbackHandler[] */ protected $listeners = array(); /** * @var SendResponseEvent */ protected $event; /** * @var EventManagerInterface */ protected $eventManager; /** * Inject an EventManager instance * * @param EventManagerInterface $eventManager * @return SendResponseListener */ public function setEventManager(EventManagerInterface $eventManager) { $eventManager->setIdentifiers(array( __CLASS__, get_class($this), )); $this->eventManager = $eventManager; $this->attachDefaultListeners(); return $this; } /** * Retrieve the event manager * * Lazy-loads an EventManager instance if none registered. * * @return EventManagerInterface */ public function getEventManager() { if (!$this->eventManager instanceof EventManagerInterface) { $this->setEventManager(new EventManager()); } return $this->eventManager; } /** * Attach the aggregate to the specified event manager * * @param EventManagerInterface $events * @return void */ public function attach(EventManagerInterface $events) { $this->listeners[] = $events->attach(MvcEvent::EVENT_FINISH, array($this, 'sendResponse'), -10000); } /** * Detach aggregate listeners from the specified event manager * * @param EventManagerInterface $events * @return void */ public function detach(EventManagerInterface $events) { foreach ($this->listeners as $index => $listener) { if ($events->detach($listener)) { unset($this->listeners[$index]); } } } /** * Send the response * * @param MvcEvent $e * @return void */ public function sendResponse(MvcEvent $e) { $response = $e->getResponse(); if (!$response instanceof Response) { return; // there is no response to send } $event = $this->getEvent(); $event->setResponse($response); $event->setTarget($this); $this->getEventManager()->trigger($event); } /** * Get the send response event * * @return SendResponseEvent */ public function getEvent() { if (!$this->event instanceof SendResponseEvent) { $this->setEvent(new SendResponseEvent()); } return $this->event; } /** * Set the send response event * * @param SendResponseEvent $e * @return SendResponseEvent */ public function setEvent(SendResponseEvent $e) { $this->event = $e; return $this; } /** * Register the default event listeners * * The order in which the response sender are listed here, is by their usage: * PhpEnvironmentResponseSender has highest priority, because it's used most often. * ConsoleResponseSender and SimpleStreamResponseSender are not used that often, yo they have a lower priority. * You can attach your response sender before or after every default response sender implementation. * All default response sender implementation have negative priority. * You are able to attach listeners without giving a priority and your response sender would be first to try. * * @return SendResponseListener */ protected function attachDefaultListeners() { $events = $this->getEventManager(); $events->attach(SendResponseEvent::EVENT_SEND_RESPONSE, new PhpEnvironmentResponseSender(), -1000); $events->attach(SendResponseEvent::EVENT_SEND_RESPONSE, new ConsoleResponseSender(), -2000); $events->attach(SendResponseEvent::EVENT_SEND_RESPONSE, new SimpleStreamResponseSender(), -3000); $events->attach(SendResponseEvent::EVENT_SEND_RESPONSE, new HttpResponseSender(), -4000); } }
JorikVartanov/zf2
zf2_project/vendor/zendframework/zendframework/library/Zend/Mvc/SendResponseListener.php
PHP
bsd-3-clause
4,935
#ifndef __ASM_POWERPC_MMU_CONTEXT_H #define __ASM_POWERPC_MMU_CONTEXT_H #ifdef __KERNEL__ #include <linux/kernel.h> #include <linux/mm.h> #include <linux/sched.h> #include <linux/spinlock.h> #include <asm/mmu.h> #include <asm/cputable.h> #include <asm-generic/mm_hooks.h> #include <asm/cputhreads.h> /* * Most if the context management is out of line */ extern int init_new_context(struct task_struct *tsk, struct mm_struct *mm); extern void destroy_context(struct mm_struct *mm); extern void switch_mmu_context(struct mm_struct *prev, struct mm_struct *next); extern void switch_stab(struct task_struct *tsk, struct mm_struct *mm); extern void switch_slb(struct task_struct *tsk, struct mm_struct *mm); extern void set_context(unsigned long id, pgd_t *pgd); #ifdef CONFIG_PPC_BOOK3S_64 static inline void mmu_context_init(void) { } #else extern void mmu_context_init(void); #endif /* * switch_mm is the entry point called from the architecture independent * code in kernel/sched.c */ static inline void switch_mm(struct mm_struct *prev, struct mm_struct *next, struct task_struct *tsk) { /* Mark this context has been used on the new CPU */ cpumask_set_cpu(smp_processor_id(), mm_cpumask(next)); /* 32-bit keeps track of the current PGDIR in the thread struct */ #ifdef CONFIG_PPC32 tsk->thread.pgdir = next->pgd; #endif /* CONFIG_PPC32 */ /* 64-bit Book3E keeps track of current PGD in the PACA */ #ifdef CONFIG_PPC_BOOK3E_64 get_paca()->pgd = next->pgd; #endif /* Nothing else to do if we aren't actually switching */ if (prev == next) return; /* We must stop all altivec streams before changing the HW * context */ #ifdef CONFIG_ALTIVEC if (cpu_has_feature(CPU_FTR_ALTIVEC)) asm volatile ("dssall"); #endif /* CONFIG_ALTIVEC */ /* The actual HW switching method differs between the various * sub architectures. */ #ifdef CONFIG_PPC_STD_MMU_64 if (cpu_has_feature(CPU_FTR_SLB)) switch_slb(tsk, next); else switch_stab(tsk, next); #else /* Out of line for now */ switch_mmu_context(prev, next); #endif } #define deactivate_mm(tsk,mm) do { } while (0) /* * After we have set current->mm to a new value, this activates * the context for the new mm so we see the new mappings. */ static inline void activate_mm(struct mm_struct *prev, struct mm_struct *next) { unsigned long flags; local_irq_save(flags); switch_mm(prev, next, current); local_irq_restore(flags); } /* We don't currently use enter_lazy_tlb() for anything */ static inline void enter_lazy_tlb(struct mm_struct *mm, struct task_struct *tsk) { /* 64-bit Book3E keeps track of current PGD in the PACA */ #ifdef CONFIG_PPC_BOOK3E_64 get_paca()->pgd = NULL; #endif } #endif /* __KERNEL__ */ #endif /* __ASM_POWERPC_MMU_CONTEXT_H */
go2ev-devteam/Gplus_2159_0801
openplatform/sdk/os/kernel-2.6.32/arch/powerpc/include/asm/mmu_context.h
C
gpl-2.0
2,766
/////////////////////////////////////////////////////////////////////////////// /// \file regex_compiler.hpp /// Contains the definition of regex_compiler, a factory for building regex objects /// from strings. // // Copyright 2008 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_XPRESSIVE_REGEX_COMPILER_HPP_EAN_10_04_2005 #define BOOST_XPRESSIVE_REGEX_COMPILER_HPP_EAN_10_04_2005 // MS compatible compilers support #pragma once #if defined(_MSC_VER) # pragma once #endif #include <map> #include <boost/config.hpp> #include <boost/assert.hpp> #include <boost/next_prior.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/mpl/assert.hpp> #include <boost/throw_exception.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/type_traits/is_pointer.hpp> #include <boost/utility/enable_if.hpp> #include <boost/iterator/iterator_traits.hpp> #include <boost/xpressive/basic_regex.hpp> #include <boost/xpressive/detail/dynamic/parser.hpp> #include <boost/xpressive/detail/dynamic/parse_charset.hpp> #include <boost/xpressive/detail/dynamic/parser_enum.hpp> #include <boost/xpressive/detail/dynamic/parser_traits.hpp> #include <boost/xpressive/detail/core/linker.hpp> #include <boost/xpressive/detail/core/optimize.hpp> namespace boost { namespace xpressive { /////////////////////////////////////////////////////////////////////////////// // regex_compiler // /// \brief Class template regex_compiler is a factory for building basic_regex objects from a string. /// /// Class template regex_compiler is used to construct a basic_regex object from a string. The string /// should contain a valid regular expression. You can imbue a regex_compiler object with a locale, /// after which all basic_regex objects created with that regex_compiler object will use that locale. /// After creating a regex_compiler object, and optionally imbueing it with a locale, you can call the /// compile() method to construct a basic_regex object, passing it the string representing the regular /// expression. You can call compile() multiple times on the same regex_compiler object. Two basic_regex /// objects compiled from the same string will have different regex_id's. template<typename BidiIter, typename RegexTraits, typename CompilerTraits> struct regex_compiler { typedef BidiIter iterator_type; typedef typename iterator_value<BidiIter>::type char_type; typedef regex_constants::syntax_option_type flag_type; typedef RegexTraits traits_type; typedef typename traits_type::string_type string_type; typedef typename traits_type::locale_type locale_type; typedef typename traits_type::char_class_type char_class_type; explicit regex_compiler(RegexTraits const &traits = RegexTraits()) : mark_count_(0) , hidden_mark_count_(0) , traits_(traits) , upper_(0) , self_() , rules_() { this->upper_ = lookup_classname(this->rxtraits(), "upper"); } /////////////////////////////////////////////////////////////////////////// // imbue /// Specify the locale to be used by a regex_compiler. /// /// \param loc The locale that this regex_compiler should use. /// \return The previous locale. locale_type imbue(locale_type loc) { locale_type oldloc = this->traits_.imbue(loc); this->upper_ = lookup_classname(this->rxtraits(), "upper"); return oldloc; } /////////////////////////////////////////////////////////////////////////// // getloc /// Get the locale used by a regex_compiler. /// /// \return The locale used by this regex_compiler. locale_type getloc() const { return this->traits_.getloc(); } /////////////////////////////////////////////////////////////////////////// // compile /// Builds a basic_regex object from a range of characters. /// /// \param begin The beginning of a range of characters representing the /// regular expression to compile. /// \param end The end of a range of characters representing the /// regular expression to compile. /// \param flags Optional bitmask that determines how the pat string is /// interpreted. (See syntax_option_type.) /// \return A basic_regex object corresponding to the regular expression /// represented by the character range. /// \pre InputIter is a model of the InputIterator concept. /// \pre [begin,end) is a valid range. /// \pre The range of characters specified by [begin,end) contains a /// valid string-based representation of a regular expression. /// \throw regex_error when the range of characters has invalid regular /// expression syntax. template<typename InputIter> basic_regex<BidiIter> compile(InputIter begin, InputIter end, flag_type flags = regex_constants::ECMAScript) { typedef typename iterator_category<InputIter>::type category; return this->compile_(begin, end, flags, category()); } /// \overload /// template<typename InputRange> typename disable_if<is_pointer<InputRange>, basic_regex<BidiIter> >::type compile(InputRange const &pat, flag_type flags = regex_constants::ECMAScript) { return this->compile(boost::begin(pat), boost::end(pat), flags); } /// \overload /// basic_regex<BidiIter> compile(char_type const *begin, flag_type flags = regex_constants::ECMAScript) { BOOST_ASSERT(0 != begin); char_type const *end = begin + std::char_traits<char_type>::length(begin); return this->compile(begin, end, flags); } /// \overload /// basic_regex<BidiIter> compile(char_type const *begin, std::size_t size, flag_type flags) { BOOST_ASSERT(0 != begin); char_type const *end = begin + size; return this->compile(begin, end, flags); } /////////////////////////////////////////////////////////////////////////// // operator[] /// Return a reference to the named regular expression. If no such named /// regular expression exists, create a new regular expression and return /// a reference to it. /// /// \param name A std::string containing the name of the regular expression. /// \pre The string is not empty. /// \throw bad_alloc on allocation failure. basic_regex<BidiIter> &operator [](string_type const &name) { BOOST_ASSERT(!name.empty()); return this->rules_[name]; } /// \overload /// basic_regex<BidiIter> const &operator [](string_type const &name) const { BOOST_ASSERT(!name.empty()); return this->rules_[name]; } private: typedef detail::escape_value<char_type, char_class_type> escape_value; typedef detail::alternate_matcher<detail::alternates_vector<BidiIter>, RegexTraits> alternate_matcher; /////////////////////////////////////////////////////////////////////////// // compile_ /// INTERNAL ONLY template<typename FwdIter> basic_regex<BidiIter> compile_(FwdIter begin, FwdIter end, flag_type flags, std::forward_iterator_tag) { BOOST_MPL_ASSERT((is_same<char_type, typename iterator_value<FwdIter>::type>)); using namespace regex_constants; this->reset(); this->traits_.flags(flags); basic_regex<BidiIter> rextmp, *prex = &rextmp; FwdIter tmp = begin; // Check if this regex is a named rule: string_type name; if(token_group_begin == this->traits_.get_token(tmp, end) && BOOST_XPR_ENSURE_(tmp != end, error_paren, "mismatched parenthesis") && token_rule_assign == this->traits_.get_group_type(tmp, end, name)) { begin = tmp; BOOST_XPR_ENSURE_ ( begin != end && token_group_end == this->traits_.get_token(begin, end) , error_paren , "mismatched parenthesis" ); prex = &this->rules_[name]; } this->self_ = detail::core_access<BidiIter>::get_regex_impl(*prex); // at the top level, a regex is a sequence of alternates detail::sequence<BidiIter> seq = this->parse_alternates(begin, end); BOOST_XPR_ENSURE_(begin == end, error_paren, "mismatched parenthesis"); // terminate the sequence seq += detail::make_dynamic<BidiIter>(detail::end_matcher()); // bundle the regex information into a regex_impl object detail::common_compile(seq.xpr().matchable(), *this->self_, this->rxtraits()); this->self_->traits_ = new detail::traits_holder<RegexTraits>(this->rxtraits()); this->self_->mark_count_ = this->mark_count_; this->self_->hidden_mark_count_ = this->hidden_mark_count_; // References changed, update dependencies. this->self_->tracking_update(); this->self_.reset(); return *prex; } /////////////////////////////////////////////////////////////////////////// // compile_ /// INTERNAL ONLY template<typename InputIter> basic_regex<BidiIter> compile_(InputIter begin, InputIter end, flag_type flags, std::input_iterator_tag) { string_type pat(begin, end); return this->compile_(boost::begin(pat), boost::end(pat), flags, std::forward_iterator_tag()); } /////////////////////////////////////////////////////////////////////////// // reset /// INTERNAL ONLY void reset() { this->mark_count_ = 0; this->hidden_mark_count_ = 0; this->traits_.flags(regex_constants::ECMAScript); } /////////////////////////////////////////////////////////////////////////// // regex_traits /// INTERNAL ONLY traits_type &rxtraits() { return this->traits_.traits(); } /////////////////////////////////////////////////////////////////////////// // regex_traits /// INTERNAL ONLY traits_type const &rxtraits() const { return this->traits_.traits(); } /////////////////////////////////////////////////////////////////////////// // parse_alternates /// INTERNAL ONLY template<typename FwdIter> detail::sequence<BidiIter> parse_alternates(FwdIter &begin, FwdIter end) { using namespace regex_constants; int count = 0; FwdIter tmp = begin; detail::sequence<BidiIter> seq; do switch(++count) { case 1: seq = this->parse_sequence(tmp, end); break; case 2: seq = detail::make_dynamic<BidiIter>(alternate_matcher()) | seq; BOOST_FALLTHROUGH; default: seq |= this->parse_sequence(tmp, end); } while((begin = tmp) != end && token_alternate == this->traits_.get_token(tmp, end)); return seq; } /////////////////////////////////////////////////////////////////////////// // parse_group /// INTERNAL ONLY template<typename FwdIter> detail::sequence<BidiIter> parse_group(FwdIter &begin, FwdIter end) { using namespace regex_constants; int mark_nbr = 0; bool keeper = false; bool lookahead = false; bool lookbehind = false; bool negative = false; string_type name; detail::sequence<BidiIter> seq, seq_end; FwdIter tmp = FwdIter(); syntax_option_type old_flags = this->traits_.flags(); switch(this->traits_.get_group_type(begin, end, name)) { case token_no_mark: // Don't process empty groups like (?:) or (?i) // BUGBUG this doesn't handle the degenerate (?:)+ correctly if(token_group_end == this->traits_.get_token(tmp = begin, end)) { return this->parse_atom(begin = tmp, end); } break; case token_negative_lookahead: negative = true; BOOST_FALLTHROUGH; case token_positive_lookahead: lookahead = true; break; case token_negative_lookbehind: negative = true; BOOST_FALLTHROUGH; case token_positive_lookbehind: lookbehind = true; break; case token_independent_sub_expression: keeper = true; break; case token_comment: while(BOOST_XPR_ENSURE_(begin != end, error_paren, "mismatched parenthesis")) { switch(this->traits_.get_token(begin, end)) { case token_group_end: return this->parse_atom(begin, end); case token_escape: BOOST_XPR_ENSURE_(begin != end, error_escape, "incomplete escape sequence"); BOOST_FALLTHROUGH; case token_literal: ++begin; break; default: break; } } break; case token_recurse: BOOST_XPR_ENSURE_ ( begin != end && token_group_end == this->traits_.get_token(begin, end) , error_paren , "mismatched parenthesis" ); return detail::make_dynamic<BidiIter>(detail::regex_byref_matcher<BidiIter>(this->self_)); case token_rule_assign: BOOST_THROW_EXCEPTION( regex_error(error_badrule, "rule assignments must be at the front of the regex") ); break; case token_rule_ref: { typedef detail::core_access<BidiIter> access; BOOST_XPR_ENSURE_ ( begin != end && token_group_end == this->traits_.get_token(begin, end) , error_paren , "mismatched parenthesis" ); basic_regex<BidiIter> &rex = this->rules_[name]; shared_ptr<detail::regex_impl<BidiIter> > impl = access::get_regex_impl(rex); this->self_->track_reference(*impl); return detail::make_dynamic<BidiIter>(detail::regex_byref_matcher<BidiIter>(impl)); } case token_named_mark: mark_nbr = static_cast<int>(++this->mark_count_); for(std::size_t i = 0; i < this->self_->named_marks_.size(); ++i) { BOOST_XPR_ENSURE_(this->self_->named_marks_[i].name_ != name, error_badmark, "named mark already exists"); } this->self_->named_marks_.push_back(detail::named_mark<char_type>(name, this->mark_count_)); seq = detail::make_dynamic<BidiIter>(detail::mark_begin_matcher(mark_nbr)); seq_end = detail::make_dynamic<BidiIter>(detail::mark_end_matcher(mark_nbr)); break; case token_named_mark_ref: BOOST_XPR_ENSURE_ ( begin != end && token_group_end == this->traits_.get_token(begin, end) , error_paren , "mismatched parenthesis" ); for(std::size_t i = 0; i < this->self_->named_marks_.size(); ++i) { if(this->self_->named_marks_[i].name_ == name) { mark_nbr = static_cast<int>(this->self_->named_marks_[i].mark_nbr_); return detail::make_backref_xpression<BidiIter> ( mark_nbr, this->traits_.flags(), this->rxtraits() ); } } BOOST_THROW_EXCEPTION(regex_error(error_badmark, "invalid named back-reference")); break; default: mark_nbr = static_cast<int>(++this->mark_count_); seq = detail::make_dynamic<BidiIter>(detail::mark_begin_matcher(mark_nbr)); seq_end = detail::make_dynamic<BidiIter>(detail::mark_end_matcher(mark_nbr)); break; } // alternates seq += this->parse_alternates(begin, end); seq += seq_end; BOOST_XPR_ENSURE_ ( begin != end && token_group_end == this->traits_.get_token(begin, end) , error_paren , "mismatched parenthesis" ); typedef detail::shared_matchable<BidiIter> xpr_type; if(lookahead) { seq += detail::make_independent_end_xpression<BidiIter>(seq.pure()); detail::lookahead_matcher<xpr_type> lam(seq.xpr(), negative, seq.pure()); seq = detail::make_dynamic<BidiIter>(lam); } else if(lookbehind) { seq += detail::make_independent_end_xpression<BidiIter>(seq.pure()); detail::lookbehind_matcher<xpr_type> lbm(seq.xpr(), seq.width().value(), negative, seq.pure()); seq = detail::make_dynamic<BidiIter>(lbm); } else if(keeper) // independent sub-expression { seq += detail::make_independent_end_xpression<BidiIter>(seq.pure()); detail::keeper_matcher<xpr_type> km(seq.xpr(), seq.pure()); seq = detail::make_dynamic<BidiIter>(km); } // restore the modifiers this->traits_.flags(old_flags); return seq; } /////////////////////////////////////////////////////////////////////////// // parse_charset /// INTERNAL ONLY template<typename FwdIter> detail::sequence<BidiIter> parse_charset(FwdIter &begin, FwdIter end) { detail::compound_charset<traits_type> chset; // call out to a helper to actually parse the character set detail::parse_charset(begin, end, chset, this->traits_); return detail::make_charset_xpression<BidiIter> ( chset , this->rxtraits() , this->traits_.flags() ); } /////////////////////////////////////////////////////////////////////////// // parse_atom /// INTERNAL ONLY template<typename FwdIter> detail::sequence<BidiIter> parse_atom(FwdIter &begin, FwdIter end) { using namespace regex_constants; escape_value esc = { 0, 0, 0, detail::escape_char }; FwdIter old_begin = begin; switch(this->traits_.get_token(begin, end)) { case token_literal: return detail::make_literal_xpression<BidiIter> ( this->parse_literal(begin, end), this->traits_.flags(), this->rxtraits() ); case token_any: return detail::make_any_xpression<BidiIter>(this->traits_.flags(), this->rxtraits()); case token_assert_begin_sequence: return detail::make_dynamic<BidiIter>(detail::assert_bos_matcher()); case token_assert_end_sequence: return detail::make_dynamic<BidiIter>(detail::assert_eos_matcher()); case token_assert_begin_line: return detail::make_assert_begin_line<BidiIter>(this->traits_.flags(), this->rxtraits()); case token_assert_end_line: return detail::make_assert_end_line<BidiIter>(this->traits_.flags(), this->rxtraits()); case token_assert_word_boundary: return detail::make_assert_word<BidiIter>(detail::word_boundary<mpl::true_>(), this->rxtraits()); case token_assert_not_word_boundary: return detail::make_assert_word<BidiIter>(detail::word_boundary<mpl::false_>(), this->rxtraits()); case token_assert_word_begin: return detail::make_assert_word<BidiIter>(detail::word_begin(), this->rxtraits()); case token_assert_word_end: return detail::make_assert_word<BidiIter>(detail::word_end(), this->rxtraits()); case token_escape: esc = this->parse_escape(begin, end); switch(esc.type_) { case detail::escape_mark: return detail::make_backref_xpression<BidiIter> ( esc.mark_nbr_, this->traits_.flags(), this->rxtraits() ); case detail::escape_char: return detail::make_char_xpression<BidiIter> ( esc.ch_, this->traits_.flags(), this->rxtraits() ); case detail::escape_class: return detail::make_posix_charset_xpression<BidiIter> ( esc.class_ , this->is_upper_(*begin++) , this->traits_.flags() , this->rxtraits() ); } case token_group_begin: return this->parse_group(begin, end); case token_charset_begin: return this->parse_charset(begin, end); case token_invalid_quantifier: BOOST_THROW_EXCEPTION(regex_error(error_badrepeat, "quantifier not expected")); break; case token_quote_meta_begin: return detail::make_literal_xpression<BidiIter> ( this->parse_quote_meta(begin, end), this->traits_.flags(), this->rxtraits() ); case token_quote_meta_end: BOOST_THROW_EXCEPTION( regex_error( error_escape , "found quote-meta end without corresponding quote-meta begin" ) ); break; case token_end_of_pattern: break; default: begin = old_begin; break; } return detail::sequence<BidiIter>(); } /////////////////////////////////////////////////////////////////////////// // parse_quant /// INTERNAL ONLY template<typename FwdIter> detail::sequence<BidiIter> parse_quant(FwdIter &begin, FwdIter end) { BOOST_ASSERT(begin != end); detail::quant_spec spec = { 0, 0, false, &this->hidden_mark_count_ }; detail::sequence<BidiIter> seq = this->parse_atom(begin, end); // BUGBUG this doesn't handle the degenerate (?:)+ correctly if(!seq.empty() && begin != end && detail::quant_none != seq.quant()) { if(this->traits_.get_quant_spec(begin, end, spec)) { BOOST_ASSERT(spec.min_ <= spec.max_); if(0 == spec.max_) // quant {0,0} is degenerate -- matches nothing. { seq = this->parse_quant(begin, end); } else { seq.repeat(spec); } } } return seq; } /////////////////////////////////////////////////////////////////////////// // parse_sequence /// INTERNAL ONLY template<typename FwdIter> detail::sequence<BidiIter> parse_sequence(FwdIter &begin, FwdIter end) { detail::sequence<BidiIter> seq; while(begin != end) { detail::sequence<BidiIter> seq_quant = this->parse_quant(begin, end); // did we find a quantified atom? if(seq_quant.empty()) break; // chain it to the end of the xpression sequence seq += seq_quant; } return seq; } /////////////////////////////////////////////////////////////////////////// // parse_literal // scan ahead looking for char literals to be globbed together into a string literal /// INTERNAL ONLY template<typename FwdIter> string_type parse_literal(FwdIter &begin, FwdIter end) { using namespace regex_constants; BOOST_ASSERT(begin != end); BOOST_ASSERT(token_literal == this->traits_.get_token(begin, end)); escape_value esc = { 0, 0, 0, detail::escape_char }; string_type literal(1, *begin); for(FwdIter prev = begin, tmp = ++begin; begin != end; prev = begin, begin = tmp) { detail::quant_spec spec = { 0, 0, false, &this->hidden_mark_count_ }; if(this->traits_.get_quant_spec(tmp, end, spec)) { if(literal.size() != 1) { begin = prev; literal.erase(boost::prior(literal.end())); } return literal; } else switch(this->traits_.get_token(tmp, end)) { case token_escape: esc = this->parse_escape(tmp, end); if(detail::escape_char != esc.type_) return literal; literal.insert(literal.end(), esc.ch_); break; case token_literal: literal.insert(literal.end(), *tmp++); break; default: return literal; } } return literal; } /////////////////////////////////////////////////////////////////////////// // parse_quote_meta // scan ahead looking for char literals to be globbed together into a string literal /// INTERNAL ONLY template<typename FwdIter> string_type parse_quote_meta(FwdIter &begin, FwdIter end) { using namespace regex_constants; FwdIter old_begin = begin, old_end; while(end != (old_end = begin)) { switch(this->traits_.get_token(begin, end)) { case token_quote_meta_end: return string_type(old_begin, old_end); case token_escape: BOOST_XPR_ENSURE_(begin != end, error_escape, "incomplete escape sequence"); BOOST_FALLTHROUGH; case token_invalid_quantifier: case token_literal: ++begin; break; default: break; } } return string_type(old_begin, begin); } /////////////////////////////////////////////////////////////////////////////// // parse_escape /// INTERNAL ONLY template<typename FwdIter> escape_value parse_escape(FwdIter &begin, FwdIter end) { BOOST_XPR_ENSURE_(begin != end, regex_constants::error_escape, "incomplete escape sequence"); // first, check to see if this can be a backreference if(0 < this->rxtraits().value(*begin, 10)) { // Parse at most 3 decimal digits. FwdIter tmp = begin; int mark_nbr = detail::toi(tmp, end, this->rxtraits(), 10, 999); // If the resulting number could conceivably be a backref, then it is. if(10 > mark_nbr || mark_nbr <= static_cast<int>(this->mark_count_)) { begin = tmp; escape_value esc = {0, mark_nbr, 0, detail::escape_mark}; return esc; } } // Not a backreference, defer to the parse_escape helper return detail::parse_escape(begin, end, this->traits_); } bool is_upper_(char_type ch) const { return 0 != this->upper_ && this->rxtraits().isctype(ch, this->upper_); } std::size_t mark_count_; std::size_t hidden_mark_count_; CompilerTraits traits_; typename RegexTraits::char_class_type upper_; shared_ptr<detail::regex_impl<BidiIter> > self_; std::map<string_type, basic_regex<BidiIter> > rules_; }; }} // namespace boost::xpressive #endif
edlund/fabl-ng
vendor/builds/boost-1.58/include/boost/xpressive/regex_compiler.hpp
C++
gpl-3.0
27,496
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef _ASM_POWERPC_AGP_H #define _ASM_POWERPC_AGP_H #ifdef __KERNEL__ #include <asm/io.h> #define map_page_into_agp(page) #define unmap_page_from_agp(page) #define flush_agp_cache() mb() /* GATT allocation. Returns/accepts GATT kernel virtual address. */ #define alloc_gatt_pages(order) \ ((char *)__get_free_pages(GFP_KERNEL, (order))) #define free_gatt_pages(table, order) \ free_pages((unsigned long)(table), (order)) #endif /* __KERNEL__ */ #endif /* _ASM_POWERPC_AGP_H */
CSE3320/kernel-code
linux-5.8/arch/powerpc/include/asm/agp.h
C
gpl-2.0
525
<?php namespace Drupal\field\Plugin\migrate\process; use Drupal\Component\Plugin\Exception\PluginNotFoundException; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Drupal\migrate\MigrateExecutableInterface; use Drupal\migrate\Plugin\MigrationInterface; use Drupal\migrate\Plugin\migrate\process\StaticMap; use Drupal\migrate\Row; use Drupal\migrate_drupal\Plugin\MigrateCckFieldPluginManagerInterface; use Drupal\migrate_drupal\Plugin\MigrateFieldPluginManagerInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * @MigrateProcessPlugin( * id = "field_type" * ) */ class FieldType extends StaticMap implements ContainerFactoryPluginInterface { /** * The cckfield plugin manager. * * @var \Drupal\migrate_drupal\Plugin\MigrateCckFieldPluginManagerInterface */ protected $cckPluginManager; /** * The field plugin manager. * * @var \Drupal\migrate_drupal\Plugin\MigrateFieldPluginManagerInterface */ protected $fieldPluginManager; /** * The migration object. * * @var \Drupal\migrate\Plugin\MigrationInterface */ protected $migration; /** * Constructs a FieldType plugin. * * @param array $configuration * The plugin configuration. * @param string $plugin_id * The plugin ID. * @param mixed $plugin_definition * The plugin definition. * @param \Drupal\migrate_drupal\Plugin\MigrateCckFieldPluginManagerInterface $cck_plugin_manager * The cckfield plugin manager. * @param \Drupal\migrate_drupal\Plugin\MigrateFieldPluginManagerInterface $field_plugin_manager * The field plugin manager. * @param \Drupal\migrate\Plugin\MigrationInterface $migration * The migration being run. */ public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrateCckFieldPluginManagerInterface $cck_plugin_manager, MigrateFieldPluginManagerInterface $field_plugin_manager, MigrationInterface $migration = NULL) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->cckPluginManager = $cck_plugin_manager; $this->fieldPluginManager = $field_plugin_manager; $this->migration = $migration; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('plugin.manager.migrate.cckfield'), $container->get('plugin.manager.migrate.field'), $migration ); } /** * {@inheritdoc} */ public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) { $field_type = is_array($value) ? $value[0] : $value; try { $plugin_id = $this->fieldPluginManager->getPluginIdFromFieldType($field_type, [], $this->migration); return $this->fieldPluginManager->createInstance($plugin_id, [], $this->migration)->getFieldType($row); } catch (PluginNotFoundException $e) { try { $plugin_id = $this->cckPluginManager->getPluginIdFromFieldType($field_type, [], $this->migration); return $this->cckPluginManager->createInstance($plugin_id, [], $this->migration)->getFieldType($row); } catch (PluginNotFoundException $e) { return parent::transform($value, $migrate_executable, $row, $destination_property); } } } }
JeramyK/training
web/core/modules/field/src/Plugin/migrate/process/FieldType.php
PHP
gpl-2.0
3,485
<!DOCTYPE html> <!-- DO NOT EDIT! This test has been generated by tools/gentest.py. --> <title>Canvas test: 2d.fillStyle.parse.invalid.name-3</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/canvas-tests.js"></script> <link rel="stylesheet" href="/common/canvas-tests.css"> <body class="show_output"> <h1>2d.fillStyle.parse.invalid.name-3</h1> <p class="desc"></p> <p class="output">Actual output:</p> <canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas> <p class="output expectedtext">Expected output:<p><img src="/images/green-100x50.png" class="output expected" id="expected" alt=""> <ul id="d"></ul> <script> var t = async_test(""); _addTest(function(canvas, ctx) { ctx.fillStyle = '#0f0'; try { ctx.fillStyle = 'red blue'; } catch (e) { } // this shouldn't throw, but it shouldn't matter here if it does ctx.fillRect(0, 0, 100, 50); _assertPixel(canvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255"); }); </script>
cr/fxos-certsuite
web-platform-tests/tests/2dcontext/fill-and-stroke-styles/2d.fillStyle.parse.invalid.name-3.html
HTML
mpl-2.0
1,070
define( "dojo/cldr/nls/hu/currency", //begin v1.x content { "HKD_displayName": "hongkongi dollár", "CHF_displayName": "svájci frank", "JPY_symbol": "¥", "CAD_displayName": "kanadai dollár", "HKD_symbol": "HKD", "CNY_displayName": "Kínai jüan renminbi", "USD_symbol": "$", "AUD_displayName": "ausztrál dollár", "JPY_displayName": "japán jen", "CAD_symbol": "CAD", "USD_displayName": "USA-dollár", "EUR_symbol": "EUR", "CNY_symbol": "CNY", "GBP_displayName": "brit font sterling", "GBP_symbol": "GBP", "AUD_symbol": "AUD", "EUR_displayName": "euró" } //end v1.x content );
Caspar12/zh.sw
zh.web.site.admin/src/main/resources/static/js/dojo/dojo/cldr/nls/hu/currency.js.uncompressed.js
JavaScript
apache-2.0
598
/* * Common Block IO controller cgroup interface * * Based on ideas and code from CFQ, CFS and BFQ: * Copyright (C) 2003 Jens Axboe <[email protected]> * * Copyright (C) 2008 Fabio Checconi <[email protected]> * Paolo Valente <[email protected]> * * Copyright (C) 2009 Vivek Goyal <[email protected]> * Nauman Rafique <[email protected]> */ #include <linux/ioprio.h> #include <linux/seq_file.h> #include <linux/kdev_t.h> #include <linux/module.h> #include <linux/err.h> #include <linux/blkdev.h> #include <linux/slab.h> #include "blk-cgroup.h" #include <linux/genhd.h> #define MAX_KEY_LEN 100 static DEFINE_SPINLOCK(blkio_list_lock); static LIST_HEAD(blkio_list); struct blkio_cgroup blkio_root_cgroup = { .weight = 2*BLKIO_WEIGHT_DEFAULT }; EXPORT_SYMBOL_GPL(blkio_root_cgroup); static struct cgroup_subsys_state *blkiocg_create(struct cgroup_subsys *, struct cgroup *); static int blkiocg_can_attach(struct cgroup_subsys *, struct cgroup *, struct task_struct *, bool); static void blkiocg_attach(struct cgroup_subsys *, struct cgroup *, struct cgroup *, struct task_struct *, bool); static void blkiocg_destroy(struct cgroup_subsys *, struct cgroup *); static int blkiocg_populate(struct cgroup_subsys *, struct cgroup *); struct cgroup_subsys blkio_subsys = { .name = "blkio", .create = blkiocg_create, .can_attach = blkiocg_can_attach, .attach = blkiocg_attach, .destroy = blkiocg_destroy, .populate = blkiocg_populate, #ifdef CONFIG_BLK_CGROUP /* note: blkio_subsys_id is otherwise defined in blk-cgroup.h */ .subsys_id = blkio_subsys_id, #endif .use_id = 1, .module = THIS_MODULE, }; EXPORT_SYMBOL_GPL(blkio_subsys); static inline void blkio_policy_insert_node(struct blkio_cgroup *blkcg, struct blkio_policy_node *pn) { list_add(&pn->node, &blkcg->policy_list); } /* Must be called with blkcg->lock held */ static inline void blkio_policy_delete_node(struct blkio_policy_node *pn) { list_del(&pn->node); } /* Must be called with blkcg->lock held */ static struct blkio_policy_node * blkio_policy_search_node(const struct blkio_cgroup *blkcg, dev_t dev) { struct blkio_policy_node *pn; list_for_each_entry(pn, &blkcg->policy_list, node) { if (pn->dev == dev) return pn; } return NULL; } struct blkio_cgroup *cgroup_to_blkio_cgroup(struct cgroup *cgroup) { return container_of(cgroup_subsys_state(cgroup, blkio_subsys_id), struct blkio_cgroup, css); } EXPORT_SYMBOL_GPL(cgroup_to_blkio_cgroup); /* * Add to the appropriate stat variable depending on the request type. * This should be called with the blkg->stats_lock held. */ static void blkio_add_stat(uint64_t *stat, uint64_t add, bool direction, bool sync) { if (direction) stat[BLKIO_STAT_WRITE] += add; else stat[BLKIO_STAT_READ] += add; if (sync) stat[BLKIO_STAT_SYNC] += add; else stat[BLKIO_STAT_ASYNC] += add; } /* * Decrements the appropriate stat variable if non-zero depending on the * request type. Panics on value being zero. * This should be called with the blkg->stats_lock held. */ static void blkio_check_and_dec_stat(uint64_t *stat, bool direction, bool sync) { if (direction) { BUG_ON(stat[BLKIO_STAT_WRITE] == 0); stat[BLKIO_STAT_WRITE]--; } else { BUG_ON(stat[BLKIO_STAT_READ] == 0); stat[BLKIO_STAT_READ]--; } if (sync) { BUG_ON(stat[BLKIO_STAT_SYNC] == 0); stat[BLKIO_STAT_SYNC]--; } else { BUG_ON(stat[BLKIO_STAT_ASYNC] == 0); stat[BLKIO_STAT_ASYNC]--; } } #ifdef CONFIG_DEBUG_BLK_CGROUP /* This should be called with the blkg->stats_lock held. */ static void blkio_set_start_group_wait_time(struct blkio_group *blkg, struct blkio_group *curr_blkg) { if (blkio_blkg_waiting(&blkg->stats)) return; if (blkg == curr_blkg) return; blkg->stats.start_group_wait_time = sched_clock(); blkio_mark_blkg_waiting(&blkg->stats); } /* This should be called with the blkg->stats_lock held. */ static void blkio_update_group_wait_time(struct blkio_group_stats *stats) { unsigned long long now; if (!blkio_blkg_waiting(stats)) return; now = sched_clock(); if (time_after64(now, stats->start_group_wait_time)) stats->group_wait_time += now - stats->start_group_wait_time; blkio_clear_blkg_waiting(stats); } /* This should be called with the blkg->stats_lock held. */ static void blkio_end_empty_time(struct blkio_group_stats *stats) { unsigned long long now; if (!blkio_blkg_empty(stats)) return; now = sched_clock(); if (time_after64(now, stats->start_empty_time)) stats->empty_time += now - stats->start_empty_time; blkio_clear_blkg_empty(stats); } void blkiocg_update_set_idle_time_stats(struct blkio_group *blkg) { unsigned long flags; spin_lock_irqsave(&blkg->stats_lock, flags); BUG_ON(blkio_blkg_idling(&blkg->stats)); blkg->stats.start_idle_time = sched_clock(); blkio_mark_blkg_idling(&blkg->stats); spin_unlock_irqrestore(&blkg->stats_lock, flags); } EXPORT_SYMBOL_GPL(blkiocg_update_set_idle_time_stats); void blkiocg_update_idle_time_stats(struct blkio_group *blkg) { unsigned long flags; unsigned long long now; struct blkio_group_stats *stats; spin_lock_irqsave(&blkg->stats_lock, flags); stats = &blkg->stats; if (blkio_blkg_idling(stats)) { now = sched_clock(); if (time_after64(now, stats->start_idle_time)) stats->idle_time += now - stats->start_idle_time; blkio_clear_blkg_idling(stats); } spin_unlock_irqrestore(&blkg->stats_lock, flags); } EXPORT_SYMBOL_GPL(blkiocg_update_idle_time_stats); void blkiocg_update_avg_queue_size_stats(struct blkio_group *blkg) { unsigned long flags; struct blkio_group_stats *stats; spin_lock_irqsave(&blkg->stats_lock, flags); stats = &blkg->stats; stats->avg_queue_size_sum += stats->stat_arr[BLKIO_STAT_QUEUED][BLKIO_STAT_READ] + stats->stat_arr[BLKIO_STAT_QUEUED][BLKIO_STAT_WRITE]; stats->avg_queue_size_samples++; blkio_update_group_wait_time(stats); spin_unlock_irqrestore(&blkg->stats_lock, flags); } EXPORT_SYMBOL_GPL(blkiocg_update_avg_queue_size_stats); void blkiocg_set_start_empty_time(struct blkio_group *blkg) { unsigned long flags; struct blkio_group_stats *stats; spin_lock_irqsave(&blkg->stats_lock, flags); stats = &blkg->stats; if (stats->stat_arr[BLKIO_STAT_QUEUED][BLKIO_STAT_READ] || stats->stat_arr[BLKIO_STAT_QUEUED][BLKIO_STAT_WRITE]) { spin_unlock_irqrestore(&blkg->stats_lock, flags); return; } /* * group is already marked empty. This can happen if cfqq got new * request in parent group and moved to this group while being added * to service tree. Just ignore the event and move on. */ if(blkio_blkg_empty(stats)) { spin_unlock_irqrestore(&blkg->stats_lock, flags); return; } stats->start_empty_time = sched_clock(); blkio_mark_blkg_empty(stats); spin_unlock_irqrestore(&blkg->stats_lock, flags); } EXPORT_SYMBOL_GPL(blkiocg_set_start_empty_time); void blkiocg_update_dequeue_stats(struct blkio_group *blkg, unsigned long dequeue) { blkg->stats.dequeue += dequeue; } EXPORT_SYMBOL_GPL(blkiocg_update_dequeue_stats); #else static inline void blkio_set_start_group_wait_time(struct blkio_group *blkg, struct blkio_group *curr_blkg) {} static inline void blkio_end_empty_time(struct blkio_group_stats *stats) {} #endif void blkiocg_update_io_add_stats(struct blkio_group *blkg, struct blkio_group *curr_blkg, bool direction, bool sync) { unsigned long flags; spin_lock_irqsave(&blkg->stats_lock, flags); blkio_add_stat(blkg->stats.stat_arr[BLKIO_STAT_QUEUED], 1, direction, sync); blkio_end_empty_time(&blkg->stats); blkio_set_start_group_wait_time(blkg, curr_blkg); spin_unlock_irqrestore(&blkg->stats_lock, flags); } EXPORT_SYMBOL_GPL(blkiocg_update_io_add_stats); void blkiocg_update_io_remove_stats(struct blkio_group *blkg, bool direction, bool sync) { unsigned long flags; spin_lock_irqsave(&blkg->stats_lock, flags); blkio_check_and_dec_stat(blkg->stats.stat_arr[BLKIO_STAT_QUEUED], direction, sync); spin_unlock_irqrestore(&blkg->stats_lock, flags); } EXPORT_SYMBOL_GPL(blkiocg_update_io_remove_stats); void blkiocg_update_timeslice_used(struct blkio_group *blkg, unsigned long time) { unsigned long flags; spin_lock_irqsave(&blkg->stats_lock, flags); blkg->stats.time += time; spin_unlock_irqrestore(&blkg->stats_lock, flags); } EXPORT_SYMBOL_GPL(blkiocg_update_timeslice_used); void blkiocg_update_dispatch_stats(struct blkio_group *blkg, uint64_t bytes, bool direction, bool sync) { struct blkio_group_stats *stats; unsigned long flags; spin_lock_irqsave(&blkg->stats_lock, flags); stats = &blkg->stats; stats->sectors += bytes >> 9; blkio_add_stat(stats->stat_arr[BLKIO_STAT_SERVICED], 1, direction, sync); blkio_add_stat(stats->stat_arr[BLKIO_STAT_SERVICE_BYTES], bytes, direction, sync); spin_unlock_irqrestore(&blkg->stats_lock, flags); } EXPORT_SYMBOL_GPL(blkiocg_update_dispatch_stats); void blkiocg_update_completion_stats(struct blkio_group *blkg, uint64_t start_time, uint64_t io_start_time, bool direction, bool sync) { struct blkio_group_stats *stats; unsigned long flags; unsigned long long now = sched_clock(); spin_lock_irqsave(&blkg->stats_lock, flags); stats = &blkg->stats; if (time_after64(now, io_start_time)) blkio_add_stat(stats->stat_arr[BLKIO_STAT_SERVICE_TIME], now - io_start_time, direction, sync); if (time_after64(io_start_time, start_time)) blkio_add_stat(stats->stat_arr[BLKIO_STAT_WAIT_TIME], io_start_time - start_time, direction, sync); spin_unlock_irqrestore(&blkg->stats_lock, flags); } EXPORT_SYMBOL_GPL(blkiocg_update_completion_stats); void blkiocg_update_io_merged_stats(struct blkio_group *blkg, bool direction, bool sync) { unsigned long flags; spin_lock_irqsave(&blkg->stats_lock, flags); blkio_add_stat(blkg->stats.stat_arr[BLKIO_STAT_MERGED], 1, direction, sync); spin_unlock_irqrestore(&blkg->stats_lock, flags); } EXPORT_SYMBOL_GPL(blkiocg_update_io_merged_stats); void blkiocg_add_blkio_group(struct blkio_cgroup *blkcg, struct blkio_group *blkg, void *key, dev_t dev) { unsigned long flags; spin_lock_irqsave(&blkcg->lock, flags); spin_lock_init(&blkg->stats_lock); rcu_assign_pointer(blkg->key, key); blkg->blkcg_id = css_id(&blkcg->css); hlist_add_head_rcu(&blkg->blkcg_node, &blkcg->blkg_list); spin_unlock_irqrestore(&blkcg->lock, flags); /* Need to take css reference ? */ cgroup_path(blkcg->css.cgroup, blkg->path, sizeof(blkg->path)); blkg->dev = dev; } EXPORT_SYMBOL_GPL(blkiocg_add_blkio_group); static void __blkiocg_del_blkio_group(struct blkio_group *blkg) { hlist_del_init_rcu(&blkg->blkcg_node); blkg->blkcg_id = 0; } /* * returns 0 if blkio_group was still on cgroup list. Otherwise returns 1 * indicating that blk_group was unhashed by the time we got to it. */ int blkiocg_del_blkio_group(struct blkio_group *blkg) { struct blkio_cgroup *blkcg; unsigned long flags; struct cgroup_subsys_state *css; int ret = 1; rcu_read_lock(); css = css_lookup(&blkio_subsys, blkg->blkcg_id); if (css) { blkcg = container_of(css, struct blkio_cgroup, css); spin_lock_irqsave(&blkcg->lock, flags); if (!hlist_unhashed(&blkg->blkcg_node)) { __blkiocg_del_blkio_group(blkg); ret = 0; } spin_unlock_irqrestore(&blkcg->lock, flags); } rcu_read_unlock(); return ret; } EXPORT_SYMBOL_GPL(blkiocg_del_blkio_group); /* called under rcu_read_lock(). */ struct blkio_group *blkiocg_lookup_group(struct blkio_cgroup *blkcg, void *key) { struct blkio_group *blkg; struct hlist_node *n; void *__key; hlist_for_each_entry_rcu(blkg, n, &blkcg->blkg_list, blkcg_node) { __key = blkg->key; if (__key == key) return blkg; } return NULL; } EXPORT_SYMBOL_GPL(blkiocg_lookup_group); #define SHOW_FUNCTION(__VAR) \ static u64 blkiocg_##__VAR##_read(struct cgroup *cgroup, \ struct cftype *cftype) \ { \ struct blkio_cgroup *blkcg; \ \ blkcg = cgroup_to_blkio_cgroup(cgroup); \ return (u64)blkcg->__VAR; \ } SHOW_FUNCTION(weight); #undef SHOW_FUNCTION static int blkiocg_weight_write(struct cgroup *cgroup, struct cftype *cftype, u64 val) { struct blkio_cgroup *blkcg; struct blkio_group *blkg; struct hlist_node *n; struct blkio_policy_type *blkiop; struct blkio_policy_node *pn; if (val < BLKIO_WEIGHT_MIN || val > BLKIO_WEIGHT_MAX) return -EINVAL; blkcg = cgroup_to_blkio_cgroup(cgroup); spin_lock(&blkio_list_lock); spin_lock_irq(&blkcg->lock); blkcg->weight = (unsigned int)val; hlist_for_each_entry(blkg, n, &blkcg->blkg_list, blkcg_node) { pn = blkio_policy_search_node(blkcg, blkg->dev); if (pn) continue; list_for_each_entry(blkiop, &blkio_list, list) blkiop->ops.blkio_update_group_weight_fn(blkg, blkcg->weight); } spin_unlock_irq(&blkcg->lock); spin_unlock(&blkio_list_lock); return 0; } static int blkiocg_reset_stats(struct cgroup *cgroup, struct cftype *cftype, u64 val) { struct blkio_cgroup *blkcg; struct blkio_group *blkg; struct blkio_group_stats *stats; struct hlist_node *n; uint64_t queued[BLKIO_STAT_TOTAL]; int i; #ifdef CONFIG_DEBUG_BLK_CGROUP bool idling, waiting, empty; unsigned long long now = sched_clock(); #endif blkcg = cgroup_to_blkio_cgroup(cgroup); spin_lock_irq(&blkcg->lock); hlist_for_each_entry(blkg, n, &blkcg->blkg_list, blkcg_node) { spin_lock(&blkg->stats_lock); stats = &blkg->stats; #ifdef CONFIG_DEBUG_BLK_CGROUP idling = blkio_blkg_idling(stats); waiting = blkio_blkg_waiting(stats); empty = blkio_blkg_empty(stats); #endif for (i = 0; i < BLKIO_STAT_TOTAL; i++) queued[i] = stats->stat_arr[BLKIO_STAT_QUEUED][i]; memset(stats, 0, sizeof(struct blkio_group_stats)); for (i = 0; i < BLKIO_STAT_TOTAL; i++) stats->stat_arr[BLKIO_STAT_QUEUED][i] = queued[i]; #ifdef CONFIG_DEBUG_BLK_CGROUP if (idling) { blkio_mark_blkg_idling(stats); stats->start_idle_time = now; } if (waiting) { blkio_mark_blkg_waiting(stats); stats->start_group_wait_time = now; } if (empty) { blkio_mark_blkg_empty(stats); stats->start_empty_time = now; } #endif spin_unlock(&blkg->stats_lock); } spin_unlock_irq(&blkcg->lock); return 0; } static void blkio_get_key_name(enum stat_sub_type type, dev_t dev, char *str, int chars_left, bool diskname_only) { snprintf(str, chars_left, "%d:%d", MAJOR(dev), MINOR(dev)); chars_left -= strlen(str); if (chars_left <= 0) { printk(KERN_WARNING "Possibly incorrect cgroup stat display format"); return; } if (diskname_only) return; switch (type) { case BLKIO_STAT_READ: strlcat(str, " Read", chars_left); break; case BLKIO_STAT_WRITE: strlcat(str, " Write", chars_left); break; case BLKIO_STAT_SYNC: strlcat(str, " Sync", chars_left); break; case BLKIO_STAT_ASYNC: strlcat(str, " Async", chars_left); break; case BLKIO_STAT_TOTAL: strlcat(str, " Total", chars_left); break; default: strlcat(str, " Invalid", chars_left); } } static uint64_t blkio_fill_stat(char *str, int chars_left, uint64_t val, struct cgroup_map_cb *cb, dev_t dev) { blkio_get_key_name(0, dev, str, chars_left, true); cb->fill(cb, str, val); return val; } /* This should be called with blkg->stats_lock held */ static uint64_t blkio_get_stat(struct blkio_group *blkg, struct cgroup_map_cb *cb, dev_t dev, enum stat_type type) { uint64_t disk_total; char key_str[MAX_KEY_LEN]; enum stat_sub_type sub_type; if (type == BLKIO_STAT_TIME) return blkio_fill_stat(key_str, MAX_KEY_LEN - 1, blkg->stats.time, cb, dev); if (type == BLKIO_STAT_SECTORS) return blkio_fill_stat(key_str, MAX_KEY_LEN - 1, blkg->stats.sectors, cb, dev); #ifdef CONFIG_DEBUG_BLK_CGROUP if (type == BLKIO_STAT_AVG_QUEUE_SIZE) { uint64_t sum = blkg->stats.avg_queue_size_sum; uint64_t samples = blkg->stats.avg_queue_size_samples; if (samples) do_div(sum, samples); else sum = 0; return blkio_fill_stat(key_str, MAX_KEY_LEN - 1, sum, cb, dev); } if (type == BLKIO_STAT_GROUP_WAIT_TIME) return blkio_fill_stat(key_str, MAX_KEY_LEN - 1, blkg->stats.group_wait_time, cb, dev); if (type == BLKIO_STAT_IDLE_TIME) return blkio_fill_stat(key_str, MAX_KEY_LEN - 1, blkg->stats.idle_time, cb, dev); if (type == BLKIO_STAT_EMPTY_TIME) return blkio_fill_stat(key_str, MAX_KEY_LEN - 1, blkg->stats.empty_time, cb, dev); if (type == BLKIO_STAT_DEQUEUE) return blkio_fill_stat(key_str, MAX_KEY_LEN - 1, blkg->stats.dequeue, cb, dev); #endif for (sub_type = BLKIO_STAT_READ; sub_type < BLKIO_STAT_TOTAL; sub_type++) { blkio_get_key_name(sub_type, dev, key_str, MAX_KEY_LEN, false); cb->fill(cb, key_str, blkg->stats.stat_arr[type][sub_type]); } disk_total = blkg->stats.stat_arr[type][BLKIO_STAT_READ] + blkg->stats.stat_arr[type][BLKIO_STAT_WRITE]; blkio_get_key_name(BLKIO_STAT_TOTAL, dev, key_str, MAX_KEY_LEN, false); cb->fill(cb, key_str, disk_total); return disk_total; } #define SHOW_FUNCTION_PER_GROUP(__VAR, type, show_total) \ static int blkiocg_##__VAR##_read(struct cgroup *cgroup, \ struct cftype *cftype, struct cgroup_map_cb *cb) \ { \ struct blkio_cgroup *blkcg; \ struct blkio_group *blkg; \ struct hlist_node *n; \ uint64_t cgroup_total = 0; \ \ if (!cgroup_lock_live_group(cgroup)) \ return -ENODEV; \ \ blkcg = cgroup_to_blkio_cgroup(cgroup); \ rcu_read_lock(); \ hlist_for_each_entry_rcu(blkg, n, &blkcg->blkg_list, blkcg_node) {\ if (blkg->dev) { \ spin_lock_irq(&blkg->stats_lock); \ cgroup_total += blkio_get_stat(blkg, cb, \ blkg->dev, type); \ spin_unlock_irq(&blkg->stats_lock); \ } \ } \ if (show_total) \ cb->fill(cb, "Total", cgroup_total); \ rcu_read_unlock(); \ cgroup_unlock(); \ return 0; \ } SHOW_FUNCTION_PER_GROUP(time, BLKIO_STAT_TIME, 0); SHOW_FUNCTION_PER_GROUP(sectors, BLKIO_STAT_SECTORS, 0); SHOW_FUNCTION_PER_GROUP(io_service_bytes, BLKIO_STAT_SERVICE_BYTES, 1); SHOW_FUNCTION_PER_GROUP(io_serviced, BLKIO_STAT_SERVICED, 1); SHOW_FUNCTION_PER_GROUP(io_service_time, BLKIO_STAT_SERVICE_TIME, 1); SHOW_FUNCTION_PER_GROUP(io_wait_time, BLKIO_STAT_WAIT_TIME, 1); SHOW_FUNCTION_PER_GROUP(io_merged, BLKIO_STAT_MERGED, 1); SHOW_FUNCTION_PER_GROUP(io_queued, BLKIO_STAT_QUEUED, 1); #ifdef CONFIG_DEBUG_BLK_CGROUP SHOW_FUNCTION_PER_GROUP(dequeue, BLKIO_STAT_DEQUEUE, 0); SHOW_FUNCTION_PER_GROUP(avg_queue_size, BLKIO_STAT_AVG_QUEUE_SIZE, 0); SHOW_FUNCTION_PER_GROUP(group_wait_time, BLKIO_STAT_GROUP_WAIT_TIME, 0); SHOW_FUNCTION_PER_GROUP(idle_time, BLKIO_STAT_IDLE_TIME, 0); SHOW_FUNCTION_PER_GROUP(empty_time, BLKIO_STAT_EMPTY_TIME, 0); #endif #undef SHOW_FUNCTION_PER_GROUP static int blkio_check_dev_num(dev_t dev) { int part = 0; struct gendisk *disk; disk = get_gendisk(dev, &part); if (!disk || part) return -ENODEV; return 0; } static int blkio_policy_parse_and_set(char *buf, struct blkio_policy_node *newpn) { char *s[4], *p, *major_s = NULL, *minor_s = NULL; int ret; unsigned long major, minor, temp; int i = 0; dev_t dev; memset(s, 0, sizeof(s)); while ((p = strsep(&buf, " ")) != NULL) { if (!*p) continue; s[i++] = p; /* Prevent from inputing too many things */ if (i == 3) break; } if (i != 2) return -EINVAL; p = strsep(&s[0], ":"); if (p != NULL) major_s = p; else return -EINVAL; minor_s = s[0]; if (!minor_s) return -EINVAL; ret = strict_strtoul(major_s, 10, &major); if (ret) return -EINVAL; ret = strict_strtoul(minor_s, 10, &minor); if (ret) return -EINVAL; dev = MKDEV(major, minor); ret = blkio_check_dev_num(dev); if (ret) return ret; newpn->dev = dev; if (s[1] == NULL) return -EINVAL; ret = strict_strtoul(s[1], 10, &temp); if (ret || (temp < BLKIO_WEIGHT_MIN && temp > 0) || temp > BLKIO_WEIGHT_MAX) return -EINVAL; newpn->weight = temp; return 0; } unsigned int blkcg_get_weight(struct blkio_cgroup *blkcg, dev_t dev) { struct blkio_policy_node *pn; pn = blkio_policy_search_node(blkcg, dev); if (pn) return pn->weight; else return blkcg->weight; } EXPORT_SYMBOL_GPL(blkcg_get_weight); static int blkiocg_weight_device_write(struct cgroup *cgrp, struct cftype *cft, const char *buffer) { int ret = 0; char *buf; struct blkio_policy_node *newpn, *pn; struct blkio_cgroup *blkcg; struct blkio_group *blkg; int keep_newpn = 0; struct hlist_node *n; struct blkio_policy_type *blkiop; buf = kstrdup(buffer, GFP_KERNEL); if (!buf) return -ENOMEM; newpn = kzalloc(sizeof(*newpn), GFP_KERNEL); if (!newpn) { ret = -ENOMEM; goto free_buf; } ret = blkio_policy_parse_and_set(buf, newpn); if (ret) goto free_newpn; blkcg = cgroup_to_blkio_cgroup(cgrp); spin_lock_irq(&blkcg->lock); pn = blkio_policy_search_node(blkcg, newpn->dev); if (!pn) { if (newpn->weight != 0) { blkio_policy_insert_node(blkcg, newpn); keep_newpn = 1; } spin_unlock_irq(&blkcg->lock); goto update_io_group; } if (newpn->weight == 0) { /* weight == 0 means deleteing a specific weight */ blkio_policy_delete_node(pn); spin_unlock_irq(&blkcg->lock); goto update_io_group; } spin_unlock_irq(&blkcg->lock); pn->weight = newpn->weight; update_io_group: /* update weight for each cfqg */ spin_lock(&blkio_list_lock); spin_lock_irq(&blkcg->lock); hlist_for_each_entry(blkg, n, &blkcg->blkg_list, blkcg_node) { if (newpn->dev == blkg->dev) { list_for_each_entry(blkiop, &blkio_list, list) blkiop->ops.blkio_update_group_weight_fn(blkg, newpn->weight ? newpn->weight : blkcg->weight); } } spin_unlock_irq(&blkcg->lock); spin_unlock(&blkio_list_lock); free_newpn: if (!keep_newpn) kfree(newpn); free_buf: kfree(buf); return ret; } static int blkiocg_weight_device_read(struct cgroup *cgrp, struct cftype *cft, struct seq_file *m) { struct blkio_cgroup *blkcg; struct blkio_policy_node *pn; seq_printf(m, "dev\tweight\n"); blkcg = cgroup_to_blkio_cgroup(cgrp); if (!list_empty(&blkcg->policy_list)) { spin_lock_irq(&blkcg->lock); list_for_each_entry(pn, &blkcg->policy_list, node) { seq_printf(m, "%u:%u\t%u\n", MAJOR(pn->dev), MINOR(pn->dev), pn->weight); } spin_unlock_irq(&blkcg->lock); } return 0; } struct cftype blkio_files[] = { { .name = "weight_device", .read_seq_string = blkiocg_weight_device_read, .write_string = blkiocg_weight_device_write, .max_write_len = 256, }, { .name = "weight", .read_u64 = blkiocg_weight_read, .write_u64 = blkiocg_weight_write, }, { .name = "time", .read_map = blkiocg_time_read, }, { .name = "sectors", .read_map = blkiocg_sectors_read, }, { .name = "io_service_bytes", .read_map = blkiocg_io_service_bytes_read, }, { .name = "io_serviced", .read_map = blkiocg_io_serviced_read, }, { .name = "io_service_time", .read_map = blkiocg_io_service_time_read, }, { .name = "io_wait_time", .read_map = blkiocg_io_wait_time_read, }, { .name = "io_merged", .read_map = blkiocg_io_merged_read, }, { .name = "io_queued", .read_map = blkiocg_io_queued_read, }, { .name = "reset_stats", .write_u64 = blkiocg_reset_stats, }, #ifdef CONFIG_DEBUG_BLK_CGROUP { .name = "avg_queue_size", .read_map = blkiocg_avg_queue_size_read, }, { .name = "group_wait_time", .read_map = blkiocg_group_wait_time_read, }, { .name = "idle_time", .read_map = blkiocg_idle_time_read, }, { .name = "empty_time", .read_map = blkiocg_empty_time_read, }, { .name = "dequeue", .read_map = blkiocg_dequeue_read, }, #endif }; static int blkiocg_populate(struct cgroup_subsys *subsys, struct cgroup *cgroup) { return cgroup_add_files(cgroup, subsys, blkio_files, ARRAY_SIZE(blkio_files)); } static void blkiocg_destroy(struct cgroup_subsys *subsys, struct cgroup *cgroup) { struct blkio_cgroup *blkcg = cgroup_to_blkio_cgroup(cgroup); unsigned long flags; struct blkio_group *blkg; void *key; struct blkio_policy_type *blkiop; struct blkio_policy_node *pn, *pntmp; rcu_read_lock(); do { spin_lock_irqsave(&blkcg->lock, flags); if (hlist_empty(&blkcg->blkg_list)) { spin_unlock_irqrestore(&blkcg->lock, flags); break; } blkg = hlist_entry(blkcg->blkg_list.first, struct blkio_group, blkcg_node); key = rcu_dereference(blkg->key); __blkiocg_del_blkio_group(blkg); spin_unlock_irqrestore(&blkcg->lock, flags); /* * This blkio_group is being unlinked as associated cgroup is * going away. Let all the IO controlling policies know about * this event. Currently this is static call to one io * controlling policy. Once we have more policies in place, we * need some dynamic registration of callback function. */ spin_lock(&blkio_list_lock); list_for_each_entry(blkiop, &blkio_list, list) blkiop->ops.blkio_unlink_group_fn(key, blkg); spin_unlock(&blkio_list_lock); } while (1); list_for_each_entry_safe(pn, pntmp, &blkcg->policy_list, node) { blkio_policy_delete_node(pn); kfree(pn); } free_css_id(&blkio_subsys, &blkcg->css); rcu_read_unlock(); if (blkcg != &blkio_root_cgroup) kfree(blkcg); } static struct cgroup_subsys_state * blkiocg_create(struct cgroup_subsys *subsys, struct cgroup *cgroup) { struct blkio_cgroup *blkcg; struct cgroup *parent = cgroup->parent; if (!parent) { blkcg = &blkio_root_cgroup; goto done; } /* Currently we do not support hierarchy deeper than two level (0,1) */ if (parent != cgroup->top_cgroup) return ERR_PTR(-EINVAL); blkcg = kzalloc(sizeof(*blkcg), GFP_KERNEL); if (!blkcg) return ERR_PTR(-ENOMEM); blkcg->weight = BLKIO_WEIGHT_DEFAULT; done: spin_lock_init(&blkcg->lock); INIT_HLIST_HEAD(&blkcg->blkg_list); INIT_LIST_HEAD(&blkcg->policy_list); return &blkcg->css; } /* * We cannot support shared io contexts, as we have no mean to support * two tasks with the same ioc in two different groups without major rework * of the main cic data structures. For now we allow a task to change * its cgroup only if it's the only owner of its ioc. */ static int blkiocg_can_attach(struct cgroup_subsys *subsys, struct cgroup *cgroup, struct task_struct *tsk, bool threadgroup) { struct io_context *ioc; int ret = 0; /* task_lock() is needed to avoid races with exit_io_context() */ task_lock(tsk); ioc = tsk->io_context; if (ioc && atomic_read(&ioc->nr_tasks) > 1) ret = -EINVAL; task_unlock(tsk); return ret; } static void blkiocg_attach(struct cgroup_subsys *subsys, struct cgroup *cgroup, struct cgroup *prev, struct task_struct *tsk, bool threadgroup) { struct io_context *ioc; task_lock(tsk); ioc = tsk->io_context; if (ioc) ioc->cgroup_changed = 1; task_unlock(tsk); } void blkio_policy_register(struct blkio_policy_type *blkiop) { spin_lock(&blkio_list_lock); list_add_tail(&blkiop->list, &blkio_list); spin_unlock(&blkio_list_lock); } EXPORT_SYMBOL_GPL(blkio_policy_register); void blkio_policy_unregister(struct blkio_policy_type *blkiop) { spin_lock(&blkio_list_lock); list_del_init(&blkiop->list); spin_unlock(&blkio_list_lock); } EXPORT_SYMBOL_GPL(blkio_policy_unregister); static int __init init_cgroup_blkio(void) { return cgroup_load_subsys(&blkio_subsys); } static void __exit exit_cgroup_blkio(void) { cgroup_unload_subsys(&blkio_subsys); } module_init(init_cgroup_blkio); module_exit(exit_cgroup_blkio); MODULE_LICENSE("GPL");
damageless/linux-kernel-ican-tab
trash/blk-cgroup.c
C
gpl-2.0
27,408
/* * Copyright © 2009 Intel Corporation * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #include <linux/i2c.h> #include <linux/pm_runtime.h> #include <drm/drmP.h> #include "framebuffer.h" #include "psb_drv.h" #include "psb_intel_drv.h" #include "psb_intel_reg.h" #include "gma_display.h" #include "power.h" #define MRST_LIMIT_LVDS_100L 0 #define MRST_LIMIT_LVDS_83 1 #define MRST_LIMIT_LVDS_100 2 #define MRST_LIMIT_SDVO 3 #define MRST_DOT_MIN 19750 #define MRST_DOT_MAX 120000 #define MRST_M_MIN_100L 20 #define MRST_M_MIN_100 10 #define MRST_M_MIN_83 12 #define MRST_M_MAX_100L 34 #define MRST_M_MAX_100 17 #define MRST_M_MAX_83 20 #define MRST_P1_MIN 2 #define MRST_P1_MAX_0 7 #define MRST_P1_MAX_1 8 static bool mrst_lvds_find_best_pll(const struct gma_limit_t *limit, struct drm_crtc *crtc, int target, int refclk, struct gma_clock_t *best_clock); static bool mrst_sdvo_find_best_pll(const struct gma_limit_t *limit, struct drm_crtc *crtc, int target, int refclk, struct gma_clock_t *best_clock); static const struct gma_limit_t mrst_limits[] = { { /* MRST_LIMIT_LVDS_100L */ .dot = {.min = MRST_DOT_MIN, .max = MRST_DOT_MAX}, .m = {.min = MRST_M_MIN_100L, .max = MRST_M_MAX_100L}, .p1 = {.min = MRST_P1_MIN, .max = MRST_P1_MAX_1}, .find_pll = mrst_lvds_find_best_pll, }, { /* MRST_LIMIT_LVDS_83L */ .dot = {.min = MRST_DOT_MIN, .max = MRST_DOT_MAX}, .m = {.min = MRST_M_MIN_83, .max = MRST_M_MAX_83}, .p1 = {.min = MRST_P1_MIN, .max = MRST_P1_MAX_0}, .find_pll = mrst_lvds_find_best_pll, }, { /* MRST_LIMIT_LVDS_100 */ .dot = {.min = MRST_DOT_MIN, .max = MRST_DOT_MAX}, .m = {.min = MRST_M_MIN_100, .max = MRST_M_MAX_100}, .p1 = {.min = MRST_P1_MIN, .max = MRST_P1_MAX_1}, .find_pll = mrst_lvds_find_best_pll, }, { /* MRST_LIMIT_SDVO */ .vco = {.min = 1400000, .max = 2800000}, .n = {.min = 3, .max = 7}, .m = {.min = 80, .max = 137}, .p1 = {.min = 1, .max = 2}, .p2 = {.dot_limit = 200000, .p2_slow = 10, .p2_fast = 10}, .find_pll = mrst_sdvo_find_best_pll, }, }; #define MRST_M_MIN 10 static const u32 oaktrail_m_converts[] = { 0x2B, 0x15, 0x2A, 0x35, 0x1A, 0x0D, 0x26, 0x33, 0x19, 0x2C, 0x36, 0x3B, 0x1D, 0x2E, 0x37, 0x1B, 0x2D, 0x16, 0x0B, 0x25, 0x12, 0x09, 0x24, 0x32, 0x39, 0x1c, }; static const struct gma_limit_t *mrst_limit(struct drm_crtc *crtc, int refclk) { const struct gma_limit_t *limit = NULL; struct drm_device *dev = crtc->dev; struct drm_psb_private *dev_priv = dev->dev_private; if (gma_pipe_has_type(crtc, INTEL_OUTPUT_LVDS) || gma_pipe_has_type(crtc, INTEL_OUTPUT_MIPI)) { switch (dev_priv->core_freq) { case 100: limit = &mrst_limits[MRST_LIMIT_LVDS_100L]; break; case 166: limit = &mrst_limits[MRST_LIMIT_LVDS_83]; break; case 200: limit = &mrst_limits[MRST_LIMIT_LVDS_100]; break; } } else if (gma_pipe_has_type(crtc, INTEL_OUTPUT_SDVO)) { limit = &mrst_limits[MRST_LIMIT_SDVO]; } else { limit = NULL; dev_err(dev->dev, "mrst_limit Wrong display type.\n"); } return limit; } /** Derive the pixel clock for the given refclk and divisors for 8xx chips. */ static void mrst_lvds_clock(int refclk, struct gma_clock_t *clock) { clock->dot = (refclk * clock->m) / (14 * clock->p1); } static void mrst_print_pll(struct gma_clock_t *clock) { DRM_DEBUG_DRIVER("dotclock=%d, m=%d, m1=%d, m2=%d, n=%d, p1=%d, p2=%d\n", clock->dot, clock->m, clock->m1, clock->m2, clock->n, clock->p1, clock->p2); } static bool mrst_sdvo_find_best_pll(const struct gma_limit_t *limit, struct drm_crtc *crtc, int target, int refclk, struct gma_clock_t *best_clock) { struct gma_clock_t clock; u32 target_vco, actual_freq; s32 freq_error, min_error = 100000; memset(best_clock, 0, sizeof(*best_clock)); for (clock.m = limit->m.min; clock.m <= limit->m.max; clock.m++) { for (clock.n = limit->n.min; clock.n <= limit->n.max; clock.n++) { for (clock.p1 = limit->p1.min; clock.p1 <= limit->p1.max; clock.p1++) { /* p2 value always stored in p2_slow on SDVO */ clock.p = clock.p1 * limit->p2.p2_slow; target_vco = target * clock.p; /* VCO will increase at this point so break */ if (target_vco > limit->vco.max) break; if (target_vco < limit->vco.min) continue; actual_freq = (refclk * clock.m) / (clock.n * clock.p); freq_error = 10000 - ((target * 10000) / actual_freq); if (freq_error < -min_error) { /* freq_error will start to decrease at this point so break */ break; } if (freq_error < 0) freq_error = -freq_error; if (freq_error < min_error) { min_error = freq_error; *best_clock = clock; } } } if (min_error == 0) break; } return min_error == 0; } /** * Returns a set of divisors for the desired target clock with the given refclk, * or FALSE. Divisor values are the actual divisors for */ static bool mrst_lvds_find_best_pll(const struct gma_limit_t *limit, struct drm_crtc *crtc, int target, int refclk, struct gma_clock_t *best_clock) { struct gma_clock_t clock; int err = target; memset(best_clock, 0, sizeof(*best_clock)); for (clock.m = limit->m.min; clock.m <= limit->m.max; clock.m++) { for (clock.p1 = limit->p1.min; clock.p1 <= limit->p1.max; clock.p1++) { int this_err; mrst_lvds_clock(refclk, &clock); this_err = abs(clock.dot - target); if (this_err < err) { *best_clock = clock; err = this_err; } } } return err != target; } /** * Sets the power management mode of the pipe and plane. * * This code should probably grow support for turning the cursor off and back * on appropriately at the same time as we're turning the pipe off/on. */ static void oaktrail_crtc_dpms(struct drm_crtc *crtc, int mode) { struct drm_device *dev = crtc->dev; struct drm_psb_private *dev_priv = dev->dev_private; struct gma_crtc *gma_crtc = to_gma_crtc(crtc); int pipe = gma_crtc->pipe; const struct psb_offset *map = &dev_priv->regmap[pipe]; u32 temp; int i; int need_aux = gma_pipe_has_type(crtc, INTEL_OUTPUT_SDVO) ? 1 : 0; if (gma_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) { oaktrail_crtc_hdmi_dpms(crtc, mode); return; } if (!gma_power_begin(dev, true)) return; /* XXX: When our outputs are all unaware of DPMS modes other than off * and on, we should map those modes to DRM_MODE_DPMS_OFF in the CRTC. */ switch (mode) { case DRM_MODE_DPMS_ON: case DRM_MODE_DPMS_STANDBY: case DRM_MODE_DPMS_SUSPEND: for (i = 0; i <= need_aux; i++) { /* Enable the DPLL */ temp = REG_READ_WITH_AUX(map->dpll, i); if ((temp & DPLL_VCO_ENABLE) == 0) { REG_WRITE_WITH_AUX(map->dpll, temp, i); REG_READ_WITH_AUX(map->dpll, i); /* Wait for the clocks to stabilize. */ udelay(150); REG_WRITE_WITH_AUX(map->dpll, temp | DPLL_VCO_ENABLE, i); REG_READ_WITH_AUX(map->dpll, i); /* Wait for the clocks to stabilize. */ udelay(150); REG_WRITE_WITH_AUX(map->dpll, temp | DPLL_VCO_ENABLE, i); REG_READ_WITH_AUX(map->dpll, i); /* Wait for the clocks to stabilize. */ udelay(150); } /* Enable the pipe */ temp = REG_READ_WITH_AUX(map->conf, i); if ((temp & PIPEACONF_ENABLE) == 0) { REG_WRITE_WITH_AUX(map->conf, temp | PIPEACONF_ENABLE, i); } /* Enable the plane */ temp = REG_READ_WITH_AUX(map->cntr, i); if ((temp & DISPLAY_PLANE_ENABLE) == 0) { REG_WRITE_WITH_AUX(map->cntr, temp | DISPLAY_PLANE_ENABLE, i); /* Flush the plane changes */ REG_WRITE_WITH_AUX(map->base, REG_READ_WITH_AUX(map->base, i), i); } } gma_crtc_load_lut(crtc); /* Give the overlay scaler a chance to enable if it's on this pipe */ /* psb_intel_crtc_dpms_video(crtc, true); TODO */ break; case DRM_MODE_DPMS_OFF: /* Give the overlay scaler a chance to disable * if it's on this pipe */ /* psb_intel_crtc_dpms_video(crtc, FALSE); TODO */ for (i = 0; i <= need_aux; i++) { /* Disable the VGA plane that we never use */ REG_WRITE_WITH_AUX(VGACNTRL, VGA_DISP_DISABLE, i); /* Disable display plane */ temp = REG_READ_WITH_AUX(map->cntr, i); if ((temp & DISPLAY_PLANE_ENABLE) != 0) { REG_WRITE_WITH_AUX(map->cntr, temp & ~DISPLAY_PLANE_ENABLE, i); /* Flush the plane changes */ REG_WRITE_WITH_AUX(map->base, REG_READ(map->base), i); REG_READ_WITH_AUX(map->base, i); } /* Next, disable display pipes */ temp = REG_READ_WITH_AUX(map->conf, i); if ((temp & PIPEACONF_ENABLE) != 0) { REG_WRITE_WITH_AUX(map->conf, temp & ~PIPEACONF_ENABLE, i); REG_READ_WITH_AUX(map->conf, i); } /* Wait for for the pipe disable to take effect. */ gma_wait_for_vblank(dev); temp = REG_READ_WITH_AUX(map->dpll, i); if ((temp & DPLL_VCO_ENABLE) != 0) { REG_WRITE_WITH_AUX(map->dpll, temp & ~DPLL_VCO_ENABLE, i); REG_READ_WITH_AUX(map->dpll, i); } /* Wait for the clocks to turn off. */ udelay(150); } break; } /* Set FIFO Watermarks (values taken from EMGD) */ REG_WRITE(DSPARB, 0x3f80); REG_WRITE(DSPFW1, 0x3f8f0404); REG_WRITE(DSPFW2, 0x04040f04); REG_WRITE(DSPFW3, 0x0); REG_WRITE(DSPFW4, 0x04040404); REG_WRITE(DSPFW5, 0x04040404); REG_WRITE(DSPFW6, 0x78); REG_WRITE(DSPCHICKENBIT, REG_READ(DSPCHICKENBIT) | 0xc040); gma_power_end(dev); } /** * Return the pipe currently connected to the panel fitter, * or -1 if the panel fitter is not present or not in use */ static int oaktrail_panel_fitter_pipe(struct drm_device *dev) { u32 pfit_control; pfit_control = REG_READ(PFIT_CONTROL); /* See if the panel fitter is in use */ if ((pfit_control & PFIT_ENABLE) == 0) return -1; return (pfit_control >> 29) & 3; } static int oaktrail_crtc_mode_set(struct drm_crtc *crtc, struct drm_display_mode *mode, struct drm_display_mode *adjusted_mode, int x, int y, struct drm_framebuffer *old_fb) { struct drm_device *dev = crtc->dev; struct gma_crtc *gma_crtc = to_gma_crtc(crtc); struct drm_psb_private *dev_priv = dev->dev_private; int pipe = gma_crtc->pipe; const struct psb_offset *map = &dev_priv->regmap[pipe]; int refclk = 0; struct gma_clock_t clock; const struct gma_limit_t *limit; u32 dpll = 0, fp = 0, dspcntr, pipeconf; bool ok, is_sdvo = false; bool is_lvds = false; bool is_mipi = false; struct drm_mode_config *mode_config = &dev->mode_config; struct gma_encoder *gma_encoder = NULL; uint64_t scalingType = DRM_MODE_SCALE_FULLSCREEN; struct drm_connector *connector; int i; int need_aux = gma_pipe_has_type(crtc, INTEL_OUTPUT_SDVO) ? 1 : 0; if (gma_pipe_has_type(crtc, INTEL_OUTPUT_HDMI)) return oaktrail_crtc_hdmi_mode_set(crtc, mode, adjusted_mode, x, y, old_fb); if (!gma_power_begin(dev, true)) return 0; memcpy(&gma_crtc->saved_mode, mode, sizeof(struct drm_display_mode)); memcpy(&gma_crtc->saved_adjusted_mode, adjusted_mode, sizeof(struct drm_display_mode)); list_for_each_entry(connector, &mode_config->connector_list, head) { if (!connector->encoder || connector->encoder->crtc != crtc) continue; gma_encoder = gma_attached_encoder(connector); switch (gma_encoder->type) { case INTEL_OUTPUT_LVDS: is_lvds = true; break; case INTEL_OUTPUT_SDVO: is_sdvo = true; break; case INTEL_OUTPUT_MIPI: is_mipi = true; break; } } /* Disable the VGA plane that we never use */ for (i = 0; i <= need_aux; i++) REG_WRITE_WITH_AUX(VGACNTRL, VGA_DISP_DISABLE, i); /* Disable the panel fitter if it was on our pipe */ if (oaktrail_panel_fitter_pipe(dev) == pipe) REG_WRITE(PFIT_CONTROL, 0); for (i = 0; i <= need_aux; i++) { REG_WRITE_WITH_AUX(map->src, ((mode->crtc_hdisplay - 1) << 16) | (mode->crtc_vdisplay - 1), i); } if (gma_encoder) drm_object_property_get_value(&connector->base, dev->mode_config.scaling_mode_property, &scalingType); if (scalingType == DRM_MODE_SCALE_NO_SCALE) { /* Moorestown doesn't have register support for centering so * we need to mess with the h/vblank and h/vsync start and * ends to get centering */ int offsetX = 0, offsetY = 0; offsetX = (adjusted_mode->crtc_hdisplay - mode->crtc_hdisplay) / 2; offsetY = (adjusted_mode->crtc_vdisplay - mode->crtc_vdisplay) / 2; for (i = 0; i <= need_aux; i++) { REG_WRITE_WITH_AUX(map->htotal, (mode->crtc_hdisplay - 1) | ((adjusted_mode->crtc_htotal - 1) << 16), i); REG_WRITE_WITH_AUX(map->vtotal, (mode->crtc_vdisplay - 1) | ((adjusted_mode->crtc_vtotal - 1) << 16), i); REG_WRITE_WITH_AUX(map->hblank, (adjusted_mode->crtc_hblank_start - offsetX - 1) | ((adjusted_mode->crtc_hblank_end - offsetX - 1) << 16), i); REG_WRITE_WITH_AUX(map->hsync, (adjusted_mode->crtc_hsync_start - offsetX - 1) | ((adjusted_mode->crtc_hsync_end - offsetX - 1) << 16), i); REG_WRITE_WITH_AUX(map->vblank, (adjusted_mode->crtc_vblank_start - offsetY - 1) | ((adjusted_mode->crtc_vblank_end - offsetY - 1) << 16), i); REG_WRITE_WITH_AUX(map->vsync, (adjusted_mode->crtc_vsync_start - offsetY - 1) | ((adjusted_mode->crtc_vsync_end - offsetY - 1) << 16), i); } } else { for (i = 0; i <= need_aux; i++) { REG_WRITE_WITH_AUX(map->htotal, (adjusted_mode->crtc_hdisplay - 1) | ((adjusted_mode->crtc_htotal - 1) << 16), i); REG_WRITE_WITH_AUX(map->vtotal, (adjusted_mode->crtc_vdisplay - 1) | ((adjusted_mode->crtc_vtotal - 1) << 16), i); REG_WRITE_WITH_AUX(map->hblank, (adjusted_mode->crtc_hblank_start - 1) | ((adjusted_mode->crtc_hblank_end - 1) << 16), i); REG_WRITE_WITH_AUX(map->hsync, (adjusted_mode->crtc_hsync_start - 1) | ((adjusted_mode->crtc_hsync_end - 1) << 16), i); REG_WRITE_WITH_AUX(map->vblank, (adjusted_mode->crtc_vblank_start - 1) | ((adjusted_mode->crtc_vblank_end - 1) << 16), i); REG_WRITE_WITH_AUX(map->vsync, (adjusted_mode->crtc_vsync_start - 1) | ((adjusted_mode->crtc_vsync_end - 1) << 16), i); } } /* Flush the plane changes */ { const struct drm_crtc_helper_funcs *crtc_funcs = crtc->helper_private; crtc_funcs->mode_set_base(crtc, x, y, old_fb); } /* setup pipeconf */ pipeconf = REG_READ(map->conf); /* Set up the display plane register */ dspcntr = REG_READ(map->cntr); dspcntr |= DISPPLANE_GAMMA_ENABLE; if (pipe == 0) dspcntr |= DISPPLANE_SEL_PIPE_A; else dspcntr |= DISPPLANE_SEL_PIPE_B; if (is_mipi) goto oaktrail_crtc_mode_set_exit; dpll = 0; /*BIT16 = 0 for 100MHz reference */ refclk = is_sdvo ? 96000 : dev_priv->core_freq * 1000; limit = mrst_limit(crtc, refclk); ok = limit->find_pll(limit, crtc, adjusted_mode->clock, refclk, &clock); if (is_sdvo) { /* Convert calculated values to register values */ clock.p1 = (1L << (clock.p1 - 1)); clock.m -= 2; clock.n = (1L << (clock.n - 1)); } if (!ok) DRM_ERROR("Failed to find proper PLL settings"); mrst_print_pll(&clock); if (is_sdvo) fp = clock.n << 16 | clock.m; else fp = oaktrail_m_converts[(clock.m - MRST_M_MIN)] << 8; dpll |= DPLL_VGA_MODE_DIS; dpll |= DPLL_VCO_ENABLE; if (is_lvds) dpll |= DPLLA_MODE_LVDS; else dpll |= DPLLB_MODE_DAC_SERIAL; if (is_sdvo) { int sdvo_pixel_multiply = adjusted_mode->clock / mode->clock; dpll |= DPLL_DVO_HIGH_SPEED; dpll |= (sdvo_pixel_multiply - 1) << SDVO_MULTIPLIER_SHIFT_HIRES; } /* compute bitmask from p1 value */ if (is_sdvo) dpll |= clock.p1 << 16; // dpll |= (1 << (clock.p1 - 1)) << 16; else dpll |= (1 << (clock.p1 - 2)) << 17; dpll |= DPLL_VCO_ENABLE; if (dpll & DPLL_VCO_ENABLE) { for (i = 0; i <= need_aux; i++) { REG_WRITE_WITH_AUX(map->fp0, fp, i); REG_WRITE_WITH_AUX(map->dpll, dpll & ~DPLL_VCO_ENABLE, i); REG_READ_WITH_AUX(map->dpll, i); /* Check the DPLLA lock bit PIPEACONF[29] */ udelay(150); } } for (i = 0; i <= need_aux; i++) { REG_WRITE_WITH_AUX(map->fp0, fp, i); REG_WRITE_WITH_AUX(map->dpll, dpll, i); REG_READ_WITH_AUX(map->dpll, i); /* Wait for the clocks to stabilize. */ udelay(150); /* write it again -- the BIOS does, after all */ REG_WRITE_WITH_AUX(map->dpll, dpll, i); REG_READ_WITH_AUX(map->dpll, i); /* Wait for the clocks to stabilize. */ udelay(150); REG_WRITE_WITH_AUX(map->conf, pipeconf, i); REG_READ_WITH_AUX(map->conf, i); gma_wait_for_vblank(dev); REG_WRITE_WITH_AUX(map->cntr, dspcntr, i); gma_wait_for_vblank(dev); } oaktrail_crtc_mode_set_exit: gma_power_end(dev); return 0; } static int oaktrail_pipe_set_base(struct drm_crtc *crtc, int x, int y, struct drm_framebuffer *old_fb) { struct drm_device *dev = crtc->dev; struct drm_psb_private *dev_priv = dev->dev_private; struct gma_crtc *gma_crtc = to_gma_crtc(crtc); struct psb_framebuffer *psbfb = to_psb_fb(crtc->primary->fb); int pipe = gma_crtc->pipe; const struct psb_offset *map = &dev_priv->regmap[pipe]; unsigned long start, offset; u32 dspcntr; int ret = 0; /* no fb bound */ if (!crtc->primary->fb) { dev_dbg(dev->dev, "No FB bound\n"); return 0; } if (!gma_power_begin(dev, true)) return 0; start = psbfb->gtt->offset; offset = y * crtc->primary->fb->pitches[0] + x * (crtc->primary->fb->bits_per_pixel / 8); REG_WRITE(map->stride, crtc->primary->fb->pitches[0]); dspcntr = REG_READ(map->cntr); dspcntr &= ~DISPPLANE_PIXFORMAT_MASK; switch (crtc->primary->fb->bits_per_pixel) { case 8: dspcntr |= DISPPLANE_8BPP; break; case 16: if (crtc->primary->fb->depth == 15) dspcntr |= DISPPLANE_15_16BPP; else dspcntr |= DISPPLANE_16BPP; break; case 24: case 32: dspcntr |= DISPPLANE_32BPP_NO_ALPHA; break; default: dev_err(dev->dev, "Unknown color depth\n"); ret = -EINVAL; goto pipe_set_base_exit; } REG_WRITE(map->cntr, dspcntr); REG_WRITE(map->base, offset); REG_READ(map->base); REG_WRITE(map->surf, start); REG_READ(map->surf); pipe_set_base_exit: gma_power_end(dev); return ret; } const struct drm_crtc_helper_funcs oaktrail_helper_funcs = { .dpms = oaktrail_crtc_dpms, .mode_set = oaktrail_crtc_mode_set, .mode_set_base = oaktrail_pipe_set_base, .prepare = gma_crtc_prepare, .commit = gma_crtc_commit, }; /* Not used yet */ const struct gma_clock_funcs mrst_clock_funcs = { .clock = mrst_lvds_clock, .limit = mrst_limit, .pll_is_valid = gma_pll_is_valid, };
geminy/aidear
oss/linux/linux-4.7/drivers/gpu/drm/gma500/oaktrail_crtc.c
C
gpl-3.0
19,081
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * @fileoverview Manages Firefox binaries. This module is considered internal; * users should use {@link ./firefox selenium-webdriver/firefox}. */ 'use strict'; const child = require('child_process'), fs = require('fs'), path = require('path'), util = require('util'); const isDevMode = require('../lib/devmode'), promise = require('../lib/promise'), Symbols = require('../lib/symbols'), io = require('../io'), exec = require('../io/exec'); /** @const */ const NO_FOCUS_LIB_X86 = isDevMode ? path.join(__dirname, '../../../../cpp/prebuilt/i386/libnoblur.so') : path.join(__dirname, '../lib/firefox/i386/libnoblur.so') ; /** @const */ const NO_FOCUS_LIB_AMD64 = isDevMode ? path.join(__dirname, '../../../../cpp/prebuilt/amd64/libnoblur64.so') : path.join(__dirname, '../lib/firefox/amd64/libnoblur64.so') ; const X_IGNORE_NO_FOCUS_LIB = 'x_ignore_nofocus.so'; let foundBinary = null; let foundDevBinary = null; /** * Checks the default Windows Firefox locations in Program Files. * * @param {boolean=} opt_dev Whether to find the Developer Edition. * @return {!Promise<?string>} A promise for the located executable. * The promise will resolve to {@code null} if Firefox was not found. */ function defaultWindowsLocation(opt_dev) { var files = [ process.env['PROGRAMFILES'] || 'C:\\Program Files', process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)' ].map(function(prefix) { if (opt_dev) { return path.join(prefix, 'Firefox Developer Edition\\firefox.exe'); } return path.join(prefix, 'Mozilla Firefox\\firefox.exe'); }); return io.exists(files[0]).then(function(exists) { return exists ? files[0] : io.exists(files[1]).then(function(exists) { return exists ? files[1] : null; }); }); } /** * Locates the Firefox binary for the current system. * * @param {boolean=} opt_dev Whether to find the Developer Edition. This only * used on Windows and OSX. * @return {!Promise<string>} A promise for the located binary. The promise will * be rejected if Firefox cannot be located. */ function findFirefox(opt_dev) { if (opt_dev && foundDevBinary) { return foundDevBinary; } if (!opt_dev && foundBinary) { return foundBinary; } let found; if (process.platform === 'darwin') { let exe = opt_dev ? '/Applications/FirefoxDeveloperEdition.app/Contents/MacOS/firefox-bin' : '/Applications/Firefox.app/Contents/MacOS/firefox-bin'; found = io.exists(exe).then(exists => exists ? exe : null); } else if (process.platform === 'win32') { found = defaultWindowsLocation(opt_dev); } else { found = Promise.resolve(io.findInPath('firefox')); } found = found.then(found => { if (found) { return found; } throw Error('Could not locate Firefox on the current system'); }); if (opt_dev) { return foundDevBinary = found; } else { return foundBinary = found; } } /** * Copies the no focus libs into the given profile directory. * @param {string} profileDir Path to the profile directory to install into. * @return {!promise.Promise.<string>} The LD_LIBRARY_PATH prefix string to use * for the installed libs. */ function installNoFocusLibs(profileDir) { var x86 = path.join(profileDir, 'x86'); var amd64 = path.join(profileDir, 'amd64'); return mkdir(x86) .then(copyLib.bind(null, NO_FOCUS_LIB_X86, x86)) .then(mkdir.bind(null, amd64)) .then(copyLib.bind(null, NO_FOCUS_LIB_AMD64, amd64)) .then(function() { return x86 + ':' + amd64; }); function mkdir(dir) { return io.exists(dir).then(function(exists) { if (!exists) { return promise.checkedNodeCall(fs.mkdir, dir); } }); } function copyLib(src, dir) { return io.copy(src, path.join(dir, X_IGNORE_NO_FOCUS_LIB)); } } /** * Provides a mechanism to configure and launch Firefox in a subprocess for * use with WebDriver. * * If created _without_ a path for the Firefox binary to use, this class will * attempt to find Firefox when {@link #launch()} is called. For OSX and * Windows, this class will look for Firefox in the current platform's default * installation location (e.g. /Applications/Firefox.app on OSX). For all other * platforms, the Firefox executable must be available on your system `PATH`. * * @final */ class Binary { /** * @param {string=} opt_exe Path to the Firefox binary to use. */ constructor(opt_exe) { /** @private {(string|undefined)} */ this.exe_ = opt_exe; /** @private {!Array.<string>} */ this.args_ = []; /** @private {!Object<string, string>} */ this.env_ = {}; Object.assign(this.env_, process.env, { MOZ_CRASHREPORTER_DISABLE: '1', MOZ_NO_REMOTE: '1', NO_EM_RESTART: '1' }); /** @private {boolean} */ this.devEdition_ = false; } /** * Add arguments to the command line used to start Firefox. * @param {...(string|!Array.<string>)} var_args Either the arguments to add * as varargs, or the arguments as an array. */ addArguments(var_args) { for (var i = 0; i < arguments.length; i++) { if (Array.isArray(arguments[i])) { this.args_ = this.args_.concat(arguments[i]); } else { this.args_.push(arguments[i]); } } } /** * Specifies whether to use Firefox Developer Edition instead of the normal * stable channel. Setting this option has no effect if this instance was * created with a path to a specific Firefox binary. * * This method has no effect on Unix systems where the Firefox application * has the same (default) name regardless of version. * * @param {boolean=} opt_use Whether to use the developer edition. Defaults to * true. */ useDevEdition(opt_use) { this.devEdition_ = opt_use === undefined || !!opt_use; } /** * Returns a promise for the Firefox executable used by this instance. The * returned promise will be immediately resolved if the user supplied an * executable path when this instance was created. Otherwise, an attempt will * be made to find Firefox on the current system. * * @return {!promise.Promise<string>} a promise for the path to the Firefox * executable used by this instance. */ locate() { return promise.fulfilled(this.exe_ || findFirefox(this.devEdition_)); } /** * Launches Firefox and returns a promise that will be fulfilled when the * process terminates. * @param {string} profile Path to the profile directory to use. * @return {!promise.Promise<!exec.Command>} A promise for the handle to the * started subprocess. */ launch(profile) { let env = {}; Object.assign(env, this.env_, {XRE_PROFILE_PATH: profile}); let args = ['-foreground'].concat(this.args_); return this.locate().then(function(firefox) { if (process.platform === 'win32' || process.platform === 'darwin') { return exec(firefox, {args: args, env: env}); } return installNoFocusLibs(profile).then(function(ldLibraryPath) { env['LD_LIBRARY_PATH'] = ldLibraryPath + ':' + env['LD_LIBRARY_PATH']; env['LD_PRELOAD'] = X_IGNORE_NO_FOCUS_LIB; return exec(firefox, {args: args, env: env}); }); }); } /** * Returns a promise for the wire representation of this binary. Note: the * FirefoxDriver only supports passing the path to the binary executable over * the wire; all command line arguments and environment variables will be * discarded. * * @return {!promise.Promise<string>} A promise for this binary's wire * representation. */ [Symbols.serialize]() { return this.locate(); } } // PUBLIC API exports.Binary = Binary;
mo-norant/FinHeartBel
website/node_modules/selenium-webdriver/firefox/binary.js
JavaScript
gpl-3.0
8,611
/* YUI 3.17.1 (build 0eb5a52) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ /*! Pure v0.4.2 Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. https://github.com/yui/pure/blob/master/LICENSE.md */ /*csslint regex-selectors:false, known-properties:false, duplicate-properties:false*/ .yui3-g { letter-spacing: -0.31em; /* Webkit: collapse white-space between units */ *letter-spacing: normal; /* reset IE < 8 */ *word-spacing: -0.43em; /* IE < 8: collapse white-space between units */ text-rendering: optimizespeed; /* Webkit: fixes text-rendering: optimizeLegibility */ /* Sets the font stack to fonts known to work properly with the above letter and word spacings. See: https://github.com/yui/pure/issues/41/ The following font stack makes Pure Grids work on all known environments. * FreeSans: Ships with many Linux distros, including Ubuntu * Arimo: Ships with Chrome OS. Arimo has to be defined before Helvetica and Arial to get picked up by the browser, even though neither is available in Chrome OS. * Droid Sans: Ships with all versions of Android. * Helvetica, Arial, sans-serif: Common font stack on OS X and Windows. */ font-family: FreeSans, Arimo, "Droid Sans", Helvetica, Arial, sans-serif; /* Use flexbox when possible to avoid `letter-spacing` side-effects. NOTE: Firefox (as of 25) does not currently support flex-wrap, so the `-moz-` prefix version is omitted. */ display: -webkit-flex; -webkit-flex-flow: row wrap; /* IE10 uses display: flexbox */ display: -ms-flexbox; -ms-flex-flow: row wrap; } /* Opera as of 12 on Windows needs word-spacing. The ".opera-only" selector is used to prevent actual prefocus styling and is not required in markup. */ .opera-only :-o-prefocus, .yui3-g { word-spacing: -0.43em; } .yui3-u { display: inline-block; *display: inline; /* IE < 8: fake inline-block */ zoom: 1; letter-spacing: normal; word-spacing: normal; vertical-align: top; text-rendering: auto; } /* Resets the font family back to the OS/browser's default sans-serif font, this the same font stack that Normalize.css sets for the `body`. */ .yui3-g [class *= "yui3-u"] { font-family: sans-serif; } .yui3-u-1, .yui3-u-1-1, .yui3-u-1-2, .yui3-u-1-3, .yui3-u-2-3, .yui3-u-1-4, .yui3-u-3-4, .yui3-u-1-5, .yui3-u-2-5, .yui3-u-3-5, .yui3-u-4-5, .yui3-u-5-5, .yui3-u-1-6, .yui3-u-5-6, .yui3-u-1-8, .yui3-u-3-8, .yui3-u-5-8, .yui3-u-7-8, .yui3-u-1-12, .yui3-u-5-12, .yui3-u-7-12, .yui3-u-11-12, .yui3-u-1-24, .yui3-u-2-24, .yui3-u-3-24, .yui3-u-4-24, .yui3-u-5-24, .yui3-u-6-24, .yui3-u-7-24, .yui3-u-8-24, .yui3-u-9-24, .yui3-u-10-24, .yui3-u-11-24, .yui3-u-12-24, .yui3-u-13-24, .yui3-u-14-24, .yui3-u-15-24, .yui3-u-16-24, .yui3-u-17-24, .yui3-u-18-24, .yui3-u-19-24, .yui3-u-20-24, .yui3-u-21-24, .yui3-u-22-24, .yui3-u-23-24, .yui3-u-24-24 { display: inline-block; *display: inline; zoom: 1; letter-spacing: normal; word-spacing: normal; vertical-align: top; text-rendering: auto; } .yui3-u-1-24 { width: 4.1667%; *width: 4.1357%; } .yui3-u-1-12, .yui3-u-2-24 { width: 8.3333%; *width: 8.3023%; } .yui3-u-1-8, .yui3-u-3-24 { width: 12.5000%; *width: 12.4690%; } .yui3-u-1-6, .yui3-u-4-24 { width: 16.6667%; *width: 16.6357%; } .yui3-u-1-5 { width: 20%; *width: 19.9690%; } .yui3-u-5-24 { width: 20.8333%; *width: 20.8023%; } .yui3-u-1-4, .yui3-u-6-24 { width: 25%; *width: 24.9690%; } .yui3-u-7-24 { width: 29.1667%; *width: 29.1357%; } .yui3-u-1-3, .yui3-u-8-24 { width: 33.3333%; *width: 33.3023%; } .yui3-u-3-8, .yui3-u-9-24 { width: 37.5000%; *width: 37.4690%; } .yui3-u-2-5 { width: 40%; *width: 39.9690%; } .yui3-u-5-12, .yui3-u-10-24 { width: 41.6667%; *width: 41.6357%; } .yui3-u-11-24 { width: 45.8333%; *width: 45.8023%; } .yui3-u-1-2, .yui3-u-12-24 { width: 50%; *width: 49.9690%; } .yui3-u-13-24 { width: 54.1667%; *width: 54.1357%; } .yui3-u-7-12, .yui3-u-14-24 { width: 58.3333%; *width: 58.3023%; } .yui3-u-3-5 { width: 60%; *width: 59.9690%; } .yui3-u-5-8, .yui3-u-15-24 { width: 62.5000%; *width: 62.4690%; } .yui3-u-2-3, .yui3-u-16-24 { width: 66.6667%; *width: 66.6357%; } .yui3-u-17-24 { width: 70.8333%; *width: 70.8023%; } .yui3-u-3-4, .yui3-u-18-24 { width: 75%; *width: 74.9690%; } .yui3-u-19-24 { width: 79.1667%; *width: 79.1357%; } .yui3-u-4-5 { width: 80%; *width: 79.9690%; } .yui3-u-5-6, .yui3-u-20-24 { width: 83.3333%; *width: 83.3023%; } .yui3-u-7-8, .yui3-u-21-24 { width: 87.5000%; *width: 87.4690%; } .yui3-u-11-12, .yui3-u-22-24 { width: 91.6667%; *width: 91.6357%; } .yui3-u-23-24 { width: 95.8333%; *width: 95.8023%; } .yui3-u-1, .yui3-u-1-1, .yui3-u-5-5, .yui3-u-24-24 { width: 100%; } /*csslint regex-selectors:false, known-properties:false, duplicate-properties:false*/ .yui3-g-r { letter-spacing: -0.31em; *letter-spacing: normal; *word-spacing: -0.43em; /* Sets the font stack to fonts known to work properly with the above letter and word spacings. See: https://github.com/yui/pure/issues/41/ The following font stack makes Pure Grids work on all known environments. * FreeSans: Ships with many Linux distros, including Ubuntu * Arimo: Ships with Chrome OS. Arimo has to be defined before Helvetica and Arial to get picked up by the browser, even though neither is available in Chrome OS. * Droid Sans: Ships with all versions of Android. * Helvetica, Arial, sans-serif: Common font stack on OS X and Windows. */ font-family: FreeSans, Arimo, "Droid Sans", Helvetica, Arial, sans-serif; /* Use flexbox when possible to avoid `letter-spacing` side-effects. NOTE: Firefox (as of 25) does not currently support flex-wrap, so the `-moz-` prefix version is omitted. */ display: -webkit-flex; -webkit-flex-flow: row wrap; /* IE10 uses display: flexbox */ display: -ms-flexbox; -ms-flex-flow: row wrap; } /* Opera as of 12 on Windows needs word-spacing. The ".opera-only" selector is used to prevent actual prefocus styling and is not required in markup. */ .opera-only :-o-prefocus, .yui3-g-r { word-spacing: -0.43em; } /* Resets the font family back to the OS/browser's default sans-serif font, this the same font stack that Normalize.css sets for the `body`. */ .yui3-g-r [class *= "yui3-u"] { font-family: sans-serif; } .yui3-g-r img { max-width: 100%; height: auto; } @media (min-width: 980px) { .yui3-visible-phone { display: none; } .yui3-visible-tablet { display: none; } .yui3-hidden-desktop { display: none; } } @media (max-width: 480px) { .yui3-g-r > .yui3-u, .yui3-g-r > [class *= "yui3-u-"] { width: 100%; } } @media (max-width: 767px) { .yui3-g-r > .yui3-u, .yui3-g-r > [class *= "yui3-u-"] { width: 100%; } .yui3-hidden-phone { display: none; } .yui3-visible-desktop { display: none; } } @media (min-width: 768px) and (max-width: 979px) { .yui3-hidden-tablet { display: none; } .yui3-visible-desktop { display: none; } } /* YUI CSS Detection Stamp */ #yui3-css-stamp.cssgrids-responsive { display: none; }
stevermeister/cdnjs
ajax/libs/yui/3.17.1/cssgrids-responsive/cssgrids-responsive.css
CSS
mit
7,629
#!/bin/bash # SPDX-License-Identifier: GPL-2.0 CHECK_TC="yes" # Can be overridden by the configuration file. See lib.sh TC_HIT_TIMEOUT=${TC_HIT_TIMEOUT:=1000} # ms tc_check_packets() { local id=$1 local handle=$2 local count=$3 busywait "$TC_HIT_TIMEOUT" until_counter_is "== $count" \ tc_rule_handle_stats_get "$id" "$handle" > /dev/null } tc_check_at_least_x_packets() { local id=$1 local handle=$2 local count=$3 busywait "$TC_HIT_TIMEOUT" until_counter_is ">= $count" \ tc_rule_handle_stats_get "$id" "$handle" > /dev/null } tc_check_packets_hitting() { local id=$1 local handle=$2 busywait "$TC_HIT_TIMEOUT" until_counter_is "> 0" \ tc_rule_handle_stats_get "$id" "$handle" > /dev/null }
rperier/linux
tools/testing/selftests/net/forwarding/tc_common.sh
Shell
gpl-2.0
721
/* * ms5637.c - Support for Measurement-Specialties MS5637, MS5805 * MS5837 and MS8607 pressure & temperature sensor * * Copyright (c) 2015 Measurement-Specialties * * Licensed under the GPL-2. * * (7-bit I2C slave address 0x76) * * Datasheet: * http://www.meas-spec.com/downloads/MS5637-02BA03.pdf * Datasheet: * http://www.meas-spec.com/downloads/MS5805-02BA01.pdf * Datasheet: * http://www.meas-spec.com/downloads/MS5837-30BA.pdf * Datasheet: * http://www.meas-spec.com/downloads/MS8607-02BA01.pdf */ #include <linux/init.h> #include <linux/device.h> #include <linux/kernel.h> #include <linux/stat.h> #include <linux/module.h> #include <linux/i2c.h> #include <linux/iio/iio.h> #include <linux/iio/sysfs.h> #include <linux/mutex.h> #include "../common/ms_sensors/ms_sensors_i2c.h" static const int ms5637_samp_freq[6] = { 960, 480, 240, 120, 60, 30 }; /* String copy of the above const for readability purpose */ static const char ms5637_show_samp_freq[] = "960 480 240 120 60 30"; static int ms5637_read_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *channel, int *val, int *val2, long mask) { int ret; int temperature; unsigned int pressure; struct ms_tp_dev *dev_data = iio_priv(indio_dev); switch (mask) { case IIO_CHAN_INFO_PROCESSED: ret = ms_sensors_read_temp_and_pressure(dev_data, &temperature, &pressure); if (ret) return ret; switch (channel->type) { case IIO_TEMP: /* in milli °C */ *val = temperature; return IIO_VAL_INT; case IIO_PRESSURE: /* in kPa */ *val = pressure / 1000; *val2 = (pressure % 1000) * 1000; return IIO_VAL_INT_PLUS_MICRO; default: return -EINVAL; } case IIO_CHAN_INFO_SAMP_FREQ: *val = ms5637_samp_freq[dev_data->res_index]; return IIO_VAL_INT; default: return -EINVAL; } } static int ms5637_write_raw(struct iio_dev *indio_dev, struct iio_chan_spec const *chan, int val, int val2, long mask) { struct ms_tp_dev *dev_data = iio_priv(indio_dev); int i; switch (mask) { case IIO_CHAN_INFO_SAMP_FREQ: i = ARRAY_SIZE(ms5637_samp_freq); while (i-- > 0) if (val == ms5637_samp_freq[i]) break; if (i < 0) return -EINVAL; dev_data->res_index = i; return 0; default: return -EINVAL; } } static const struct iio_chan_spec ms5637_channels[] = { { .type = IIO_TEMP, .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ), }, { .type = IIO_PRESSURE, .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ), } }; static IIO_CONST_ATTR_SAMP_FREQ_AVAIL(ms5637_show_samp_freq); static struct attribute *ms5637_attributes[] = { &iio_const_attr_sampling_frequency_available.dev_attr.attr, NULL, }; static const struct attribute_group ms5637_attribute_group = { .attrs = ms5637_attributes, }; static const struct iio_info ms5637_info = { .read_raw = ms5637_read_raw, .write_raw = ms5637_write_raw, .attrs = &ms5637_attribute_group, .driver_module = THIS_MODULE, }; static int ms5637_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct ms_tp_dev *dev_data; struct iio_dev *indio_dev; int ret; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA | I2C_FUNC_SMBUS_WRITE_BYTE | I2C_FUNC_SMBUS_READ_I2C_BLOCK)) { dev_err(&client->dev, "Adapter does not support some i2c transaction\n"); return -EOPNOTSUPP; } indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*dev_data)); if (!indio_dev) return -ENOMEM; dev_data = iio_priv(indio_dev); dev_data->client = client; dev_data->res_index = 5; mutex_init(&dev_data->lock); indio_dev->info = &ms5637_info; indio_dev->name = id->name; indio_dev->dev.parent = &client->dev; indio_dev->modes = INDIO_DIRECT_MODE; indio_dev->channels = ms5637_channels; indio_dev->num_channels = ARRAY_SIZE(ms5637_channels); i2c_set_clientdata(client, indio_dev); ret = ms_sensors_reset(client, 0x1E, 3000); if (ret) return ret; ret = ms_sensors_tp_read_prom(dev_data); if (ret) return ret; return devm_iio_device_register(&client->dev, indio_dev); } static const struct i2c_device_id ms5637_id[] = { {"ms5637", 0}, {"ms5805", 0}, {"ms5837", 0}, {"ms8607-temppressure", 0}, {} }; MODULE_DEVICE_TABLE(i2c, ms5637_id); static struct i2c_driver ms5637_driver = { .probe = ms5637_probe, .id_table = ms5637_id, .driver = { .name = "ms5637" }, }; module_i2c_driver(ms5637_driver); MODULE_DESCRIPTION("Measurement-Specialties ms5637 temperature & pressure driver"); MODULE_AUTHOR("William Markezana <[email protected]>"); MODULE_AUTHOR("Ludovic Tancerel <[email protected]>"); MODULE_LICENSE("GPL v2");
eabatalov/au-linux-kernel-autumn-2017
linux/drivers/iio/pressure/ms5637.c
C
gpl-3.0
4,817
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Db\Adapter\Driver\Pdo; use Iterator; use PDOStatement; use Zend\Db\Adapter\Driver\ResultInterface; use Zend\Db\Adapter\Exception; class Result implements Iterator, ResultInterface { const STATEMENT_MODE_SCROLLABLE = 'scrollable'; const STATEMENT_MODE_FORWARD = 'forward'; /** * * @var string */ protected $statementMode = self::STATEMENT_MODE_FORWARD; /** * @var int */ protected $fetchMode = \PDO::FETCH_ASSOC; /** * @var PDOStatement */ protected $resource = null; /** * @var array Result options */ protected $options; /** * Is the current complete? * @var bool */ protected $currentComplete = false; /** * Track current item in recordset * @var mixed */ protected $currentData = null; /** * Current position of scrollable statement * @var int */ protected $position = -1; /** * @var mixed */ protected $generatedValue = null; /** * @var null */ protected $rowCount = null; /** * Initialize * * @param PDOStatement $resource * @param $generatedValue * @param int $rowCount * @return Result */ public function initialize(PDOStatement $resource, $generatedValue, $rowCount = null) { $this->resource = $resource; $this->generatedValue = $generatedValue; $this->rowCount = $rowCount; return $this; } /** * @return null */ public function buffer() { return; } /** * @return bool|null */ public function isBuffered() { return false; } /** * @param int $fetchMode * @throws Exception\InvalidArgumentException on invalid fetch mode */ public function setFetchMode($fetchMode) { if ($fetchMode < 1 || $fetchMode > 10) { throw new Exception\InvalidArgumentException( 'The fetch mode must be one of the PDO::FETCH_* constants.' ); } $this->fetchMode = (int) $fetchMode; } /** * @return int */ public function getFetchMode() { return $this->fetchMode; } /** * Get resource * * @return mixed */ public function getResource() { return $this->resource; } /** * Get the data * @return array */ public function current() { if ($this->currentComplete) { return $this->currentData; } $this->currentData = $this->resource->fetch($this->fetchMode); $this->currentComplete = true; return $this->currentData; } /** * Next * * @return mixed */ public function next() { $this->currentData = $this->resource->fetch($this->fetchMode); $this->currentComplete = true; $this->position++; return $this->currentData; } /** * Key * * @return mixed */ public function key() { return $this->position; } /** * @throws Exception\RuntimeException * @return void */ public function rewind() { if ($this->statementMode == self::STATEMENT_MODE_FORWARD && $this->position > 0) { throw new Exception\RuntimeException( 'This result is a forward only result set, calling rewind() after moving forward is not supported' ); } $this->currentData = $this->resource->fetch($this->fetchMode); $this->currentComplete = true; $this->position = 0; } /** * Valid * * @return bool */ public function valid() { return ($this->currentData !== false); } /** * Count * * @return int */ public function count() { if (is_int($this->rowCount)) { return $this->rowCount; } if ($this->rowCount instanceof \Closure) { $this->rowCount = (int) call_user_func($this->rowCount); } else { $this->rowCount = (int) $this->resource->rowCount(); } return $this->rowCount; } /** * @return int */ public function getFieldCount() { return $this->resource->columnCount(); } /** * Is query result * * @return bool */ public function isQueryResult() { return ($this->resource->columnCount() > 0); } /** * Get affected rows * * @return int */ public function getAffectedRows() { return $this->resource->rowCount(); } /** * @return mixed|null */ public function getGeneratedValue() { return $this->generatedValue; } }
pdhwi/hwi_test
z/ZendFramework-2.4.3/library/Zend/Db/Adapter/Driver/Pdo/Result.php
PHP
bsd-3-clause
5,161
<?php namespace redisent\tests; require_once __DIR__.'/../simpletest/autorun.php'; require_once __DIR__.'/../src/redisent/Redis.php'; class StringsTest extends \UnitTestCase { private $dsn = 'redis://localhost/'; function setUp() { $this->r = new \redisent\Redis($this->dsn); $this->assertIsA($this->r, 'redisent\Redis'); } function testSet() { $this->assertTrue($this->r->set('foo', 'bar')); $this->assertEqual($this->r->get('foo'), 'bar'); } function testExists() { $this->assertEqual($this->r->exists('foo'), 1); $this->assertEqual($this->r->exists('bar'), 0); } function testDel() { $this->assertEqual($this->r->del('foo'), 1); $this->assertNull($this->r->get('foo')); } }
jdp/redisent
tests/strings_test.php
PHP
isc
737
"use strict"; var deferred = require("../../../deferred"); module.exports = function (t, a) { var x = {}, d = deferred(), p = d.promise, invoked = false; a(p.aside(), p, "Callback is optional"); a( p.aside(function (o) { a(o, x, "Unresolved: arguments"); invoked = true; }, a.never), p, "Returns self promise" ); a(invoked, false, "Callback not invoked on unresolved promise"); d.resolve(x); a(invoked, true, "Callback invoked immediately on resolution"); invoked = false; p.aside(function (o) { a(o, x, "Resolved: arguments"); invoked = true; }, a.never); a(invoked, true, "Callback invoked immediately on resolved promise"); p = deferred((x = new Error("Error"))); invoked = false; p.aside(a.never, function (err) { a(err, x, "Erronous: arguments"); invoked = true; }); a(invoked, true, "Called on erronous"); p.aside(a.never, null); p = deferred((x = {})); p.aside(null, a.never); };
medikoo/deferred
test/ext/promise/aside.js
JavaScript
isc
934
# veneer-py Python module to support scripting eWater Source models through the Veneer (RESTful HTTP) plugin ## Installation You'll need Python 3, a compatible version of eWater Source along with the [Veneer plugin](https://github.com/flowmatters/veneer) and veneer-py. I expect most users of veneer-py will install [Anaconda Python](https://www.continuum.io/downloads). Anaconda will provide most of the analytics libraries you're likely to want, along with the Jupyter Notebook system. Install the most recent version of Anaconda Python with Python 3 (NOT Python 2). Instructions for installing Veneer can be found on [its homepage](https://github.com/flowmatters/veneer). Download the most recent [Veneer release](https://github.com/flowmatters/Veneer/releases) that is compatible with your version of eWater Source. Note that certain veneer-py features may not work with older versions of Source/Veneer. veneer-py can be installed using `pip` from an Anaconda command prompt: ``` pip install https://github.com/flowmatters/veneer-py/archive/master.zip ``` At this stage we haven't tagged releases so you just install from the latest version. To upgrade, uninstall the one you've got, then install again ``` pip uninstall veneer-py pip install https://github.com/flowmatters/veneer-py/archive/master.zip ``` Alternatively, clone the git repository and do a develop install to allow you to easily modify the veneer-py code as you use it. ``` python setup.py develop ``` ## Getting started 1. Install the Veneer plugin for Source as per its [instructions](https://github.com/flowmatters/veneer). 2. Start Source, load a project and then start the Veneer service from within Source. 3. Within Python (eg within a notebook), initialise a Veneer client object and run a query. For example ```python from veneer import Veneer v = Veneer() # uses default port number of 9876 # Alternatively, for a different port # v = Veneer(port=9876) network = v.network() # Returns a GeoJSON coverage representing the Source network nodes = network['features'].find_by_feature_type('node') node_names = nodes._unique_values('name') print(node_names) ``` ## Exploring the system Most of the key functions of the Veneer object have docstrings and you are encouraged to explore these. Using IPython or the Jupyter Notebook gives you tab key completion, so, for example, you can type ``` v.r ``` Hit `tab` and see a list of methods starting with `r`. To get help on a specific command, put a `?` after the full method name, such as ``` v.retrieve_multiple_time_series? ``` ## Documentation and Training Reference docs are at [https://flowmatters.github.io/veneer-py](https://flowmatters.github.io/veneer-py). Training notebooks and sample data are at [doc/training](doc/training) ## Contributions ... Are most welcome... We'll formalise contributor guidelines in the future.
ConnectedSystems/veneer-py
README.md
Markdown
isc
2,886
module Examples.Print where import Types import Statements import BasicPrelude import qualified Data.Map.Lazy as M zero :: Value zero = Value $ NumberConst (0 :: Int) one :: Value one = Value $ NumberConst (1 :: Int) textStore :: M.Map Text Value textStore = M.fromList [("n", Value $ SquanchyString ("25" :: Text))] textTest :: Prog textTest = Seq [Print (Value $ (SquanchyVar "n" :: Expr Text))] boolStore :: M.Map Text Value boolStore = M.fromList [("n", Value $ BoolConst (True :: Bool))] boolTest :: Prog boolTest = Seq [Print (Value $ (SquanchyVar "n" :: Expr Bool))] intStore :: M.Map Text Value intStore = M.fromList [("n", Value $ NumberConst (1 :: Int))] intTest :: Prog intTest = Seq [Print (Value $ (SquanchyVar "n" :: Expr Int))] floatStore :: M.Map Text Value floatStore = M.fromList [("n", Value $ NumberConst (1 :: Float))] floatTest :: Prog floatTest = Seq [Print (Value $ (SquanchyVar "n" :: Expr Float))]
mlitchard/squanchy
src/Examples/Print.hs
Haskell
isc
936
from unittest2 import TestCase from snippets.tag import Tag class TagTests(TestCase): def setUp(self): Tag.registry.clear() def test_does_not_create_new_tags_with_the_same_name(self): self.assertIs(Tag('Django'), Tag('Django')) self.assertIs(Tag('Django'), Tag('django')) def test_first_tag_tag_name_is_saved(self): Tag('Django') self.assertEqual(Tag('django').name, 'Django') def test_relpath(self): self.assertEqual(Tag('Django').get_relpath(), 'tags/django.html') def test_converts_to_unicode(self): self.assertEqual(unicode(Tag('Django')), u'Django')
trilan/snippets
tests/test_tag.py
Python
isc
638
using System; using Ookii.Dialogs.Wpf; namespace Aim.SpecLogLogoReplacer.UI.ViewModel { public class WpfDialogServices : IDialogServices { public string BrowseForFile(string extension) { var vistaOpenFileDialog = new VistaOpenFileDialog(); vistaOpenFileDialog.CheckFileExists = true; vistaOpenFileDialog.DefaultExt = extension; vistaOpenFileDialog.Multiselect = false; vistaOpenFileDialog.ShowDialog(); return vistaOpenFileDialog.FileName; } } }
dirkrombauts/SpecLogLogoReplacer
UI/ViewModel/WpfDialogServices.cs
C#
isc
503
/** * @file * UDPTransport is an implementation of UDPTransportBase for daemons. */ /****************************************************************************** * Copyright (c) 2009-2014, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #include <qcc/platform.h> #include <qcc/IPAddress.h> #include <qcc/Socket.h> #include <qcc/Thread.h> #include <qcc/String.h> #include <qcc/StringUtil.h> #include <qcc/IfConfig.h> #include <alljoyn/AllJoynStd.h> #include <alljoyn/BusAttachment.h> #include <alljoyn/Session.h> #include <alljoyn/TransportMask.h> #include <BusUtil.h> #include "BusInternal.h" #include "BusController.h" #include "ConfigDB.h" #include "RemoteEndpoint.h" #include "Router.h" #include "DaemonRouter.h" #include "ArdpProtocol.h" #include "ns/IpNameService.h" #include "UDPTransport.h" /* * How the transport fits into the system * ====================================== * * AllJoyn provides the concept of a Transport which provides a relatively * abstract way for the daemon to use different network mechanisms for getting * Messages from place to another. Conceptually, think of, for example, a Unix * transport that moves bits using unix domain sockets, a Bluetooth transport * that moves bits over a Bluetooth link, or a TCP transport that moves Messages * over a TCP connection. A UDP transport moves Messages over UDP datagrams * using a reliability layer. * * BSD sockets is oriented toward clients and servers. There are different * sockets calls required for a program implementing a server-side part and a * client side part. The server-side listens for incoming connection requests * and the client-side initiates the requests. AllJoyn clients are bus * attachments that our Applications may use and these can only initiate * connection requests to AllJoyn daemons. Although dameons may at first blush * appear as the service side of a typical BSD sockets client-server pair, it * turns out that while daemons obviously must listen for incoming connections, * they also must be able to initiate connection requests to other daemons. * This explains the presence of both connect-like methods and listen-like * methods here. * * A fundamental idiom in the AllJoyn system is that of a thread. Active * objects in the system that have threads wandering through them will implement * Start(), Stop() and Join() methods. These methods work together to manage * the autonomous activities that can happen in a UDPTransport. These * activities are carried out by so-called hardware threads. POSIX defines * functions used to control hardware threads, which it calls pthreads. Many * threading packages use similar constructs. * * In a threading package, a start method asks the underlying system to arrange * for the start of thread execution. Threads are not necessarily running when * the start method returns, but they are being *started*. Some time later, a * thread of execution appears in a thread run function, at which point the * thread is considered *running*. In the case of the UDPTransport, the Start() * method spins up a thread to run the basic maintenance operations such as * deciding when to listen and advertise. Another thread(s) is started to deal * with handling callbacks for deadlock avoidance. The AllJoyn daemon is a * fundamentally multithreaded environemnt, so multiple threads may be trying to * connect, disconnect, and write from the daemon side, and at the same time * connect, disconnect, read and write callbacks may be coming from the network * side. This means that as soon as UDPTransport::Start() is executed, multiple * threads, originating both in the transport and from outside, may be wandering * around in objects used by the tansport; and so one must be very careful about * resource management. This is the source of much of the complexity in this * module. * * In generic threads packages, executing a stop method asks the underlying * system to arrange for a thread to end its execution. The system typically * sends a message to the thread to ask it to stop doing what it is doing. The * thread is running until it responds to the stop message, at which time the * run method exits and the thread is considered *stopping*. The UDPTransport * provides a Stop() method to do exactly that. Note that neither of Start() * nor Stop() are synchronous in the sense that one has actually accomplished * the desired effect upon the return from a call. Of particular interest is * the fact that after a call to Stop(), threads will still be *running* for * some non-deterministic time. In order to wait until all of the threads have * actually stopped, a blocking call is required. In threading packages this is * typically called join, and our corresponding method is called Join(). A user * of the UDPTransport must assume that immediately after a call to Start() is * begun, and until a call to Join() returns, there may be threads of execution * wandering anywhere in the transport and in any callback registered by the * caller. The same model applies to connection endpoints (_UDPEndpoint) * instances. Further complicating _UDPEndpoint design is that the thread * lifetime methods may be called repeatedly or never (in the case of some forms * of timeout); and so the transport needs to ensure that all combinations of * these state transitions occur in an orderly and deterministic manner. * * The high-level process regarding how an advertisement translates into a * transport Connect() is a bit opaque, so we paint a high-level picture here. * First, a service (that will be *handling* RPC calls and *emitting* signals) * acquires a name on the bus, binds a session port and calls AdvertiseName. * This filters down (possibly through language bindings) to the AllJoyn Object. * The AllJoynObj essentially turns a DBus into an AllJoyn bus. The AllJoyn * Object consults the transports on the transport list (the UDP transport is * one of those) and eventually sends an advertisement request to each specified * transport by calling each transport's EnableAdvertisement() method. We * transnslate this call to a call to the the IpNameService::AdvertiseName() * method we call since we are an IP-based transport. The IP name service will * multicast the advertisements to other daemons listening on our device's * connected networks. * * A client that is interested in using the service calls the discovery * method FindAdvertisedName. This filters down (possibly through * language bindings) to the AllJoyn object, into the transports on the * transport list (us) and we eventually call IpNameService::FindAdvertisedName() * since we are an IP-based transport. The IP name service multicasts the * discovery message to other daemons listening on our networks. * * The daemon remembers which clients have expressed interest in which services, * and expects name services to call back with the bus addresses of daemons they * find which have the associated services. When a new advertisement is * received, the name service fires a callback into the transport, and it, in turn, calls * into its associated BusListener to pass the information back to the daemon. * * The callback includes information about the discovered name, the IP address, * port and daemon GUID of the remote daemon (now Routing Node). This bus * address is "hidden" from interested clients and replaced with a more generic * name and TransportMask bit (for us it will be TRANSPORT_UDP). The client * either responds by (1) ignoring the advertisement; (2) waiting to accumulate * more answers to see what the options are; or (3) joins a session to the * implied daemon/service. A reference to a SessionOpts object is provided as a * parameter to a JoinSession call if the client wants to connect. This * SessionOpts reference is passed down into the transport (selected by the * TransportMask) into the Connect() method which is used to establish the * connection and can be used to determine if the discovered name posesses * certain desired characteristics (to aid in determine the course of action * of the client * * There are four basic connection mechanisms that are described by the options. * These can be viewed as a matrix; * * IPv4 IPv6 * --------------- --------------- * TRAFFIC MESSAGES | TRAFFIC_RAW_RELIABLE | Reliable IPv4 Reliable IPv6 * TRAFFIC_RAW_UNRELIABLE | Unreliable IPv4 Unreliable IPv6 * * Note that although the UDP protocol is unreliable, the AllJoyn Reliable Datagram * Protocol is an additional reliability layer, so that TRAFFIC_MESSAGES are actually * sent over the UDP protocol. * The bits in the provided SessionOpts select the row, but the column is left * free (unspecified). This means that it is up to the transport to figure out * which one to use. Clearly, if only one of the two address flavors is * possible (known from examining the returned bus address which is called a * connect spec in the Connect() method) the transport should choose that one. * If both IPv4 or IPv6 are available, it is up to the transport (again, us) to * choose the "best" method since we don't bother clients with that level of * detail. * * Perhaps somewhat counter-intuitively, advertisements relating to the UDP * Transport use the u4addr (unreliable IPv4 address), u4port (unreliable IPv4 * port), u6addr (unreliable IPv6 address), and u6port (unreliable IPv6 port). * At the same time, the UDP Transport tells clients of the transport that it * supports TRAFFIC MESSAGES only. This is because the underlying network * protocol used is UDP which is inherently unreliable. We provide a * reliability layer to translate the unreliable UDP4 and UDP6 datagrams into * reliable AllJoyn messages. The UDP Transpot does not provide RAW sockets * which is a deprecated traffic type. * * Internals * ========= * * We spend a lot of time on the threading aspects of the transport since they * are often the hardest part to get right and are complicated. This is where * the bugs live. * * As mentioned above, the AllJoyn system uses the concept of a Transport. You * are looking at the UDPTransport. Each transport also has the concept of an * Endpoint. The most important function fo an endpoint is to provide (usually) * non-blocking semantics to higher level code. If the source thread overruns * the ability of the transport to move bits (reliably), we must apply * back-pressure by blocking the calling thread, but usually a call to PushBytes * results in an immediate UDP datagram sendto. In the UDP transport there are * separate worker threads assigned to reading UDP datagrams, running the * reliability layer and dispatching received AllJoyn messages. * * Endpoints are specialized into the LocalEndpoint and the RemoteEndpoint * classes. LocalEndpoint represents a connection from a router to the local * bus attachment or daemon (within the "current" process). A RemoteEndpoint * represents a connection from a router to a remote attachment or daemon. By * definition, the UDPTransport provides RemoteEndpoint functionality. * * RemoteEndpoints are further specialized according to the flavor of the * corresponding transport, and so you will see a UDPEndpoint class defined * below which provides functionality to send messages from the local router to * a destination off of the local process using a UDP transport mechanism. * * RemoteEndpoints use AllJoyn stream objects to actually move bits. In UDP * this is a bit of an oxymoron, however an AllJoyn stream is a thin layer on * top of a Socket (which is another thin layer on top of a BSD socket) that * provides a PushBytes() method. Although UDP is not a stream-based protocol, * we treat each received datagram as a separate stream for the purposes of * passing back to the AllJoyn core which expectes to be able to read bytes from * a message backing object. * * Unlike a TCP transport, there are no dedicated receive threads. Receive * operations in UDP are not associted with a particular endpoint at all, other * than using the required endpoint as a convencient place holder for a * connection data structure. The UDP Transport operates more in an * Asynchronous IO-like fashion. Received datagrams appear out of the ARDP * protocol as callbacks and are sent into a callback dispatcher thread. Once * the dispatcher has an inbound datagram(s) it reassembles and unmarshals the * datagrams into an AllJoyn Message. It then calls into the daemon * (PushMessage) to arrange for delivery. A separate thread runs the * maintenance aspects of the UDP reliability layer (to drive retransmissions, * timeouts, etc.) and the endpoint management code (to drive the lifetime state * transitions of endpoints). * * The UDPEndpoint inherits some infrastructure from the more generic * RemoteEndpoint class. Since the UDP transport is a not a stream-based * protocol, it does redefine some of the basic operation of the RemoteEndpoint * to suit its needs. The RemoteEndpoint is also somewhat bound to the concept * of stream and receive thread, so we have to jump through some hoops to * coexist. * * The UDP endpoint does not use SASL for authentication and implements required * dameon exchanges in the SYN, SYN + ACK echanges of the underlying ARDP * protocol. Although there is no authentication, per se, we still call this * handshake phase authentication since the BusHello is part of the * authentication phase of the TCP Transport. Authentication can, of course, * succeed or fail based on timely interaction between the two sides, but it can * also be abused in a denial of service attack. If a client simply starts the * process but never responds, it could tie up a daemon's resources, and * coordinated action could bring down a daemon. Because of this, we provide a * way to reach in and abort authentications that are "taking too long" and free * the associated resources. * * As described above, a daemon can listen for inbound connections and it can * initiate connections to remote daemons. Authentication must happen in both * cases and so we need to worry about denial of service in both directions and * recover gracefully. * * When the daemon is brought up, its TransportList is Start()ed. The transport * specs string (e.g., "unix:abstract=alljoyn;udp:;tcp:;bluetooth:") is provided * to TransportList::Start() as a parameter. The transport specs string is * parsed and in the example above, results in "unix" transports, "tcp" * transports, "udp" transports and "bluetooth" transports being instantiated * and started. As mentioned previously "udp:" in the daemon translates into * UDPTransport. Once the desired transports are instantiated, each is * Start()ed in turn. In the case of the UDPTransport, this will start the * maintenance loop. Initially there are no sockets to listen on. * * The daemon then needs to start listening on inbound addresses and ports. * This is done by the StartListen() command. This also takes the same kind of * server args string shown above but this time the address and port information * are used. For example, one might use the string * "udp:u4addr=0.0.0.0,u4port=9955;" to specify which address and port to listen * to. This Bus::StartListen() call is translated into a transport * StartListen() call which is provided with the string described above, which * we call a "listen spec". Our UDPTransport::StartListen() will arange to * create a Socket, bind the socket to the address and port provided and save * the new socket on a list of "listenFds" (we may listen on separate sockets * corresponding to multiple network interfaces). Another of the many * complications we have to deal with is that the Android Compatibility Test * Suite (CTS) requires that an idle phone not have any sockets listening for * inbound data. In order to pass the CTS in the case of the pre-installed * daemon, we must only have open name service sockets when actively advertising * or discovering. This implies that we need to track the adveritsement state * and enable or disable the name service depending on that state. * * An inbound connection request in the UDP transport is consists of receiving a * SYN datagram. The AcceptCb() is called from the reliability layer (on * reception of a SYN packet) in order to ask whether or not the connection * should be accepted. If AcceptCb() determines there are enough resources for * a new connection it will call ARDP_Accept to provide a BusHello reply and * return true indicating acceptance, or false which means rejection. If the * connection is accepted, a ConnectCb() is fired and the callback dispatcher * thread will ultimately handle the incoming request and create a UDPEndpoint * for the *proposed* new connection. * * Recall that an endpoint is not brought up immediately, but an authentication * step must be performed. The required information (BusHello reply) is * provided back in the SYN + ACK packet. The final ACK of the three-way * handshake completes the inbound connection establishment process. * If the authentication takes "too long" we assume that a denial of service * attack in in progress. We fail such partial connections and the endpoint * management code removes them. * * A daemon transport can accept incoming connections, and it can make outgoing * connections to another daemon. This case is simpler than the accept case * since it is expected that a socket connect can block higner level code, so it * is possible to do authentication in the context of the thread calling * Connect(). Connect() is provided a so-called "connect spec" which provides * an IP address ("u4addr=xxxx"), port ("y4port=yyyy") in a String. A check is * always made to catch an attempt for the daemon to connect to itself which is * a system-defined error (it causes the daemon grief, so we avoid it here by * looking to see if one of the listenFds is listening on an interface that * corresponds to the address in the connect spec). If the connect is allowed, * ee kick off a process in the underlying UDP reliability layer that * corresponds to the 3-way handshake of TCP. * * Shutting the UDPTransport down involves orchestrating the orderly termination * of: * * 1) Threads that may be running in the maintenance loop with associated Events * and their dependent socketFds stored in the listenFds list; * 3) The callback dispatcher thread that may be out wandering around in the * daemon doing its work; * 2) Threads that may be running around in endpoints and streams trying to write * Mesages to the network. * * We have to be careful to follow the AllJoyn threading model transitions in * both the UDPTransport and all of its associated _UdpEndpoints. There are * reference counts of endpoints to be respected as well. In order to ensure * orderly termination of endoints and deterministic disposition of threads * which may be executing in those endpoints, We want the last reference count * held on an endpoint to be the one held by the transport. There is much * work (see IncrementAndFetch, DecrementAndFetch, ManagedObj for example) * done to ensure this outcome. * * There are a lot of very carefully managed relationships here, so be careful * when making changes to the thread and resource management aspects of any * transport. Taking lock order lightly is a recipe for disaster. Always * consider what locks are taken where and in what order. It's quite easy to * shoot yourself in multiple feet you never knew you had if you make an unwise * modification, and this can sometimes result in tiny little time-bombs set to * go off in seemingly completely unrelated code. * * A note on connection establishment * ================================== * * In the TCP transport, a separate synchronous sequence is executed before * AllJoyn messages can begin flowing. First a NUL byte is sent as is required * in the DBus spec. In order to get a destination address for the BusHello * message, the local side relies on the SASL three-way handshake exchange: * * SYN ------------> * <- SYN + ACK * ACK ------------> * NUL ------------> * AUTH ANONYMOUS -> * <- OK <GUID> * BEGIN ----------> * * Once this is done, the active connector sends a BusHello Message and the * passive side sends a response * * BusHello -------> * <- BusHello reply * * In the UDP Transport, we get rid of basically the whole Authentication * process and exchange required information in the SYN, SYN + ACK and * ACK packets of the protocol three-way handshake. * * The initial ARDP SYN packet *implies* AUTH_ANONYMOUS and contains the * BusHello message data from the Local (initiating/active) side of the * connection. The SYN + ACK segment in response from the remote side contains * the response to the BusHello that was sent in the SYN packet. * * SYN + BusHello --> * <- SYN + ACK + BusHello Reply * ACK -------------> * * This all happens in a TCP-like SYN, SYN + ACK, ACK exchange with AllJoyn * data. At the reception of the final ACK, the connection is up and running. * * This exchange is implemented using a number of callback functions that * fire on the local (active) and remote (passive) side of the connection. * * 1) The actively connecting side provides a BusHello message in call to * ARDP_Connect(). As described above, ARDP provides this message as data in * the SYN segment which is the first part of the three-way handshake; * * 2) When the passive side receives the SYN segment, its AcceptCb() callback is * fired. The data provided in the accept callback contains the BusHello * message from the actively opening side. The passive side, if it chooses * to accept the connection, makes a call to ARDP_Accept() with its reply to * the BusHello from the active side as data. ARDP provides this data back * in the SYN + ACK segment as the second part of its three-way handshake; * * 3) The actively connecting side receives a ConnectCb() callback as a result * of the SYN + ACK coming back from the passive side. This indicates that * the newly established connection is going into the OPEN state from the * local side's (ARDP) perspective. Prior to firing the callback, ARDP * automatically sends the final ACK and completes the three-way handshake. * The ConectCb() with the active indication means that a SYN + ACK has been * received that includes the reply to the original BusHello message. * * 4) When the final ACK of the three-way handshake is delivered to the passive * opener side, it transitions the passive side to the OPEN state and fires * a ConnectCb() callback with the passive indication meaning that the final * ACK of the three-way handhake has arrived. * * From the perspective of the UDP Transport, this translates into the following * sequence diagram that reflects the three-way handshake that is going on under * the whole thing. * * Active Side Passive Side * =========== ============ * ARDP_Connect([out]BusHello message) --> AcceptCb([in]BusHello message) -----+ * | * +--- ConnectCb([in]BusHello reply) <-------- ARDP_Accept([out]BusHello reply) <--+ * | * +------------------------------------------> ConnectCb(NULL) * */ #define QCC_MODULE "UDP" #define SENT_SANITY 1 using namespace std; using namespace qcc; /** * This is the time between calls to ManageEndpoints if nothing external is * happening to drive it. Usually, something happens to drive ManageEndpoints * like a connection starting or stopping or a connection timing out. This is * basically a watchdog to to keep the pump primed. */ const uint32_t UDP_ENDPOINT_MANAGEMENT_TIMER = 1000; const uint32_t UDP_CONNECT_TIMEOUT = 3000; /**< How long before we expect a connection to complete */ const uint32_t UDP_CONNECT_RETRIES = 3; /**< How many times do we retry a connection before giving up */ const uint32_t UDP_DATA_TIMEOUT = 3000; /**< How long do we wait before retrying sending data */ const uint32_t UDP_DATA_RETRIES = 5; /**< How many times to we try do send data before giving up and terminating a connection */ const uint32_t UDP_PERSIST_TIMEOUT = 5000; /**< How long do we wait before pinging the other side due to a zero window */ const uint32_t UDP_PERSIST_RETRIES = 5; /**< How many times do we do a zero window ping before giving up and terminating a connection */ const uint32_t UDP_PROBE_TIMEOUT = 10000; /**< How long to we wait on an idle link before generating link activity */ const uint32_t UDP_PROBE_RETRIES = 5; /**< How many times do we try to probe on an idle link before terminating the connection */ const uint32_t UDP_DUPACK_COUNTER = 1; /**< How many duplicate acknowledgements to we need to trigger a data retransmission */ const uint32_t UDP_TIMEWAIT = 1000; /**< How long do we stay in TIMWAIT state before releasing the per-connection resources */ namespace ajn { /** * Name of transport used in transport specs. */ const char* UDPTransport::TransportName = "udp"; /** * Default router advertisement prefix. Currently Thin Library devices cannot * connect to routing nodes over UDP. */ #if ADVERTISE_ROUTER_OVER_UDP const char* const UDPTransport::ALLJOYN_DEFAULT_ROUTER_ADVERTISEMENT_PREFIX = "org.alljoyn.BusNode."; #endif const char* TestConnStr = "ARDP TEST CONNECT REQUEST"; const char* TestAcceptStr = "ARDP TEST ACCEPT"; #ifndef NDEBUG static void DumpLine(uint8_t* buf, uint32_t len, uint32_t width) { for (uint32_t i = 0; i < width; ++i) { if (i > len) { printf(" "); } else { printf("%02x ", buf[i]); } } printf(": "); for (uint32_t i = 0; i < len && i < width; ++i) { if (iscntrl(buf[i]) || !isascii(buf[i])) { printf("."); } else { printf("%c", buf[i]); } } printf("\n"); } static void DumpBytes(uint8_t* buf, uint32_t len) { if (_QCC_DbgPrintCheck(DBG_GEN_MESSAGE, QCC_MODULE)) { for (uint32_t i = 0; i < len; i += 16) { DumpLine(buf + i, len - i > 16 ? 16 : len - i, 16); } } } #endif // NDEBUG #ifndef NDEBUG #define SEAL_SIZE 4 void SealBuffer(uint8_t* p) { *p++ = 'S'; *p++ = 'E'; *p++ = 'A'; *p++ = 'L'; } void CheckSeal(uint8_t* p) { assert(*p++ == 'S' && *p++ == 'E' && *p++ == 'A' && *p++ == 'L' && "CheckSeal(): Seal blown"); } #endif class _UDPEndpoint; /** * A skeletal variety of a Stream used to fake the system into believing that * there is a stream-based protocol at work here. This is not intended to be * wired into IODispatch but is used to allow the daemon to to run in a * threadless, streamless environment without major changes. */ class ArdpStream : public qcc::Stream { public: ArdpStream() : m_transport(NULL), m_endpoint(NULL), m_handle(NULL), m_conn(NULL), m_dataTimeout(0), m_dataRetries(0), m_lock(), m_disc(false), m_discSent(false), m_discStatus(ER_OK), m_writeEvent(NULL), m_writesOutstanding(0), m_writeWaits(0), m_buffers() { QCC_DbgTrace(("ArdpStream::ArdpStream()")); m_writeEvent = new qcc::Event(); } virtual ~ArdpStream() { QCC_DbgTrace(("ArdpStream::~ArdpStream()")); QCC_DbgPrintf(("ArdpStream::~ArdpStream(): delete events")); delete m_writeEvent; m_writeEvent = NULL; } /** * Get a pointer to the associated UDP transport instance. */ UDPTransport* GetTransport() const { QCC_DbgTrace(("ArdpStream::GetTransport(): => %p", m_transport)); return m_transport; } /** * Set the pointer to the associated UDP transport instance. */ void SetTransport(UDPTransport* transport) { QCC_DbgTrace(("ArdpStream::SetTransport(transport=%p)", transport)); m_transport = transport; } /** * Get a pointer to the associated UDP endpoint. */ _UDPEndpoint* GetEndpoint() const { QCC_DbgTrace(("ArdpStream::GetEndpoint(): => %p", m_endpoint)); return m_endpoint; } /** * Set the pointer to the associated UDP endpoint instance. */ void SetEndpoint(_UDPEndpoint* endpoint) { QCC_DbgTrace(("ArdpStream::SetEndpoint(endpoint=%p)", endpoint)); m_endpoint = endpoint; } /** * Get the information that describes the underlying ARDP protocol connection. */ ArdpHandle* GetHandle() const { QCC_DbgTrace(("ArdpStream::GetHandle(): => %p", m_handle)); return m_handle; } /** * Set the handle to the underlying ARDP protocol instance. */ void SetHandle(ArdpHandle* handle) { QCC_DbgTrace(("ArdpStream::SetHandle(handle=%p)", handle)); m_handle = handle; } /** * Get the information that describes the underlying ARDP protocol * connection. */ ArdpConnRecord* GetConn() const { QCC_DbgTrace(("ArdpStream::GetConn(): => %p", m_conn)); return m_conn; } /** * Set the information that describes the underlying ARDP protocol * connection. */ void SetConn(ArdpConnRecord* conn) { QCC_DbgTrace(("ArdpStream::SetConn(conn=%p)", conn)); m_conn = conn; } /** * Get the number of outstanding write operations in process on the stream. * connection. */ uint32_t GetWritesOutstanding() { QCC_DbgTrace(("ArdpStream::GetWritesOutstanding() => %d.", m_writesOutstanding)); return m_writesOutstanding; } /** * Add the currently running thread to a set of threads that may be * currently referencing the internals of the stream. We need this list to * make sure we don't try to delete the stream if there are threads * currently using the stream, and to wake those threads in case the threads * are blocked waiting for a send to complete when the associated endpoint * is shut down. */ void AddCurrentThread() { QCC_DbgTrace(("ArdpStream::AddCurrentThread()")); ThreadEntry entry; entry.m_thread = qcc::Thread::GetThread(); entry.m_stream = this; m_lock.Lock(MUTEX_CONTEXT); m_threads.insert(entry); m_lock.Unlock(MUTEX_CONTEXT); } /** * Remove the currently running thread from the set of threads that may be * currently referencing the internals of the stream. */ void RemoveCurrentThread() { QCC_DbgTrace(("ArdpStream::RemoveCurrentThread()")); ThreadEntry entry; entry.m_thread = qcc::Thread::GetThread(); entry.m_stream = this; m_lock.Lock(MUTEX_CONTEXT); set<ThreadEntry>::iterator i = m_threads.find(entry); assert(i != m_threads.end() && "ArdpStream::RemoveCurrentThread(): Thread not on m_threads"); m_threads.erase(i); m_lock.Unlock(MUTEX_CONTEXT); } void WakeThreadSet() { QCC_DbgTrace(("ArdpStream::WakeThreadSet()")); m_lock.Lock(MUTEX_CONTEXT); for (set<ThreadEntry>::iterator i = m_threads.begin(); i != m_threads.end(); ++i) { QCC_DbgTrace(("ArdpStream::Alert(): Wake thread %p waiting on stream %p", i->m_thread, i->m_stream)); i->m_stream->m_writeEvent->SetEvent(); } m_lock.Unlock(MUTEX_CONTEXT); } /** * Determine whether or not there is a thread waiting on the stream for a write * operation to complete. */ bool ThreadSetEmpty() { QCC_DbgTrace(("ArdpStream::ThreadSetEmpty()")); m_lock.Lock(MUTEX_CONTEXT); bool empty = m_threads.empty(); m_lock.Unlock(MUTEX_CONTEXT); QCC_DbgTrace(("ArdpStream::ThreadSetEmpty(): -> %s", empty ? "true" : "false")); return empty; } /** * Get the data transmission timeout that the underlying ARDP protocol * connection will be using */ uint32_t GetDataTimeout() const { QCC_DbgTrace(("ArdpStream::GetDataTimeout(): => %d.", m_dataTimeout)); return m_dataTimeout; } /** * Set the data transmission timeout that the underlying ARDP protocol * connection will be using */ void SetDataTimeout(uint32_t dataTimeout) { QCC_DbgTrace(("ArdpStream::SetDataTimeout(dataTimeout=%d.)", dataTimeout)); m_dataTimeout = dataTimeout; } /** * Get the data transmission retries that the underlying ARDP protocol * connection will be using */ uint32_t GetDataRetries() const { QCC_DbgTrace(("ArdpStream::GetDataRetries(): => %d.", m_dataRetries)); return m_dataRetries; } /** * Set the data transmission retries that the underlying ARDP protocol * connection will be using */ void SetDataRetries(uint32_t dataRetries) { QCC_DbgTrace(("ArdpStream::SetDataRetries(dataRetries=%d.)", dataRetries)); m_dataRetries = dataRetries; } /** * Set the stream's write event if it exists */ void SetWriteEvent() { QCC_DbgTrace(("ArdpStream::SetWriteEvent()")); m_lock.Lock(MUTEX_CONTEXT); if (m_writeEvent) { m_writeEvent->SetEvent(); } m_lock.Unlock(MUTEX_CONTEXT); } /** * Send some bytes to the other side of the conection described by the * m_conn member variable. * * The caller of this function is most likely the daemon router that is * moving a message to a remote destination. It was written expecting this * call to copy bytes into TCP or block when TCP applies backpressure. As * soon as the call returns, the router expects to be able to delete the * message backing buffer (our buf) and go on about its business. * * That means we basically have to do the same thing here unless we start * ripping the guts out of the system. That means the daemon router expects * to see and endpoint with a stream in it that has this PushBytes method. * * we need to copy the data in and return immediately if there is no * backpressure from the protocol; or copy the data in and block the caller * if there is backpressure. Backpressure is indicated by the * ER_ARDP_BACKPRESSURE return. If this happens, we cannot send any more * data until we get a send callback indicating the other side has consumed * some data. In this case we need to block the calling thread until it can * continue. * * TODO: Note that the blocking is on an endpoint-by-endpoint basis, which * means there is a write event per endpoint. This could be changed to one * event per transport, but would mean waking all blocked threads only to * have one of them succeed and the rest go back to sleep if the event * wasn't directed at them. This is the classic thundering herd, but trades * CPU for event resources which may be a good way to go since our events * can be so expensive. It's a simple change conceptually but there is no * bradcast condition variable in common, which would be the way to go. * * For now, we will take the one event per endpoint approach and optimize * that as time permits. * * When a buffer is sent, the ARDP protocol takes ownership of it until it * is ACKed by the other side or it times out. When the ACK happens, a send * callback is fired that will record the actual status of the send and free * the buffer. The status of the write is not known until the next read or * write operation. */ QStatus PushBytes(const void* buf, size_t numBytes, size_t& numSent, uint32_t ttl) { QCC_DbgTrace(("ArdpStream::PushBytes(buf=%p, numBytes=%d., numSent=%p)", buf, numBytes, &numSent)); QStatus status; if (m_transport->IsRunning() == false || m_transport->m_stopping == true) { status = ER_UDP_STOPPING; QCC_LogError(status, ("ArdpStream::PushBytes(): UDP Transport not running or stopping")); return status; } if (m_disc) { status = m_discStatus; QCC_LogError(status, ("ArdpStream::PushBytes(): ARDP connection found disconnected")); return status; } /* * There's a new thread in town, so add it to the list of threads * wandering around in the associated endpoint. We need to keep track * of this in case the endpoint is stopped while the current thread is * wandering around in the stream trying to get its send done. */ AddCurrentThread(); #ifndef NDEBUG DumpBytes((uint8_t*)buf, numBytes); #endif /* * Copy in the bytes to preserve the buffer management approach expected by * higher level code. */ QCC_DbgPrintf(("ArdpStream::PushBytes(): Copy in")); #ifndef NDEBUG uint8_t* buffer = new uint8_t[numBytes + SEAL_SIZE]; SealBuffer(buffer + numBytes); #else uint8_t* buffer = new uint8_t[numBytes]; #endif memcpy(buffer, buf, numBytes); /* * Set up a timeout on the write. If we call ARDP_Send, we expect it to * come back with some a send callback if it accepts the data. As a * double-check, we add our own timeout that expires some time after we * expect ARDP to time out. On a write that would be at * * dataTimeout * (1 + dataRetries) * * To give ARDP a chance, we timeout one retry interval later, at * * dataTimeout * (2 + dataRetries) * */ uint32_t timeout = GetDataTimeout() * (2 + GetDataRetries()); Timespec tStart; GetTimeNow(&tStart); QCC_DbgPrintf(("ArdpStream::PushBytes(): Start time is %d.", tStart)); /* * Now we get down to business. We are going to enter a loop in which * we retry the write until it succeeds. The write can either be a soft * failure which means that the protocol is applying backpressure and we * should try again "later" or it can be a hard failure which means the * underlying UDP send has failed. In that case, we give up since * presumably something bad has happened, like the Wi-Fi has * disassociated or someone has unplugged a cable. */ while (true) { if (m_transport->IsRunning() == false || m_transport->m_stopping == true) { #ifndef NDEBUG CheckSeal(buffer + numBytes); #endif delete[] buffer; status = ER_UDP_STOPPING; QCC_LogError(status, ("ArdpStream::PushBytes(): UDP Transport not running or stopping")); RemoveCurrentThread(); return status; } Timespec tNow; GetTimeNow(&tNow); int32_t tRemaining = tStart + timeout - tNow; QCC_DbgPrintf(("ArdpStream::PushBytes(): tRemaining is %d.", tRemaining)); if (tRemaining <= 0) { #ifndef NDEBUG CheckSeal(buffer + numBytes); #endif delete[] buffer; status = ER_TIMEOUT; QCC_LogError(status, ("ArdpStream::PushBytes(): Timed out")); RemoveCurrentThread(); return status; } m_transport->m_ardpLock.Lock(); status = ARDP_Send(m_handle, m_conn, buffer, numBytes, ttl); m_transport->m_ardpLock.Unlock(); /* * If we do something that is going to bug the ARDP protocol, we need * to call back into ARDP ASAP to get it moving. This is done in the * main thread, which we need to wake up. Note that we don't set * m_manage so we don't trigger endpoint management, we just trigger * ARDP_Run to happen. */ m_transport->Alert(); /* * If the send succeeded, then the bits are on their way off to the * destination. The send callback associated with this PushBytes() * will take care of freeing the buffer we allocated. We return back * to the caller as if we were TCP and had copied the bytes into the * kernel. */ if (status == ER_OK) { m_transport->m_cbLock.Lock(); #if SENT_SANITY m_sentSet.insert(buffer); #endif ++m_writesOutstanding; QCC_DbgPrintf(("ArdpStream::PushBytes(): ARDP_Send(): Success. m_writesOutstanding=%d.", m_writesOutstanding)); m_transport->m_cbLock.Unlock(); numSent = numBytes; RemoveCurrentThread(); return status; } /* * If the send failed, and the failure was not due to the application * of backpressure by the protocol, we have a hard failure and we need * to give up. Since the buffer wasn't sent, the callback won't happen * and we need to dispose of it here and now. */ if (status != ER_ARDP_BACKPRESSURE) { #ifndef NDEBUG CheckSeal(buffer + numBytes); #endif delete[] buffer; QCC_LogError(status, ("ArdpStream::PushBytes(): ARDP_Send(): Hard failure")); RemoveCurrentThread(); return status; } /* * Backpressure has been applied. We can't send another message on * this connection until the other side ACKs one of the outstanding * datagrams. It communicates this to us by a send callback which, * in turn, sets an event that wakes us up. */ if (status == ER_ARDP_BACKPRESSURE) { QCC_DbgPrintf(("ArdpStream::PushBytes(): ER_ARDP_BACKPRESSURE")); /* * Multiple threads could conceivably be trying to write at the * same time another thread fires callbacks, so we have to be * careful. If m_writesOutstanding is non-zero, the ARDP * protocol has a contract with us to call back when writes are * is complete. To make sure we are synchronized with the * callback thread, we release the callback lock during the call * to Event::Wait(). * * To make sure only one of the threads does the reset of the * event (confusing another), we keep track of how many are * waiting at any one time and only let the first one reset the * underlying event. This means that a second waiter could be * awakened unnecessarily, but it will immediately try agian and * go back to sleep. */ m_transport->m_cbLock.Lock(); QCC_DbgPrintf(("ArdpStream::PushBytes(): Backpressure. m_writesOutstanding=%d.", m_writesOutstanding)); /* * It is possible that between the time we called ARDP_Send and * the time we just took the callback lock immediately above, * all (especially if the window is one) of the previous sends * that caused the rejection of the current send has actually * completed and relieved the backpressure. Now that we are in * firm control of the process with the lock taken, check to see * if there are any writes outstanding. If there are not, we * will never get a callback to wake us up, so we need to loop * back around and see if we can write again. Since there are * no writes outstanding, the answer will be yes. */ if (m_writesOutstanding == 0) { m_transport->m_cbLock.Unlock(); QCC_DbgPrintf(("ArdpStream::PushBytes(): Backpressure relieved")); continue; } /* * Multiple threads could conceivably be trying to write at the * same time another thread fires callbacks, so we have to be * careful. To make sure only one of the writer threads does * the reset of the event (confusing another), we keep track of * how many are waiting at any one time and only let the first * one reset the underlying event. This means that a second * waiter could be awakened unnecessarily, but it will * immediately try again and go back to sleep. To make sure we * are synchronized with the callback thread, we release the * callback lock during the call to Event::Wait(). */ QCC_DbgPrintf(("ArdpStream::PushBytes(): Backpressure. m_writeWaits=%d.", m_writeWaits)); if (m_writeWaits == 0) { QCC_DbgPrintf(("ArdpStream::PushBytes(): Backpressure. Reset write event")); m_writeEvent->ResetEvent(); } ++m_writeWaits; QCC_DbgPrintf(("ArdpStream::PushBytes(): Backpressure. Event::Wait(). m_writeWaits=%d.", m_writeWaits)); status = qcc::Event::Wait(*m_writeEvent, m_transport->m_cbLock, tRemaining); m_transport->m_cbLock.Lock(); QCC_DbgPrintf(("ArdpStream::PushBytes(): Backpressure. Back from Event::Wait(). m_writeWaits=%d.", m_writeWaits)); --m_writeWaits; QCC_DbgPrintf(("ArdpStream::PushBytes(): Backpressure. Decremented m_writeWaits=%d.", m_writeWaits)); m_transport->m_cbLock.Unlock(); /* * If the wait fails, then there's nothing we can do but bail. If we * never actually started the send sucessfully, the callback will never * happen and we need to free the buffer we newed here. */ if (status != ER_OK && status != ER_TIMEOUT) { #ifndef NDEBUG CheckSeal(buffer + numBytes); #endif delete[] buffer; QCC_LogError(status, ("ArdpStream::PushBytes(): WaitWriteEvent() failed")); RemoveCurrentThread(); return status; } /* * If there was a disconnect in the underlying connection, there's * nothing we can do but return the error. */ if (m_disc) { #ifndef NDEBUG CheckSeal(buffer + numBytes); #endif delete[] buffer; QCC_LogError(m_discStatus, ("ArdpStream::PushBytes(): Disconnected")); RemoveCurrentThread(); return m_discStatus; } QCC_DbgPrintf(("ArdpStream::PushBytes(): Backpressure loop")); } /* * We detected backpressure and waited until a callback indicated * that the backpressure was relieved. We gave up the cb lock, * so now we loop back around and try the ARDP_Send again, maybe * waiting again. */ } assert(0 && "ArdpStream::PushBytes(): Impossible condition"); RemoveCurrentThread(); return ER_FAIL; } /* * A version of PushBytes that doesn't care about TTL. */ QStatus PushBytes(const void* buf, size_t numBytes, size_t& numSent) { QCC_DbgTrace(("ArdpStream::PushBytes(buf=%p, numBytes=%d., numSent=%p)", buf, numBytes, &numSent)); return PushBytes(buf, numBytes, numSent, 0); } /** * Get some bytes from the other side of the conection described by the * m_conn member variable. Data must be present in the message buffer * list since we expect that a RecvCb that added a buffer to that list is * what is going to be doing the read that will eventually call PullBytes. * In that case, since the data is expected to be present, <timeout> will * be zero. */ QStatus PullBytes(void* buf, size_t reqBytes, size_t& actualBytes, uint32_t timeout) { QCC_DbgTrace(("ArdpStream::PullBytes(buf=%p, reqBytes=%d., actualBytes=%d., timeout=%d.)", buf, reqBytes, actualBytes, timeout)); assert(0 && "ArdpStream::PullBytes(): Should never be called"); return ER_FAIL; } /** * Set the stram up for being torn down before going through the expected * lifetime state transitions. */ void EarlyExit() { QCC_DbgTrace(("ArdpStream::EarlyExit()")); /* * An EarlyExit is one when a stream has been created in the expectation * that an endpoint will be brought up, but the system changed its mind * in mid-"stream" and therefore there is no disconnect processing needed * and there must be no threads waiting. */ m_lock.Lock(MUTEX_CONTEXT); m_disc = true; m_conn = NULL; m_discStatus = ER_UDP_EARLY_EXIT; m_lock.Unlock(MUTEX_CONTEXT); } /** * Get the disconnected status. If the stream has been disconnected, return * true otherwise false. */ bool GetDisconnected() { QCC_DbgTrace(("ArdpStream::Disconnected(): -> %s", m_disc ? "true" : "false")); return m_disc; } /** * In the case of a local disconnect, disc sent means that ARDP_Disconnect() * has been called. Determine if this call has been made or not. */ bool GetDiscSent() { QCC_DbgTrace(("ArdpStream::GetDiscSent(): -> %s", m_discSent ? "true" : "false")); return m_discSent; } /** * Process a disconnect event, either local or remote. */ void Disconnect(bool sudden, QStatus status) { if (status == ER_OK) { assert(sudden == false); } if (sudden) { assert(status != ER_OK); } QCC_DbgTrace(("ArdpStream::Disconnect(sudden==%d., status==\"%s\")", sudden, QCC_StatusText(status))); /* * A "sudden" disconnect is an unexpected or unsolicited disconnect * initiated from the remote side. In this case, we will have have * gotten an ARDP DisconnectCb() which tells us that the connection is * gone and we shouldn't use it again. * * If sudden is not true, then this is as a result of a local request to * terminate the connection. This means we need to call ARDP and let it * know we are disconnecting. We wait for the DisconnectCb() that must * happen as a result of the ARDP_Disconnect() to declare the connection * completely gone. * * The details can get very intricate becuase once a remote side has * disconnected, we can get a flood of disconnects from different local * users of the endopint as the daemon figures out what it no longer * needs as a result of a remote endpoint going away. We just have to * harden ourselves against many duplicate calls. There are three bits * to worry about (sudden, m_discSent, and m_disc) and so there are * eight possibile conditions/states here. We just break them all out. */ QCC_DbgPrintf(("ArdpStream::Disconnect(): sudden==%d., m_disc==%d., m_discSent==%d., status==\"%s\"", sudden, m_disc, m_discSent, QCC_StatusText(status))); m_lock.Lock(MUTEX_CONTEXT); if (sudden == false) { if (m_disc == false) { if (m_discSent == false) { /* * sudden = false, m_disc = false, m_discSent == false * * This is a new solicited local disconnect event that is * happening on a stream that has never seen a disconnect * event. We need to do an ARDP_Disconnect() to start the * disconnect process. We expect status to be * ER_UDP_LOCAL_DISCONNECT by contract. If we fail to send * the ARDP_Disconnect() the disconnect status is updated * to the reason we couldn't send it. */ assert(status == ER_UDP_LOCAL_DISCONNECT && "ArdpStream::Disconnect(): Unexpected status"); m_transport->m_ardpLock.Lock(); status = ARDP_Disconnect(m_handle, m_conn); m_transport->m_ardpLock.Unlock(); if (status == ER_OK) { m_discSent = true; m_discStatus = ER_UDP_LOCAL_DISCONNECT; } else { QCC_LogError(status, ("ArdpStream::Disconnect(): Cannot send ARDP_Disconnect()")); m_disc = true; m_conn = NULL; m_discSent = true; m_discStatus = status; } /* * Tell the endpoint manager that something interesting has * happened */ m_transport->m_manage = UDPTransport::STATE_MANAGE; m_transport->Alert(); } else { /* * sudden = false, m_disc = false, m_discSent == true * * This disconnect event is happening as a result of the * ARDP disconnect callback. We expect that the status * passed in is ER_OK to confirm that this is the response * to the ARDP_Disconnect(). This completes the locally * initiated disconnect process. If this happens, we expect * status to be ER_OK by contract and we expect the * disconnect status to have been set to * ER_UDP_LOCAL_DISCONNECT by us. */ assert(status == ER_OK && "ArdpStream::Disconnect(): Unexpected status"); assert(m_discStatus == ER_UDP_LOCAL_DISCONNECT && "ArdpStream::Disconnect(): Unexpected status"); m_disc = true; m_conn = NULL; /* * Tell the endpoint manager that something interesting has * happened */ m_transport->m_manage = UDPTransport::STATE_MANAGE; m_transport->Alert(); } } else { if (m_discSent == false) { /* * sudden = false, m_disc = true, m_discSent == false * * This is a locally initiated disconnect that happens as a * result of a previously received remote disconnect. This * can happen when the daemon begins dereferencing * (Stopping) endpoints as a result of a previously reported * disconnect. * * The connection should already be gone. */ assert(m_conn == NULL && "ArdpStream::Disconnect(): m_conn unexpectedly live"); assert(m_disc == true && "ArdpStream::Disconnect(): unexpectedly not disconnected"); } else { /* * sudden = false, m_disc = true, m_discSent == true * * This is a locally initiated disconnect that happens after * a local disconnect that has completed (ARDP_Disconnect() * has been called and its DisconnectCb() has been received. * This can happen when the daemon begins dereferencing * (Stopping) endpoints as a result of a previously reported * disconnect but is a little slow at doing so. * * The connection should already be gone. */ assert(m_conn == NULL && "ArdpStream::Disconnect(): m_conn unexpectedly live"); assert(m_disc == true && "ArdpStream::Disconnect(): unexpectedly not disconnected"); } } } else { if (m_disc == false) { if (m_discSent == false) { /* * sudden = true, m_disc = false, m_discSent == false * * This is a new unsolicited remote disconnect event that is * happening on a stream that has never seen a disconnect * event. */ m_conn = NULL; m_disc = true; m_discStatus = status; } else { /* * sudden = true, m_disc = false, m_discSent == true * * This is an unsolicited remote disconnect event that is * happening on a stream that has previously gotten a local * disconnect event and called ARDP_Disconnect() but has not * yet received the DisconnectCb() as a result of that * ARDP_Disconnect(). * * This indicates a race between the local disconnect and a * remote disconnect. Any sudden disconnect means the * connection is gone; so a remote disconnect trumps an * in-process local disconnect. This means we go right to * m_disc = true. We'll leave the original m_discStatus * alone. */ m_conn = NULL; m_disc = true; } } else { if (m_discSent == false) { /* * sudden = true, m_disc = true, m_discSent == false * * This is a second unsolicited remote disconnect event that * is happening on a stream that has previously gotten a * remote disconnect event -- a duplicate in other words. * We'll leave the original m_discStatus alone. * * The connection should already be gone. */ assert(m_conn == NULL && "ArdpStream::Disconnect(): m_conn unexpectedly live"); assert(m_disc == true && "ArdpStream::Disconnect(): unexpectedly not disconnected"); } else { /* * sudden = true, m_disc = true, m_discSent == true * * This is an unsolicited remote disconnect event that is * happening on a stream that has previously gotten a local * disconnect event that has completed. We have already * called ARDP_Disconnect() and gotten the DisconnectCb() * and the connection is gone. This can happen if both * sides decide to take down connections at about the same * time. We'll leave the original m_discStatus alone. * * The connection should already be gone. */ assert(m_conn == NULL && "ArdpStream::Disconnect(): m_conn unexpectedly live"); assert(m_disc == true && "ArdpStream::Disconnect(): unexpectedly not disconnected"); } } } m_lock.Unlock(MUTEX_CONTEXT); } /** * This is the data sent callback which is plumbed from the ARDP protocol up * to this stream. This callback means that the buffer is no longer * required and may be freed. The ARDP protocol only had temporary custody * of the buffer. */ void SendCb(ArdpHandle* handle, ArdpConnRecord* conn, uint8_t* buf, uint32_t len, QStatus status) { QCC_DbgTrace(("ArdpStream::SendCb(handle=%p, conn=%p, buf=%p, len=%d.)", handle, conn, buf, len)); #if SENT_SANITY m_transport->m_cbLock.Lock(); set<uint8_t*>::iterator i = find(m_sentSet.begin(), m_sentSet.end(), buf); if (i == m_sentSet.end()) { QCC_LogError(ER_FAIL, ("ArdpStream::SendCb(): Callback for buffer never sent or already freed (%p, %d.). Ignored", buf, len)); } else { m_sentSet.erase(i); #ifndef NDEBUG CheckSeal(buf + len); #endif delete[] buf; } m_transport->m_cbLock.Unlock(); #else #ifndef NDEBUG CheckSeal(buf + len); #endif delete[] buf; #endif /* * If there are any threads waiting for a chance to send bits, wake them * up. They will retry their sends when this event gets set. If the * send callbacks are part of normal operation, the sends may succeed * the next time around. If this callback is part of disconnect * processing the next send will fail with an error; and PushBytes() * will manage the outstanding write count. */ if (m_writeEvent) { QCC_DbgPrintf(("ArdpStream::SendCb(): SetEvent()")); m_transport->m_cbLock.Lock(); m_writeEvent->SetEvent(); m_transport->m_cbLock.Unlock(); } } class ThreadEntry { public: qcc::Thread* m_thread; ArdpStream* m_stream; }; private: ArdpStream(const ArdpStream& other); ArdpStream operator=(const ArdpStream& other); UDPTransport* m_transport; /**< The transport that created the endpoint that created the stream */ _UDPEndpoint* m_endpoint; /**< The endpoint that created the stream */ ArdpHandle* m_handle; /**< The handle to the ARDP protocol instance this stream works with */ ArdpConnRecord* m_conn; /**< The ARDP connection associated with this endpoint / stream combination */ uint32_t m_dataTimeout; /**< The timeout that the ARDP protocol will use when retrying sends */ uint32_t m_dataRetries; /**< The number of retries that the ARDP protocol will use when sending */ qcc::Mutex m_lock; /**< Mutex that protects m_threads and disconnect state */ bool m_disc; /**< Set to true when ARDP fires the DisconnectCb on the associated connection */ bool m_discSent; /**< Set to true when the endpoint calls ARDP_Disconnect */ QStatus m_discStatus; /**< The status code that was the reason for the last disconnect */ qcc::Event* m_writeEvent; /**< The write event that callers are blocked on to apply backpressure */ int32_t m_writesOutstanding; /**< The number of writes that are outstanding with ARDP */ int32_t m_writeWaits; /**< The number of Threads that are blocked trying to write to an ARDP connection */ std::set<ThreadEntry> m_threads; /**< Threads that are wandering around in the stream and possibly associated endpoint */ #if SENT_SANITY std::set<uint8_t*> m_sentSet; #endif class BufEntry { public: BufEntry() : m_buf(NULL), m_len(0), m_pulled(0), m_rcv(NULL), m_cnt(0) { } uint8_t* m_buf; uint16_t m_len; uint16_t m_pulled; ArdpRcvBuf* m_rcv; uint16_t m_cnt; }; std::list<BufEntry> m_buffers; }; bool operator<(const ArdpStream::ThreadEntry& lhs, const ArdpStream::ThreadEntry& rhs) { return lhs.m_thread < rhs.m_thread; } /* * An endpoint class to handle the details of authenticating a connection in a * way that avoids denial of service attacks. */ class _UDPEndpoint : public _RemoteEndpoint { public: /** * The UDP Transport is a flavor of a RemoteEndpoint. The daemon thinks of * remote endpoints as moving through a number of states, some that have * threads wandering around and some that do not. In order to make sure we * are in agreement with what the daemon things we will be doing we keep * state regarding what threads would be doing if they were actually here * and running. */ enum EndpointState { EP_ILLEGAL = 0, EP_INITIALIZED, /**< This endpoint structure has been allocated but not used */ EP_FAILED, /**< Starting has failed and this endpoint is not usable */ EP_STARTING, /**< The endpoint is being started, threads would be starting */ EP_STARTED, /**< The endpoint is ready for use, threads would be running */ EP_STOPPING, /**< The endpoint is stopping but join has not been called */ EP_JOINED, /**< The endpoint is stopping and join has been called */ EP_DONE /**< Threads have been shut down and joined */ }; /** * Connections can either be created as a result of incoming or outgoing * connection requests. If a connection happens as a result of a Connect() * it is the active side of a connection. If a connection happens because * of an accept of an inbound ARDP SYN it is the passive side of an ARDP * connection. This is important because of reference counting of * bus-to-bus endpoints. The daemon calls Connect() or ARDP calls * AcceptCb() to form connections. The daemon actually never calls * disconnect, it removes a final reference to a remote endpoint. ARDP * does, however call a disconnect callback. */ enum SideState { SIDE_ILLEGAL = 0, SIDE_INITIALIZED, /**< This endpoint structure has been allocated but don't know if active or passive yet */ SIDE_ACTIVE, /**< This endpoint is the active side of a connection */ SIDE_PASSIVE /**< This endpoint is the passive side of a connection */ }; /** * Construct a remote endpoint suitable for the UDP transport. */ _UDPEndpoint(UDPTransport* transport, BusAttachment& bus, bool incoming, const qcc::String connectSpec) : _RemoteEndpoint(bus, incoming, connectSpec, NULL, transport->GetTransportName(), false, true), m_transport(transport), m_stream(NULL), m_handle(NULL), m_conn(NULL), m_id(0), m_ipAddr(), m_ipPort(0), m_suddenDisconnect(incoming), m_registered(false), m_sideState(SIDE_INITIALIZED), m_epState(EP_INITIALIZED), m_tStart(qcc::Timespec(0)), m_remoteExited(false), m_exitScheduled(false), m_disconnected(false), m_refCount(0), m_stateLock() { QCC_DbgHLPrintf(("_UDPEndpoint::_UDPEndpoint(transport=%p, bus=%p, incoming=%d., connectSpec=\"%s\")", transport, &bus, incoming, connectSpec.c_str())); } /** * Destroy a UDP transport remote endpoint. */ virtual ~_UDPEndpoint() { QCC_DbgHLPrintf(("_UDPEndpoint::~_UDPEndpoint()")); QCC_DbgHLPrintf(("_UDPEndpoint::~_UDPEndpoint(): m_refCount==%d.", m_refCount)); /* * Double check that the remote endpoint is sure that its threads are gone, * since our destructor is going to call its Stop() and Join() anyway. * before deleting it. */ _RemoteEndpoint::Stop(); _RemoteEndpoint::Exited(); _RemoteEndpoint::Join(); assert(IncrementAndFetch(&m_refCount) == 1 && "_UDPEndpoint::~_UDPEndpoint(): non-zero reference count"); /* * Make sure that the endpoint isn't in a condition where a thread might * conceivably be wandering around in it. At this point, if everything * is working as expected there should be no reason for taking a lock, * but then again, if everything is working there also should be no * reason for an assert. */ if (m_stream) { /* * If we have gotten to this point, there certainly must have been a * call to Stop() which must have called the stream Disconnect(). This * means that it is safe to call delete the stream. We double-check * that there are no threads waiting on completions of send operations * and the ARDP connection is/was disconnected. */ assert(m_stream->ThreadSetEmpty() != false && "_UDPEndpoint::~_UDPEndpoint(): Threads present during destruction"); assert(m_stream->GetDisconnected() && "_UDPEndpoint::~_UDPEndpoint(): Not disconnected"); } DestroyStream(); } /** * This is really part of debug code to absolutely, positively ensure that * there are no threads wandering around in an endpoint as it gets destroyed. */ uint32_t IncrementRefs() { return IncrementAndFetch(&m_refCount); } /** * This is really part of debug code to absolutely, positively ensure that * there are no threads wandering around in an endpoint as it gets destroyed. */ uint32_t DecrementRefs() { return DecrementAndFetch(&m_refCount); } /** * Override Start() since we are not going to hook in IOdispatch or start TX and * RX threads or anything like that. */ QStatus Start() { IncrementAndFetch(&m_refCount); /* * Whenever we change state, we need to protect against multiple threads * trying to do something at the same time. Since state changes may be * initiated on threads that know nothing about our endpionts and what * state they are really in, we need to lock the endpoint list to make * sure nothing is changed out from under us. We are careful to keep * this lock order the same "everywhere." Since we are often called * from endpoint management code that holds the endpoint list lock, we * take that one first (reentrancy is enabled so we get it if we already * hold it). */ m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT); m_stateLock.Lock(MUTEX_CONTEXT); QCC_DbgHLPrintf(("_UDPEndpoint::Start()")); QCC_DbgPrintf(("_UDPEndpoint::Start(): isBusToBus = %s, allowRemote = %s)", GetFeatures().isBusToBus ? "true" : "false", GetFeatures().allowRemote ? "true" : "false")); if (m_stream) { bool empty = m_stream->ThreadSetEmpty(); assert(empty && "_UDPEndpoint::Start(): Threads present during Start()"); if (empty == false) { QCC_LogError(ER_FAIL, ("_UDPEndpoint::Start(): Threads present during Start()")); m_stateLock.Unlock(MUTEX_CONTEXT); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return ER_FAIL; } } if (GetFeatures().isBusToBus) { QCC_DbgPrintf(("_UDPEndpoint::Start(): endpoint switching to ENDPOINT_TYPE_BUS2BUS")); SetEndpointType(ENDPOINT_TYPE_BUS2BUS); } #ifndef NDEBUG /* * Debug consistency check. If we are starting an endpoint it must be * on either the m_authList or the m_endpointList exactly once, and it * must be associated with an ARDP connection. */ uint32_t found = 0; for (set<UDPEndpoint>::iterator i = m_transport->m_authList.begin(); i != m_transport->m_authList.end(); ++i) { UDPEndpoint ep = *i; if (GetConnId() == ep->GetConnId()) { QCC_DbgPrintf(("_UDPEndpoint::Start(): found endpoint with conn ID == %d. on m_authList", GetConnId())); ++found; } } for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) { UDPEndpoint ep = *i; if (GetConnId() == ep->GetConnId()) { QCC_DbgPrintf(("_UDPEndpoint::Start(): found endpoint with conn ID == %d. on m_endpointList", GetConnId())); ++found; } } assert(found == 1 && "_UDPEndpoint::Start(): Endpoint not on exactly one pending list"); #endif /* * No threads to Start(), so we jump right to started state. */ assert(GetEpState() == EP_INITIALIZED && "_UDPEndpoint::Start(): Endpoint not in EP_INITIALIZED state"); SetEpStarted(); /* * We need to hook back into the router and do what RemoteEndpoint would have * done had we really started RX and TX threads. Since we know an instance of * this object is on exactly one of our endpoint lists, we'll get a reference * to a valid object here. */ SetStarted(true); BusEndpoint bep = BusEndpoint::wrap(this); /* * We know we hold a reference, so now we can call out to the daemon * with it. We also never call back out to the daemon with a lock held * since you really never know what it might do. We do keep the thread * reference count bumped since there is a thread that will wander back * out through here eventually. */ m_stateLock.Unlock(MUTEX_CONTEXT); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); QCC_DbgPrintf(("_UDPEndpoint::Start(): RegisterEndpoint()")); QStatus status = m_transport->m_bus.GetInternal().GetRouter().RegisterEndpoint(bep); if (status == ER_OK) { m_registered = true; } DecrementAndFetch(&m_refCount); return status; } /** * Perform the AllJoyn thread lifecycle Stop() operation. Unlike the * standard method, Stop() can be called multiple times in this transport * since not all operations are serialized through a single RemoteEndpoint * ThreadExit. * * Override RemoteEndpoint::Stop() since we are not going to unhook * IOdispatch or stop TX and RX threads or anything like that. */ QStatus Stop() { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("_UDPEndpoint::Stop()")); QCC_DbgPrintf(("_UDPEndpoint::Stop(): Unique name == %s", GetUniqueName().c_str())); /* * Whenever we change state, we need to protect against multiple threads * trying to do something at the same time. Since state changes may be * initiated on threads that know nothing about our endpionts and what * state they are really in, we need to lock the endpoint list to make * sure nothing is changed out from under us. We are careful to keep * this lock order the same "everywhere." Since we are often called * from endpoint management code that holds the endpoint list lock, we * take that one first (reentrancy is enabled so we get it if we already * hold it). */ m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT); m_stateLock.Lock(MUTEX_CONTEXT); /* * If we've never been started, there's nothing to do. */ if (GetEpState() == EP_INITIALIZED) { QCC_DbgPrintf(("_UDPEndpoint::Stop(): Never Start()ed")); if (m_stream) { m_stream->EarlyExit(); } m_stateLock.Unlock(MUTEX_CONTEXT); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return ER_OK; } /* * If we're already on the way toward being shut down, there's nothing to do. */ if (GetEpState() != EP_STARTED) { QCC_DbgPrintf(("_UDPEndpoint::Stop(): Already stopping or done")); m_stateLock.Unlock(MUTEX_CONTEXT); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return ER_OK; } #ifndef NDEBUG /* * Debug consistency check. If we are stopping an endpoint it must be * on either the m_authList or the m_endpointList exactly once, and it * must be associated with an ARDP connection. */ uint32_t found = 0; for (set<UDPEndpoint>::iterator i = m_transport->m_authList.begin(); i != m_transport->m_authList.end(); ++i) { UDPEndpoint ep = *i; if (GetConnId() == ep->GetConnId()) { QCC_DbgPrintf(("_UDPEndpoint::Start(): found endpoint with conn ID == %d. on m_authList", GetConnId())); ++found; } } for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) { UDPEndpoint ep = *i; if (GetConnId() == ep->GetConnId()) { QCC_DbgPrintf(("_UDPEndpoint::Start(): found endpoint with conn ID == %d. on m_endpointList", GetConnId())); ++found; } } assert(found == 1 && "_UDPEndpoint::Stop(): Endpoint not on exactly one pending list"); #endif /* * If there was a remote (sudden) disconnect, the disconnect callback * will disconnect the stream and call Stop. This may precipitate a * flood of events in the daemon with router endpoints being dereferenced * and disconnected and destroyed. This will likely result in Stop() * being called multiple times. The stream remembers what started it all * and so it is safe to call it with ER_UDP_LOCAL_DISCONNECT even though * this stop may have been called as part of remote disconnect handling * just so long as the disconnect callback got there first. * * The Disconnect() below will call ARDP_Disconnect(). Calling out to * ARDP with locks held is dangerous from a deadlock perspective. For * example, we took the endpoint list lock above, and will want to take * ARDP lock in Disconnect(); but in the accept callback it will be * called with ARDP lock taken and want to get the endpoint list lock. * This is a recipe for deadlock. We must set the state and talk to * the management thread, then release the locks and finally call out * to Disconnect(). Through this process we leave the thread reference * count incremented so we know there is a thread that will reappear * popping back out through here eventually. */ SetEpStopping(); m_transport->m_manage = UDPTransport::STATE_MANAGE; m_transport->Alert(); m_stateLock.Unlock(MUTEX_CONTEXT); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); if (m_stream) { m_stream->WakeThreadSet(); m_stream->Disconnect(false, ER_UDP_LOCAL_DISCONNECT); } DecrementAndFetch(&m_refCount); return ER_OK; } /** * Perform the AllJoyn thread lifecycle Join() operation. Join() can be called * multiple times. */ QStatus Join() { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("_UDPEndpoint::Join()")); /* * Whenever we change state, we need to protect against multiple threads * trying to do something at the same time. Since state changes may be * initiated on threads that know nothing about our endpionts and what * state they are really in, we need to lock the endpoint list to make * sure nothing is changed out from under us. We are careful to keep * this lock order the same "everywhere." Since we are often called * from endpoint management code that holds the endpoint list lock, we * take that one first (reentrancy is enabled so we get it if we already * hold it). */ m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT); m_stateLock.Lock(MUTEX_CONTEXT); /* * If we've never been started, there's nothing to do. */ if (GetEpState() == EP_INITIALIZED) { QCC_DbgPrintf(("_UDPEndpoint::Join(): Never Start()ed")); if (m_stream) { m_stream->EarlyExit(); } m_stateLock.Unlock(MUTEX_CONTEXT); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return ER_OK; } /* * The AllJoyn threading model requires that we allow multiple calls to * Join(). We expect that the first time through the state will be * EP_STOPPING, in which case we may have things to do. Once we have * done a successful Join(), the state will be EP_JOINED or eventually * EP_DONE or EP_FAILED, all of which mean we have nothing to do. */ if (GetEpState() == EP_JOINED || GetEpState() == EP_DONE || GetEpState() == EP_FAILED) { QCC_DbgPrintf(("_UDPEndpoint::Join(): Already Join()ed")); m_stateLock.Unlock(MUTEX_CONTEXT); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return ER_OK; } /* * Now, down to business. If there were any threads blocked waiting to * get bytes through to a remote host, they should have been woken up in * Stop() and in the normal course of events they should have woken up * and left of their own accord. ManageEndpoints should have waited * for that to happen before calling Join(). If we happen to get caught * with active endpoints alive when the TRANSPORT is shutting down, * however, we may have to wait for that to happen here. We can't do * anything until there are no threads wandering around in the endpoint * or risk crashing the daemon. We just have to trust that they will * cooperate. */ int32_t timewait = m_transport->m_ardpConfig.timewait; while (m_stream && m_stream->ThreadSetEmpty() == false) { QCC_DbgPrintf(("_UDPEndpoint::Join(): Waiting for threads to exit")); /* * Make sure the threads are "poked" to wake them up. */ m_stream->WakeThreadSet(); /* * Note that we are calling Sleep() with both the endpoint list lock * and the state lock taken. This is dangerous from a deadlock * point of view, but the threads that we want to wake up are * waiting on an event in the ArdpStream associated with the * endpoint. They will never ask for one of our locks, so they * won't deadlock. What can happen is that we block either the * maintenance thread or the dispatcher for timwait milliseconds * (typically one second). This sounds bad, but we have added code * in the maintenance theread to wait until these threads are gone * beore calling Join() so in the normal course of events, this code * should never be executed. It is here to make sure threads are * gone before deleting the endpoint in the case of the UDP * Transport being torn down unexpectedly. In that case, it will * not be a problem to bock other threads, since they are going * away or are already gone. */ qcc::Sleep(10); timewait -= 10; if (timewait <= 0) { QCC_DbgPrintf(("_UDPEndpoint::Join(): TIMWAIT expired with threads pending")); break; } } /* * The same story as in the comment above applies to the disconnect callback. * We expect that in the normal course of events, the endpoint management * thread will wait until the disconnection process is complete before * actually calling Join. */ if (m_stream && m_stream->GetDisconnected() == false) { QCC_LogError(ER_UDP_STOPPING, ("_UDPEndpoint::Join(): Not disconnected")); m_stream->EarlyExit(); } SetEpJoined(); /* * Tell the endpoint management code that something has happened that * it may be concerned about. */ m_transport->m_manage = UDPTransport::STATE_MANAGE; m_transport->Alert(); m_stateLock.Unlock(MUTEX_CONTEXT); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return ER_OK; } /* * Stop() and Join() are relly internal to the UDP Transport threading model. * We can consider ourselves free to call Stop() and Join() from everywhere * and anywhere just so long as we don't release our reference to the endpoint * until after we are sure that the daemon has no more references to the * endpoint. * * The last thing we need to do is to arrange for all references to the * endpoint to be removed by calling DaemonRouter::UnregisterEndpoint(). * Unfortunately, the RemoteEndpoint has the idea of TX and RX threading * calling out into streams ingrained into it, so we can't just do this * shutdown ourselves. We really have to call into the RemoteEndpoint(). * We have an Exit() function there that does what needs to be done in the * case of no threads to call an exit callback, but we also have to be very * careful about calling it from any old thread context since * UnregisterEndoint() will need to take the daemon name table lock, which * is often held during call-outs. To avoid deadlocks, we need to esure * that calls to Exit() are done on our dispatcher thread which we know will * not be holding any locks. */ QStatus Exit() { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("_UDPEndpoint::Exit()")); /* * Whenever we change state, we need to protect against multiple threads * trying to do something at the same time. We have to be careful since * _RemoteEndpoint can happily call out to the daemon or call back into * our endpoint. Don't take any locks while the possibility exists of * the daemon wandering off and doing something. Whatever it is doing * the endpoint management code will hold a reference to the endpoint * until Exit() completes so we let the daemon go and grab the locks * after it returns. Note that we do increment the thread reference * count that indicates that a thread is wandering around and will pop * back up through this function sometime later. */ _RemoteEndpoint::Exit(); _RemoteEndpoint::Stop(); m_remoteExited = true; m_registered = false; m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT); m_stateLock.Lock(MUTEX_CONTEXT); /* * Jump to done state. Our ManageEndpoints() will pick up on the fact * that this endpoint is done and deal with it by releasing any * references to it. */ SetEpDone(); /* * Tell the endpoint management code that something has happened that * it may be concerned about. */ m_transport->m_manage = UDPTransport::STATE_MANAGE; m_transport->Alert(); m_stateLock.Unlock(MUTEX_CONTEXT); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return ER_OK; } /** * Get the boolean indication that the RemoteEndpoint exit function has been * called. */ bool GetExited() { QCC_DbgHLPrintf(("_UDPEndpoint::GetExited(): -> %s", m_remoteExited ? "true" : "false")); return m_remoteExited; } /** * Set the boolean indication that the RemoteEndpoint exit function has been * scheduled. */ void SetExitScheduled() { QCC_DbgHLPrintf(("_UDPEndpoint::SetExitScheduled()")); m_exitScheduled = true; } /** * Get the boolean indication that the RemoteEndpoint exit function has been * scheduled. */ bool GetExitScheduled() { QCC_DbgHLPrintf(("_UDPEndpoint::GetExitScheduled(): -> %s", m_exitScheduled ? "true" : "false")); return m_exitScheduled; } /** * Get a boolean indication that the endpoint has been registered with the * daemon. */ bool GetRegistered() { QCC_DbgHLPrintf(("_UDPEndpoint::GetRegistered(): -> %s", m_registered ? "true" : "false")); return m_registered; } /** * Create a skeletal stream that we'll use basically as a place to hold some * connection information. */ void CreateStream(ArdpHandle* handle, ArdpConnRecord* conn, uint32_t dataTimeout, uint32_t dataRetries) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("_UDPEndpoint::CreateStream(handle=0x%0, conn=%p)", handle, conn)); m_transport->m_ardpLock.Lock(); assert(m_stream == NULL && "_UDPEndpoint::CreateStream(): stream already exists"); /* * The stream for a UDP endpoint is basically just a convenient place to * stick the connection identifier. For the TCP transport it is a real * stream that connects to an underlying socket stream. */ m_stream = new ArdpStream(); m_stream->SetTransport(m_transport); m_stream->SetEndpoint(this); m_stream->SetHandle(handle); m_stream->SetConn(conn); m_stream->SetDataTimeout(dataTimeout); m_stream->SetDataRetries(dataRetries); /* * This is actually a call to the underlying endpoint that provides the * stream for Marshaling and unmarshaling. This is what hooks our * PushMessage() back into the ArdpStream PushBytes(). */ SetStream(m_stream); m_transport->m_ardpLock.Unlock(); DecrementAndFetch(&m_refCount); } /** * Get the ArdpStream* pointer to the skeletal stream associated with this * endpoint. */ ArdpStream* GetStream() { QCC_DbgTrace(("_UDPEndpoint::GetStream() => %p", m_stream)); return m_stream; } /** * Delete the skeletal stream that we used to stash our connection * information. */ void DestroyStream() { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("_UDPEndpoint::DestroyStream()")); if (m_stream) { assert(m_stream->GetConn() == NULL && "_UDPEndpoint::DestroyStream(): Cannot destroy stream unless stream's m_conn is NULL"); m_stream->SetHandle(NULL); delete m_stream; } m_stream = NULL; m_conn = NULL; DecrementAndFetch(&m_refCount); } /** * Take a Message destined to be send over the connection represented * by the UDP Endpoint and ask it to Deliver() itself though this * remote endpoint (we are a descendent). DeliverNonBlocking() will * end up calling PushBytes() on the Stream Sink associated with the * endpoint. This will find its way down to the PushBytes() defined * in our ARDP Stream. */ QStatus PushMessage(Message& msg) { IncrementAndFetch(&m_refCount); /* * We need to make sure that this endpoint stays on one of our endpoint * lists while we figure out what to do with it. If we are taken off * the endpoint list we could actually be deleted while doing this * operation, so take the lock to make sure at least the UDP transport * holds a reference during this process. */ m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT); QCC_DbgHLPrintf(("_UDPEndpoint::PushMessage(msg=%p)", &msg)); if (GetEpState() != EP_STARTED) { QStatus status = ER_UDP_STOPPING; QCC_LogError(status, ("_UDPEndpoint::PushBytes(): UDP Transport stopping")); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return status; } /* * Find the managed endpoint to which the connection ID of the current * object refers. If the endpoint state was EP_STARTED above, and we * hold the endpoint lock, we should find the endpoint on the list. */ uint32_t found = 0; for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) { UDPEndpoint ep = *i; if (GetConnId() == ep->GetConnId()) { QCC_DbgPrintf(("_UDPEndpoint::PushMessage(): found endpoint with conn ID == %d. on m_endpointList", GetConnId())); ++found; } } if (found == 0) { QCC_LogError(ER_UDP_STOPPING, ("_UDPEndpoint::PushMessage(): Endpoint is gone")); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return ER_UDP_STOPPING; } /* * Since we know an instance of this object is on our endpoint list, * we'll get a reference to a valid object here. */ RemoteEndpoint rep = RemoteEndpoint::wrap(this); /* * If we are going to pass the Message off to be delivered, the act of * delivering will change the write state of the message. Since * delivering to a multipoint session is done by taking a Message and * sending it off to multiple endpoints for delivery, if we just use the * Message we are given, we will eventually change the writeState of the * message to MESSAGE_COMPLETE when we've pushed all of the bits. That * would cause any subsequent PushMessage calls to complete before * actually writing any bits since they would think they are done. This * means we have to do a deep copy of every message before we send it. */ Message msgCopy = Message(msg, true); /* * We know we hold a reference, so now we can call out to the daemon * with it. Even if we release the endpoint list lock, our thread will * be registered in the endpoint so it won't go away. The message * handler should call right back into our stream and we should pop back * out in short order. */ m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); QCC_DbgPrintf(("_UDPEndpoint::PushMessage(): DeliverNonBlocking()")); QStatus status = msgCopy->DeliverNonBlocking(rep); QCC_DbgPrintf(("_UDPEndpoint::PushMessage(): DeliverNonBlocking() returns \"%s\"", QCC_StatusText(status))); DecrementAndFetch(&m_refCount); return status; } /** * Callback (indirectly) from the ARDP implementation letting us know that * our connection has been disconnected for some reason. */ void DisconnectCb(ArdpHandle* handle, ArdpConnRecord* conn, QStatus status) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("_UDPEndpoint::DisconnectCb(handle=%p, conn=%p)", handle, conn)); /* * We need to look and see if this endpoint is on the endopint list * and then make sure that it stays on the list, so take the lock to make sure * at least the UDP transport holds a reference during this process. */ m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT); #ifndef NDEBUG /* * The callback dispatcher looked to see if the endpoint was on the * endpoint list before it made the call here, and it incremented the * thread reference count before calling. We should find an endpoint * still on the endpoint list since the management thread should not * remove the endpoint with threads wandering around in it. */ uint32_t found = 0; for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) { UDPEndpoint ep = *i; if (GetConnId() == ep->GetConnId()) { QCC_DbgPrintf(("_UDPEndpoint::DisconnectCb(): found endpoint with conn ID == %d. on m_endpointList", GetConnId())); ++found; } } assert(found == 1 && "_UDPEndpoint::DisconnectCb(): Endpoint is gone"); #endif /* * We need to figure out if this disconnect callback is due to an * unforeseen event on the network (coming out of the protocol) or if it * is a callback in response to a local disconnect. The key is the * reported status will only be ER_OK if the callback is in response to * a local disconnect that has already begun through a call to * _UDPEndpoint::Stop(). We turn the fact that this is a part of a * local disconnect in to the fact that it is not a "sudden" or * unexpected callback and give it to the stream Disconnect() function * that is going to handle the details of managing the state of the * connection. */ bool sudden = (status != ER_OK); SetSuddenDisconnect(sudden); QCC_DbgPrintf(("_UDPEndpoint::DisconnectCb(): sudden==\"%s\"", sudden ? "true" : "false")); /* * Always let the stream see the disconnect event. It is the piece of * code that is really dealing with the hard details. */ if (m_stream) { QCC_DbgPrintf(("_UDPEndpoint::DisconnectCb(): Disconnect(): m_stream=%p", m_stream)); m_stream->Disconnect(sudden, status); } /* * We believe that the connection must go away here since this is either * an unsolicited remote disconnection which always resutls in the * connection going away or a confirmation of a local disconnect that * also results in the connection going away. */ m_conn = NULL; /* * Since we know an instance of this object is on exactly one of our * endpoint lists we'll get a reference to a valid object here. The * thread reference count being non-zero means we will not be deleted * out from under the call. */ RemoteEndpoint rep = RemoteEndpoint::wrap(this); /* * Since this is a disconnect it will eventually require endpoint * management, so we make a note to run the endpoint management code. */ m_transport->m_manage = UDPTransport::STATE_MANAGE; m_transport->Alert(); /* * Never, ever call out to the daemon with a lock taken. You will * eventually regret it. */ m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); /* * Tell any listeners that the connection was lost. Since we have a * disconnect callback we know that the connection is gone, one way * or the other. */ if (m_transport->m_listener) { m_transport->m_listener->BusConnectionLost(rep->GetConnectSpec()); } /* * The connection is gone, so Stop() so it can continue being torn down * by the daemon router (and us). This may have already been done in * the case of a local disconnect callback. It was the original Stop() * that must have happened that precipitated the confirmation callback. */ Stop(); DecrementAndFetch(&m_refCount); } /** * Callback letting us know that we received data over our connection. We * are passed responsibility for the buffer in this callback. * * for deadlock avoidance purposes, this callback always comes from the * transport dispatcher thread. */ void RecvCb(ArdpHandle* handle, ArdpConnRecord* conn, ArdpRcvBuf* rcv, QStatus status) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("_UDPEndpoint::RecvCb(handle=%p, conn=%p, rcv=%p, status=%s)", handle, conn, rcv, QCC_StatusText(status))); /* * We need to look and see if this endpoint is on the endopint list * and then make sure that it stays on the list, so take the lock to make sure * at least the UDP transport holds a reference during this process. */ m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT); #ifndef NDEBUG /* * The callback dispatcher looked to see if the endpoint was on the * endpoint list before it made the call here, and it incremented the * thread reference count before calling. We should find an endpoint * still on the endpoint list since the management thread should not * remove the endpoint with threads wandering around in it. */ uint32_t found = 0; for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) { UDPEndpoint ep = *i; if (GetConnId() == ep->GetConnId()) { QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): found endpoint with conn ID == %d. on m_endpointList", GetConnId())); ++found; } } assert(found == 1 && "_UDPEndpoint::RecvCb(): Endpoint is gone"); #endif if (GetEpState() != EP_STARTING && GetEpState() != EP_STARTED) { QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Not accepting inbound messages")); QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady()")); m_transport->m_ardpLock.Lock(); ARDP_RecvReady(handle, conn, rcv); m_transport->m_ardpLock.Unlock(); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return; } if (rcv == NULL || rcv->data == NULL || rcv->datalen == 0) { QCC_LogError(ER_UDP_INVALID, ("_UDPEndpoint::RecvCb(): No data on RecvCb()")); QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady()")); m_transport->m_ardpLock.Lock(); ARDP_RecvReady(handle, conn, rcv); m_transport->m_ardpLock.Unlock(); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); assert(false && "_UDPEndpoint::RecvCb(): No data on RecvCb()"); return; } if (rcv->fcnt == 0 || rcv->fcnt > 3) { QCC_LogError(ER_UDP_INVALID, ("_UDPEndpoint::RecvCb(): Unexpected rcv->fcnt==%d.", rcv->fcnt)); QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady()")); m_transport->m_ardpLock.Lock(); ARDP_RecvReady(handle, conn, rcv); m_transport->m_ardpLock.Unlock(); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); assert(false && "_UDPEndpoint::RecvCb(): unexpected rcv->fcnt"); return; } /* * The daemon knows nothing about message fragments, so we must * reassemble the fragements into a contiguous buffer before doling it * out to the daemon router. What we get is a singly linked list of * ArdpRcvBuf* that we have to walk. There is no cumulative length, so * we have to do two passes through the list: one pass to calculate the * length so we can allocate a contiguous buffer, and one to copy the * data into the buffer. */ uint8_t* msgbuf = NULL; uint32_t mlen = 0; if (rcv->fcnt != 1) { QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Calculating message length")); ArdpRcvBuf* tmp = rcv; for (uint32_t i = 0; i < rcv->fcnt; ++i) { QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Found fragment of %d. bytes", tmp->datalen)); if (tmp->datalen == 0 || tmp->datalen > 65535) { QCC_LogError(ER_UDP_INVALID, ("_UDPEndpoint::RecvCb(): Unexpected tmp->datalen==%d.", tmp->datalen)); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady()")); m_transport->m_ardpLock.Lock(); ARDP_RecvReady(handle, conn, rcv); m_transport->m_ardpLock.Unlock(); DecrementAndFetch(&m_refCount); assert(false && "_UDPEndpoint::RecvCb(): unexpected rcv->fcnt"); return; } mlen += tmp->datalen; tmp = tmp->next; } QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Found Message of %d. bytes", mlen)); #ifndef NDEBUG msgbuf = new uint8_t[mlen + SEAL_SIZE]; SealBuffer(msgbuf + mlen); #else msgbuf = new uint8_t[mlen]; #endif uint32_t offset = 0; tmp = rcv; QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Reassembling fragements")); for (uint32_t i = 0; i < rcv->fcnt; ++i) { QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Copying fragment of %d. bytes", tmp->datalen)); memcpy(msgbuf + offset, tmp->data, tmp->datalen); offset += tmp->datalen; tmp = tmp->next; } QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Message of %d. bytes reassembled", mlen)); } uint8_t* messageBuf = msgbuf ? msgbuf : rcv->data; uint32_t messageLen = mlen ? mlen : rcv->datalen; #ifndef NDEBUG DumpBytes(messageBuf, messageLen); #endif /* * Since we know the callback dispatcher verified it could find an * intance of this object is on an endpoint lists, and it bumped the * thread reference count, we know we'll get a reference to a * still-valid object here. */ RemoteEndpoint rep = RemoteEndpoint::wrap(this); BusEndpoint bep = BusEndpoint::cast(rep); /* * We know we hold a reference that will stay alive until we leave this * function, so now we can call out to the daemon all we want. */ m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); /* * The point here is to create an AllJoyn Message from the * inbound bytes which we know a priori to contain exactly one * Message if present. We have a back door in the Message code * that lets us load our bytes directly into the message. Note * that this LoadBytes does a buffer copy, so we are free to * release ownership of the incoming buffer at any time after * that. */ Message msg(m_transport->m_bus); QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): LoadBytes()")); status = msg->LoadBytes(messageBuf, messageLen); if (status != ER_OK) { QCC_LogError(status, ("_UDPEndpoint::RecvCb(): Cannot load bytes")); /* * If there's some kind of problem, we have to give the buffer * back to the protocol now. */ m_transport->m_ardpLock.Lock(); ARDP_RecvReady(handle, conn, rcv); m_transport->m_ardpLock.Unlock(); /* * If we allocated a reassembly buffer, free it too. */ if (msgbuf) { #ifndef NDEBUG CheckSeal(msgbuf + mlen); #endif delete[] msgbuf; msgbuf = NULL; } /* * If we do something that is going to bug the ARDP protocol, we * need to call back into ARDP ASAP to get it moving. This is done * in the main thread, which we need to wake up. */ m_transport->Alert(); DecrementAndFetch(&m_refCount); return; } /* * The bytes are now loaded into what amounts to a backing buffer for * the Message. With the exception of the Message header, these are * still the raw bytes from the wire, so we have to Unmarshal() them * before proceeding (remembering to free the reassembly buffer if it * exists. */ if (msgbuf) { #ifndef NDEBUG CheckSeal(msgbuf + mlen); #endif delete[] msgbuf; msgbuf = NULL; } qcc::String endpointName(rep->GetUniqueName()); QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): Unmarshal()")); status = msg->Unmarshal(endpointName, false, false, true, 0); if (status != ER_OK) { QCC_LogError(status, ("_UDPEndpoint::RecvCb(): Can't Unmarhsal() Message")); /* * If there's some kind of problem, we have to give the buffer * back to the protocol now. */ m_transport->m_ardpLock.Lock(); ARDP_RecvReady(handle, conn, rcv); m_transport->m_ardpLock.Unlock(); /* * If we do something that is going to bug the ARDP protocol, we * need to call back into ARDP ASAP to get it moving. This is done * in the main thread, which we need to wake up. */ m_transport->Alert(); DecrementAndFetch(&m_refCount); return; } /* * Now, we have an AllJoyn Message that is ready for delivery. * We just hand it off to the daemon router at this point. It * will try to find the implied destination endpoint and stick * it on the receive queue for that endpoint. * * TODO: If the PushMessage cannot enqueue the message it blocks! We * need it to fail, not to block. */ QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): PushMessage()")); status = m_transport->m_bus.GetInternal().GetRouter().PushMessage(msg, bep); if (status != ER_OK) { QCC_LogError(status, ("_UDPEndpoint::RecvCb(): PushMessage failed")); } /* * TODO: If the daemon router cannot deliver the message, we need to * enqueue it on a list and NOT call ARDP_RecvReady(). This opens the * receive window for the protocol, so after we enqueue a receive * window's full of data the protocol will apply backpressure to the * remote side which will stop sending data and further apply * backpressure to the ultimate sender. We either need to retry * delivery or get a callback from the destination endpoint telling us * to retry. */ QCC_DbgPrintf(("_UDPEndpoint::RecvCb(): ARDP_RecvReady()")); m_transport->m_ardpLock.Lock(); ARDP_RecvReady(handle, conn, rcv); m_transport->m_ardpLock.Unlock(); /* * If we do something that is going to bug the ARDP protocol, we need to * call back into ARDP ASAP to get it moving. This is done in the main * thread, which we need to wake up. */ m_transport->Alert(); DecrementAndFetch(&m_refCount); } /** * Callback from the ARDP implementation letting us know that the remote side * has acknowledged reception of our data and the buffer can be recycled/freed */ void SendCb(ArdpHandle* handle, ArdpConnRecord* conn, uint8_t* buf, uint32_t len, QStatus status) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("_UDPEndpoint::SendCb(handle=%p, conn=%p, buf=%p, len=%d.)", handle, conn, buf, len)); /* * We need to look and see if this endpoint is on the endopint list * and then make sure that it stays on the list, so take the lock to make sure * at least the UDP transport holds a reference during this process. */ m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT); #ifndef NDEBUG /* * The callback dispatcher looked to see if the endpoint was on the * endpoint list before it made the call here, and it incremented the * thread reference count before calling. We should find an endpoint * still on the endpoint list since the management thread should not * remove the endpoint with threads wandering around in it. */ uint32_t found = 0; for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) { UDPEndpoint ep = *i; if (GetConnId() == ep->GetConnId()) { QCC_DbgPrintf(("_UDPEndpoint::SendCb(): found endpoint with conn ID == %d. on m_endpointList", GetConnId())); ++found; } } assert(found == 1 && "_UDPEndpoint::SendCb(): Endpoint is gone"); #endif /* * We know we are still on the endpoint list and we know we have the * thread reference count bumped so it is safe to release the lock. */ m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); /* * If there is a thread trying to send bytes in this in this endpoint, * it first calls into PushMessage() and this indirectly calls into the * underlying stream's PushBytes(). If there is a pending PushBytes() a * thread will be blocked waiting for its ARDP send to complete. In * that case, we must call back into the stream to unblock that pending * thread. The stream actually does some more involved checking of the * returned buffers, so we let it do the free unless it is gone. * * If there is no stream, we are guaranteed there is no thread waiting * for something and so we can just proceed to free the memory since the * failure will have already been communicated up to the caller by * another mechanism, e.g., DisconnectCb(). */ if (m_stream) { m_stream->SendCb(handle, conn, buf, len, status); } else { #ifndef NDEBUG CheckSeal(buf + len); #endif delete[] buf; } DecrementAndFetch(&m_refCount); } /** * Get the handle to the underlying ARDP protocol implementation. */ ArdpHandle* GetHandle() { QCC_DbgTrace(("_UDPEndpoint::GetHandle() => %p", m_handle)); return m_handle; } /** * Set the handle to the underlying ARDP protocol implementation. */ void SetHandle(ArdpHandle* handle) { QCC_DbgTrace(("_UDPEndpoint::SetHandle(handle=%p)", handle)); m_handle = handle; } /** * Get the pointer to the underlying ARDP protocol connection information. */ ArdpConnRecord* GetConn() { QCC_DbgTrace(("_UDPEndpoint::GetConn(): => %p", m_conn)); return m_conn; } /** * Set the pointer to the underlying ARDP protocol connection information. */ void SetConn(ArdpConnRecord* conn) { QCC_DbgTrace(("_UDPEndpoint::SetConn(conn=%p)", conn)); m_conn = conn; SetConnId(ARDP_GetConnId(m_handle, conn)); } /** * Get the connection ID of the original ARDP protocol connection. We keep * this around for debugging purposes after the connection goes away. */ uint32_t GetConnId() { QCC_DbgTrace(("_UDPEndpoint::GetConnId(): => %d.", m_id)); return m_id; } /** * Set the connection ID of the original ARDP protocol connection. We keep * this around for debugging purposes after the connection goes away. */ void SetConnId(uint32_t id) { QCC_DbgTrace(("_UDPEndpoint::SetConnId(id=%d.)", id)); m_id = id; } /** * Get the IP address of the remote side of the connection. */ qcc::IPAddress GetIpAddr() { QCC_DbgTrace(("_UDPEndpoint::GetIpAddr(): => \"%s\"", m_ipAddr.ToString().c_str())); return m_ipAddr; } /** * Set the IP address of the remote side of the connection. */ void SetIpAddr(qcc::IPAddress& ipAddr) { QCC_DbgTrace(("_UDPEndpoint::SetIpAddr(ipAddr=\"%s\")", ipAddr.ToString().c_str())); m_ipAddr = ipAddr; } /** * Get the UDP/IP port of the remote side of the connection. */ uint16_t GetIpPort() { QCC_DbgTrace(("_UDPEndpoint::GetIpPort(): => %d.", m_ipPort)); return m_ipPort; } /** * Set the UDP/IP port of the remote side of the connection. */ void SetIpPort(uint16_t ipPort) { QCC_DbgTrace(("_UDPEndpoint::SetIpPort(ipPort=%d.)", ipPort)); m_ipPort = ipPort; } /** * Get the sudden disconnect indication. If true, it means that the * connection was unexpectedly disconnected. If false, it means we * are still connected, or we initiated the disconnection. */ bool GetSuddenDisconnect() { QCC_DbgTrace(("_UDPEndpoint::GetSuddenDisconnect(): => %d.", m_suddenDisconnect)); return m_suddenDisconnect; } /** * Get the sudden disconnect indication. If true, it means that the * connection was unexpectedly disconnected. If false, it means we * are still connected, or we initiated the disconnection. */ void SetSuddenDisconnect(bool suddenDisconnect) { QCC_DbgTrace(("_UDPEndpoint::SetSuddenDisconnect(suddenDisconnect(suddenDisconnect=%d.)", suddenDisconnect)); m_suddenDisconnect = suddenDisconnect; } /** * Getting the local IP is not supported */ QStatus GetLocalIp(qcc::String& ipAddrStr) { // Can get this through conn if it remembers local address to which its socket was bound assert(0); return ER_UDP_NOT_IMPLEMENTED; }; /** * Get the IP address of the remote side of the connection. */ QStatus GetRemoteIp(qcc::String& ipAddrStr) { QCC_DbgTrace(("_UDPEndpoint::GetRemoteIp(ipAddrStr=%p): => \"%s\"", &ipAddrStr, m_ipAddr.ToString().c_str())); ipAddrStr = m_ipAddr.ToString(); return ER_OK; }; /** * Set the time at which authentication was started. */ void SetStartTime(qcc::Timespec tStart) { QCC_DbgTrace(("_UDPEndpoint::SetStartTime()")); m_tStart = tStart; } /** * Get the time at which authentication was started. */ qcc::Timespec GetStartTime(void) { QCC_DbgTrace(("_UDPEndpoint::GetStartTime(): => %d.", m_tStart)); return m_tStart; } /** * Set the time at which the stop process for the endpoint was begun. */ void SetStopTime(qcc::Timespec tStop) { QCC_DbgTrace(("_UDPEndpoint::SetStopTime()")); m_tStop = tStop; } /** * Get the time at which the stop process for the endpoint was begun. */ qcc::Timespec GetStopTime(void) { QCC_DbgTrace(("_UDPEndpoint::GetStopTime(): => %d.", m_tStop)); return m_tStop; } /** * Which side of a connection are we -- active or passive */ SideState GetSideState(void) { QCC_DbgTrace(("_UDPEndpoint::GetSideState(): => %d.", m_sideState)); return m_sideState; } /** * Note that we are the active side of a connection */ void SetActive(void) { QCC_DbgTrace(("_UDPEndpoint::SetActive()")); m_sideState = SIDE_ACTIVE; } /** * Note that we are the passive side of a connection */ void SetPassive(void) { QCC_DbgTrace(("_UDPEndpoint::SetPassive()")); m_sideState = SIDE_PASSIVE; } /** * Get the state of the overall endpoint. Failed, starting, stopping, etc. */ EndpointState GetEpState(void) { QCC_DbgTrace(("_UDPEndpoint::GetEpState(): => %d.", m_epState)); return m_epState; } /** * Set the state of the endpoint to failed */ void SetEpFailed(void) { QCC_DbgTrace(("_UDPEndpoint::GetEpFailed()")); m_epState = EP_FAILED; } /** * Set the state of the endpoint to starting */ void SetEpStarting(void) { QCC_DbgTrace(("_UDPEndpoint::SetEpStarting()")); assert(m_epState != EP_STARTING && m_epState != EP_STARTED); m_epState = EP_STARTING; } /** * Set the state of the endpoint to started */ void SetEpStarted(void) { QCC_DbgTrace(("_UDPEndpoint::SetEpStarted()")); assert(m_epState != EP_STARTED); m_epState = EP_STARTED; } /** * Set the state of the endpoint to stopping */ void SetEpStopping(void) { QCC_DbgTrace(("_UDPEndpoint::SetEpStopping()")); if (m_epState != EP_STARTING && m_epState == EP_STARTED) { QCC_DbgPrintf(("_UDPEndpoint::SetEpStopping(): m_epState == %d", m_epState)); } assert(m_epState == EP_STOPPING || m_epState == EP_STARTING || m_epState == EP_STARTED); Timespec tNow; GetTimeNow(&tNow); SetStopTime(tNow); m_epState = EP_STOPPING; } /** * Set the state of the endpoint to joined */ void SetEpJoined(void) { QCC_DbgTrace(("_UDPEndpoint::SetEpJoined()")); /* * Pretty much any state is legal to call Join() in except started * state. This always requires a Stop() first. */ assert(m_epState != EP_STARTED); m_epState = EP_JOINED; } /** * Set the state of the endpoint to done */ void SetEpDone(void) { QCC_DbgTrace(("_UDPEndpoint::SetEpDone()")); assert(m_epState == EP_FAILED || m_epState == EP_JOINED); m_epState = EP_DONE; } /** * Set the boolean indicating that the disconenct logic has happened. This * is provided so that the transport can manually override this logic if an * error is detected prior to calling start (and where the disconnect * callback that drives that logic will never be called). */ void SetDisconnected() { QCC_DbgTrace(("_UDPEndpoint::SetDisconnected()")); m_disconnected = true; } /** * Set the link timeout for this connection * * TODO: How does the link timeout set by the application play with the * default link timeout managed by the protocol. We certainly don't want to * trigger the link timeout functionality of the remote endpoint since it is * going to expect all of the usual stream, thread, event functionality. * * For now, we just silently ignore SetLinkTimeout() and use the underlhing * ARDP mechanism. */ QStatus SetLinkTimeout(uint32_t& linkTimeout) { QCC_DbgTrace(("_UDPEndpoint::SetLinkTimeout(linkTimeout=%d.)", linkTimeout)); QStatus status = ER_OK; QCC_LogError(status, ("_UDPEndpoint::SetLinkTimeout(): Ignored")); return status; } private: UDPTransport* m_transport; /**< The server holding the connection */ ArdpStream* m_stream; /**< Convenient pointer to the underlying stream */ ArdpHandle* m_handle; /**< The handle to the underlying protocol */ ArdpConnRecord* m_conn; /**< The connection record for the underlying protocol */ uint32_t m_id; /**< The ID of the connection record for the underlying protocol */ qcc::IPAddress m_ipAddr; /**< Remote IP address. */ uint16_t m_ipPort; /**< Remote port. */ bool m_suddenDisconnect; /**< If true, assumption is that any disconnect will be/was unexpected */ bool m_registered; /**< If true, a call-out to the daemon has been made to register this endpoint */ volatile SideState m_sideState; /**< Is this an active or passive connection */ volatile EndpointState m_epState; /**< The state of the endpoint itself */ qcc::Timespec m_tStart; /**< Timestamp indicating when the authentication process started */ qcc::Timespec m_tStop; /**< Timestamp indicating when the stop process for the endpoint was begun */ bool m_remoteExited; /**< Indicates if the remote endpoint exit function has been run. Cannot delete until true. */ bool m_exitScheduled; /**< Indicates if the remote endpoint exit function has been scheduled. */ volatile bool m_disconnected; /**< Indicates an interlocked handling of the ARDP_Disconnect has happened */ volatile int32_t m_refCount; /**< Incremented if a thread is wandering through the endpoint, decrememted when it leaves */ qcc::Mutex m_stateLock; /**< Mutex protecting the endpoint state against multiple threads attempting changes */ }; /** * Construct a UDP Transport object. */ UDPTransport::UDPTransport(BusAttachment& bus) : Thread("UDPTransport"), m_bus(bus), m_stopping(false), m_listener(0), m_foundCallback(m_listener), m_isAdvertising(false), m_isDiscovering(false), m_isListening(false), m_isNsEnabled(false), m_reload(STATE_RELOADING), m_manage(STATE_MANAGE), m_listenPort(0), m_nsReleaseCount(0), m_routerName(), m_maxUntrustedClients(0), m_numUntrustedClients(0), m_authTimeout(0), m_sessionSetupTimeout(0), m_maxAuth(0), m_currAuth(0), m_maxConn(0), m_currConn(0), m_ardpLock(), m_cbLock(), m_handle(NULL), m_dispatcher(NULL), m_workerCommandQueue(), m_workerCommandQueueLock() { QCC_DbgHLPrintf(("UDPTransport::UDPTransport()")); /* * We know we are daemon code, so we'd better be running with a daemon * router. This is assumed elsewhere. */ assert(m_bus.GetInternal().GetRouter().IsDaemon()); /* * We need to find the defaults for our connection limits. These limits * can be specified in the configuration database with corresponding limits * used for DBus. If any of those are present, we use them, otherwise we * provide some hopefully reasonable defaults. */ ConfigDB* config = ConfigDB::GetConfigDB(); m_authTimeout = config->GetLimit("auth_timeout", ALLJOYN_AUTH_TIMEOUT_DEFAULT); m_sessionSetupTimeout = config->GetLimit("session_setup_timeout", ALLJOYN_SESSION_SETUP_TIMEOUT_DEFAULT); m_maxAuth = config->GetLimit("max_incomplete_connections", ALLJOYN_MAX_INCOMPLETE_CONNECTIONS_UDP_DEFAULT); m_maxConn = config->GetLimit("max_completed_connections", ALLJOYN_MAX_COMPLETED_CONNECTIONS_UDP_DEFAULT); ArdpGlobalConfig ardpConfig; ardpConfig.connectTimeout = config->GetLimit("udp_connect_timeout", UDP_CONNECT_TIMEOUT); ardpConfig.connectRetries = config->GetLimit("udp_connect_retries", UDP_CONNECT_RETRIES); ardpConfig.dataTimeout = config->GetLimit("udp_data_timeout", UDP_DATA_TIMEOUT); ardpConfig.dataRetries = config->GetLimit("udp_data_retries", UDP_DATA_RETRIES); ardpConfig.persistTimeout = config->GetLimit("udp_persist_timeout", UDP_PERSIST_TIMEOUT); ardpConfig.persistRetries = config->GetLimit("udp_persist_retries", UDP_PERSIST_RETRIES); ardpConfig.probeTimeout = config->GetLimit("udp_probe_timeout", UDP_PROBE_TIMEOUT); ardpConfig.probeRetries = config->GetLimit("udp_probe_retries", UDP_PROBE_RETRIES); ardpConfig.dupackCounter = config->GetLimit("udp_dupack_counter", UDP_DUPACK_COUNTER); ardpConfig.timewait = config->GetLimit("udp_timewait", UDP_TIMEWAIT); memcpy(&m_ardpConfig, &ardpConfig, sizeof(ArdpGlobalConfig)); /* * User configured UDP-specific values trump defaults if longer. */ qcc::Timespec t = Timespec(ardpConfig.connectTimeout * ardpConfig.connectRetries); if (m_authTimeout < t) { m_authTimeout = m_sessionSetupTimeout = t; } /* * Initialize the hooks to and from the ARDP protocol */ m_ardpLock.Lock(); m_handle = ARDP_AllocHandle(&ardpConfig); ARDP_SetHandleContext(m_handle, this); ARDP_SetAcceptCb(m_handle, ArdpAcceptCb); ARDP_SetConnectCb(m_handle, ArdpConnectCb); ARDP_SetDisconnectCb(m_handle, ArdpDisconnectCb); ARDP_SetRecvCb(m_handle, ArdpRecvCb); ARDP_SetSendCb(m_handle, ArdpSendCb); ARDP_SetSendWindowCb(m_handle, ArdpSendWindowCb); ARDP_StartPassive(m_handle); m_ardpLock.Unlock(); } /** * Destroy a UDP Transport object. */ UDPTransport::~UDPTransport() { QCC_DbgHLPrintf(("UDPTransport::~UDPTransport()")); Stop(); Join(); ARDP_FreeHandle(m_handle); m_handle = NULL; QCC_DbgPrintf(("UDPTransport::~UDPTransport(): m_mAuthList.size() == %d", m_authList.size())); QCC_DbgPrintf(("UDPTransport::~UDPTransport(): m_mEndpointList.size() == %d", m_endpointList.size())); assert(m_preList.size() + m_authList.size() + m_endpointList.size() == 0 && "UDPTransport::~UDPTransport(): Destroying with enlisted endpoints"); //assert(IncrementAndFetch(&m_refCount) == 1 && "UDPTransport::~UDPTransport(): non-zero reference count"); } /** * Define an EndpointExit function even though it is not used in the UDP * Transport. This virtual function is expected by the daemon and must be * defined even though we will not use it. We short-circuit the EndpointExit * functionality by defining a new RemoteEndpoint::Stop() function that doesn't * require the functionality. */ void UDPTransport::EndpointExit(RemoteEndpoint& ep) { QCC_DbgTrace(("UDPTransport::EndpointExit()")); } /* * A thread to dispatch all of the callbacks from the ARDP protocol. */ ThreadReturn STDCALL UDPTransport::DispatcherThread::Run(void* arg) { IncrementAndFetch(&m_transport->m_refCount); QCC_DbgTrace(("UDPTransport::DispatcherThread::Run()")); vector<Event*> checkEvents, signaledEvents; checkEvents.push_back(&stopEvent); while (!IsStopping()) { QCC_DbgTrace(("UDPTransport::DispatcherThread::Run(): Wait for some action")); signaledEvents.clear(); QStatus status = Event::Wait(checkEvents, signaledEvents); /* * This should never happen since we provide a timeout value of * WAIT_FOREVER by default, but it does. This means that there is a * problem in the Windows implementation of Event::Wait(). */ if (status == ER_TIMEOUT) { // QCC_LogError(status, ("UDPTransport::DispatcherThread::Run(): Catching Windows returning ER_TIMEOUT from Event::Wait()")); continue; } if (ER_OK != status) { QCC_LogError(status, ("UDPTransport::DispatcherThread::Run(): Event::Wait failed")); break; } for (vector<Event*>::iterator i = signaledEvents.begin(); i != signaledEvents.end(); ++i) { if (*i == &stopEvent) { QCC_DbgTrace(("UDPTransport::DispatcherThread::Run(): Reset stopEvent")); stopEvent.ResetEvent(); } } bool drained = false; do { WorkerCommandQueueEntry entry; /* * Pull an entry that describes what it is we need to do from the * queue. */ m_transport->m_workerCommandQueueLock.Lock(MUTEX_CONTEXT); if (m_transport->m_workerCommandQueue.empty()) { drained = true; } else { entry = m_transport->m_workerCommandQueue.front(); m_transport->m_workerCommandQueue.pop(); } m_transport->m_workerCommandQueueLock.Unlock(MUTEX_CONTEXT); /* * We keep at it until we completely drain this queue every time we * wake up. */ if (drained == false) { QCC_DbgTrace(("UDPTransport::DispatcherThread::Run(): command=%d., handle=%p, conn=%p., connId=%d.," "rcv=%p, passive=%d., buf=%p, len=%d., status=\"%s\"", entry.m_command, entry.m_handle, entry.m_conn, entry.m_connId, entry.m_rcv, entry.m_passive, entry.m_buf, entry.m_len, QCC_StatusText(entry.m_status))); /* * If the command is a connect callback, we may not have an * endpoint created yet. Otherwise we have a connection ID in * our command entry, and we expect it to refer to an endpoint * that is on the endpoint list. If it has been deleted out * from under us we shouldn't use it. Use the connection ID to * make the connection between ArdpConnRecord* and UDPEndpoint * (which also serves as our protocol demux functionality). */ if (entry.m_command == WorkerCommandQueueEntry::CONNECT_CB) { /* * We can't call out to some possibly windy code path out * through the daemon router with the m_endpointListLock * taken. */ QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): CONNECT_CB: DoConnectCb()")); m_transport->DoConnectCb(entry.m_handle, entry.m_conn, entry.m_passive, entry.m_buf, entry.m_len, entry.m_status); } else { bool haveLock = true; m_transport->m_endpointListLock.Lock(MUTEX_CONTEXT); for (set<UDPEndpoint>::iterator i = m_transport->m_endpointList.begin(); i != m_transport->m_endpointList.end(); ++i) { UDPEndpoint ep = *i; if (entry.m_connId == ep->GetConnId()) { /* * We can't call out to some possibly windy code path * out through the daemon router with the * m_endpointListLock taken. But since we are going to * call into the endpoint, we'll bump the reference * count to indicate a thread is coming. If the ref * count bumped, the endpoint management code will not * kill the endpoint out from under us. */ ep->IncrementRefs(); m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); haveLock = false; /* * This probably seems like a lot of trouble to make a * single method call. The problem is that if we don't * go through the trouble, we do the calls in an ARDP * callback. If we do it in a callback, that callback * must have been driven by a call to ARDP_Run() which * must have been called with the ardpLock taken. When * Start() (for example) does its RegisterEndpoint() the * daemon wants to take the name table lock to add the * endpoint to the name table. * * If another thread is sending a message through the * daemon, it wants to call into daemon router which * takes the nameTableLock to figure out which endpoint * to send to. If that destination endpoint happens to * be a UDP endpoint, it will need to take the ardpLock * to actually send the bits using ARDP_send. * * In once case the lock order is ardpLock, then * nameTableLock; in the other case the lock order is * nameTableLock, then ardpLock. Deadlock. * * Similar situations abound if we call out to the * daemon, so we cannot call into the daemon directly * from a callback which would imply the ardpLock is * taken. Instead of playing with fire, we route * callbacks to this thread to get the one call done. * * This approach does have the benefit of keeping all of * the call-outs from the ARDP protocol very quick, * amounting to usually a push onto a messsage queue. */ switch (entry.m_command) { case WorkerCommandQueueEntry::EXIT: { QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): EXIT: Exit()")); ep->Exit(); break; } case WorkerCommandQueueEntry::SEND_CB: { QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): SEND_CB: SendCb()")); ep->SendCb(entry.m_handle, entry.m_conn, entry.m_buf, entry.m_len, entry.m_status); break; } case WorkerCommandQueueEntry::RECV_CB: { QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): RECV_CB: RecvCb()")); ep->RecvCb(entry.m_handle, entry.m_conn, entry.m_rcv, entry.m_status); break; } case WorkerCommandQueueEntry::DISCONNECT_CB: { QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): DISCONNECT_CB: DisconnectCb()")); ep->DisconnectCb(entry.m_handle, entry.m_conn, entry.m_status); break; } default: { assert(false && "UDPTransport::DispatcherThread::Run(): Unexpected command"); break; } } // switch(entry.m_command) /* * At this point, we assume that we have given the * m_endpointListLock and decremented the thread count * in the endpoint; and our iterator can no longer be * trusted (or is not there in the case of a CONNECT_CB * request. */ ep->DecrementRefs(); assert(haveLock == false && "UDPTransport::DispatcherThread::Run(): Should not have m_endpointListLock here"); break; } // if (entry.m_connId == ep->GetConnId()) } // for (set<UDPEndpoint>::iterator i ... /* * If we found an endpoint, we gave the lock, did the * operation and broke out of the iterator loop assuming the * iterator was no good any more. If we did not find the * endpoint, we still have the lock and we need to give it * up. Also, if we did not find an endpoint, we may have * a receive buffer we have to dispose of. We assume that * when the endpoint bailed, any callers waiting to write * were ejected and so there are no transmit buffers to * deal with. */ if (haveLock) { m_transport->m_endpointListLock.Unlock(MUTEX_CONTEXT); switch (entry.m_command) { case WorkerCommandQueueEntry::RECV_CB: { QCC_DbgPrintf(("UDPTransport::DispatcherThread::Run(): Orphaned RECV_CB: ARDP_RecvReady()")); m_transport->m_ardpLock.Lock(); ARDP_RecvReady(entry.m_handle, entry.m_conn, entry.m_rcv); m_transport->m_ardpLock.Unlock(); break; } default: break; } } } // else not CONNECT_CB } // if (drained == false) } while (drained == false); } QCC_DbgTrace(("UDPTransport::DispatcherThread::Run(): Exiting")); DecrementAndFetch(&m_transport->m_refCount); return 0; } /** * Start the UDP Transport and prepare it for accepting inbound connections or * forming outbound connections. */ QStatus UDPTransport::Start() { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::Start()")); /* * The AllJoyn threading model says exactly one Start() can be done. */ if (IsRunning()) { QCC_LogError(ER_BUS_BUS_ALREADY_STARTED, ("UDPTransport::Start(): Already started")); DecrementAndFetch(&m_refCount); return ER_BUS_BUS_ALREADY_STARTED; } m_stopping = false; /* * Get the guid from the bus attachment which will act as the globally unique * ID of the daemon. */ qcc::String guidStr = m_bus.GetInternal().GetGlobalGUID().ToString(); /* * We're a UDP transport, and UDP is an IP protocol, so we want to use the IP * name service for our advertisement and discovery work. When we acquire * the name service, we are basically bumping a reference count and starting * it if required. * * Start() will legally be called exactly once, but Stop() and Join() may be called * multiple times. Since we are essentially reference counting the name service * singleton, we can only call Release() on it once. So we have a release count * variable that allows us to only release the singleton on the first transport * Join() */ QCC_DbgPrintf(("UDPTransport::Start(): Aquire instance of NS")); m_nsReleaseCount = 0; IpNameService::Instance().Acquire(guidStr); /* * Tell the name service to call us back on our FoundCallback method when * we hear about a new well-known bus name. */ QCC_DbgPrintf(("UDPTransport::Start(): Set NS callback")); IpNameService::Instance().SetCallback(TRANSPORT_UDP, new CallbackImpl<FoundCallback, void, const qcc::String&, const qcc::String&, std::vector<qcc::String>&, uint32_t> (&m_foundCallback, &FoundCallback::Found)); QCC_DbgPrintf(("UDPTransport::Start(): Spin up message dispatcher thread")); m_dispatcher = new DispatcherThread(this); QStatus status = m_dispatcher->Start(NULL, NULL); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::Start(): Failed to Start() message dispatcher thread")); DecrementAndFetch(&m_refCount); return status; } /* * Start the maintenance loop through the thread base class. This will * close or open the IsRunning() gate we use to control access to our public * API. */ QCC_DbgPrintf(("UDPTransport::Start(): Spin up main thread")); status = Thread::Start(); DecrementAndFetch(&m_refCount); return status; } bool operator<(const UDPTransport::ConnectEntry& lhs, const UDPTransport::ConnectEntry& rhs) { return lhs.m_connId < rhs.m_connId; } /** * Ask all of the threads that may be wandering around in the UDP Transport or * its associated endpoints to begin leaving. */ QStatus UDPTransport::Stop(void) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::Stop()")); /* * It is legal to call Stop() more than once, so it must be possible to * call Stop() on a stopped transport. */ m_stopping = true; /* * Tell the name service to stop calling us back if it's there (we may get * called more than once in the chain of destruction) so the pointer is not * required to be non-NULL. */ QCC_DbgPrintf(("UDPTransport::Stop(): Clear NS callback")); IpNameService::Instance().SetCallback(TRANSPORT_UDP, NULL); /* * Ask any running endpoints to shut down and stop allowing routing to * happen through this transport. The endpoint needs to wake any threads * that may be waiting for I/O and arrange for itself to be cleaned up by * the maintenance thread. */ QCC_DbgPrintf(("UDPTransport::Stop(): Stop endpoints")); m_endpointListLock.Lock(MUTEX_CONTEXT); for (set<UDPEndpoint>::iterator i = m_authList.begin(); i != m_authList.end(); ++i) { UDPEndpoint ep = *i; ep->Stop(); } for (set<UDPEndpoint>::iterator i = m_endpointList.begin(); i != m_endpointList.end(); ++i) { UDPEndpoint ep = *i; ep->Stop(); } /* * If there are any threads blocked trying to connect to a remote host, we * need to wake them up so they leave before we actually go away. We are * guaranteed by contract that if there is an entry in the connect threads * set, the thread is still there and the event has not been destroyed. * This is critical since the event was created on the stack of the * connecting thread. These entries will be verified as being gone in * Join(). */ QCC_DbgPrintf(("UDPTransport::Stop(): Alert connectThreads")); for (set<ConnectEntry>::const_iterator i = m_connectThreads.begin(); i != m_connectThreads.end(); ++i) { i->m_event->SetEvent(); } m_endpointListLock.Unlock(MUTEX_CONTEXT); QCC_DbgPrintf(("UDPTransport::Stop(): Stop dispatcher thread")); if (m_dispatcher) { m_dispatcher->Stop(); } /* * Tell the server maintenance loop thread to shut down. It needs to wait * for all of those threads and endpoints to shut down so it doesn't * unexpectedly disappear out from underneath them. We'll wait for it * to actually stop when we do a required Join() below. */ QCC_DbgPrintf(("UDPTransport::Stop(): Stop main thread")); QStatus status = Thread::Stop(); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::Stop(): Failed to Stop() server thread")); DecrementAndFetch(&m_refCount); return status; } DecrementAndFetch(&m_refCount); return ER_OK; } /** * Wait for all of the threads that may be wandering around in the UDP Transport * or its associated endpoints to complete their cleanup process and leave the * transport. When this method completes, it must be safe to delete the object. * Note that this method may be called multiple times. */ QStatus UDPTransport::Join(void) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::Join()")); QCC_DbgPrintf(("UDPTransport::Join(): Join and delete dispatcher thread")); if (m_dispatcher) { m_dispatcher->Join(); delete m_dispatcher; m_dispatcher = NULL; } QCC_DbgPrintf(("UDPTransport::Join(): Return unused message buffers to ARDP")); while (m_workerCommandQueue.empty() == false) { WorkerCommandQueueEntry entry = m_workerCommandQueue.front(); m_workerCommandQueue.pop(); /* * However, the ARDP module will have allocated memory (in some private * way) for any messages that are waiting to be routed. We can't just * ignore that situation or we may leak memory. Give any buffers back * to the protocol before leaving. */ if (entry.m_command == WorkerCommandQueueEntry::RECV_CB) { m_ardpLock.Lock(); ARDP_RecvReady(entry.m_handle, entry.m_conn, entry.m_rcv); m_ardpLock.Unlock(); /* * If we do something that is going to bug the ARDP protocol, we * need to call back into ARDP ASAP to get it moving. This is done * in the main thread, which we need to wake up. */ Alert(); } /* * Similarly, we may have copied out the BusHello in a connect callback * so we need to delete that buffer if it's there. */ if (entry.m_command == WorkerCommandQueueEntry::CONNECT_CB) { #ifndef NDEBUG CheckSeal(entry.m_buf + entry.m_len); #endif delete[] entry.m_buf; } } /* * It is legal to call Join() more than once, so it must be possible to * call Join() on a joined transport and also on a joined name service. * Note that the thread we are joining here is the single UDP Transport * maintenance thread. When it finally closes, all of the threads * previously wandering around in the transport must be gone. */ QCC_DbgPrintf(("UDPTransport::Join(): Join main thread")); QStatus status = Thread::Join(); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::Join(): Failed to Join() server thread")); DecrementAndFetch(&m_refCount); return status; } /* * Tell the IP name service instance that we will no longer be making calls * and it may shut down if we were the last transport. This release can * be thought of as a reference counted Stop()/Join() so it is appropriate * to make it here since we are expecting the possibility of blocking. * * Since it is reference counted, we can't just call it willy-nilly. We * have to be careful since our Join() can be called multiple times. */ int count = qcc::IncrementAndFetch(&m_nsReleaseCount); if (count == 1) { IpNameService::Instance().Release(); } /* * We must have asked any running endpoints to shut down and to wake any * threads that may be waiting for I/O. Before we delete the endpoints * out from under those threads, we need to wait until they actually * all leave the endpoints. We are in a Join() so it's okay if we take * our time and since the transport is shutting down, no new endpoints * will be formed, so it is okay to hold the endpoint lock during the * Join()s. */ m_endpointListLock.Lock(MUTEX_CONTEXT); for (set<UDPEndpoint>::iterator i = m_authList.begin(); i != m_authList.end(); ++i) { UDPEndpoint ep = *i; ep->Join(); } for (set<UDPEndpoint>::iterator i = m_endpointList.begin(); i != m_endpointList.end(); ++i) { UDPEndpoint ep = *i; ep->Join(); } /* * If there were any threads blocked waiting to connect through to a * remote host, they should have been woken up in Stop() and they should * now wake up and be leaving of their own accord. We need to wait * until they are all actually done and gone before proceeding to what * will ultimately mean the destruction of the transport. */ while (m_connectThreads.empty() == false) { QCC_DbgTrace(("UDPTransport::Join(): Waiting for %d. threads to exit", m_connectThreads.size())); /* * Okay, this is the last call. If there are still any threads waiting * in UDPTransport::Connect() we need to convince them to leave. Bug * Their events again. */ for (set<ConnectEntry>::iterator j = m_connectThreads.begin(); j != m_connectThreads.end(); ++j) { j->m_event->SetEvent(); } /* * Wait for "a while." This means long enough to get all of the * threads scheduled and run so they can wander out of the endpoint. * We would like to wait on an event that is bugged when all threads * have left the endpoint, but that would mean an expensive event * per endpoint only to optimize during shutdown and we just can't * afford that. So we poll, waiting long enough to ensure that our * thread is rescheduled. * * Some Linux boxes will busy-wait if the time is two milliseconds * or less, and most will round up to jiffy resolution (defaults to * 10 ms) and then bump again to the next higher Jiffy to ensure * that at least the requested time has elapsed. So we pick 10 ms * and expect the loop to run every 20 ms in the usual case, * ensuring that the waiting threads get time to run and leave. */ m_endpointListLock.Unlock(MUTEX_CONTEXT); qcc::Sleep(10); m_endpointListLock.Lock(MUTEX_CONTEXT); } /* * The above loop will not terminate until all connecting threads are gone. * There are now no threads running in UDP endpoints or in the transport and * since we already Join()ed the maintenance thread we can delete all of the * endpoints here. */ set<UDPEndpoint>::iterator i; while ((i = m_preList.begin()) != m_preList.end()) { #ifndef NDEBUG UDPEndpoint ep = *i; QCC_DbgTrace(("UDPTransport::Join(): Erasing endpoint with conn ID == %d. from m_preList", ep->GetConnId())); #endif m_preList.erase(i); } while ((i = m_authList.begin()) != m_authList.end()) { #ifndef NDEBUG UDPEndpoint ep = *i; QCC_DbgTrace(("UDPTransport::Join(): Erasing endpoint with conn ID == %d. from m_authList", ep->GetConnId())); #endif m_authList.erase(i); DecrementAndFetch(&m_currAuth); } while ((i = m_endpointList.begin()) != m_endpointList.end()) { #ifndef NDEBUG UDPEndpoint ep = *i; QCC_DbgTrace(("UDPTransport::Join(): Erasing endpoint with conn ID == %d. from m_endpointList", ep->GetConnId())); #endif m_endpointList.erase(i); DecrementAndFetch(&m_currConn); } m_endpointListLock.Unlock(MUTEX_CONTEXT); m_stopping = false; DecrementAndFetch(&m_refCount); return ER_OK; } /* * The default interface for the name service to use. The wildcard character * means to listen and transmit over all interfaces that are up and multicast * capable, with any IP address they happen to have. This default also applies * to the search for listen address interfaces. */ static const char* INTERFACES_DEFAULT = "*"; /** * This is a somewhat obscure method used by the AllJoyn object to determine if * there are possibly multiple ways to connect to an advertised bus address. * Our goal is to enumerate all of the possible interfaces over which we can be * contacted -- for example, eth0, wlan0 -- and construct bus address strings * matching each one. */ QStatus UDPTransport::GetListenAddresses(const SessionOpts& opts, std::vector<qcc::String>& busAddrs) const { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::GetListenAddresses()")); /* * We are given a session options structure that defines the kind of * transports that are being sought. The UDP transport provides reliable * traffic as understood by the session options, so we only return someting * if the traffic type is TRAFFIC_MESSAGES or TRAFFIC_RAW_RELIABLE. It's * not an error if we don't match, we just don't have anything to offer. */ if (opts.traffic != SessionOpts::TRAFFIC_MESSAGES && opts.traffic != SessionOpts::TRAFFIC_RAW_RELIABLE) { QCC_DbgPrintf(("UDPTransport::GetListenAddresses(): traffic mismatch")); DecrementAndFetch(&m_refCount); return ER_OK; } /* * The other session option that we need to filter on is the transport * bitfield. We have no easy way of figuring out if we are a wireless * local-area, wireless wide-area, wired local-area or local transport, * but we do exist, so we respond if the caller is asking for any of * those: cogito ergo some. */ if (!(opts.transports & (TRANSPORT_WLAN | TRANSPORT_WWAN | TRANSPORT_LAN))) { QCC_DbgPrintf(("UDPTransport::GetListenAddresses(): transport mismatch")); DecrementAndFetch(&m_refCount); return ER_OK; } /* * The name service is initialized by the call to Init() in our Start() * method and then started there. It is Stop()ped in our Stop() method and * joined in our Join(). In the case of a call here, the transport will * probably be started, and we will probably find the name service started, * but there is no requirement to ensure this. If m_ns is NULL, we need to * complain so the user learns to Start() the transport before calling * IfConfig. A call to IsRunning() here is superfluous since we really * don't care about anything but the name service in this method. */ if (IpNameService::Instance().Started() == false) { QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("UDPTransport::GetListenAddresses(): NameService not started")); DecrementAndFetch(&m_refCount); return ER_BUS_TRANSPORT_NOT_STARTED; } /* * Our goal is here is to match a list of interfaces provided in the * configuration database (or a wildcard) to a list of interfaces that are * IFF_UP in the system. The first order of business is to get the list of * interfaces in the system. We do that using a convenient OS-inependent * call into the name service. * * We can't cache this list since it may change as the phone wanders in * and out of range of this and that and the underlying IP addresses change * as DHCP doles out whatever it feels like at any moment. */ QCC_DbgPrintf(("UDPTransport::GetListenAddresses(): IfConfig()")); std::vector<qcc::IfConfigEntry> entries; QStatus status = qcc::IfConfig(entries); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::GetListenAddresses(): ns.IfConfig() failed")); DecrementAndFetch(&m_refCount); return status; } /* * The next thing to do is to get the list of interfaces from the config * file. These are required to be formatted in a comma separated list, * with '*' being a wildcard indicating that we want to match any interface. * If there is no configuration item, we default to something rational. */ QCC_DbgPrintf(("UDPTransport::GetListenAddresses(): GetProperty()")); qcc::String interfaces = ConfigDB::GetConfigDB()->GetProperty("ns_interfaces"); if (interfaces.size() == 0) { interfaces = INTERFACES_DEFAULT; } /* * Check for wildcard anywhere in the configuration string. This trumps * anything else that may be there and ensures we get only one copy of * the addresses if someone tries to trick us with "*,*". */ bool haveWildcard = false; const char*wildcard = "*"; size_t i = interfaces.find(wildcard); if (i != qcc::String::npos) { QCC_DbgPrintf(("UDPTransport::GetListenAddresses(): wildcard search")); haveWildcard = true; interfaces = wildcard; } /* * Walk the comma separated list from the configuration file and and try * to mach it up with interfaces actually found in the system. */ while (interfaces.size()) { /* * We got a comma-separated list, so we need to work our way through * the list. Each entry in the list may be an interface name, or a * wildcard. */ qcc::String currentInterface; size_t i = interfaces.find(","); if (i != qcc::String::npos) { currentInterface = interfaces.substr(0, i); interfaces = interfaces.substr(i + 1, interfaces.size() - i - 1); } else { currentInterface = interfaces; interfaces.clear(); } QCC_DbgPrintf(("UDPTransport::GetListenAddresses(): looking for interface %s", currentInterface.c_str())); /* * Walk the list of interfaces that we got from the system and see if * we find a match. */ for (uint32_t i = 0; i < entries.size(); ++i) { QCC_DbgPrintf(("UDPTransport::GetListenAddresses(): matching %s", entries[i].m_name.c_str())); /* * To match a configuration entry, the name of the interface must: * * - match the name in the currentInterface (or be wildcarded); * - be UP which means it has an IP address assigned; * - not be the LOOPBACK device and therefore be remotely available. */ uint32_t mask = qcc::IfConfigEntry::UP | qcc::IfConfigEntry::LOOPBACK; uint32_t state = qcc::IfConfigEntry::UP; if ((entries[i].m_flags & mask) == state) { QCC_DbgPrintf(("UDPTransport::GetListenAddresses(): %s has correct state", entries[i].m_name.c_str())); if (haveWildcard || entries[i].m_name == currentInterface) { QCC_DbgPrintf(("UDPTransport::GetListenAddresses(): %s has correct name", entries[i].m_name.c_str())); /* * This entry matches our search criteria, so we need to * turn the IP address that we found into a busAddr. We * must be a UDP transport, and we have an IP address * already in a string, so we can easily put together the * desired busAddr. */ QCC_DbgPrintf(("UDPTransport::GetListenAddresses(): %s match found", entries[i].m_name.c_str())); /* * We know we have an interface that speaks IP and which has * an IP address we can pass back. We know it is capable of * receiving incoming connections, but the $64,000 questions * are, does it have a listener and what port is that * listener listening on. * * There is one name service associated with the daemon UDP * transport, and it is advertising at most one port. It * may be advertising that port over multiple interfaces, * but there is currently just one port being advertised. * If multiple listeners are created, the name service only * advertises the lastly set port. In the future we may * need to add the ability to advertise different ports on * different interfaces, but the answer is simple now. Ask * the name service for the one port it is advertising and * that must be the answer. */ qcc::String ipv4address; qcc::String ipv6address; uint16_t reliableIpv4Port, reliableIpv6Port, unreliableIpv4Port, unreliableIpv6port; IpNameService::Instance().Enabled(TRANSPORT_UDP, reliableIpv4Port, reliableIpv6Port, unreliableIpv4Port, unreliableIpv6port); /* * If the port is zero, then it hasn't been set and this * implies that UDPTransport::StartListen hasn't * been called and there is no listener for this transport. * We should only return an address if we have a listener. */ if (unreliableIpv4Port) { /* * Now put this information together into a bus address * that the rest of the AllJoyn world can understand. */ if (!entries[i].m_addr.empty() && (entries[i].m_family == QCC_AF_INET)) { qcc::String busAddr = "udp:u4addr=" + entries[i].m_addr + "," "u4port=" + U32ToString(unreliableIpv4Port) + "," "family=ipv4"; busAddrs.push_back(busAddr); } } } } } } /* * If we can get the list and walk it, we have succeeded. It is not an * error to have no available interfaces. In fact, it is quite expected * in a phone if it is not associated with an access point over wi-fi. */ QCC_DbgPrintf(("UDPTransport::GetListenAddresses(): done")); DecrementAndFetch(&m_refCount); return ER_OK; } /** * This method is used to deal with the lifecycle of all endpoints created by * the UDP Transport. It is called on-demand and periodically by the main run * loop in order to detect connections / endpoints that are taking too long to * authenticate and also to deal with endpoints that are being torn down. * * The main complexities here are to ensure that there are no threads wandering * around in endpoints before we remove them, ensuring that the endpoints are * completely detached from the router and that the UDP Transport holds the final * reference to endpoints to make absolutely sure that there are going to be no * suprise threads popping up in a deleted object. We also cannot block waiting * for things to happen, since we would block the protocol (as it stands now there * is one thread managing endpoints and driving ARDP). */ void UDPTransport::ManageEndpoints(Timespec authTimeout, Timespec sessionSetupTimeout) { set<UDPEndpoint>::iterator i; m_endpointListLock.Lock(MUTEX_CONTEXT); /* * If there are any endpoints on the preList, move them to the authList. */ m_preListLock.Lock(MUTEX_CONTEXT); i = m_preList.begin(); while (i != m_preList.end()) { QCC_DbgPrintf(("UDPTransport::ManageEndpoints(): Moving endpoint from m_preList to m_authList")); UDPEndpoint ep = *i; m_authList.insert(ep); m_preList.erase(i); i = m_preList.begin(); } m_preListLock.Unlock(MUTEX_CONTEXT); /* * Run through the list of connections on the authList and cleanup any that * are taking too long to authenticate. These are connections that are in * the middle of the three-way handshake. */ bool changeMade = false; i = m_authList.begin(); while (i != m_authList.end()) { UDPEndpoint ep = *i; Timespec tNow; GetTimeNow(&tNow); if (ep->GetStartTime() + authTimeout < tNow) { QCC_DbgPrintf(("UDPTransport::ManageEndpoints(): Scavenging slow authenticator")); /* * If the authentication doesn't happen, the three-way handshake * doesn't complete and the endpoint just goes quiescent without * ever starting up. If an endpoint sits on the list of endpoints * currently authenticating for too long, we need to just whack it. * If the endpoint was created during a passive accept, there is no * problem, but if the endpoint was created as part of an active * connection, there is a thread waiting for the Connect to finish, * so we need to wake it and let it leave before getting rid of the * endpoint. */ bool threadWaiting = false; set<ConnectEntry>::iterator j = m_connectThreads.begin(); for (; j != m_connectThreads.end(); ++j) { /* * The question of the moment will be: is the endpoint referred * to by the endpoint iterator i the same one referred to by the * connect thread entry referred to by the entry iterator j. If * it is, then we have a thread blocked on that endpoint and we * must wake it. We rely on matching the connection IDs to make * that call. * * Once we set the event to wake the thread, we still can't do * anything until the thread actually leaves, at which point we * will no longer find it in the connect threads set. */ if (j->m_connId == ep->GetConnId()) { QCC_DbgTrace(("UDPTransport::ManageEndpoints(): Waking thread on slow authenticator with conn ID == %d.", j->m_connId)); j->m_event->SetEvent(); threadWaiting = true; changeMade = true; } } /* * No threads waiting in this endpoint. Just take it off of the * authList, make sure it is at least stopping and put it on the * endpoint list where it will be picked up and done away with. */ if (threadWaiting == false) { QCC_DbgHLPrintf(("UDPTransport::ManageEndpoints(): Moving slow authenticator with conn ID == %d. to m_endpointList", ep->GetConnId())); m_authList.erase(i); DecrementAndFetch(&m_currAuth); m_endpointList.insert(ep); IncrementAndFetch(&m_currConn); ep->Stop(); i = m_authList.upper_bound(ep); changeMade = true; continue; } } ++i; } /* * We've handled the authList, so now run through the list of connections on * the endpointList and cleanup any that are no longer running. */ i = m_endpointList.begin(); while (i != m_endpointList.end()) { UDPEndpoint ep = *i; /* * Get the internal (UDP) endpoint state. We use this to figure out the * correct strategy for getting rid of endpoints at the end of their * lifetimes. */ _UDPEndpoint::EndpointState endpointState = ep->GetEpState(); /* * This can be a little tricky since the daemon wants to reference count * the endpoints and will call Stop() but not Join() in * RemoveSessionRef() for example. This is because it doesn't want to * take possibly unbounded time to wait for the threads in the endpoint * to exit. What that means is that we can arbitrarily find ourselves * with endpoints in EP_STOPPING state, and we will have to do the * Join() to finish tearing down the endpoint. That means we have to do * a Join(), but we must also be sensitive to blocking for long periods * of time since we are called out of the main loop of the transport and * in the thread that is driving ARDP. */ if (endpointState == _UDPEndpoint::EP_STOPPING || endpointState == _UDPEndpoint::EP_JOINED) { QCC_DbgPrintf(("UDPTransport::ManageEndpoints(): Endpoint with conn ID == %d is EP_STOPPING or EP_JOINED", ep->GetConnId())); /* * If we are in state EP_STOPPING, not surprisingly Stop() must have * been called. What we need to do is to wait until the * after-effects of that Stop() have settled before we call Join() * so it doesn't block. When Stop() was called, it Alerted the set * of (daemon) threads that may have been waiting on the endpoint * and if no previous sudden disconnect happened it called ARDP_Disconnect * to start a local disconnect. We have to wait for the threads to * leave and the disconnect to complete before doing the Join(). */ ArdpStream* stream = ep->GetStream(); assert(stream && "UDPTransport::ManageEndpoints(): stream must exist in state EP_STOPPING"); /* * Wait for the threads blocked on the endpoint for writing to exit, * pending writes to finish (or be discarded) and the required * disconnect callback to happen. */ bool threadSetEmpty = stream->ThreadSetEmpty(); bool disconnected = stream->GetDisconnected(); /* * We keep an eye on endpoints that seem to be stalled waiting to * have the expected things happen. There's not much we can do if * things have gone wrong, but we log errors in the hope that * someone notices. */ Timespec tNow; GetTimeNow(&tNow); Timespec tStop = ep->GetStopTime(); int32_t tRemaining = tStop + (m_ardpConfig.connectTimeout * m_ardpConfig.connectRetries) - tNow; if (tRemaining < 0) { QCC_LogError(ER_UDP_ENDPOINT_STALLED, ("UDPTransport::ManageEndpoints(): Endpoint with conn ID == %d stalled", ep->GetConnId())); if (threadSetEmpty == false) { QCC_LogError(ER_UDP_ENDPOINT_STALLED, ("UDPTransport::ManageEndpoints(): stalled not threadSetEmpty")); } if (disconnected == false) { QCC_LogError(ER_UDP_ENDPOINT_STALLED, ("UDPTransport::ManageEndpoints(): stalled not disconnected")); #ifndef NDEBUG ArdpStream* stream = ep->GetStream(); if (stream) { bool disc = stream->GetDisconnected(); bool discSent = stream->GetDiscSent(); ArdpConnRecord* conn = stream->GetConn(); bool suddenDisconnect = ep->GetSuddenDisconnect(); QCC_LogError(ER_UDP_ENDPOINT_STALLED, ("UDPTransport::ManageEndpoints(): stalled not disconneccted. disc=\"%s\", discSent=\"%s\", conn=%p, suddendisconnect=\"%s\"", disc ? "true" : "false", discSent ? "true" : "false", conn, suddenDisconnect ? "true" : "false")); } else { QCC_LogError(ER_UDP_ENDPOINT_STALLED, ("UDPTransport::ManageEndpoints(): stalled not disconnected. No stream")); } #endif } } if (threadSetEmpty && disconnected) { QCC_DbgHLPrintf(("UDPTransport::ManageEndpoints(): Join()ing stopping endpoint with conn ID == %d.", ep->GetConnId())); /* * We now expect that Join() will complete without having to * wait for anything. */ if (endpointState != _UDPEndpoint::EP_JOINED) { ep->Join(); changeMade = true; } /* * Now, schedule the endpoint exit function to be run if it has * not been run before. This will ensure that the endpoint is * detached (unregistered) from the daemon (running in another * thread to avoid deadlocks). At this point we have stopped * and joined the endpoint, but we must wait until the detach * happens, as indicated by EndpointExited() returning true, * before removing our (last) reference to the endpoint below. * When the endpoint Exit() function is actually run by the * dispatcher, it sets the endpoint state to EP_DONE. */ if (ep->GetRegistered() && ep->GetExitScheduled() == false) { ep->SetExitScheduled(); ExitEndpoint(ep->GetConnId()); endpointState = ep->GetEpState(); changeMade = true; } #ifndef NDEBUG } else { QCC_DbgPrintf(("UDPTransport::ManageEndpoints(): Endpoint with conn ID == %d. is not idle", ep->GetConnId())); #endif } } /* * If we find the endpoint in the EP_FAILED or EP_DONE state, the * endpoint is ready to go away and there must be no pending operations * of any sort. Given that caveat, we can just pitch it. When the * reference count goes to zero as a result of removing it from the * endpoint list it will be destroyed. */ if (endpointState == _UDPEndpoint::EP_FAILED || endpointState == _UDPEndpoint::EP_DONE) { if (ep->GetExited()) { QCC_DbgHLPrintf(("UDPTransport::ManageEndpoints(): Removing reference for failed or done endpoint with conn ID == %d.", ep->GetConnId())); int32_t refs = ep->IncrementRefs(); if (refs == 1) { ep->DecrementRefs(); QCC_DbgHLPrintf(("UDPTransport::ManageEndpoints(): Endpoint with conn ID == %d. is histoire", ep->GetConnId())); m_endpointList.erase(i); DecrementAndFetch(&m_currConn); i = m_endpointList.upper_bound(ep); changeMade = true; continue; } ep->DecrementRefs(); } } ++i; } if (changeMade) { m_manage = STATE_MANAGE; Alert(); } m_endpointListLock.Unlock(MUTEX_CONTEXT); } /** * Callback from the ARDP Protocol. We just plumb this callback directly into the transport. */ bool UDPTransport::ArdpAcceptCb(ArdpHandle* handle, qcc::IPAddress ipAddr, uint16_t ipPort, ArdpConnRecord* conn, uint8_t* buf, uint16_t len, QStatus status) { QCC_DbgTrace(("UDPTransport::ArdpAcceptCb(handle=%p, ipAddr=\"%s\", port=%d., conn=%p, buf =%p, len = %d)", handle, ipAddr.ToString().c_str(), ipPort, conn, buf, len)); UDPTransport* const transport = static_cast<UDPTransport* const>(ARDP_GetHandleContext(handle)); return transport->AcceptCb(handle, ipAddr, ipPort, conn, buf, len, status); } /** * Callback from the ARDP Protocol. We just plumb this callback directly into the transport. */ void UDPTransport::ArdpConnectCb(ArdpHandle* handle, ArdpConnRecord* conn, bool passive, uint8_t* buf, uint16_t len, QStatus status) { QCC_DbgTrace(("UDPTransport::ArdpConnectCb(handle=%p, conn=%p, passive=%s, buf = %p, len = %d, status=%s)", handle, conn, passive ? "true" : "false", buf, len, QCC_StatusText(status))); UDPTransport* const transport = static_cast<UDPTransport* const>(ARDP_GetHandleContext(handle)); transport->ConnectCb(handle, conn, passive, buf, len, status); } /** * Callback from the ARDP Protocol. We just plumb this callback directly into the transport. */ void UDPTransport::ArdpDisconnectCb(ArdpHandle* handle, ArdpConnRecord* conn, QStatus status) { QCC_DbgTrace(("UDPTransport::ArdpDisconnectCb(handle=%p, conn=%p, foreign=%d.)", handle, conn)); UDPTransport* const transport = static_cast<UDPTransport* const>(ARDP_GetHandleContext(handle)); transport->DisconnectCb(handle, conn, status); } /** * Callback from the ARDP Protocol. We just plumb this callback directly into the transport. */ void UDPTransport::ArdpRecvCb(ArdpHandle* handle, ArdpConnRecord* conn, ArdpRcvBuf* rcv, QStatus status) { QCC_DbgTrace(("UDPTransport::ArdpRecvCb(handle=%p, conn=%p, buf=%p, status=%s)", handle, conn, rcv, QCC_StatusText(status))); UDPTransport* const transport = static_cast<UDPTransport* const>(ARDP_GetHandleContext(handle)); transport->RecvCb(handle, conn, rcv, status); } /** * Callback from the ARDP Protocol. We just plumb this callback directly into the transport. */ void UDPTransport::ArdpSendCb(ArdpHandle* handle, ArdpConnRecord* conn, uint8_t* buf, uint32_t len, QStatus status) { QCC_DbgTrace(("UDPTransport::ArdpSendCb(handle=%p, conn=%p, buf=%p, len=%d.)", handle, conn, buf, len)); UDPTransport* const transport = static_cast<UDPTransport* const>(ARDP_GetHandleContext(handle)); transport->SendCb(handle, conn, buf, len, status); } /** * Callback from the ARDP Protocol. We just plumb this callback directly into the transport. */ void UDPTransport::ArdpSendWindowCb(ArdpHandle* handle, ArdpConnRecord* conn, uint16_t window, QStatus status) { QCC_DbgTrace(("UDPTransport::ArdpSendWindowCb(handle=%p, conn=%p, window=%d.)", handle, conn, window)); UDPTransport* const transport = static_cast<UDPTransport* const>(ARDP_GetHandleContext(handle)); transport->SendWindowCb(handle, conn, window, status); } /* * See the note on connection establishment to really make sense of this. * * This callback indicates that we are receiving a passive open request. We are * in LISTEN state and are responding to another side that has done an * ARDP_Connect(). We expect it to have provided a Hello message which we get * in the data that comes along with the SYN segment. Status should always be * ER_OK since it had to be to successfully get us to this point. * * If we can accept a new connection, we send a reply to the incoming Hello * message by calling ARDP_Accept() and we return true indicating that we have, * in fact, accepted the connection. */ bool UDPTransport::AcceptCb(ArdpHandle* handle, qcc::IPAddress ipAddr, uint16_t ipPort, ArdpConnRecord* conn, uint8_t* buf, uint16_t len, QStatus status) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::AcceptCb(handle=%p, ipAddr=\"%s\", ipPort=%d., conn=%p)", handle, ipAddr.ToString().c_str(), ipPort, conn)); if (buf == NULL || len == 0) { QCC_LogError(ER_UDP_INVALID, ("UDPTransport::AcceptCb(): No BusHello with SYN")); DecrementAndFetch(&m_refCount); return false; } /* * Here's the diffulty. It is very common for external threads to call into * the UDP transport and take the endpoint list lock to locate an endpoint * and then take the ARDP lock to do do something with the network protocol * based on the stream in that endpoint. The lock order here is * endpointListLock, then ardpLock. It is also equally common for the main * thread to take the ardpLock and then call into ARDP_Run(), which can call * out into a callback. Those callbacks then want to take the * enpointListLock to figure out how to deal with the callback. The lock * order there is ardpLock, then endpointListLock. * * We usually get around that problem by dispatching all callbacks on the * dispatcher thread which can also use the endpointListLock, then ardpLock * lock order just like external threads. * * The problem here is that AcceptCb() needs to return a boolean indicating * whether or not it can accept a connection, and this depends on the number * of endpoints. In order to look at the size of the lists of endpoints, * you need to take the endpoint list lock, which would result in a * potential deadlock. Also, if we create an endpoint, we need to take the * endpointListLock in order to add it to the auth list. In other words, we * must take the endpoint list lock, but we cannot take the endpoint list * lock. * * To work around the number of available endpoints issue, we keep an * atomically incremented and decremented number of available endpoints * around so we don't have to take a lock and call a size() method on a * couple of lists, as the TCP Transport would. To work around the second * problem we do the addition of the new endpoint to a "pre" queue protected * by a third lock that must never held while either holding or taking the * ARDP lock (which is held here since we are in a callback). * * Bringing up a connection means transiently adding a connection to the * count of currently authenticating connections. This number is never * allowed to exceed a configured value. The number of authenticating plus * acive connections may never exceed a configured value. */ uint32_t currAuth = IncrementAndFetch(&m_currAuth); uint32_t currConn = IncrementAndFetch(&m_currConn); if (currAuth > m_maxAuth || currAuth + currConn > m_maxConn + 1) { QCC_LogError(ER_BUS_CONNECTION_REJECTED, ("UDPTransport::AcceptCb(): No slot for new connection")); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return false; } /* * The connection is not actually complete yet and there is no corresponding * endpoint on the the endpoint list so we can't claim it as existing yet. * We do consider the not yet existing endpoint as existing since we need a * placeholder for it. We just have to be careful about the accounting. */ DecrementAndFetch(&m_currConn); QCC_DbgPrintf(("UDPTransport::AcceptCb(): Inbound connection accepted")); /* * We expect to get an org.alljoyn.Bus.BusHello message from the active side * in the data. */ Message activeHello(m_bus); status = activeHello->LoadBytes(buf, len); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::AcceptCb(): Can't LoadBytes() BusHello Message")); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return false; } /* * Unmarshal the message. We need to provide and endpoint unique name for * error reporting purposes, in order to to affix blame here if something * goes awry. If we don't pass true in checkSender Unmarshal won't validate * the endpoint name and will just print it out in case of problems. We * make (an illegal) one up since we don't have an endpoint yet. */ qcc::String endpointName(":0.0"); status = activeHello->Unmarshal(endpointName, false, false, true, 0); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::AcceptCb(): Can't Unmarhsal() BusHello Message")); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return false; } /* * Validate the fields in the incoming BusHello Message */ if (strcmp(activeHello->GetInterface(), org::alljoyn::Bus::InterfaceName) != 0) { status = ER_BUS_ESTABLISH_FAILED; QCC_LogError(status, ("UDPTransport::AcceptCb(): Unexpected interface=\"%s\" in BusHello Message", activeHello->GetInterface())); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return false; } if (activeHello->GetCallSerial() == 0) { status = ER_BUS_ESTABLISH_FAILED; QCC_LogError(status, ("UDPTransport::AcceptCb(): Unexpected zero serial in BusHello Message")); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return false; } if (strcmp(activeHello->GetDestination(), org::alljoyn::Bus::WellKnownName) != 0) { status = ER_BUS_ESTABLISH_FAILED; QCC_LogError(status, ("UDPTransport::AcceptCb(): Unexpected destination=\"%s\" in BusHello Message", activeHello->GetDestination())); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return false; } if (strcmp(activeHello->GetObjectPath(), org::alljoyn::Bus::ObjectPath) != 0) { status = ER_BUS_ESTABLISH_FAILED; QCC_LogError(status, ("UDPTransport::AcceptCb(): Unexpected object path=\"%s\" in BusHello Message", activeHello->GetObjectPath())); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return false; } if (strcmp(activeHello->GetMemberName(), "BusHello") != 0) { status = ER_BUS_ESTABLISH_FAILED; QCC_LogError(status, ("UDPTransport::AcceptCb(): Unexpected member name=\"%s\" in BusHello Message", activeHello->GetMemberName())); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return false; } /* * The remote name of the endpoint on the passive side of the connection is * the sender of the BusHello Message, presumably the local bus attachment * of the remote daemon doing the imlied Connect(). */ qcc::String remoteName = activeHello->GetSender(); QCC_DbgPrintf(("UDPTransport::AcceptCb(): BusHello Message from sender=\"%s\"", remoteName.c_str())); status = activeHello->UnmarshalArgs("su"); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::AcceptCb(): Can't UnmarhsalArgs() BusHello Message")); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return false; } /* * We expect two arguments in the message: a remoteGUID and a protocol * version. The high order two bits of the protocol version are the * nameTransfer bits that will tell the allJoyn obj how many names to * exchange during ExchangeNames. */ size_t numArgs; const MsgArg* args; activeHello->GetArgs(numArgs, args); if (numArgs != 2 || args[0].typeId != ALLJOYN_STRING || args[1].typeId != ALLJOYN_UINT32) { status = ER_BUS_ESTABLISH_FAILED; QCC_LogError(status, ("UDPTransport::AcceptCb(): Unexpected number or type of arguments in BusHello Message")); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return false; } qcc::String remoteGUID = args[0].v_string.str; uint32_t protocolVersion = args[1].v_uint32 & 0x3FFFFFFF; uint32_t nameTransfer = args[1].v_uint32 >> 30; QCC_DbgPrintf(("UDPTransport::AcceptCb(): Got BusHello(). remoteGuid=\"%s\", protocolVersion=%d., nameTransfer=%d.", remoteGUID.c_str(), protocolVersion, nameTransfer)); if (remoteGUID == m_bus.GetInternal().GetGlobalGUID().ToString()) { status = ER_BUS_SELF_CONNECT; QCC_LogError(status, ("UDPTransport::AcceptCb(): BusHello was sent to self")); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return false; } /* * We need to reply to the hello from the other side. In order to do so we * need the unique name of the endpoint we are creating. This means that it * is now time to create that new endpoint. */ static const bool truthiness = true; UDPTransport* ptr = this; String normSpec = "udp:guid=" + remoteGUID + ",u4addr=" + ipAddr.ToString() + ",u4port=" + U32ToString(ipPort); UDPEndpoint udpEp(ptr, m_bus, truthiness, normSpec); /* * Some of this would "normally" be handled by EndpointAuth, but since we * are short-circuiting the process, we have to do the bookkeeping * ourselves. */ udpEp->GetFeatures().isBusToBus = true; udpEp->GetFeatures().allowRemote = true; udpEp->GetFeatures().protocolVersion = protocolVersion; udpEp->GetFeatures().trusted = false; udpEp->GetFeatures().nameTransfer = static_cast<SessionOpts::NameTransferType>(nameTransfer); udpEp->SetRemoteGUID(remoteGUID); udpEp->SetPassive(); udpEp->SetIpAddr(ipAddr); udpEp->SetIpPort(ipPort); udpEp->CreateStream(handle, conn, m_ardpConfig.dataTimeout, m_ardpConfig.dataRetries); udpEp->SetHandle(handle); udpEp->SetConn(conn); /* * The unique name of the endpoint on the passive side of the connection is * a unique name generated on the passive side. We are calling out to the * daemon but only to construct a GUID, so this is okay. */ udpEp->SetUniqueName(m_bus.GetInternal().GetRouter().GenerateUniqueName()); /* * the remote name of the endpoint on the passive side of the connection is * the sender of the BusHello, which is the local bus attachement on the * remote side that did the impled Connect(). */ udpEp->SetRemoteName(remoteName); /* * Now, we have an endpoint that we need to keep alive but not fully * connected and ready to flow AllJoyn Messages until we get the expected * response to our Hello. That will come in as the ConnectCb we get in * passive mode that marks the end of the connection establishment phase. * Set a timestamp in case this never comes for some reason. */ Timespec tNow; GetTimeNow(&tNow); udpEp->SetStartTime(tNow); udpEp->SetStopTime(tNow); /* * Note that our endpoint isn't actually connected to anything yet or saved * anywhere. Send a hello reply from our local endpoint. The unique name * in the BusHello reponse is the unique name of our UDP endpoint we just * allocated above. */ QCC_DbgPrintf(("UDPTransport::AcceptCb(): HelloReply(true, \"%s\")", udpEp->GetUniqueName().c_str())); status = activeHello->HelloReply(true, udpEp->GetUniqueName()); if (status != ER_OK) { status = ER_UDP_BUSHELLO; QCC_LogError(status, ("UDPTransport::AcceptCb(): Can't make a BusHello Reply Message")); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return status; } /* * The Function HelloReply creates and marshals the BusHello reply for * the remote side. Once it is marshaled, there is a buffer associated * with the message that contains the on-the-wire version of the * messsage. The ARDP code expects to take responsibility for the * buffer since it may need to retransmit it, so we need to copy out the * contents of that (small) buffer. */ size_t helloReplyBufLen = activeHello->GetBufferSize(); #ifndef NDEBUG uint8_t* helloReplyBuf = new uint8_t[helloReplyBufLen + SEAL_SIZE]; SealBuffer(helloReplyBuf + helloReplyBufLen); #else uint8_t* helloReplyBuf = new uint8_t[helloReplyBufLen]; #endif memcpy(helloReplyBuf, const_cast<uint8_t*>(activeHello->GetBuffer()), helloReplyBufLen); /* * Since we are in a callback from ARDP we can note a few assumptions. * First, that callback must have been driven by a call to ARDP_Run() which * must be called with the ARDP lock taken; so we don't have to do it again. * Second, since ARDP is calling out to us, and it is the UDP transport main * thread that drives ARDP, the only thing that is going to happen is that * the SYN + ACK will be sent. We don't have to deal with any possibility * of ARDP processing any inbound data while it is doing the accept. We * take advantage of this by not putting the endpoint on the auth list until * we get status back from ARDP_Accept. */ QCC_DbgPrintf(("UDPTransport::AcceptCb(): ARDP_Accept()")); status = ARDP_Accept(handle, conn, ARDP_SEGMAX, ARDP_SEGBMAX, helloReplyBuf, helloReplyBufLen); if (status != ER_OK) { /* * If ARDP_Accept returns an error, most likely it is becuase the underlying * SYN + ACK didn't go out. The contract with ARDP says that if an error * happens here, we shouldn't expect an disconnect, so we just don't bother * to finish seting up the endpoint. * * Even though we haven't actually started the endpoint, we call Stop() to * set it up for the destruction process to make sure its state is changed * to be deletable (when we release our reference to it and the end of the * current scope). */ udpEp->Stop(); delete[] helloReplyBuf; helloReplyBuf = NULL; QCC_LogError(status, ("UDPTransport::AcceptCb(): ARDP_Accept() failed")); DecrementAndFetch(&m_currAuth); DecrementAndFetch(&m_refCount); return status; } /* * Okay, this is now where we need to work around problem number two. We * are going to tell ARDP to proceed with the connection shortly and we need * the endpoint we just created to make it onto the list of currently * authenticating endpoints, and we need this to happen without taking the * endpointListLock. What we do is to put it on a "pre" authenticating list * that is dealt with especially carefully with respect to locks. */ QCC_DbgPrintf(("UDPTransport::AcceptCb(): Taking pre-auth list lock")); m_preListLock.Lock(MUTEX_CONTEXT); QCC_DbgPrintf(("UDPTransport::AcceptCb(): Adding endpoint with conn ID == %d. to m_preList", udpEp->GetConnId())); m_preList.insert(udpEp); QCC_DbgPrintf(("UDPTransport::AcceptCb(): giving pre-auth list lock")); m_preListLock.Unlock(MUTEX_CONTEXT); /* * If we do something that is going to bug the ARDP protocol, we need to * call back into ARDP ASAP to get it moving. This is done in the main * thread, which we need to wake up. Since this is an accept it will * eventually require endpoint management, so we make a note to run the * endpoint management code. */ m_manage = STATE_MANAGE; Alert(); DecrementAndFetch(&m_refCount); return true; } #ifndef NDEBUG void UDPTransport::DebugAuthListCheck(UDPEndpoint uep) { QCC_DbgTrace(("UDPTransport::DebugAuthListCheck()")); m_endpointListLock.Lock(MUTEX_CONTEXT); for (set<UDPEndpoint>::iterator i = m_authList.begin(); i != m_authList.end(); ++i) { UDPEndpoint ep = *i; if (uep->GetConnId() == ep->GetConnId()) { QCC_DbgPrintf(("UDPTransport::DebugAuthListCheck(): Endpoint with conn ID == %d. already on m_authList", uep->GetConnId())); assert(0 && "UDPTransport::DebugAuthListCheck(): Endpoint already on m_authList"); } } m_endpointListLock.Unlock(MUTEX_CONTEXT); } void UDPTransport::DebugEndpointListCheck(UDPEndpoint uep) { QCC_DbgTrace(("UDPTransport::DebugEndpointListCheck()")); m_endpointListLock.Lock(MUTEX_CONTEXT); for (set<UDPEndpoint>::iterator i = m_endpointList.begin(); i != m_endpointList.end(); ++i) { UDPEndpoint ep = *i; if (uep->GetConnId() == ep->GetConnId()) { QCC_DbgPrintf(("UDPTransport::DebugEndpointListCheck(): Endpoint with conn ID == %d. already on m_endpointList", uep->GetConnId())); assert(0 && "UDPTransport::DebugAuthListCheck(): Endpoint already on m_endpointList"); } } m_endpointListLock.Unlock(MUTEX_CONTEXT); } #endif /* * See the note on connection establishment in the start of this file to make * sense of this. * * If passive is true, and status = ER_OK, this callback indicates that we are * getting the final callback as a result of the ARDP_Acknowledge which drove * the ACK back from the active opener as the final part of the three-way * handshake. We should see a BusHello reply from the active side to our * passive Hello in the data provided. * * If passive is false, and status = ER_OK, this callback indicates that the * passive side has accepted the connection and has returned the SYN + ACK. We * should see a BusHello message and a BusHello reply from the passive side in * the data provided. * * If status != ER_OK, the status should be ER_TIMEOUT indicating that for some * reason the three-way handshake did not complete in the expected time/retries. */ void UDPTransport::DoConnectCb(ArdpHandle* handle, ArdpConnRecord* conn, bool passive, uint8_t* buf, uint16_t len, QStatus status) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::DoConnectCb(handle=%p, conn=%p)", handle, conn)); /* * We are in DoConnectCb() which is always run off of the dispatcher thread. * If we are going to take the preListLock and munge the preList we * absolutely, positively must not try to take ardpLock with preListLock * taken or we risk deadlock. In AcceptCb() which did have ardpLock taken, * we put any endpoints starting the authentication process on the * m_preList, so we have to move those to the m_authList where they are * really expected to be from now on. ManageEndpoints touches both lists * using the lock order endpointList, preList; so we must do the same. */ QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Taking endpoint list lock")); m_endpointListLock.Lock(MUTEX_CONTEXT); QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Taking pre-auth list lock")); m_preListLock.Lock(MUTEX_CONTEXT); set<UDPEndpoint>::iterator i = m_preList.begin(); while (i != m_preList.end()) { QCC_DbgPrintf(("UDPTransport::ManageEndpoints(): Moving endpoint from m_preList to m_authList")); UDPEndpoint ep = *i; m_authList.insert(ep); m_preList.erase(i); i = m_preList.begin(); } QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Giving pre-auth list lock")); m_preListLock.Unlock(MUTEX_CONTEXT); QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Giving endpoint list lock")); m_endpointListLock.Unlock(MUTEX_CONTEXT); /* * Useful to have laying around for debug prints */ #ifndef NDEBUG uint32_t connId = ARDP_GetConnId(handle, conn); #endif if (passive) { /* * On the passive side, when we get a ConnectCb, we're done with the * three-way handshake if no error is returned. This marks the end of * the connection establishment phase and after we return, we should * expect AllJoyn messages to be flowing on the connection. * * If this is happening, we should have a UDPEndpoint on the m_authList * that reflects the ARDP connection that is in the process of being * formed. We need to find that endpoint (based on the provided conn), * take it off of the m_authlist and put it on the active enpoint list. * * If an error has been returned, we are getting the one notification * that the connection has failed. We nedd to find the endpoint that * has failed, so the error case looks pretty much like the success * case except for the final disposition. */ QCC_DbgPrintf(("UDPTransport::DoConnectCb(): passive connection callback with conn ID == %d.", connId)); QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Finding endpoint with conn ID == %d. in m_authList", connId)); QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Taking endpoint list lock")); m_endpointListLock.Lock(MUTEX_CONTEXT); bool haveLock = true; set<UDPEndpoint>::iterator i; for (i = m_authList.begin(); i != m_authList.end(); ++i) { UDPEndpoint ep = *i; if (ep->GetConn() == conn && ARDP_GetConnId(m_handle, ep->GetConn()) == ARDP_GetConnId(m_handle, conn)) { QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Moving endpoint with conn ID == %d to m_endpointList", connId)); m_authList.erase(i); DecrementAndFetch(&m_currAuth); #ifndef NDEBUG DebugEndpointListCheck(ep); #endif m_endpointList.insert(ep); IncrementAndFetch(&m_currConn); QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Start()ing endpoint with conn ID == %d.", connId)); /* * Cannot call out with the endpoint list lock taken. */ QCC_DbgPrintf(("UDPTransport::DoConnectCb(): giving endpoint list lock")); /* * If the inbound connection succeeded, we need to tell the daemon * that a new connection is ready to go. If the connection failed * we need to mark the connection for deletion and bug the endpoint * management code so it can purge the endpoint without delay. */ if (status == ER_OK) { m_endpointListLock.Unlock(MUTEX_CONTEXT); haveLock = false; ep->SetListener(this); ep->Start(); } else { ArdpStream* stream = ep->GetStream(); assert(stream && "UDPTransport::DoConnectCb(): must have a stream at this point"); stream->Disconnect(false, ER_UDP_LOCAL_DISCONNECT); ep->Stop(); m_endpointListLock.Unlock(MUTEX_CONTEXT); haveLock = false; ARDP_ReleaseConnection(handle, conn); m_manage = UDPTransport::STATE_MANAGE; Alert(); } break; } } /* * If we didn't find the endpoint for the connection, we still have the * lock taken. */ if (haveLock) { QCC_DbgPrintf(("UDPTransport::DoConnectCb(): giving endpoint list lock")); m_endpointListLock.Unlock(MUTEX_CONTEXT); } DecrementAndFetch(&m_refCount); return; } else { /* * On the active side, we expect to be getting this callback when the * passive side does a SYN + ACK and provides a reply to our Hello * message that we sent in ARDP_Connect(). * * Since this is an active connection, we expect there to be a thread * driving the connection and it will be waiting for something to happen * good or bad so we need to remember to wake it up. * * An event used to wake the thread up is provided in the connection, * but we also need to make sure that the thread hasn't timed out or * been stopped for some other reason, in which case the event will not * be valid. */ QCC_DbgPrintf(("UDPTransport::DoConnectCb(): active connection callback with conn ID == %d.", connId)); qcc::Event* event = static_cast<qcc::Event*>(ARDP_GetConnContext(m_handle, conn)); assert(event && "UDPTransport::DoConnectCb(): Connection context did not provide an event"); /* * Is there still a thread with an event on its stack waiting for us * here? If there is, we need to bug it. If the thread is gone, we go * there is no point in going though the motions, and creating an * endpoint we would just have to fail. */ QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Taking endpoint list lock")); m_endpointListLock.Lock(MUTEX_CONTEXT); bool eventValid = false; for (set<ConnectEntry>::iterator j = m_connectThreads.begin(); j != m_connectThreads.end(); ++j) { if (j->m_conn == conn && j->m_connId == ARDP_GetConnId(m_handle, conn)) { assert(j->m_event == event && "UDPTransport::DoConnectCb(): event != j->m_event"); eventValid = true; break; } } /* * There is no thread waiting for the connect to complete. It must be * gone if it has removed its ConnectEntry. It must have done so with * the endpoint list lock taken, so we know it is there if this test * passes; and we know it is not there if it does not. */ if (eventValid == false) { QCC_LogError(status, ("UDPTransport::DoConnectCb(): No thread waiting for Connect() to complete")); m_endpointListLock.Unlock(MUTEX_CONTEXT); ARDP_ReleaseConnection(handle, conn); DecrementAndFetch(&m_refCount); return; } /* * If the connection failed, wake up the thread waiting for completion * without creating an endpoint for it. */ if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::DoConnectCb(): Connect error")); event->SetEvent(); m_endpointListLock.Unlock(MUTEX_CONTEXT); ARDP_ReleaseConnection(handle, conn); DecrementAndFetch(&m_refCount); return; } /* * If we cannot find a BusHello, wake up the thread waiting for * completion without creating an endpoint for it. */ if (buf == NULL || len == 0) { QCC_LogError(ER_UDP_INVALID, ("UDPTransport::DoConnectCb(): No BusHello reply with SYN + ACK")); event->SetEvent(); m_endpointListLock.Unlock(MUTEX_CONTEXT); ARDP_ReleaseConnection(handle, conn); DecrementAndFetch(&m_refCount); return; } /* * Load the bytes from the BusHello reply into a Message. */ Message helloReply(m_bus); status = helloReply->LoadBytes(buf, len); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::DoConnectCb(): Can't Unmarhsal() BusHello Reply Message")); event->SetEvent(); m_endpointListLock.Unlock(MUTEX_CONTEXT); ARDP_ReleaseConnection(handle, conn); DecrementAndFetch(&m_refCount); return; } /* * The dispatcher thread allocated a copy of the buffer from ARDP since * ARDP expected its buffer back, so we need to delete this copy. */ #ifndef NDEBUG CheckSeal(buf + len); #endif delete[] buf; buf = NULL; len = 0; /* * Unmarshal the message. We need to provide and endpoint unique name * for error reporting purposes, in order to to affix blame here if * something goes awry. If we don't pass true in checkSender Unmarshal * won't validate the endpoint name and will just print it out in case * of problems. We make (an illegal) one up since we don't have an * endpoint yet. */ qcc::String endpointName(":0.0"); status = helloReply->Unmarshal(endpointName, false, false, true, 0); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::DoConnectCb(): Can't Unmarhsal() BusHello Message")); event->SetEvent(); m_endpointListLock.Unlock(MUTEX_CONTEXT); ARDP_ReleaseConnection(handle, conn); DecrementAndFetch(&m_refCount); return; } /* * Validate the fields in the incoming BusHello Reply Message */ if (helloReply->GetType() != MESSAGE_METHOD_RET) { status = ER_BUS_ESTABLISH_FAILED; QCC_LogError(status, ("UDPTransport::DoConnectCb(): Response was not a reply Message")); event->SetEvent(); m_endpointListLock.Unlock(MUTEX_CONTEXT); ARDP_ReleaseConnection(handle, conn); DecrementAndFetch(&m_refCount); return; } /* * The remote name is the sender of the BusHello reply message, * presumably the local bus attachment of the remote daemon doing * the implied Accept() */ qcc::String remoteName = helloReply->GetSender(); QCC_DbgPrintf(("UDPTransport::DoConnectCb(): BusHello reply from sender=\"%s\"", remoteName.c_str())); status = helloReply->UnmarshalArgs("ssu"); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::DoConnectCb(): Can't UnmarhsalArgs() BusHello Reply Message")); event->SetEvent(); m_endpointListLock.Unlock(MUTEX_CONTEXT); ARDP_ReleaseConnection(handle, conn); DecrementAndFetch(&m_refCount); return; } /* * We expect three arguments in the message: the unique name of the * remote side, the remoteGUID and a protocol version. The high order two bits of the protocol version are the * nameTransfer bits that will tell the allJoyn obj how many names to * exchange during ExchangeNames. */ size_t numArgs; const MsgArg* args; helloReply->GetArgs(numArgs, args); if (numArgs != 3 || args[0].typeId != ALLJOYN_STRING || args[1].typeId != ALLJOYN_STRING || args[2].typeId != ALLJOYN_UINT32) { status = ER_BUS_ESTABLISH_FAILED; QCC_LogError(status, ("UDPTransport::DoConnectCb(): Unexpected number or type of arguments in BusHello Reply Message")); event->SetEvent(); m_endpointListLock.Unlock(MUTEX_CONTEXT); ARDP_ReleaseConnection(handle, conn); DecrementAndFetch(&m_refCount); return; } qcc::String uniqueName = args[0].v_string.str; qcc::String remoteGUID = args[1].v_string.str; uint32_t protocolVersion = args[2].v_uint32 & 0x3FFFFFFF; uint32_t nameTransfer = args[1].v_uint32 >> 30; QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Got BusHello() reply. uniqueName=\"%s\", remoteGuid=\"%s\", protocolVersion=%d., nameTransfer=%d.", uniqueName.c_str(), remoteGUID.c_str(), protocolVersion, nameTransfer)); /* * We have everything we need to start up, so it is now time to create * our new endpoint. */ qcc::IPAddress ipAddr = ARDP_GetIpAddrFromConn(handle, conn); uint16_t ipPort = ARDP_GetIpPortFromConn(handle, conn); static const bool truthiness = true; UDPTransport* ptr = this; String normSpec = "udp:guid=" + remoteGUID + ",u4addr=" + ipAddr.ToString() + ",u4port=" + U32ToString(ipPort); UDPEndpoint udpEp(ptr, m_bus, truthiness, normSpec); /* * Some of this would "normally" be handled by EndpointAuth, but since we * are short-circuiting the process, we have to do the bookkeeping * ourselves. */ udpEp->GetFeatures().isBusToBus = true; udpEp->GetFeatures().allowRemote = true; udpEp->GetFeatures().protocolVersion = protocolVersion; udpEp->GetFeatures().trusted = false; udpEp->GetFeatures().nameTransfer = static_cast<SessionOpts::NameTransferType>(nameTransfer); udpEp->SetRemoteGUID(remoteGUID); udpEp->SetActive(); udpEp->SetIpAddr(ipAddr); udpEp->SetIpPort(ipPort); udpEp->CreateStream(handle, conn, m_ardpConfig.dataTimeout, m_ardpConfig.dataRetries); udpEp->SetHandle(handle); udpEp->SetConn(conn); /* * The unique name of the endpoint on the active side of the connection is * the unique name generated on the passive side. */ udpEp->SetUniqueName(uniqueName); /* * The remote name of the endpoint on the active side of the connection * is the sender of the BusHello reply message, which is presumably the * local bus attachement on the remote side. */ udpEp->SetRemoteName(remoteName); /* * From our perspective as the active opener of the connection, we are * done. */ QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Adding endpoint with conn ID == %d. to m_endpointList", connId)); #ifndef NDEBUG DebugEndpointListCheck(udpEp); #endif m_endpointList.insert(udpEp); IncrementAndFetch(&m_currConn); /* * We cannot call out to the daemon (which Start() will do) with the * endpointListLock taken. This means that we will have to re-verify * that the thread originally attempting the connect is still there when * we come back. If it is going, we need to arrange to undo the * following work, but that's the way the threading-cookie crumbles. */ QCC_DbgPrintf(("UDPTransport::DoConnectCb(): giving endpoint list lock")); m_endpointListLock.Unlock(MUTEX_CONTEXT); /* * We now have a UDPEndpoint that needs to be Start()ed and put on the * active endpint list and hooked up to the demux so it can receive * inbound data. It needs to be Start()ed not because there are threads * that need to be started, but that is where we register our endpoint * with the router, and that is what will start the ExchangeNames * process. */ QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Start()ing endpoint with conn ID == %d.", connId)); udpEp->SetListener(this); udpEp->Start(); /* * There is a thread waiting for this process to finish, so we need to * wake it up. The moment we gave up the m_endpointListLock, though, * the endpoint management thread can decide to tear down the endpoint * and invalidate all of our work. That means that the event can * be torn down out from underneath us. So we have got to make sure * that the endpoint is still there in order to ensure the event is * still valid. */ QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Taking endpoint list lock")); m_endpointListLock.Lock(MUTEX_CONTEXT); /* * We know the endpoint is still there since we hold a managed object * reference to it. What might be missing is the thread that started * this whole long and involved process. */ eventValid = false; for (set<ConnectEntry>::iterator j = m_connectThreads.begin(); j != m_connectThreads.end(); ++j) { if (j->m_conn == conn && j->m_connId == ARDP_GetConnId(m_handle, conn)) { assert(j->m_event == event && "UDPTransport::DoConnectCb(): event != j->m_event"); eventValid = true; break; } } /* * We're all done cranking up the endpoint. If there's someone waiting, * wake them up. If there's nobody there, stop the endpoint since * someone changed their mind. */ if (eventValid) { QCC_DbgPrintf(("UDPTransport::DoConnectCb(): Waking thread waiting for endpoint")); event->SetEvent(); } else { QCC_DbgPrintf(("UDPTransport::DoConnectCb(): No thread waiting for endpoint")); udpEp->Stop(); } QCC_DbgPrintf(("UDPTransport::DoConnectCb(): giving endpoint list lock")); m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return; } } /* * This is method that is called in order to begin the process of detaching from * the router. We dispatch the call to another thread since we absolutely do * not want to hold any locks when we call out to the daemon. */ void UDPTransport::ExitEndpoint(uint32_t connId) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::ExitEndpoint(connId=%d.)", connId)); /* * If m_dispatcher is NULL, it means we are shutting down and the dispatcher * has gone away before the endpoint management thread has actually stopped * running. This is rare, but possible. */ if (m_dispatcher == NULL) { QCC_DbgPrintf(("UDPTransport::ExitEndpoint(): m_dispatcher is NULL")); DecrementAndFetch(&m_refCount); return; } UDPTransport::WorkerCommandQueueEntry entry; entry.m_command = UDPTransport::WorkerCommandQueueEntry::EXIT; entry.m_connId = connId; QCC_DbgPrintf(("UDPTransport::ExitEndpoint(): sending EXIT request to dispatcher")); m_workerCommandQueueLock.Lock(MUTEX_CONTEXT); m_workerCommandQueue.push(entry); m_workerCommandQueueLock.Unlock(MUTEX_CONTEXT); m_dispatcher->Alert(); DecrementAndFetch(&m_refCount); } /* * This is the indication from the ARDP protocol that a connection is in the * process of being formed. We want to spend as little time as possible here * (and avoid deadlocks as much as possible here) so we just immediately ask the * transport dispatcher to do something with this message and return. This case * is unlike the others because there may not be an endpoint to demux to yet. */ void UDPTransport::ConnectCb(ArdpHandle* handle, ArdpConnRecord* conn, bool passive, uint8_t* buf, uint16_t len, QStatus status) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::ConnectCb(handle=%p, conn=%p, passive=%d., buf=%p, len=%d., status=\"%s\")", handle, conn, passive, buf, len, QCC_StatusText(status))); /* * If m_dispatcher is NULL, it means we are shutting down and the dispatcher * has gone away before the endpoint management thread has actually stopped * running. This is rare, but possible. */ if (m_dispatcher == NULL) { QCC_DbgPrintf(("UDPTransport::ConnectCb(): m_dispatcher is NULL")); DecrementAndFetch(&m_refCount); return; } UDPTransport::WorkerCommandQueueEntry entry; entry.m_command = UDPTransport::WorkerCommandQueueEntry::CONNECT_CB; entry.m_handle = handle; entry.m_conn = conn; entry.m_connId = ARDP_GetConnId(handle, conn); entry.m_passive = passive; #ifndef NDEBUG entry.m_buf = new uint8_t[len + SEAL_SIZE]; SealBuffer(entry.m_buf + len); #else entry.m_buf = new uint8_t[len]; #endif entry.m_len = len; memcpy(entry.m_buf, buf, len); entry.m_status = status; QCC_DbgPrintf(("UDPTransport::ConnectCb(): sending CONNECT_CB request to dispatcher)")); m_workerCommandQueueLock.Lock(MUTEX_CONTEXT); m_workerCommandQueue.push(entry); m_workerCommandQueueLock.Unlock(MUTEX_CONTEXT); m_dispatcher->Alert(); DecrementAndFetch(&m_refCount); } /* * This is the indication from the ARDP protocol that a connection has been * disconnected. We want to spend as little time as possible here (and avoid * deadlocks as much as possible here) so we just immediately ask the transport * dispatcher to do something with this message and return. */ void UDPTransport::DisconnectCb(ArdpHandle* handle, ArdpConnRecord* conn, QStatus status) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::DisconnectCb(handle=%p, conn=%p, foreign=%d.)", handle, conn)); /* * If m_dispatcher is NULL, it means we are shutting down and the dispatcher * has gone away before the endpoint management thread has actually stopped * running. This is rare, but possible. */ if (m_dispatcher == NULL) { QCC_DbgPrintf(("UDPTransport::DisconnectCb(): m_dispatcher is NULL")); DecrementAndFetch(&m_refCount); return; } UDPTransport::WorkerCommandQueueEntry entry; entry.m_command = UDPTransport::WorkerCommandQueueEntry::DISCONNECT_CB; entry.m_handle = handle; entry.m_conn = conn; entry.m_connId = ARDP_GetConnId(handle, conn); entry.m_status = status; QCC_DbgPrintf(("UDPTransport::DisconnectCb(): sending DISCONNECT_CB request to dispatcher)")); m_workerCommandQueueLock.Lock(MUTEX_CONTEXT); m_workerCommandQueue.push(entry); m_workerCommandQueueLock.Unlock(MUTEX_CONTEXT); m_dispatcher->Alert(); DecrementAndFetch(&m_refCount); } /* * This is the indication from the ARDP protocol that we have received bytes. * We want to spend as little time as possible here (and avoid deadlocks as much * as possible here) so we just immediately ask the transport dispatcher to do * something with this message and return. The dispatcher will figure out which * endpoint this callback is destined for and demultiplex it accordingly. */ void UDPTransport::RecvCb(ArdpHandle* handle, ArdpConnRecord* conn, ArdpRcvBuf* rcv, QStatus status) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::RecvCb(handle=%p, conn=%p, rcv=%p, status=%s)", handle, conn, rcv, QCC_StatusText(status))); /* * If m_dispatcher is NULL, it means we are shutting down and the dispatcher * has gone away before the endpoint management thread has actually stopped * running. This is rare, but possible. */ if (m_dispatcher == NULL) { QCC_DbgPrintf(("UDPTransport::RecvCb(): m_dispatcher is NULL")); QCC_DbgPrintf(("UDPTransport::RecvCb(): ARDP_RecvReady()")); m_ardpLock.Lock(); ARDP_RecvReady(handle, conn, rcv); m_ardpLock.Unlock(); DecrementAndFetch(&m_refCount); return; } UDPTransport::WorkerCommandQueueEntry entry; entry.m_command = UDPTransport::WorkerCommandQueueEntry::RECV_CB; entry.m_handle = handle; entry.m_conn = conn; entry.m_connId = ARDP_GetConnId(handle, conn); entry.m_rcv = rcv; entry.m_status = status; QCC_DbgPrintf(("UDPTransport::RecvCb(): sending RECV_CB request to dispatcher)")); m_workerCommandQueueLock.Lock(MUTEX_CONTEXT); m_workerCommandQueue.push(entry); m_workerCommandQueueLock.Unlock(MUTEX_CONTEXT); m_dispatcher->Alert(); DecrementAndFetch(&m_refCount); } /* * This is the indication from the ARDP protocol that we have (usually) * successfully sent bytes. We want to spend as little time as possible here * (and avoid deadlocks as much as possible here) so we just immediately ask the * transport dispatcher to do something with this message and return. The * dispatcher will figure out which endpoint this callback is destined for and * demultiplex it accordingly. */ void UDPTransport::SendCb(ArdpHandle* handle, ArdpConnRecord* conn, uint8_t* buf, uint32_t len, QStatus status) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::SendCb(handle=%p, conn=%p, buf=%p, len=%d.)", handle, conn, buf, len)); /* * If m_dispatcher is NULL, it means we are shutting down and the dispatcher * has gone away before the endpoint management thread has actually stopped * running. This is rare, but possible. */ if (m_dispatcher == NULL) { QCC_DbgPrintf(("UDPTransport::SendCb(): m_dispatcher is NULL")); DecrementAndFetch(&m_refCount); return; } UDPTransport::WorkerCommandQueueEntry entry; entry.m_command = UDPTransport::WorkerCommandQueueEntry::SEND_CB; entry.m_handle = handle; entry.m_conn = conn; entry.m_connId = ARDP_GetConnId(handle, conn); entry.m_buf = buf; entry.m_len = len; entry.m_status = status; QCC_DbgPrintf(("UDPTransport::SendCb(): sending SEND_CB request to dispatcher)")); m_workerCommandQueueLock.Lock(MUTEX_CONTEXT); m_workerCommandQueue.push(entry); m_workerCommandQueueLock.Unlock(MUTEX_CONTEXT); m_dispatcher->Alert(); DecrementAndFetch(&m_refCount); } /** * This is an indication from the ARDP Procotol that the send window has changed. */ void UDPTransport::SendWindowCb(ArdpHandle* handle, ArdpConnRecord* conn, uint16_t window, QStatus status) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::SendWindowCb(handle=%p, conn=%p, window=%d.)", handle, conn, window)); QCC_DbgPrintf(("UDPTransport::SendWindowCb(): callback from conn ID == %d", ARDP_GetConnId(handle, conn))); DecrementAndFetch(&m_refCount); } /** * This is the run method of the main loop of the UDP Transport maintenance * thread -- the center of the UDP Transport universe. */ void* UDPTransport::Run(void* arg) { QCC_DbgTrace(("UDPTransport::Run()")); /* * We did an Acquire on the name service in our Start() method which * ultimately caused this thread to run. If we were the first transport * to Acquire() the name service, it will have done a Start() to crank * up its own run thread. Just because we did that Start() before we * did our Start(), it does not necessarily mean that thread will come * up and run before us. If we happen to come up before our name service * we'll hang around until it starts to run. After all, nobody is going * to attempt to connect until we advertise something, and we need the * name service to advertise. */ while (IpNameService::Instance().Started() == false) { QCC_DbgPrintf(("UDPTransport::Run(): Wait for IP name service")); qcc::Sleep(10); } /* * Events driving the main loop execution below. Always listen for the * (thread) stop event firing. Create a timer event that the ARDP protocol * will borrow for its timers -- it never pops unless ARDP says to, so it * starts waiting forever. */ vector<Event*> checkEvents, signaledEvents; qcc::Event ardpTimerEvent(qcc::Event::WAIT_FOREVER, 0); qcc::Event maintenanceTimerEvent(qcc::Event::WAIT_FOREVER, 0); checkEvents.push_back(&stopEvent); checkEvents.push_back(&ardpTimerEvent); checkEvents.push_back(&maintenanceTimerEvent); Timespec tLastManage; GetTimeNow(&tLastManage); QStatus status = ER_OK; /* * The purpose of this thread is to (1) manage all of our endpoints going * through the various states they do; (2) watch for the various sockets * corresponding to endpoints on sundry networks for becoming ready; and * (3) drive/whip the ARDP protocol to do our bidding. */ while (!IsStopping()) { /* * Each time through the loop we need to wait on the stop event and all * of the SocketFds of the addresses and ports we are listening on. We * expect the list of FDs to change rarely, so we want to spend most of * our time just driving the ARDP protocol and moving bits. We only * redo the list if we notice the state changed from STATE_RELOADED. * * Instead of trying to figure out the delta, we just restart the whole * shebang. */ m_listenFdsLock.Lock(MUTEX_CONTEXT); if (m_reload != STATE_RELOADED) { QCC_DbgPrintf(("UDPTransport::Run(): Not STATE_RELOADED. Deleting events")); for (vector<Event*>::iterator i = checkEvents.begin(); i != checkEvents.end(); ++i) { if (*i != &stopEvent && *i != &ardpTimerEvent && *i != &maintenanceTimerEvent) { delete *i; } } checkEvents.clear(); QCC_DbgPrintf(("UDPTransport::Run(): Not STATE_RELOADED. Creating events")); checkEvents.push_back(&stopEvent); checkEvents.push_back(&ardpTimerEvent); checkEvents.push_back(&maintenanceTimerEvent); QCC_DbgPrintf(("UDPTransport::Run(): Not STATE_RELOADED. Creating socket events")); for (list<pair<qcc::String, SocketFd> >::const_iterator i = m_listenFds.begin(); i != m_listenFds.end(); ++i) { QCC_DbgPrintf(("UDPTransport::Run(): Not STATE_RELOADED. Creating event for socket %d", i->second)); checkEvents.push_back(new Event(i->second, Event::IO_READ, false)); } m_reload = STATE_RELOADED; } m_listenFdsLock.Unlock(MUTEX_CONTEXT); /* * In order to rationalize management of resources, we manage the * various lists in one place on one thread. This isn't super-expensive * but can add up if there are lots of endpoings, so We don't want to do * this resource management exercise every time throught the socket read * loop, so limit the number of times it will be called. */ Timespec tNow; GetTimeNow(&tNow); int32_t tRemaining = tLastManage + UDP_ENDPOINT_MANAGEMENT_TIMER - tNow; if (m_manage != STATE_MANAGED || tRemaining < 0) { /* * Set m_manage to STATE_MANAGED before calling ManageEndpoints to * allow ManageEndpoints the possibility of causing itself to run * again immediately. */ m_manage = STATE_MANAGED; ManageEndpoints(m_authTimeout, m_sessionSetupTimeout); tLastManage = tNow; uint32_t tManage = UDP_ENDPOINT_MANAGEMENT_TIMER; maintenanceTimerEvent.ResetTime(tManage, 0); } /* * We have our list of events, so now wait for something to happen on * that list. The number of events in checkEvents should be 3 + the * number of sockets listened (stopEvent, ardpTimerEvent, maintenanceTimerEvent and sockets). */ signaledEvents.clear(); status = Event::Wait(checkEvents, signaledEvents); if (status == ER_TIMEOUT) { // QCC_LogError(status, ("UDPTransport::Run(): Catching Windows returning ER_TIMEOUT from Event::Wait()")); continue; } if (ER_OK != status) { QCC_LogError(status, ("UDPTransport::Run(): Event::Wait failed")); break; } /* * We're back from our Wait() so one of four things has happened. Our * thread has been asked to Stop(), our thread has been Alert()ed, our * timer has expired, or one of the socketFds we are listening on has * becomed signalled. * * If we have been asked to Stop(), or our thread has been Alert()ed, * the stopEvent will be on the list of signalled events. The way we * tell the difference is by looking at IsStopping() which we do up at * the top of the loop. In either case, we need to deal with managing * the endpoints. */ for (vector<Event*>::iterator i = signaledEvents.begin(); i != signaledEvents.end(); ++i) { /* * Reset stop and timer events since we've heard them. */ if (*i == &stopEvent) { stopEvent.ResetEvent(); } else if (*i == &maintenanceTimerEvent) { maintenanceTimerEvent.ResetEvent(); } else if (*i == &ardpTimerEvent) { ardpTimerEvent.ResetEvent(); } /* * Determine if this was a socket event (the socket became ready) or * if it was a timer event. If we are calling ARDP because * something new came in, let it know by setting a flag. * * TODO: If we are passing the socket FD in every time, * why do we have it stashed in the handle or conn? */ bool socketReady = (*i != &ardpTimerEvent && *i != &maintenanceTimerEvent && *i != &stopEvent); uint32_t ms; m_ardpLock.Lock(); ARDP_Run(m_handle, socketReady ? (*i)->GetFD() : -1, socketReady, &ms); m_ardpLock.Unlock(); /* * Every time we call ARDP_Run(), it lets us know when its next * timer will expire, so we tell our event to set itself in that * number of milliseconds so we can call back then. If it doesn't * have anything to do it returns -1 (WAIT_FOREVER). Just because * it doesn't know about something happening doesn't mean something * will not happen on this side. We need to bug this thread (send * an Alert() to wake us up) if we do anything that may require * deferred action. Since we don't know what that might be, it * means we need to do the Alert() whenever we call into ARDP and * do something we expect to require a retransmission or callback. */ ardpTimerEvent.ResetTime(ms, 0); } } /* * Don't leak events when stopping. */ for (vector<Event*>::iterator i = checkEvents.begin(); i != checkEvents.end(); ++i) { if (*i != &stopEvent && *i != &ardpTimerEvent && *i != &maintenanceTimerEvent) { delete *i; } } /* * If we're stopping, it is our responsibility to clean up the list of FDs * we are listening to. Since at this point we've Stop()ped and Join()ed * the protocol handlers, all we have to do is to close them down. * * Set m_reload to STATE_EXITED to indicate that the UDPTransport::Run * thread has exited. */ m_listenFdsLock.Lock(MUTEX_CONTEXT); for (list<pair<qcc::String, SocketFd> >::iterator i = m_listenFds.begin(); i != m_listenFds.end(); ++i) { qcc::Close(i->second); } m_listenFds.clear(); m_reload = STATE_EXITED; m_listenFdsLock.Unlock(MUTEX_CONTEXT); QCC_DbgPrintf(("UDPTransport::Run is exiting status=%s", QCC_StatusText(status))); return (void*) status; } /* * The purpose of this code is really to ensure that we don't have any listeners * active on Android systems if we have no ongoing advertisements. This is to * satisfy a requirement driven from the Android Compatibility Test Suite (CTS) * which fails systems that have processes listening for UDP connections when * the test is run. * * Listeners and advertisements are interrelated. In order to Advertise a * service, the name service must have an endpoint to include in its * advertisements; and there must be at least one listener running and ready to * receive connections before telling the name service to advertise. * * Discovery requests do not require listeners be present per se before being * forwarded to the name service. A discovery request will ulitmately lead to a * bus-to-bus connection once a remote daemon has been discovered; but the local * side will always start the connection. Sessions throw a bit of a monkey * wrench in the works, though. Since a JoinSession request is sent to the * (already connected) remote daemon and it decides what to do, we don't want to * arbitrarily constrain the remote daemon by disallowing it to try and connect * back to the local daemon. For this reason, we do require listeners to be * present before discovery starts. * * So the goal is to not have active listeners in the system unless there are * outstanding advertisements or discovery requests, but we cannot have * outstanding advertisements or discovery requests until there are active * listeners. Some care is obviously required here to accomplish this * seemingly inconsistent behavior. * * We call the state of no outstanding advertisements and not outstanding * discovery requests "Name Service Quiescent". In this case, the name service * must be disabled so that it doesn't interact with the network and cause a CTS * failure. As soon as a either a discovery request or an advertisement request * is started, we need to enable the name service to recieve and send network * packets, which will cause the daemon process to begin listening on the name * service well-known UDP port. * * Before an advertisement or a discovery request can acutally be sent over the * wire, we must start a listener which will receive connection requests, and * we must provide the name service with endpoint information that it can include * in its advertisement. So, from the name service and network perspective, * listens must preceed advertisements. * * In order to accomplish the CTS requirements, however, advertisements must * preceed listens. It turns out that this is how the high-level system wants * to work. Essentually, the system calls StartListen at the beginning of time * (when the daemon is first brought up) and it calls StopListen at the end of * time (when the daemon is going down). Advertisements and discovery requests * come and go in between as clients and services come up and go down. * * To deal with this time-inversion, we save a list of all listen requests, a * list of all advertisement requests and a list of all discovery requests. At * the beginning of time we get one or more StartListen calls and save the * listen specs, but do not actually do the socket operations to start the * corresponding socket-level listens. When the first advertisement or * discovery request comes in from the higher-level code, we first start all of * the saved listens and then enable the name service and ask it to start * advertising or discovering as appropriate. Further advertisements and * discovery requests are also saved, but the calls to the name service are * passed through when it is not quiescent. * * We keep track of the disable advertisement and discovery calls as well. Each * time an advertisement or discover operation is disabled, we remove the * corresponding entry in the associated list. As soon as all advertisements * and discovery operations are disabled, we disable the name service and remove * our UDP listeners, and therefore remove all listeners from the system. Since * we have a saved a list of listeners, they can be restarted if another * advertisement or discovery request comes in. * * We need to do all of this in one place (here) to make it easy to keep the * state of the transport (us) and the name service consistent. We are * basically a state machine handling the following transitions: * * START_LISTEN_INSTANCE: An instance of a StartListen() has happened so we * need to add the associated listen spec to our list of listeners and be * ready for a subsequent advertisement. We expect these to happen at the * beginning of time; but there is nothing preventing a StartListen after we * start advertising. In this case we need to execute the start listen. * * STOP_LISTEN_INSTANCE: An instance of a StopListen() has happened so we need * to remove the listen spec from our list of listeners. We expect these to * happen at the end of time; but there is nothing preventing a StopListen * at any other time. In this case we need to execute the stop listen and * remove the specified listener immediately * * ENABLE_ADVERTISEMENT_INSTANCE: An instance of an EnableAdvertisement() has * happened. If there are no other ongoing advertisements, we need to * enable the stored listeners, pass the endpoint information down to the * name servcie, enable the name service communication with the outside * world if it is disabled and finally pass the advertisement down to the * name service. If there are other ongoing advertisements we just pass * down the new advertisement. It is an AllJoyn system programming error to * start advertising before starting at least one listen. * * DISABLE_ADVERTISEMENT_INSTANCE: An instance of a DisableAdvertisement() * call has happened. We always want to pass the corresponding Cancel down * to the name service. If we decide that this is the last of our ongoing * advertisements, we need to continue and disable the name service from * talking to the outside world. For completeness, we remove endpoint * information from the name service. Finally, we shut down our UDP * transport listeners. * * ENABLE_DISCOVERY_INSTANCE: An instance of an EnableDiscovery() has * happened. This is a fundamentally different request than an enable * advertisement. We don't need any listeners to be present in order to do * discovery, but the name service must be enabled so it can send and * receive WHO-HAS packets. If the name service communications are * disabled, we need to enable them. In any case we pass the request down * to the name service. * * DISABLE_DISCOVERY_INSTANCE: An instance of a DisableDiscovery() call has * happened. There is no corresponding disable call in the name service, * but we do have to decide if we want to disable the name service to keep * it from listening. We do so if this is the last discovery instance and * there are no other advertisements. * * There are five member variables that reflect the state of the transport * and name service with respect to this code: * * m_isListening: The list of listeners is reflected by currently listening * sockets. We have network infrastructure in place to receive inbound * connection requests. * * m_isNsEnabled: The name service is up and running and listening on its * sockets for incoming requests. * * m_isAdvertising: We are advertising at least one well-known name either actively or quietly . * If we are m_isAdvertising then m_isNsEnabled must be true. * * m_isDiscovering: The list of discovery requests has been sent to the name * service. If we are m_isDiscovering then m_isNsEnabled must be true. */ void UDPTransport::RunListenMachine(ListenRequest& listenRequest) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::RunListenMachine()")); /* * Do some consistency checks to make sure we're not confused about what * is going on. * * First, if we are not listening, then we had better not think we're * advertising(actively or quietly) or discovering. If we are * not listening, then the name service must not be enabled and sending * or responding to external daemons. */ if (m_isListening == false) { assert(m_isAdvertising == false); assert(m_isDiscovering == false); assert(m_isNsEnabled == false); } /* * If we think the name service is enabled, it had better think it is * enabled. It must be enabled either because we are advertising * (actively or quietly) or we are discovering. If we are * advertising(actively or quietly) or discovering, then there * must be listeners waiting for connections as a result of those * advertisements or discovery requests. If there are listeners, then * there must be a non-zero listenPort. */ if (m_isNsEnabled) { assert(m_isAdvertising || m_isDiscovering); assert(m_isListening); assert(m_listenPort); } /* * If we think we are advertising, we'd better have an entry in * the advertisements list to advertise, and there must be * listeners waiting for inbound connections as a result of those * advertisements. If we are advertising the name service had * better be enabled. */ if (m_isAdvertising) { assert(!m_advertising.empty()); assert(m_isListening); assert(m_listenPort); assert(m_isNsEnabled); } /* * If we are discovering, we'd better have an entry in the discovering * list to make us discover, and there must be listeners waiting for * inbound connections as a result of session operations driven by those * discoveries. If we are discovering the name service had better be * enabled. */ if (m_isDiscovering) { assert(!m_discovering.empty()); assert(m_isListening); assert(m_listenPort); assert(m_isNsEnabled); } /* * Now that are sure we have a consistent view of the world, let's do * what needs to be done. */ switch (listenRequest.m_requestOp) { case START_LISTEN_INSTANCE: StartListenInstance(listenRequest); break; case STOP_LISTEN_INSTANCE: StopListenInstance(listenRequest); break; case ENABLE_ADVERTISEMENT_INSTANCE: EnableAdvertisementInstance(listenRequest); break; case DISABLE_ADVERTISEMENT_INSTANCE: DisableAdvertisementInstance(listenRequest); break; case ENABLE_DISCOVERY_INSTANCE: EnableDiscoveryInstance(listenRequest); break; case DISABLE_DISCOVERY_INSTANCE: DisableDiscoveryInstance(listenRequest); break; } DecrementAndFetch(&m_refCount); } void UDPTransport::StartListenInstance(ListenRequest& listenRequest) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::StartListenInstance()")); /* * We have a new StartListen request, so save the listen spec so we * can restart the listen if we stop advertising. */ NewListenOp(START_LISTEN, listenRequest.m_requestParam); /* * There is only one quiet advertisement that needs to be done * automagically, and this is the daemon router advertisement we do based on * configuration. So, we take a peek at this configuration item and if it * is set, we go ahead and execute the DoStartListen to crank up a listener. * We actually start the quiet advertisement there in DoStartListen, after * we have a valid listener to respond to remote requests. Note that we are * just driving the start listen, and there is no quiet advertisement yet so * the corresponding <m_isAdvertising> must not yet be set. */ ConfigDB* config = ConfigDB::GetConfigDB(); m_maxUntrustedClients = config->GetLimit("max_untrusted_clients", ALLJOYN_MAX_UNTRUSTED_CLIENTS_DEFAULT); #if ADVERTISE_ROUTER_OVER_UDP m_routerName = config->GetProperty("router_advertisement_prefix", ALLJOYN_DEFAULT_ROUTER_ADVERTISEMENT_PREFIX); #endif if (m_isAdvertising || m_isDiscovering || (!m_routerName.empty() && (m_numUntrustedClients < m_maxUntrustedClients))) { m_routerName.append(m_bus.GetInternal().GetGlobalGUID().ToShortString()); DoStartListen(listenRequest.m_requestParam); } DecrementAndFetch(&m_refCount); } void UDPTransport::StopListenInstance(ListenRequest& listenRequest) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::StopListenInstance()")); /* * We have a new StopListen request, so we need to remove this * particular listen spec from our lists so it will not be * restarted. */ bool empty = NewListenOp(STOP_LISTEN, listenRequest.m_requestParam); /* * If we have just removed the last listener, we have a problem if we have * advertisements. This is because we will be advertising soon to be * non-existent endpoints. The question is, what do we want to do about it. * We could just ignore it since since clients receiving advertisements may * just try to connect to a non-existent endpoint and fail. It does seem * better to log an error and then cancel any outstanding advertisements * since they are soon to be meaningless. */ if (empty && m_isAdvertising) { QCC_LogError(ER_UDP_NO_LISTENER, ("UDPTransport::StopListenInstance(): No listeners with outstanding advertisements")); for (list<qcc::String>::iterator i = m_advertising.begin(); i != m_advertising.end(); ++i) { IpNameService::Instance().CancelAdvertiseName(TRANSPORT_UDP, *i, TRANSPORT_UDP); } } /* * Execute the code that will actually tear down the specified * listening endpoint. Note that we always stop listening * immediately since that is Good (TM) from a power and CTS point of * view. We only delay starting to listen. */ DoStopListen(listenRequest.m_requestParam); DecrementAndFetch(&m_refCount); } void UDPTransport::EnableAdvertisementInstance(ListenRequest& listenRequest) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::EnableAdvertisementInstance()")); /* * We have a new advertisement request to deal with. The first * order of business is to save the well-known name away for * use later. */ bool isFirst; NewAdvertiseOp(ENABLE_ADVERTISEMENT, listenRequest.m_requestParam, isFirst); /* * If it turned out that is the first advertisement on our list, we * need to prepare before actually doing the advertisement. */ if (isFirst) { /* * If we don't have any listeners up and running, we need to get them * up. If this is a Windows box, the listeners will start running * immediately and will never go down, so they may already be running. */ if (!m_isListening) { for (list<qcc::String>::iterator i = m_listening.begin(); i != m_listening.end(); ++i) { QStatus status = DoStartListen(*i); if (ER_OK != status) { continue; } assert(m_listenPort); } } /* * We can only enable the requested advertisement if there is something * listening inbound connections on. Therefore, we should only enable * the name service if there is a listener. This catches the case where * there was no StartListen() done before the first advertisement. */ if (m_isListening) { if (!m_isNsEnabled) { IpNameService::Instance().Enable(TRANSPORT_UDP, 0, 0, m_listenPort, 0, true, false, false, false); m_isNsEnabled = true; } } } if (!m_isListening) { QCC_LogError(ER_UDP_NO_LISTENER, ("UDPTransport::EnableAdvertisementInstance(): Advertise with no UDP listeners")); return; } /* * We think we're ready to send the advertisement. Are we really? */ assert(m_isListening); assert(m_listenPort); assert(m_isNsEnabled); assert(IpNameService::Instance().Started() && "UDPTransport::EnableAdvertisementInstance(): IpNameService not started"); QStatus status = IpNameService::Instance().AdvertiseName(TRANSPORT_UDP, listenRequest.m_requestParam, listenRequest.m_requestParamOpt, listenRequest.m_requestTransportMask); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::EnableAdvertisementInstance(): Failed to advertise \"%s\"", listenRequest.m_requestParam.c_str())); } QCC_DbgPrintf(("UDPTransport::EnableAdvertisementInstance(): Done")); m_isAdvertising = true; DecrementAndFetch(&m_refCount); } void UDPTransport::DisableAdvertisementInstance(ListenRequest& listenRequest) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::DisableAdvertisementInstance()")); /* * We have a new disable advertisement request to deal with. The first * order of business is to remove the well-known name from our saved list. */ bool isFirst; bool isEmpty = NewAdvertiseOp(DISABLE_ADVERTISEMENT, listenRequest.m_requestParam, isFirst); /* * We always cancel any advertisement to allow the name service to * send out its lost advertisement message. */ QStatus status = IpNameService::Instance().CancelAdvertiseName(TRANSPORT_UDP, listenRequest.m_requestParam, listenRequest.m_requestTransportMask); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::DisableAdvertisementInstance(): Failed to Cancel \"%s\"", listenRequest.m_requestParam.c_str())); } /* * If it turns out that this was the last advertisement on our list, we need * to think about disabling our listeners and turning off the name service. * We only to this if there are no discovery instances in progress. */ if (isEmpty && !m_isDiscovering) { /* * Since the cancel advertised name has been sent, we can disable the * name service. We do this by telling it we don't want it to be * enabled on any of the possible ports. */ IpNameService::Instance().Enable(TRANSPORT_UDP, 0, 0, m_listenPort, 0, false, false, false, false); m_isNsEnabled = false; /* * If we had the name service running, we must have had listeners * waiting for connections due to the name service. We need to stop * them all now, but only if we are not running on a Windows box. * Windows needs the listeners running at all times since it uses * UDP for the client to daemon connections. */ for (list<qcc::String>::iterator i = m_listening.begin(); i != m_listening.end(); ++i) { DoStopListen(*i); } m_isListening = false; m_listenPort = 0; } if (isEmpty) { m_isAdvertising = false; } DecrementAndFetch(&m_refCount); } void UDPTransport::EnableDiscoveryInstance(ListenRequest& listenRequest) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::EnableDiscoveryInstance()")); /* * We have a new discovery request to deal with. The first * order of business is to save the well-known name away for * use later. */ bool isFirst; NewDiscoveryOp(ENABLE_DISCOVERY, listenRequest.m_requestParam, isFirst); /* * If it turned out that is the first discovery request on our list, we need * to prepare before actually doing the discovery. */ if (isFirst) { /* * If we don't have any listeners up and running, we need to get them * up. If this is a Windows box, the listeners will start running * immediately and will never go down, so they may already be running. */ if (!m_isListening) { for (list<qcc::String>::iterator i = m_listening.begin(); i != m_listening.end(); ++i) { QStatus status = DoStartListen(*i); if (ER_OK != status) { continue; } assert(m_listenPort); } } /* * We can only enable the requested advertisement if there is something * listening inbound connections on. Therefore, we should only enable * the name service if there is a listener. This catches the case where * there was no StartListen() done before the first discover. */ if (m_isListening) { if (!m_isNsEnabled) { IpNameService::Instance().Enable(TRANSPORT_UDP, 0, 0, m_listenPort, 0, true, false, false, false); m_isNsEnabled = true; } } } if (!m_isListening) { QCC_LogError(ER_UDP_NO_LISTENER, ("UDPTransport::EnableDiscoveryInstance(): Discover with no UDP listeners")); DecrementAndFetch(&m_refCount); return; } /* * We think we're ready to send the FindAdvertisement. Are we really? */ assert(m_isListening); assert(m_listenPort); assert(m_isNsEnabled); assert(IpNameService::Instance().Started() && "UDPTransport::EnableDiscoveryInstance(): IpNameService not started"); QStatus status = IpNameService::Instance().FindAdvertisement(TRANSPORT_UDP, listenRequest.m_requestParam, listenRequest.m_requestTransportMask); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::EnableDiscoveryInstance(): Failed to begin discovery with multicast NS \"%s\"", listenRequest.m_requestParam.c_str())); } m_isDiscovering = true; DecrementAndFetch(&m_refCount); } void UDPTransport::DisableDiscoveryInstance(ListenRequest& listenRequest) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::DisableDiscoveryInstance()")); /* * We have a new disable discovery request to deal with. The first * order of business is to remove the well-known name from our saved list. */ bool isFirst; bool isEmpty = NewDiscoveryOp(DISABLE_DISCOVERY, listenRequest.m_requestParam, isFirst); if (m_isListening && m_listenPort && m_isNsEnabled && IpNameService::Instance().Started()) { QStatus status = IpNameService::Instance().CancelFindAdvertisement(TRANSPORT_UDP, listenRequest.m_requestParam, listenRequest.m_requestTransportMask); if (status != ER_OK) { QCC_LogError(status, ("TCPTransport::DisableDiscoveryInstance(): Failed to cancel discovery with \"%s\"", listenRequest.m_requestParam.c_str())); } } /* * If it turns out that this was the last discovery operation on * our list, we need to think about disabling our listeners and turning off * the name service. We only to this if there are no advertisements in * progress. */ if (isEmpty && !m_isAdvertising) { IpNameService::Instance().Enable(TRANSPORT_UDP, 0, 0, m_listenPort, 0, false, false, false, false); m_isNsEnabled = false; /* * If we had the name service running, we must have had listeners * waiting for connections due to the name service. We need to stop * them all now, but only if we are not running on a Windows box. * Windows needs the listeners running at all times since it uses * UDP for the client to daemon connections. */ for (list<qcc::String>::iterator i = m_listening.begin(); i != m_listening.end(); ++i) { DoStopListen(*i); } m_isListening = false; m_listenPort = 0; } if (isEmpty) { m_isDiscovering = false; } DecrementAndFetch(&m_refCount); } /* * The default address for use in listen specs. INADDR_ANY means to listen * for UDP connections on any interfaces that are currently up or any that may * come up in the future. */ static const char* ADDR4_DEFAULT = "0.0.0.0"; /* * The default port for use in listen specs. */ static const uint16_t PORT_DEFAULT = 9955; QStatus UDPTransport::NormalizeListenSpec(const char* inSpec, qcc::String& outSpec, map<qcc::String, qcc::String>& argMap) const { qcc::String family; /* * We don't make any calls that require us to be in any particular state * with respect to threading so we don't bother to call IsRunning() here. * * Take the string in inSpec, which must start with "udp:" and parse it, * looking for comma-separated "key=value" pairs and initialize the * argMap with those pairs. * * There are lots of legal possibilities for an IP-based transport, but * all we are going to recognize is the "reliable IPv4 mechanism" and * so we will summarily pitch everything else. * * We expect to end up with a normalized outSpec that looks something * like: * * "udp:u4addr=0.0.0.0,u4port=9955" * * That's all. We still allow "addr=0.0.0.0,port=9955,family=ipv4" but * treat addr as synonomous with u4addr, port as synonomous with u4port and * ignore family. */ QStatus status = ParseArguments(GetTransportName(), inSpec, argMap); if (status != ER_OK) { return status; } map<qcc::String, qcc::String>::iterator iter; /* * We just ignore the family since ipv4 was the only possibld working choice. */ iter = argMap.find("family"); if (iter != argMap.end()) { argMap.erase(iter); } /* * Transports, by definition, may support reliable Ipv4, unreliable IPv4, * reliable IPv6 and unreliable IPv6 mechanisms to move bits. In this * incarnation, the UDP transport will only support unrreliable IPv4; so we * log errors and ignore any requests for other mechanisms. */ iter = argMap.find("r4addr"); if (iter != argMap.end()) { QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS, ("UDPTransport::NormalizeListenSpec(): The mechanism implied by \"r4addr\" is not supported")); argMap.erase(iter); } iter = argMap.find("r4port"); if (iter != argMap.end()) { QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS, ("UDPTransport::NormalizeListenSpec(): The mechanism implied by \"r4port\" is not supported")); argMap.erase(iter); } iter = argMap.find("r6addr"); if (iter != argMap.end()) { QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS, ("UDPTransport::NormalizeListenSpec(): The mechanism implied by \"r6addr\" is not supported")); argMap.erase(iter); } iter = argMap.find("r6port"); if (iter != argMap.end()) { QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS, ("UDPTransport::NormalizeListenSpec(): The mechanism implied by \"r6port\" is not supported")); argMap.erase(iter); } iter = argMap.find("u6addr"); if (iter != argMap.end()) { QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS, ("UDPTransport::NormalizeListenSpec(): The mechanism implied by \"u6addr\" is not supported")); argMap.erase(iter); } iter = argMap.find("u6port"); if (iter != argMap.end()) { QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS, ("UDPTransport::NormalizeListenSpec(): The mechanism implied by \"u6port\" is not supported")); argMap.erase(iter); } /* * Now, begin normalizing what we want to see in a listen spec. * * All listen specs must start with the name of the transport followed by * a colon. */ outSpec = GetTransportName() + qcc::String(":"); /* * The UDP transport must absolutely support the IPv4 "unreliable" mechanism * (UDP). We therefore must provide a u4addr either from explicit keys or * generated from the defaults. */ iter = argMap.find("u4addr"); if (iter == argMap.end()) { /* * We have no value associated with an "u4addr" key. Do we have an * "addr" which would be synonymous? If so, save it as a u4addr, * erase it and point back to the new u4addr. */ iter = argMap.find("addr"); if (iter != argMap.end()) { argMap["u4addr"] = iter->second; argMap.erase(iter); } iter = argMap.find("u4addr"); } /* * Now, deal with the u4addr, possibly replaced by addr. */ if (iter != argMap.end()) { /* * We have a value associated with the "u4addr" key. Run it through a * conversion function to make sure it's a valid value and to get into * in a standard representation. */ IPAddress addr; status = addr.SetAddress(iter->second, false); if (status == ER_OK) { /* * The u4addr had better be an IPv4 address, otherwise we bail. */ if (!addr.IsIPv4()) { QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS, ("UDPTransport::NormalizeListenSpec(): The u4addr \"%s\" is not a legal IPv4 address", iter->second.c_str())); return ER_BUS_BAD_TRANSPORT_ARGS; } iter->second = addr.ToString(); outSpec.append("u4addr=" + addr.ToString()); } else { QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS, ("UDPTransport::NormalizeListenSpec(): The u4addr \"%s\" is not a legal IPv4 address", iter->second.c_str())); return ER_BUS_BAD_TRANSPORT_ARGS; } } else { /* * We have no value associated with an "u4addr" key. Use the default * IPv4 listen address for the outspec and create a new key for the * map. */ outSpec.append("u4addr=" + qcc::String(ADDR4_DEFAULT)); argMap["u4addr"] = ADDR4_DEFAULT; } /* * The UDP transport must absolutely support the IPv4 "unreliable" mechanism * (UDP). We therefore must provide a u4port either from explicit keys or * generated from the defaults. */ iter = argMap.find("u4port"); if (iter == argMap.end()) { /* * We have no value associated with a "u4port" key. Do we have a * "port" which would be synonymous? If so, save it as a u4port, * erase it and point back to the new u4port. */ iter = argMap.find("port"); if (iter != argMap.end()) { argMap["u4port"] = iter->second; argMap.erase(iter); } iter = argMap.find("u4port"); } /* * Now, deal with the u4port, possibly replaced by port. */ if (iter != argMap.end()) { /* * We have a value associated with the "u4port" key. Run it through a * conversion function to make sure it's a valid value. We put it into * a 32 bit int to make sure it will actually fit into a 16-bit port * number. */ uint32_t port = StringToU32(iter->second); if (port <= 0xffff) { outSpec.append(",u4port=" + iter->second); } else { QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS, ("UDPTransport::NormalizeListenSpec(): The key \"u4port\" has a bad value \"%s\"", iter->second.c_str())); return ER_BUS_BAD_TRANSPORT_ARGS; } } else { /* * We have no value associated with an "u4port" key. Use the default * IPv4 listen port for the outspec and create a new key for the map. */ qcc::String portString = U32ToString(PORT_DEFAULT); outSpec += ",u4port=" + portString; argMap["u4port"] = portString; } return ER_OK; } QStatus UDPTransport::NormalizeTransportSpec(const char* inSpec, qcc::String& outSpec, map<qcc::String, qcc::String>& argMap) const { QCC_DbgTrace(("UDPTransport::NormalizeTransportSpec()")); QStatus status; /* * Aside from the presence of the guid, the only fundamental difference * between a listenSpec and a transportSpec (actually a connectSpec) is that * a connectSpec must have a valid and specific address IP address to * connect to (i.e., INADDR_ANY isn't a valid IP address to connect to). * This means that we can just call NormalizeListenSpec to get everything * into standard form. */ status = NormalizeListenSpec(inSpec, outSpec, argMap); if (status != ER_OK) { return status; } /* * Since there is no guid present if we've fallen through to here, the only * difference between a connectSpec and a listenSpec is that a connectSpec * requires the presence of a non-default IP address. So we just check for * the default addresses and fail if we find one. */ map<qcc::String, qcc::String>::iterator i = argMap.find("u4addr"); assert(i != argMap.end()); if ((i->second == ADDR4_DEFAULT)) { QCC_LogError(ER_BUS_BAD_TRANSPORT_ARGS, ("UDPTransport::NormalizeTransportSpec(): The u4addr may not be the default address")); return ER_BUS_BAD_TRANSPORT_ARGS; } return ER_OK; } /** * This is the method that is called in order to initiate an outbound (active) * connection. This is called from the AllJoyn Object in the course of * processing a JoinSession request in the context of a JoinSessionThread. */ QStatus UDPTransport::Connect(const char* connectSpec, const SessionOpts& opts, BusEndpoint& newEp) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::Connect(connectSpec=%s, opts=%p, newEp-%p)", connectSpec, &opts, &newEp)); /* * We only want to allow this call to proceed if we have a running server * accept thread that isn't in the process of shutting down. We use the * thread response from IsRunning to give us an idea of what our server * accept (Run) thread is doing. See the comment in Start() for details * about what IsRunning actually means, which might be subtly different from * your intuitition. * * If we see IsRunning(), the thread might actually have gotten a Stop(), * but has not yet exited its Run routine and become STOPPING. To plug this * hole, we need to check IsRunning() and also m_stopping, which is set in * our Stop() method. */ if (IsRunning() == false || m_stopping == true) { QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("UDPTransport::Connect(): Not running or stopping; exiting")); DecrementAndFetch(&m_refCount); return ER_BUS_TRANSPORT_NOT_STARTED; } /* * If we pass the IsRunning() gate above, we must have a server accept * thread spinning up or shutting down but not yet joined. Since the name * service is started before the server accept thread is spun up, and * deleted after it is joined, we must have a started name service or someone * isn't playing by the rules; so an assert is appropriate here. */ assert(IpNameService::Instance().Started() && "UDPTransport::Connect(): IpNameService not started"); /* * UDP Transport does not support raw sockets of any flavor. */ QStatus status; if (opts.traffic & SessionOpts::TRAFFIC_RAW_RELIABLE || opts.traffic & SessionOpts::TRAFFIC_RAW_UNRELIABLE) { status = ER_UDP_UNSUPPORTED; QCC_LogError(status, ("UDPTransport::Connect(): UDP Transport does not support raw traffic")); DecrementAndFetch(&m_refCount); return status; } /* * Parse and normalize the connectArgs. When connecting to the outside * world, there are no reasonable defaults and so the addr and port keys * MUST be present. */ qcc::String normSpec; map<qcc::String, qcc::String> argMap; status = NormalizeTransportSpec(connectSpec, normSpec, argMap); if (ER_OK != status) { QCC_LogError(status, ("UDPTransport::Connect(): Invalid UDP connect spec \"%s\"", connectSpec)); DecrementAndFetch(&m_refCount); return status; } /* * These fields (addr, port) are all guaranteed to be present now and an * underlying network (even if it is Wi-Fi P2P) is assumed to be up and * functioning. */ assert(argMap.find("u4addr") != argMap.end() && "UDPTransport::Connect(): u4addr not present in argMap"); assert(argMap.find("u4port") != argMap.end() && "UDPTransport::Connect(): u4port not present in argMap"); IPAddress ipAddr(argMap.find("u4addr")->second); uint16_t ipPort = StringToU32(argMap["u4port"]); /* * The semantics of the Connect method tell us that we want to connect to a * remote daemon. UDP will happily allow us to connect to ourselves, but * this is not always possible in the various transports AllJoyn may use. * To avoid unnecessary differences, we do not allow a requested connection * to "ourself" to succeed. * * The code here is not a failsafe way to prevent this since thre are going * to be multiple processes involved that have no knowledge of what the * other is doing (for example, the wireless supplicant and this daemon). * This means we can't synchronize and there will be race conditions that * can cause the tests for selfness to fail. The final check is made in the * BusHello protocol, which will abort the connection if it detects it is * conected to itself. We just attempt to short circuit the process where * we can and not allow connections to proceed that will be bound to fail. * * One defintion of a connection to ourself is if we find that a listener * has has been started via a call to our own StartListener() with the same * connectSpec as we have now. This is the simple case, but it also turns * out to be the uncommon case. * * It is perfectly legal to start a listener using the INADDR_ANY address, * which tells the system to listen for connections on any network interface * that happens to be up or that may come up in the future. This is the * default listen address and is the most common case. If this option has * been used, we expect to find a listener with a normalized adresss that * looks like "r4addr=0.0.0.0,port=y". If we detect this kind of connectSpec * we have to look at the currently up interfaces and see if any of them * match the address provided in the connectSpec. If so, we are attempting * to connect to ourself and we must fail that request. */ char anyspec[64]; snprintf(anyspec, sizeof(anyspec), "%s:u4addr=0.0.0.0,u4port=%u", GetTransportName(), ipPort); qcc::String normAnySpec; map<qcc::String, qcc::String> normArgMap; status = NormalizeListenSpec(anyspec, normAnySpec, normArgMap); if (ER_OK != status) { QCC_LogError(status, ("UDPTransport::Connect(): Invalid INADDR_ANY connect spec")); DecrementAndFetch(&m_refCount); return status; } /* * Look to see if we are already listening on the provided connectSpec * either explicitly or via the INADDR_ANY address. */ QCC_DbgPrintf(("UDPTransport::Connect(): Checking for connection to self")); m_listenFdsLock.Lock(MUTEX_CONTEXT); bool anyEncountered = false; for (list<pair<qcc::String, SocketFd> >::iterator i = m_listenFds.begin(); i != m_listenFds.end(); ++i) { QCC_DbgPrintf(("UDPTransport::Connect(): Checking listenSpec %s", i->first.c_str())); /* * If the provided connectSpec is already explicitly listened to, it is * an error. */ if (i->first == normSpec) { m_listenFdsLock.Unlock(MUTEX_CONTEXT); QCC_DbgPrintf(("UDPTransport::Connect(): Explicit connection to self")); DecrementAndFetch(&m_refCount); return ER_BUS_ALREADY_LISTENING; } /* * If we are listening to INADDR_ANY and the supplied port, then we have * to look to the currently UP interfaces to decide if this call is bogus * or not. Set a flag to remind us. */ if (i->first == normAnySpec) { QCC_DbgPrintf(("UDPTransport::Connect(): Possible implicit connection to self detected")); anyEncountered = true; } } m_listenFdsLock.Unlock(MUTEX_CONTEXT); std::vector<qcc::IfConfigEntry> entries; status = qcc::IfConfig(entries); if (ER_OK != status) { QCC_LogError(status, ("UDPTransport::Connect(): Unable to read network interface configuration")); DecrementAndFetch(&m_refCount); return status; } /* * If we are listening to INADDR_ANY, we are going to have to see if any * currently UP interfaces have an IP address that matches the connectSpec * addr. */ if (anyEncountered) { QCC_DbgPrintf(("UDPTransport::Connect(): Checking for implicit connection to self")); /* * Loop through the network interface entries looking for an UP * interface that has the same IP address as the one we're trying to * connect to. We know any match on the address will be a hit since we * matched the port during the listener check above. Since we have a * listener listening on *any* UP interface on the specified port, a * match on the interface address with the connect address is a hit. */ for (uint32_t i = 0; i < entries.size(); ++i) { QCC_DbgPrintf(("UDPTransport::Connect(): Checking interface %s", entries[i].m_name.c_str())); if (entries[i].m_flags & qcc::IfConfigEntry::UP) { QCC_DbgPrintf(("UDPTransport::Connect(): Interface UP with addresss %s", entries[i].m_addr.c_str())); IPAddress foundAddr(entries[i].m_addr); if (foundAddr == ipAddr) { QCC_DbgPrintf(("UDPTransport::Connect(): Attempted connection to self; exiting")); DecrementAndFetch(&m_refCount); return ER_BUS_ALREADY_LISTENING; } } } } /* * Now, we have to figure out which of the current sockets we are listening * on corresponds to the network of the address in the connect spec in order * to send the connect request out on the right network. */ qcc::SocketFd sock = 0; bool foundSock = false; QCC_DbgPrintf(("UDPTransport::Connect(): Look for socket corresponding to destination network")); m_listenFdsLock.Lock(MUTEX_CONTEXT); for (list<pair<qcc::String, SocketFd> >::iterator i = m_listenFds.begin(); i != m_listenFds.end(); ++i) { /* * Get the local address of the socket in question. */ IPAddress listenAddr; uint16_t listenPort; qcc::GetLocalAddress(i->second, listenAddr, listenPort); QCC_DbgPrintf(("UDPTransport::Connect(): Check out local address \"%s\"", listenAddr.ToString().c_str())); /* * Find the corresponding interface information in the IfConfig entries. * We need the network mask from that entry so we can see if * * TODO: what if we have multiple interfaces with the same network * number i.e. 192.168.1.x? The advertisement will have come in over * one of them but we lose track of the source of the advertisement that * precipitated the JoinSession that got us here. We need to remember * that info (perhaps as a "zone index" equivalent) in the connect spec, * but that has to be plumbed in from the name service and allowed all * the way up into the AllJoyn obj and back down! */ uint32_t prefixLen = 0; for (uint32_t j = 0; j < entries.size(); ++j) { if (entries[j].m_addr == listenAddr.ToString()) { prefixLen = entries[j].m_prefixlen; } } /* * Create a netmask with a one in the leading bits for each position * implied by the prefix length. */ uint32_t mask = 0; for (uint32_t j = 0; j < prefixLen; ++j) { mask >>= 1; mask |= 0x80000000; } QCC_DbgPrintf(("UDPTransport::Connect(): net mask is 0x%x", mask)); /* * Is local address of the currently indexed listenFd on the same * network as the destination address supplied as a parameter to the * connect? If so, we use this listenFD as the socket to use when we * try to connect to the remote daemon. */ uint32_t network1 = listenAddr.GetIPv4AddressCPUOrder() & mask; uint32_t network2 = ipAddr.GetIPv4AddressCPUOrder() & mask; if (network1 == network2) { QCC_DbgPrintf(("UDPTransport::Connect(): network \"%s\" matches network \"%s\"", IPAddress(network1).ToString().c_str(), IPAddress(network2).ToString().c_str())); sock = i->second; foundSock = true; } else { QCC_DbgPrintf(("UDPTransport::Connect(): network \"%s\" does not match network \"%s\"", IPAddress(network1).ToString().c_str(), IPAddress(network2).ToString().c_str())); } } m_listenFdsLock.Unlock(MUTEX_CONTEXT); if (foundSock == false) { status = ER_UDP_NO_NETWORK; QCC_LogError(status, ("UDPTransport::Connect(): Not listening on network implied by \"%s\"", ipAddr.ToString().c_str())); DecrementAndFetch(&m_refCount); return status; } QCC_DbgPrintf(("UDPTransport::Connect(): Compose BusHello")); Message hello(m_bus); status = hello->HelloMessage(true, m_bus.GetInternal().AllowRemoteMessages(), opts.nameTransfer); if (status != ER_OK) { status = ER_UDP_BUSHELLO; QCC_LogError(status, ("UDPTransport::Connect(): Can't make a BusHello Message")); DecrementAndFetch(&m_refCount); return status; } /* * The Function HelloMessage creates and marshals the BusHello Message for * the remote side. Once it is marshaled, there is a buffer associated with * the message that contains the on-the-wire version of the messsage. The * ARDP code expects to take responsibility for the buffer since it may need * to retransmit it, so we need to copy out the contents of that (small) * buffer. */ size_t buflen = hello->GetBufferSize(); #ifndef NDEBUG uint8_t* buf = new uint8_t[buflen + SEAL_SIZE]; SealBuffer(buf + buflen); #else uint8_t* buf = new uint8_t[buflen]; #endif memcpy(buf, const_cast<uint8_t*>(hello->GetBuffer()), buflen); /* * We are about to get into a state where we are off trying to start up an * endpoint, but we are executing in the context of an arbitrary thread that * has called into UDPTransport::Connect(). We want to block this thread, * but we will be needing to wake it up when the connection process * completes and also up in case the UDP transport is shut down during the * connection process. We need the ArdpConnRecord* in order to associate * the current thread and the event we'll be using with the connection * completion callback that will happen. * * As soon as we call ARDP_Connect() we are enabling the callback to happen, * but we don't have the ArdpConnRecord* we need until after ARDP_Connect() * returns. In order to keep the connect callback from happening, we take * the ARDP lock which prevents the callback from being run and we don't * give it back until we have the ArdpConnRecord* stashed away in a place * where it can be found by the callback. * * N.B. The event in question *must* remain in scope and valid during the * entire time the ConnectEntry we're about to make is on the set we're * about to put it on. */ qcc::Event event; ArdpConnRecord* conn; /* * We need to take the endpoint list lock which is going to protect the * std::set of entries identifying the connecting thread; and we need to * take the ARDP lock to hold off the callback. When holding two locks, * always consider lock order. Unfortunately, it is a common operation * for an external thread to take the endpoint lock, wander around in the * endpoints and figure out what to do then take the ARDP lock in order * to do it. It's also a common operation for our main thread to take the * ARDP lock and call into ARDP which calls out in a callback * and We'll keep that order. */ m_endpointListLock.Lock(MUTEX_CONTEXT); m_ardpLock.Lock(); QCC_DbgPrintf(("UDPTransport::Connect(): ARDP_Connect()")); status = ARDP_Connect(m_handle, sock, ipAddr, ipPort, ARDP_SEGMAX, ARDP_SEGBMAX, &conn, buf, buflen, &event); if (status != ER_OK) { assert(conn == NULL && "UDPTransport::Connect(): ARDP_Connect() failed but returned ArdpConnRecord"); QCC_LogError(status, ("UDPTransport::Connect(): ARDP_Connect() failed")); m_ardpLock.Unlock(); m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return status; } Thread* thread = GetThread(); QCC_DbgPrintf(("UDPTransport::Connect(): Add thread=%p to m_connectThreads", thread)); assert(thread && "UDPTransport::Connect(): GetThread() returns NULL"); ConnectEntry entry(thread, conn, ARDP_GetConnId(m_handle, conn), &event); /* * Now, we can safely insert the entry into the set. We're danger close to * a horrible fate unless we get it off that list before <event> goes out of * scope. */ m_connectThreads.insert(entry); /* * If we do something that is going to bug the ARDP protocol (in this case * start connect timers), we need to call back into ARDP ASAP to get it * moving. This is done in the main thread, which we need to wake up. * Since this is a connect it will eventually require endpoint management, * so we make a note to run the endpoint management code. */ m_manage = STATE_MANAGE; Alert(); /* * All done with the tricky part, so release the locks in inverse order */ m_ardpLock.Unlock(); m_endpointListLock.Unlock(MUTEX_CONTEXT); /* * Set up a watchdog timeout on the connect. If the other side plays by the * rules, we should get a callback. If there are authentication games played * during the connect, we need to detect that and time out ourselves, so the * endpoint can be scavenged. We add our own timeout that expires some time after we * expect ARDP to time out. On a connect that would be at * * connectTimeout * (1 + connectRetries) * * To give ARDP a chance, we timeout one retry interval later, at * * connectTimeout * (2 + connectRetries) * */ uint32_t timeout = m_ardpConfig.connectTimeout * (2 + m_ardpConfig.connectRetries); QCC_DbgPrintf(("UDPTransport::Connect(): qcc::Event::Wait(): timeout=%d.", timeout)); /* * We fired off the connect request. If the connect succeeds, when we wake * up we will find a UDPEndpoint on the m_endpointList with an ARDP * connection pointer matching the connection we got above. If this doesn't * happen, the process must've failed. */ status = qcc::Event::Wait(event, timeout); /* * Whether we succeeded or failed, we are done with blocking I/O on the * current thread, so we need to remove the connectEntry from the set we * kept it in. We still have the thread reference count set indicating we * are in the endpoint, but we are awake and headed out now. */ m_endpointListLock.Lock(MUTEX_CONTEXT); QCC_DbgPrintf(("UDPTransport::Connect(): Removing thread=%p from m_connectThreads", thread)); set<ConnectEntry>::iterator j = m_connectThreads.find(entry); assert(j != m_connectThreads.end() && "UDPTransport::Connect(): Thread not on m_connectThreads"); m_connectThreads.erase(j); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::Connect(): Event::Wait() failed")); m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return status; } /* * The way we figure out if the connect succeded is by looking for an * endpoint with a connection ID that is the same as the one returned to us * by the original call to ARDP_Connect(). */ QCC_DbgPrintf(("UDPTransport::Connect(): Finding endpoint with conn ID = %d. in m_endpointList", ARDP_GetConnId(m_handle, conn))); set<UDPEndpoint>::iterator i; for (i = m_endpointList.begin(); i != m_endpointList.end(); ++i) { UDPEndpoint ep = *i; if (ep->GetConn() == conn) { QCC_DbgPrintf(("UDPTransport::Connect(): Success.")); /* * We know that we found an endpoint on the endpoint list so it has * a valid reference count, and we are doing this with the endpoint * list lock taken so nothing will be deleted out from under us. * This assignment to newEp will result in a new reference to a * valid object. */ newEp = BusEndpoint::cast(ep); break; } } m_endpointListLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return status; } /** * This is a (surprisingly) unused method call. One would expect that since it * is defined, it would be the symmetrical opposigte of Connect. That turns out * not to be the case. Some transports define implementations as if it was * used, but it is not. Our implementation is to simply assert. */ QStatus UDPTransport::Disconnect(const char* connectSpec) { IncrementAndFetch(&m_refCount); QCC_DbgHLPrintf(("UDPTransport::Disconnect(): %s", connectSpec)); /* * Disconnect is actually not used in the transports architecture. It is * misleading and confusing to have it implemented. */ assert(0 && "UDPTransport::Disconnect(): Unexpected call"); QCC_LogError(ER_FAIL, ("UDPTransport::Disconnect(): Unexpected call")); DecrementAndFetch(&m_refCount); return ER_FAIL; } /** * Start listening for inbound connections over the ARDP Protocol using the * address and port information provided in the listenSpec. */ QStatus UDPTransport::StartListen(const char* listenSpec) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::StartListen()")); /* * We only want to allow this call to proceed if we have a running server * accept thread that isn't in the process of shutting down. We use the * thread response from IsRunning to give us an idea of what our server * accept (Run) thread is doing. See the comment in Start() for details * about what IsRunning actually means, which might be subtly different from * your intuitition. * * If we see IsRunning(), the thread might actually have gotten a Stop(), * but has not yet exited its Run routine and become STOPPING. To plug this * hole, we need to check IsRunning() and also m_stopping, which is set in * our Stop() method. */ if (IsRunning() == false || m_stopping == true) { QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("UDPTransport::StartListen(): Not running or stopping; exiting")); DecrementAndFetch(&m_refCount); return ER_BUS_TRANSPORT_NOT_STARTED; } /* * Normalize the listen spec. Although this looks like a connectSpec it is * different in that reasonable defaults are possible. We do the * normalization here so we can report an error back to the caller. */ qcc::String normSpec; map<qcc::String, qcc::String> argMap; QStatus status = NormalizeListenSpec(listenSpec, normSpec, argMap); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::StartListen(): Invalid UDP listen spec \"%s\"", listenSpec)); DecrementAndFetch(&m_refCount); return status; } QCC_DbgPrintf(("UDPTransport::StartListen(): u4addr = \"%s\", u4port = \"%s\"", argMap["u4addr"].c_str(), argMap["u4port"].c_str())); /* * The daemon code is in a state where it lags in functionality a bit with * respect to the common code. Common supports the use of IPv6 addresses * but the name service is not quite ready for prime time. Until the name * service can properly distinguish between various cases, we fail any * request to listen on an IPv6 address. */ IPAddress ipAddress; status = ipAddress.SetAddress(argMap["u4addr"].c_str()); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::StartListen(): Unable to SetAddress(\"%s\")", argMap["u4addr"].c_str())); DecrementAndFetch(&m_refCount); return status; } if (ipAddress.IsIPv6()) { status = ER_INVALID_ADDRESS; QCC_LogError(status, ("UDPTransport::StartListen(): IPv6 address (\"%s\") in \"u4addr\" not allowed", argMap["u4addr"].c_str())); DecrementAndFetch(&m_refCount); return status; } /* * Because we are sending a *request* to start listening on a given * normalized listen spec to another thread, and the server thread starts * and stops listening on given listen specs when it decides to eventually * run, it is be possible for a calling thread to send multiple requests to * start or stop listening on the same listenSpec before the server thread * responds. * * In order to deal with these two timelines, we keep a list of normalized * listenSpecs that we have requested to be started, and not yet requested * to be removed. This list (the mListenSpecs) must be consistent with * client requests to start and stop listens. This list is not necessarily * consistent with what is actually being listened on. That is a separate * list called mListenFds. * * So, check to see if someone has previously requested that the address and * port in question be listened on. We need to do this here to be able to * report an error back to the caller. */ m_listenSpecsLock.Lock(MUTEX_CONTEXT); for (list<qcc::String>::iterator i = m_listenSpecs.begin(); i != m_listenSpecs.end(); ++i) { if (*i == normSpec) { m_listenSpecsLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return ER_BUS_ALREADY_LISTENING; } } m_listenSpecsLock.Unlock(MUTEX_CONTEXT); QueueStartListen(normSpec); DecrementAndFetch(&m_refCount); return ER_OK; } void UDPTransport::QueueStartListen(qcc::String& normSpec) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::QueueStartListen()")); /* * In order to start a listen, we send the maintenance thread a message * containing the START_LISTEN_INSTANCE request code and the normalized * listen spec which specifies the address and port instance to listen on. */ ListenRequest listenRequest; listenRequest.m_requestOp = START_LISTEN_INSTANCE; listenRequest.m_requestParam = normSpec; m_listenRequestsLock.Lock(MUTEX_CONTEXT); /* Process the request */ RunListenMachine(listenRequest); m_listenRequestsLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); } QStatus UDPTransport::DoStartListen(qcc::String& normSpec) { IncrementAndFetch(&m_refCount); QCC_DbgPrintf(("UDPTransport::DoStartListen()")); /* * Since the name service is created before the server accept thread is spun * up, and stopped when it is stopped, we must have a started name service or * someone isn't playing by the rules; so an assert is appropriate here. */ assert(IpNameService::Instance().Started() && "UDPTransport::DoStartListen(): IpNameService not started"); /* * Parse the normalized listen spec. The easiest way to do this is to * re-normalize it. If there's an error at this point, we have done * something wrong since the listen spec was presumably successfully * normalized before sending it in -- so we assert. */ qcc::String spec; map<qcc::String, qcc::String> argMap; QStatus status = NormalizeListenSpec(normSpec.c_str(), spec, argMap); assert(status == ER_OK && "UDPTransport::DoStartListen(): Invalid UDP listen spec"); QCC_DbgPrintf(("UDPTransport::DoStartListen(): u4addr = \"%s\", u4port = \"%s\"", argMap["u4addr"].c_str(), argMap["u4port"].c_str())); /* * Figure out what local address and port the listener should use. */ IPAddress listenAddr(argMap["u4addr"]); uint16_t listenPort = StringToU32(argMap["u4port"]); bool ephemeralPort = (listenPort == 0); /* * If we're going to listen on an address, we are going to listen on a * corresponding network interface. We need to convince the name service to * send advertisements out over that interface, or nobody will know to * connect to the listening daemon. The expected use case is that the * daemon does exactly one StartListen() which listens to INADDR_ANY * (listens for inbound connections over any interface) and the name service * is controlled by a separate configuration item that selects which * interfaces are used in discovery. Since IP addresses in a mobile * environment are dynamic, listening on the ANY address is the only option * that really makes sense, and this is the only case in which the current * implementation will really work. * * So, we need to get the configuration item telling us which network * interfaces we should run the name service over. The item can specify an * IP address, in which case the name service waits until that particular * address comes up and then uses the corresponding net device if it is * multicast-capable. The item can also specify an interface name. In this * case the name service waits until it finds the interface IFF_UP and * multicast capable with an assigned IP address and then starts using the * interface. If the configuration item contains "*" (the wildcard) it is * interpreted as meaning all multicast-capable interfaces. If the * configuration item is empty (not assigned in the configuration database) * it defaults to "*". */ qcc::String interfaces = ConfigDB::GetConfigDB()->GetProperty("ns_interfaces"); if (interfaces.size() == 0) { interfaces = INTERFACES_DEFAULT; } while (interfaces.size()) { qcc::String currentInterface; size_t i = interfaces.find(","); if (i != qcc::String::npos) { currentInterface = interfaces.substr(0, i); interfaces = interfaces.substr(i + 1, interfaces.size() - i - 1); } else { currentInterface = interfaces; interfaces.clear(); } /* * We have been given a listenSpec that provides an r4addr and an r4port * in the parameters to this method. We are expected to listen on that * address and port for inbound connections. We have a separate list of * network interface names that we are walking through that tell us * which interfaces the name service should advertise and discover over. * We always listen on the listen address and port, and we always * respect the interface names given for the name service. * * We can either be given a listenAddr of INADDR_ANY or a specific * address. If given INADDR_ANY this means that the TCP Transport will * listen for inbound connections on any currently IFF_UP interface or * any interface that may come IFF_UP in the future. If given a * specific IP address, we must only listen for connections on that * address. * * We are also given a list of interface names in the ns_interfaces * property. These tell the name service which interfaces to discover and * advertise over. There are four basic situations we will encounter: * * listen ns_interface Action * ------- ------------ ----------------------------------------- * 1. 0.0.0.0 * Listen on 0.0.0.0 and advertise/discover * over '*'. This is the default case where * the system listens on all interfaces and * advertises / discovers on all interfaces. * This is the "speak alljoyn over all of * your interfaces" situation. * * 2. a.b.c.d * Listen only on a.b.c.d, but advertise and * discover over '*'. In this case, the TCP * transport is told to listen on a specific * address, but the name service is told to * advertise and discover over all network * interfaces. This may not be exactly what * is desired, but it may be. We do what we * are told. Note that by doing this, one * is limiting the number of daemons that can * be run on a host using the same address * and port to one. Other daemons configured * this way must select another port. * * 3. 0.0.0.0 'specific' Listen on INADDR_ANY and so respond to all * inbound connections. Only advertise and * discover over a specific named network * interface. This is how we expect people * to limit AllJoyn to talking only over a * specific interface. This allows that * interface to change IP addresses on the * fly. * * 4. a.b.c.d 'specific' Listen on a specified address and so * only respond to inbound connections on * that interface. Only advertise and * discover over a specific named network * interface (presumably the same interface * but we don't require it to be set up yet). * This allows administrators to to limit * AllJoyn to both listening and advertising * and discovering only over a specific * network interface. This requires that * the IP address of the network interface * named 'specific' to be known a-priori. * * Note that the string 'specific' from the ns_interfaces configuration * can also refer to a specific IP address and is not limited to only * network interface names. Thus, if one has a statically configured * network address, one could specify both listening and advertisement * using IP addresses: * * 5. a.b.c.d 'a.b.c.d' Listen on a specified address and so * only respond to inbound connections on * that interface. Only advertise and * discover over a specific IP address * (presumably the same address but we * don't require it to be set up yet). * Note that there may, in fact, be a list * of specific IP addresses, but there can * be only one listen addresses. This is * a degenerate version of the a.b.c.d '*' * case from above since you can contemplate * adding all IP addresses in the list. * * This is much harder to describe than to implement; but the upshot is * that we listen on whatever IP address comes in with the listenSpec * and we enable the name service on whatever interface name or address * that comes in in ns_interfaces. It is up to the person doing the * configuration to understand what he or she is trying to do and the * impact of choosing those values. * * So, the first order of business is to determine whether or not the * current ns_interfaces item is an IP address or is a network interface * name. If setting an IPAddress with the current item works, it is an * IP Address, otherwise we assume it must be a network interface. Once * we know which overloaded NS function to call, just do it. */ IPAddress currentAddress; status = currentAddress.SetAddress(currentInterface, false); if (status == ER_OK) { status = IpNameService::Instance().OpenInterface(TRANSPORT_UDP, currentAddress); } else { status = IpNameService::Instance().OpenInterface(TRANSPORT_UDP, currentInterface); } if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::DoStartListen(): OpenInterface() failed for %s", currentInterface.c_str())); } } /* * We have the name service work out of the way, so we can now create the * UDP listener sockets and set SO_REUSEADDR/SO_REUSEPORT so we don't have * to wait for four minutes to relaunch the daemon if it crashes. */ QCC_DbgPrintf(("UDPTransport::DoStartListen(): Setting up socket")); SocketFd listenFd = -1; status = Socket(QCC_AF_INET, QCC_SOCK_DGRAM, listenFd); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::DoStartListen(): Socket() failed")); DecrementAndFetch(&m_refCount); return status; } QCC_DbgPrintf(("UDPTransport::DoStartListen(): listenFd=%d.", listenFd));; /* * ARDP expects us to use select and non-blocking sockets. */ QCC_DbgPrintf(("UDPTransport::DoStartListen(): SetBlocking(listenFd=%d, false)", listenFd));; status = qcc::SetBlocking(listenFd, false); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::DoStartListen(): SetBlocking() failed")); qcc::Close(listenFd); DecrementAndFetch(&m_refCount); return status; } /* * If ephemeralPort is set, it means that the listen spec did not provide a * specific port and wants us to choose one. In this case, we first try the * default port; but it that port is already taken in the system, we let the * system assign a new one from the ephemeral port range. */ if (ephemeralPort) { QCC_DbgPrintf(("UDPTransport::DoStartListen(): ephemeralPort"));; listenPort = PORT_DEFAULT; QCC_DbgPrintf(("UDPTransport::DoStartListen(): Bind(listenFd=%d., listenAddr=\"%s\", listenPort=%d.)", listenFd, listenAddr.ToString().c_str(), listenPort));; status = Bind(listenFd, listenAddr, listenPort); if (status != ER_OK) { listenPort = 0; QCC_DbgPrintf(("UDPTransport::DoStartListen(): Bind() failed. Bind(listenFd=%d., listenAddr=\"%s\", listenPort=%d.)", listenFd, listenAddr.ToString().c_str(), listenPort));; status = Bind(listenFd, listenAddr, listenPort); } } else { QCC_DbgPrintf(("UDPTransport::DoStartListen(): Bind(listenFd=%d., listenAddr=\"%s\", listenPort=%d.)", listenFd, listenAddr.ToString().c_str(), listenPort));; status = Bind(listenFd, listenAddr, listenPort); } if (status == ER_OK) { /* * If the port was not set (or set to zero) then we may have bound an ephemeral port. If * so call GetLocalAddress() to update the connect spec with the port allocated by bind. */ if (ephemeralPort) { qcc::GetLocalAddress(listenFd, listenAddr, listenPort); normSpec = "udp:u4addr=" + argMap["u4addr"] + ",u4port=" + U32ToString(listenPort); QCC_DbgPrintf(("UDPTransport::DoStartListen(): ephemeralPort. New normSpec=\"%s\"", normSpec.c_str())); } } else { QCC_LogError(status, ("UDPTransport::DoStartListen(): Failed to bind to %s/%d", listenAddr.ToString().c_str(), listenPort)); } /* * Okay, we're ready to receive datagrams on this socket now. Tell the * maintenance thread that something happened here and it needs to reload * its FDs. */ QCC_DbgPrintf(("UDPTransport::DoStartListen(): listenFds.push_back(normSpec=\"%s\", listenFd=%d)", normSpec.c_str(), listenFd)); m_listenFdsLock.Lock(MUTEX_CONTEXT); m_listenFds.push_back(pair<qcc::String, SocketFd>(normSpec, listenFd)); m_reload = STATE_RELOADING; m_listenFdsLock.Unlock(MUTEX_CONTEXT); /* * The IP name service is very flexible about what to advertise. It assumes * that a so-called transport is going to be doing the advertising. An IP * transport, by definition, has a reliable data transmission capability and * an unreliable data transmission capability. In the IP world, reliable * data is sent using TCP and unreliable data is sent using UDP (we use UDP * but build a reliability layer on top of it). Also, IP implies either * IPv4 or IPv6 addressing. * * In the UDPTransport, we only support unreliable data transfer over IPv4 * addresses, so we leave all of the other possibilities turned off (provide * a zero port). Remember the port we enabled so we can re-enable the name * service if listeners come and go. */ QCC_DbgPrintf(("UDPTransport::DoStartListen(): IpNameService::Instance().Enable()")); m_listenPort = listenPort; IpNameService::Instance().Enable(TRANSPORT_UDP, 0, 0, listenPort, 0, false, false, true, false); m_isNsEnabled = true; /* * There is a special case in which we respond to embedded AllJoyn bus * attachements actively looking for daemons to connect to. We don't want * do blindly do this all the time so we can pass the Android Compatibility * Test, so we crank up an advertisement when we do the start listen (which * is why we bother to do all of the serialization of DoStartListen work * anyway). We make this a configurable advertisement so users of bundled * daemons can change the advertisement and know they are connecting to * "their" daemons if desired. * * We pull the advertisement prefix out of the configuration and if it is * there, we append the short GUID of the daemon to make it unique and then * advertise it quietly via the IP name service. The quietly option means * that we do not send gratuitous is-at (advertisements) of the name, but we * do respond to who-has requests on the name. */ if (!m_routerName.empty() && (m_numUntrustedClients < m_maxUntrustedClients)) { QCC_DbgPrintf(("UDPTransport::DoStartListen(): Advertise m_routerName=\"%s\"", m_routerName.c_str())); bool isFirst; NewAdvertiseOp(ENABLE_ADVERTISEMENT, m_routerName, isFirst); QStatus status = IpNameService::Instance().AdvertiseName(TRANSPORT_UDP, m_routerName, true, TRANSPORT_UDP); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::DoStartListen(): Failed to AdvertiseNameQuietly \"%s\"", m_routerName.c_str())); } m_isAdvertising = true; } m_isListening = true; /* * Signal the (probably) waiting run thread so it will wake up and add this * new socket to its list of sockets it is waiting for connections on. */ if (status == ER_OK) { QCC_DbgPrintf(("UDPTransport::DoStartListen(): Alert()")); Alert(); } DecrementAndFetch(&m_refCount); return status; } /** * Since untrusted clients are only Thin Library clients, and the Thin Library * only supports TCP, this is a NOP here. */ void UDPTransport::UntrustedClientExit() { QCC_DbgTrace((" UDPTransport::UntrustedClientExit()")); } /** * Since untrusted clients are only Thin Library clients, and the Thin Library * only supports TCP, this is a NOP here. */ QStatus UDPTransport::UntrustedClientStart() { QCC_DbgTrace((" UDPTransport::UntrustedClientStart()")); return ER_UDP_NOT_IMPLEMENTED; } /** * Stop listening for inbound connections over the ARDP Protocol using the * address and port information provided in the listenSpec. Must match a * previously started listenSpec. */ QStatus UDPTransport::StopListen(const char* listenSpec) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::StopListen()")); /* * We only want to allow this call to proceed if we have a running server * accept thread that isn't in the process of shutting down. We use the * thread response from IsRunning to give us an idea of what our server * accept (Run) thread is doing. See the comment in Start() for details * about what IsRunning actually means, which might be subtly different from * your intuitition. * * If we see IsRunning(), the thread might actually have gotten a Stop(), * but has not yet exited its Run routine and become STOPPING. To plug this * hole, we need to check IsRunning() and also m_stopping, which is set in * our Stop() method. */ if (IsRunning() == false || m_stopping == true) { QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("UDPTransport::StopListen(): Not running or stopping; exiting")); DecrementAndFetch(&m_refCount); return ER_BUS_TRANSPORT_NOT_STARTED; } /* * Normalize the listen spec. We are going to use the name string that was * put together for the StartListen call to find the listener instance to * stop, so we need to do it exactly the same way. */ qcc::String normSpec; map<qcc::String, qcc::String> argMap; QStatus status = NormalizeListenSpec(listenSpec, normSpec, argMap); if (status != ER_OK) { QCC_LogError(status, ("UDPTransport::StopListen(): Invalid UDP listen spec \"%s\"", listenSpec)); DecrementAndFetch(&m_refCount); return status; } /* * Because we are sending a *request* to stop listening on a given * normalized listen spec to another thread, and the server thread starts * and stops listening on given listen specs when it decides to eventually * run, it is be possible for a calling thread to send multiple requests to * start or stop listening on the same listenSpec before the server thread * responds. * * In order to deal with these two timelines, we keep a list of normalized * listenSpecs that we have requested to be started, and not yet requested * to be removed. This list (the mListenSpecs) must be consistent with * client requests to start and stop listens. This list is not necessarily * consistent with what is actually being listened on. That is reflected by * a separate list called mListenFds. * * We consult the list of listen spects for duplicates when starting to * listen, and we make sure that a listen spec is on the list before * queueing a request to stop listening. Asking to stop listening on a * listen spec we aren't listening on is not an error, since the goal of the * user is to not listen on a given address and port -- and we aren't. */ m_listenSpecsLock.Lock(MUTEX_CONTEXT); for (list<qcc::String>::iterator i = m_listenSpecs.begin(); i != m_listenSpecs.end(); ++i) { if (*i == normSpec) { m_listenSpecs.erase(i); QueueStopListen(normSpec); break; } } m_listenSpecsLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); return ER_OK; } void UDPTransport::QueueStopListen(qcc::String& normSpec) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::QueueStopListen()")); /* * In order to stop a listen, we send the server accept thread a message * containing the STOP_LISTEN_INTANCE request code and the normalized listen * spec which specifies the address and port instance to stop listening on. */ ListenRequest listenRequest; listenRequest.m_requestOp = STOP_LISTEN_INSTANCE; listenRequest.m_requestParam = normSpec; m_listenRequestsLock.Lock(MUTEX_CONTEXT); /* Process the request */ RunListenMachine(listenRequest); m_listenRequestsLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); } void UDPTransport::DoStopListen(qcc::String& normSpec) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::DoStopListen()")); /* * Since the name service is started before the server accept thread is spun * up, and stopped after it is stopped, we must have a started name service or * someone isn't playing by the rules; so an assert is appropriate here. */ assert(IpNameService::Instance().Started() && "UDPTransport::DoStopListen(): IpNameService not started"); /* * Find the (single) listen spec and remove it from the list of active FDs * used by the maintenance thread. */ QCC_DbgPrintf(("UDPTransport::DoStopListen(): Looking for listen FD with normspec \"%s\"", normSpec.c_str())); m_listenFdsLock.Lock(MUTEX_CONTEXT); qcc::SocketFd stopFd = -1; bool found = false; for (list<pair<qcc::String, SocketFd> >::iterator i = m_listenFds.begin(); i != m_listenFds.end(); ++i) { if (i->first == normSpec) { QCC_DbgPrintf(("UDPTransport::DoStopListen(): Found normspec \"%s\"", normSpec.c_str())); stopFd = i->second; m_listenFds.erase(i); found = true; break; } } if (found) { if (m_reload != STATE_EXITED) { QCC_DbgPrintf(("UDPTransport::DoStopListen(): m_reload != STATE_EXITED")); /* * If the UDPTransport::Run thread is still running, set m_reload to * STATE_RELOADING, unlock the mutex, alert the main Run thread that * there is a change and wait for the Run thread to finish any * connections it may be accepting and then reload the set of * events. */ m_reload = STATE_RELOADING; QCC_DbgPrintf(("UDPTransport::DoStopListen(): Alert()")); Alert(); /* * Wait until UDPTransport::Run thread has reloaded the set of * events or exited. */ QCC_DbgPrintf(("UDPTransport::DoStopListen(): Wait for STATE_RELOADING()")); while (m_reload == STATE_RELOADING) { m_listenFdsLock.Unlock(MUTEX_CONTEXT); qcc::Sleep(10); m_listenFdsLock.Lock(MUTEX_CONTEXT); } QCC_DbgPrintf(("UDPTransport::DoStopListen(): Done waiting for STATE_RELOADING()")); } /* * If we took a socketFD off of the list of active FDs, we need to tear it * down. */ QCC_DbgPrintf(("UDPTransport::DoStopListen(): Close socket %d.", stopFd)); qcc::Close(stopFd); } m_listenFdsLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); } bool UDPTransport::NewDiscoveryOp(DiscoveryOp op, qcc::String namePrefix, bool& isFirst) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::NewDiscoveryOp()")); bool first = false; if (op == ENABLE_DISCOVERY) { QCC_DbgPrintf(("UDPTransport::NewDiscoveryOp(): Registering discovery of namePrefix \"%s\"", namePrefix.c_str())); first = m_advertising.empty(); m_discovering.push_back(namePrefix); } else { list<qcc::String>::iterator i = find(m_discovering.begin(), m_discovering.end(), namePrefix); if (i == m_discovering.end()) { QCC_DbgPrintf(("UDPTransport::NewDiscoveryOp(): Cancel of non-existent namePrefix \"%s\"", namePrefix.c_str())); } else { QCC_DbgPrintf(("UDPTransport::NewDiscoveryOp(): Unregistering discovery of namePrefix \"%s\"", namePrefix.c_str())); m_discovering.erase(i); } } isFirst = first; bool rc = m_discovering.empty(); DecrementAndFetch(&m_refCount); return rc; } bool UDPTransport::NewAdvertiseOp(AdvertiseOp op, qcc::String name, bool& isFirst) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::NewAdvertiseOp()")); bool first = false; if (op == ENABLE_ADVERTISEMENT) { QCC_DbgPrintf(("UDPTransport::NewAdvertiseOp(): Registering advertisement of namePrefix \"%s\"", name.c_str())); first = m_advertising.empty(); m_advertising.push_back(name); } else { list<qcc::String>::iterator i = find(m_advertising.begin(), m_advertising.end(), name); if (i == m_advertising.end()) { QCC_DbgPrintf(("UDPTransport::NewAdvertiseOp(): Cancel of non-existent name \"%s\"", name.c_str())); } else { QCC_DbgPrintf(("UDPTransport::NewAdvertiseOp(): Unregistering advertisement of namePrefix \"%s\"", name.c_str())); m_advertising.erase(i); } } isFirst = first; bool rc = m_advertising.empty(); DecrementAndFetch(&m_refCount); return rc; } bool UDPTransport::NewListenOp(ListenOp op, qcc::String normSpec) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::NewListenOp()")); if (op == START_LISTEN) { QCC_DbgPrintf(("UDPTransport::NewListenOp(): Registering listen of normSpec \"%s\"", normSpec.c_str())); m_listening.push_back(normSpec); } else { list<qcc::String>::iterator i = find(m_listening.begin(), m_listening.end(), normSpec); if (i == m_listening.end()) { QCC_DbgPrintf(("UDPTransport::NewAdvertiseOp(): StopListen of non-existent spec \"%s\"", normSpec.c_str())); } else { QCC_DbgPrintf(("UDPTransport::NewAdvertiseOp(): StopListen of normSpec \"%s\"", normSpec.c_str())); m_listening.erase(i); } } bool rc = m_listening.empty(); DecrementAndFetch(&m_refCount); return rc; } void UDPTransport::EnableDiscovery(const char* namePrefix, TransportMask transports) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::EnableDiscovery()")); /* * We only want to allow this call to proceed if we have a running server * accept thread that isn't in the process of shutting down. We use the * thread response from IsRunning to give us an idea of what our server * accept (Run) thread is doing. See the comment in Start() for details * about what IsRunning actually means, which might be subtly different from * your intuitition. * * If we see IsRunning(), the thread might actually have gotten a Stop(), * but has not yet exited its Run routine and become STOPPING. To plug this * hole, we need to check IsRunning() and also m_stopping, which is set in * our Stop() method. */ if (IsRunning() == false || m_stopping == true) { QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("UDPTransport::EnableDiscovery(): Not running or stopping; exiting")); DecrementAndFetch(&m_refCount); return; } QueueEnableDiscovery(namePrefix, transports); DecrementAndFetch(&m_refCount); } void UDPTransport::QueueEnableDiscovery(const char* namePrefix, TransportMask transports) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::QueueEnableDiscovery()")); ListenRequest listenRequest; listenRequest.m_requestOp = ENABLE_DISCOVERY_INSTANCE; listenRequest.m_requestParam = namePrefix; listenRequest.m_requestTransportMask = transports; m_listenRequestsLock.Lock(MUTEX_CONTEXT); /* Process the request */ RunListenMachine(listenRequest); m_listenRequestsLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); } void UDPTransport::DisableDiscovery(const char* namePrefix, TransportMask transports) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::DisableDiscovery()")); /* * We only want to allow this call to proceed if we have a running server * accept thread that isn't in the process of shutting down. We use the * thread response from IsRunning to give us an idea of what our server * accept (Run) thread is doing. See the comment in Start() for details * about what IsRunning actually means, which might be subtly different from * your intuitition. * * If we see IsRunning(), the thread might actually have gotten a Stop(), * but has not yet exited its Run routine and become STOPPING. To plug this * hole, we need to check IsRunning() and also m_stopping, which is set in * our Stop() method. */ if (IsRunning() == false || m_stopping == true) { QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("UDPTransport::DisbleDiscovery(): Not running or stopping; exiting")); DecrementAndFetch(&m_refCount); return; } QueueDisableDiscovery(namePrefix, transports); DecrementAndFetch(&m_refCount); } void UDPTransport::QueueDisableDiscovery(const char* namePrefix, TransportMask transports) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::QueueDisableDiscovery()")); ListenRequest listenRequest; listenRequest.m_requestOp = DISABLE_DISCOVERY_INSTANCE; listenRequest.m_requestParam = namePrefix; listenRequest.m_requestTransportMask = transports; m_listenRequestsLock.Lock(MUTEX_CONTEXT); /* Process the request */ RunListenMachine(listenRequest); m_listenRequestsLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); } QStatus UDPTransport::EnableAdvertisement(const qcc::String& advertiseName, bool quietly, TransportMask transports) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::EnableAdvertisement()")); /* * We only want to allow this call to proceed if we have a running server * accept thread that isn't in the process of shutting down. We use the * thread response from IsRunning to give us an idea of what our server * accept (Run) thread is doing. See the comment in Start() for details * about what IsRunning actually means, which might be subtly different from * your intuitition. * * If we see IsRunning(), the thread might actually have gotten a Stop(), * but has not yet exited its Run routine and become STOPPING. To plug this * hole, we need to check IsRunning() and also m_stopping, which is set in * our Stop() method. */ if (IsRunning() == false || m_stopping == true) { QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("UDPTransport::EnableAdvertisement(): Not running or stopping; exiting")); DecrementAndFetch(&m_refCount); return ER_BUS_TRANSPORT_NOT_STARTED; } QueueEnableAdvertisement(advertiseName, quietly, transports); DecrementAndFetch(&m_refCount); return ER_OK; } void UDPTransport::QueueEnableAdvertisement(const qcc::String& advertiseName, bool quietly, TransportMask transports) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::QueueEnableAdvertisement()")); ListenRequest listenRequest; listenRequest.m_requestOp = ENABLE_ADVERTISEMENT_INSTANCE; listenRequest.m_requestParam = advertiseName; listenRequest.m_requestParamOpt = quietly; listenRequest.m_requestTransportMask = transports; m_listenRequestsLock.Lock(MUTEX_CONTEXT); /* Process the request */ RunListenMachine(listenRequest); m_listenRequestsLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); } void UDPTransport::DisableAdvertisement(const qcc::String& advertiseName, TransportMask transports) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::DisableAdvertisement()")); /* * We only want to allow this call to proceed if we have a running server * accept thread that isn't in the process of shutting down. We use the * thread response from IsRunning to give us an idea of what our server * accept (Run) thread is doing. See the comment in Start() for details * about what IsRunning actually means, which might be subtly different from * your intuitition. * * If we see IsRunning(), the thread might actually have gotten a Stop(), * but has not yet exited its Run routine and become STOPPING. To plug this * hole, we need to check IsRunning() and also m_stopping, which is set in * our Stop() method. */ if (IsRunning() == false || m_stopping == true) { QCC_LogError(ER_BUS_TRANSPORT_NOT_STARTED, ("UDPTransport::DisableAdvertisement(): Not running or stopping; exiting")); DecrementAndFetch(&m_refCount); return; } QueueDisableAdvertisement(advertiseName, transports); DecrementAndFetch(&m_refCount); } void UDPTransport::QueueDisableAdvertisement(const qcc::String& advertiseName, TransportMask transports) { IncrementAndFetch(&m_refCount); QCC_DbgTrace(("UDPTransport::QueueDisableAdvertisement()")); ListenRequest listenRequest; listenRequest.m_requestOp = DISABLE_ADVERTISEMENT_INSTANCE; listenRequest.m_requestParam = advertiseName; listenRequest.m_requestTransportMask = transports; m_listenRequestsLock.Lock(MUTEX_CONTEXT); /* Process the request */ RunListenMachine(listenRequest); m_listenRequestsLock.Unlock(MUTEX_CONTEXT); DecrementAndFetch(&m_refCount); } void UDPTransport::FoundCallback::Found(const qcc::String& busAddr, const qcc::String& guid, std::vector<qcc::String>& nameList, uint32_t timer) { // Makes lots of noise! //QCC_DbgTrace(("UDPTransport::FoundCallback::Found(): busAddr = \"%s\" nameList %d", busAddr.c_str(), nameList.size())); qcc::String u4addr("u4addr="); qcc::String u4port("u4port="); qcc::String comma(","); size_t i = busAddr.find(u4addr); if (i == qcc::String::npos) { QCC_DbgPrintf(("UDPTransport::FoundCallback::Found(): No u4addr in busaddr.")); return; } i += u4addr.size(); size_t j = busAddr.find(comma, i); if (j == qcc::String::npos) { QCC_DbgPrintf(("UDPTransport::FoundCallback::Found(): No comma after u4addr in busaddr.")); return; } size_t k = busAddr.find(u4port); if (k == qcc::String::npos) { QCC_DbgPrintf(("UDPTransport::FoundCallback::Found(): No u4port in busaddr.")); return; } k += u4port.size(); /* * "u4addr=192.168.1.1,u4port=9955" * ^ ^ ^ * i j k */ qcc::String newBusAddr = qcc::String("udp:guid=") + guid + "," + u4addr + busAddr.substr(i, j - i) + "," + u4port + busAddr.substr(k); // QCC_DbgPrintf(("UDPTransport::FoundCallback::Found(): newBusAddr = \"%s\".", newBusAddr.c_str())); if (m_listener) { m_listener->FoundNames(newBusAddr, guid, TRANSPORT_UDP, &nameList, timer); } } } // namespace ajn
hybridgroup/alljoyn
alljoyn/alljoyn_core/router/UDPTransport.cc
C++
isc
335,707
// Package state manages the state needed to implement OAuth flows and to persist session values in encrypted cookies. package state import ( "context" "encoding/base64" "fmt" "net/http" "time" "github.com/davars/sohop/globals" "github.com/davars/timebox" "github.com/golang/protobuf/ptypes" ) //go:generate protoc state.proto --go_out=. const ( sessionAge = 24 * time.Hour stateAge = 5 * time.Minute maxRedirectURLLength = 2000 ) type contextKey int const ( sessionKey contextKey = iota ) func (c *cookieStore) GetSession(req *http.Request) (session *Session) { if session, ok := req.Context().Value(sessionKey).(*Session); ok { return session } defer func() { // ensure we never return nil if session == nil { session = &Session{} } // ensure we only attempt to get the session once per context *req = *req.WithContext(context.WithValue(req.Context(), sessionKey, session)) }() cookie, err := req.Cookie(c.name) if err != nil { return } session = &Session{} if !c.boxer.Open(cookie.Value, session) { session = nil } return } func (c *cookieStore) setCookie(rw http.ResponseWriter, name, value string, maxAge time.Duration) { cookie := &http.Cookie{ Name: name, Domain: c.domain, Path: "/", HttpOnly: true, Secure: true, MaxAge: int(maxAge / time.Second), Value: value, } if maxAge < 0 { cookie.Expires = time.Unix(0, 0) } else if maxAge > 0 { cookie.Expires = globals.Clock.Now().Add(maxAge) } http.SetCookie(rw, cookie) } func (c *cookieStore) Authorize(rw http.ResponseWriter, req *http.Request, user string) error { expires := globals.Clock.Now().Add(sessionAge) expiresP, _ := ptypes.TimestampProto(expires) // TODO: fix before 9999-12-31 session := &Session{User: user, Authorized: true, ExpiresAt: expiresP} value, err := c.boxer.Seal(session, sessionAge) if err != nil { return err } c.setCookie(rw, c.name, value, sessionAge) return nil } func (c *cookieStore) IsAuthorized(req *http.Request) bool { return c.GetSession(req).Authorized } // stateKeyLen is used to split the state into the portion used for the state param in the oauth flow, and the remainder // set in the state cookie's value. Use the length of the encoded nonce. var stateKeyLen = base64.RawURLEncoding.EncodedLen(24) func (c *cookieStore) CreateState(rw http.ResponseWriter, redirectURL string) (string, error) { if len(redirectURL) > maxRedirectURLLength { return "", fmt.Errorf("redirectURL %s... is too long", redirectURL[:maxRedirectURLLength]) } state, err := c.boxer.Seal(&OAuthState{RedirectUrl: redirectURL}, stateAge) if err != nil { return "", err } stateKey := state[:stateKeyLen] c.setCookie(rw, stateKey, state[stateKeyLen:], stateAge) return stateKey, nil } func (c *cookieStore) RedeemState(rw http.ResponseWriter, req *http.Request, stateKey string) (string, error) { cookie, err := req.Cookie(stateKey) if err != nil { return "", err } os := &OAuthState{} if !c.boxer.Open(stateKey+cookie.Value, os) { return "", fmt.Errorf("invalid state") } c.setCookie(rw, stateKey, "", -1) return os.RedirectUrl, nil } type cookieStore struct { name string domain string boxer *timebox.Boxer } type Store interface { Authorize(http.ResponseWriter, *http.Request, string) error IsAuthorized(*http.Request) bool CreateState(http.ResponseWriter, string) (string, error) RedeemState(http.ResponseWriter, *http.Request, string) (string, error) GetSession(*http.Request) *Session } // New returns a new cookieStore to manage the oauth state and user sessions using encrypted cookies func New(name, secret, domain string) (Store, error) { if name == "" { return nil, fmt.Errorf("name cannot be empty") } if domain == "" { return nil, fmt.Errorf("domain cannot be empty") } boxer, err := timebox.New(secret) if err != nil { return nil, err } return &cookieStore{ name: name, domain: domain, boxer: boxer, }, nil }
davars/sohop
state/store.go
GO
isc
3,988
var WebSocket= require('ws') , EventEmitter = require('events').EventEmitter , util = require('util') function ReconWs(uri, interval) { this.uri = uri this.interval = interval || 5e3 this.connected = false this.connect() } util.inherits(ReconWs, EventEmitter) ReconWs.prototype.connect = function() { this.ws = new WebSocket(this.uri) this.ws.on('open', this.wsOpen.bind(this)) this.ws.on('message', this.wsMessage.bind(this)) this.ws.on('close', this.wsClose.bind(this)) this.ws.on('error', this.wsError.bind(this)) } ReconWs.prototype.wsOpen = function() { this.connected = true this.emit('open') } ReconWs.prototype.wsClose = function() { this.connected = false this.emit('close') this.retry() } ReconWs.prototype.retry = function() { setTimeout(function() { this.connect() }.bind(this), this.interval) } ReconWs.prototype.wsError = function(err) { this.connected = false this.retry() } ReconWs.prototype.wsMessage = function(msg) { this.emit('message', msg) } ReconWs.prototype.send = function() { this.ws.send.apply(this.ws, arguments) } module.exports = ReconWs
abrkn/recon-ws
index.js
JavaScript
isc
1,166
// // protocol.cc // #include "plat_os.h" #include "plat_net.h" #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <cerrno> #include <csignal> #include <iostream> #include <iomanip> #include <sstream> #include <string> #include <vector> #include <algorithm> #include <functional> #include <deque> #include <map> #include <atomic> #include <memory> #include <thread> #include <mutex> #include <condition_variable> #include "io.h" #include "url.h" #include "log.h" #include "trie.h" #include "socket.h" #include "socket_unix.h" #include "resolver.h" #include "config_parser.h" #include "config.h" #include "pollset.h" #include "protocol.h" #include "connection.h" #include "connection.h" #include "protocol_thread.h" #include "protocol_engine.h" #include "protocol_connection.h" #include "log_thread.h" #include "http_common.h" #include "http_constants.h" #include "http_parser.h" #include "http_request.h" #include "http_response.h" #include "http_client.h" #include "http_server.h" /* protocol_object */ std::string protocol_object::to_string() { char buf[128]; poll_object_type type = get_poll_type(); protocol_sock_table *sock_table = protocol_sock::get_table(); const char *type_name = (size_t)type < sock_table->size() ? sock_table->at((size_t)type)->name.c_str() : "unknown"; snprintf(buf, sizeof(buf) - 1, "%s:%p", type_name, (void*)this); buf[sizeof(buf) - 1] = '\0'; return buf; } /* protocol_sock */ protocol_sock_map* protocol_sock::get_map() { static protocol_sock_map map; return &map; } protocol_sock_table* protocol_sock::get_table() { static protocol_sock_table table; return &table; } protocol_sock::protocol_sock(protocol *proto, std::string name, int flags, int type) : proto(proto), name(name), flags(flags), type(type) { get_map()->insert(std::pair<protocol_name_pair,protocol_sock*>(protocol_name_pair(proto, name), this)); get_table()->push_back(this); if (protocol::debug) { log_debug("protocol_sock type=0x%08x %s (flags=0x%08x)", type, to_string().c_str(), flags); } } std::string protocol_sock::to_string() const { return proto ? format_string("%s_sock_%s", proto->name.c_str(), name.c_str()) : name; } /* protocol_action */ protocol_action_map* protocol_action::get_map() { static protocol_action_map map; return &map; } protocol_action_table* protocol_action::get_table() { static protocol_action_table table; return &table; } protocol_action::protocol_action(protocol *proto, std::string name, protocol_cb *callback, int action) : proto(proto), name(name), callback(callback), action(action) { get_map()->insert(std::pair<protocol_name_pair,protocol_action*>(protocol_name_pair(proto, name), this)); get_table()->push_back(this); if (protocol::debug) { log_debug("protocol_action action=0x%08x %s", action, to_string().c_str()); } } std::string protocol_action::to_string() const { return proto ? format_string("%s_action_%s", proto->name.c_str(), name.c_str()) : name; } /* protocol_mask */ protocol_mask_map* protocol_mask::get_map() { static protocol_mask_map map; return &map; } protocol_mask_table* protocol_mask::get_table() { static protocol_mask_table table; return &table; } protocol_mask::protocol_mask(protocol *proto, std::string name, int offset, int mask) : proto(proto), name(name), offset(offset), mask(mask) { get_map()->insert(std::pair<protocol_name_pair,protocol_mask*>(protocol_name_pair(proto, name), this)); get_table()->push_back(this); if (protocol::debug) { log_debug("protocol_mask mask=0x%08x %s", mask, to_string().c_str()); } } std::string protocol_mask::to_string() const { return proto ? format_string("%s_mask_%s", proto->name.c_str(), name.c_str()) : name; } /* protocol_state */ protocol_state_map* protocol_state::get_map() { static protocol_state_map map; return &map; } protocol_state_table* protocol_state::get_table() { static protocol_state_table table; return &table; } protocol_state::protocol_state(protocol *proto, std::string name, protocol_cb *callback, int state) : proto(proto), name(name), callback(callback), state(state) { get_map()->insert(std::pair<protocol_name_pair,protocol_state*>(protocol_name_pair(proto, name), this)); get_table()->push_back(this); if (protocol::debug) { log_debug("protocol_state state=0x%08x %s", state, to_string().c_str()); } } std::string protocol_state::to_string() const { return proto ? format_string("%s_connection_%s", proto->name.c_str(), name.c_str()) : name; } /* protocol_message */ protocol_message::protocol_message() : action(-1), connection_num(-1) {} protocol_message::protocol_message(int action, int connection_num) : action(action), connection_num(connection_num) {} std::string protocol_message::to_string() const { return format_string("%s connection-%d", protocol_action::get_table()->at(action)->to_string().c_str(), connection_num); } /* protocol_config */ bool protocol_config::lookup_config_fn(std::string key, config_record &record) { auto it = config_fn_map.find(key); if (it != config_fn_map.end()) { record = it->second; return true; } return false; } bool protocol_config::lookup_block_start_fn(std::string key, block_record &record) { auto it = block_start_fn_map.find(key); if (it != block_start_fn_map.end()) { record = it->second; return true; } return false; } bool protocol_config::lookup_block_end_fn(std::string key, block_record &record) { auto it = block_end_fn_map.find(key); if (it != block_end_fn_map.end()) { record = it->second; return true; } return false; } /* protocol */ protocol protocol::proto_none("none"); protocol_sock protocol::sock_none(nullptr, "none", protocol_sock_none); protocol_sock protocol::sock_ipc(nullptr, "ipc", protocol_sock_unix_ipc); protocol_action protocol::action_none(nullptr, "none"); protocol_state protocol::state_none(nullptr, "none"); bool protocol::debug = false; std::once_flag protocol::protocol_init; protocol_map* protocol::get_map() { static protocol_map map; return &map; } protocol_table* protocol::get_table() { static protocol_table table; return &table; } protocol::protocol(std::string name, int proto) : name(name), proto(proto) { get_map()->insert(std::pair<std::string,protocol*>(name, this)); get_table()->push_back(this); if (protocol::debug) { log_debug("protocol proto=0x%08x %s", proto, name.c_str()); } } std::string protocol::to_string() const { return name; } void protocol::init() { std::call_once(protocol_init, [](){ http_client::get_proto()->proto_init(); http_server::get_proto()->proto_init(); }); }
metaparadigm/latypus
src/protocol.cc
C++
isc
6,994
#include <stdio.h> typedef union _bar { int c; double d; } bar; typedef struct _foo { int a; int b; bar c; int e; } foo; int main (int argc, char **argv) { printf("sizeof(int) = %d\n", sizeof(int)); printf("sizeof(double) = %d\n", sizeof(long)); printf("sizeof(bar) = %d\n", sizeof(bar)); printf("sizeof(foo) = %d\n", sizeof(foo)); bar b1 = { .c = 2 }; bar b2 = { .d = 4.0 }; printf("sizeof(b1) = %d\n", sizeof(b1)); printf("sizeof(b2) = %d\n", sizeof(b2)); foo f1 = { .a = 1, .b = 2, .c = b1, .e = 1 }; foo f2 = { .a = 1, .b = 2, .c = b2, .e = 1 }; printf("sizeof(f1) = %d\n", sizeof(f1)); printf("sizeof(f2) = %d\n", sizeof(f2)); return 0; }
fredmorcos/attic
snippets/c/union-size.c
C
isc
699
/* $Id: dns.nc 45 2007-04-09 04:05:23Z mark $ */ /* * Copyright (c) 2004, 2005, 2006, 2007 Mark Heily <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /** @file DNS stub resolver. */ #include "config.h" #include <errno.h> #include <netdb.h> #include "nc_exception.h" #include "nc_file.h" #include "nc_log.h" #include "nc_list.h" #include "nc_hash.h" #include "nc_host.h" //#include "nc_options.h" #include "nc_socket.h" #include "nc_string.h" #include "nc_thread.h" #include "nc_dns.h" /* Splint cannot parse these system header files */ #ifndef S_SPLINT_S #include <arpa/nameser.h> #if HAVE_ARPA_NAMESER_COMPAT_H #include <arpa/nameser_compat.h> #endif #include <resolv.h> #endif /* GLOBAL PRIVATE VARIABLES */ /** Set to true after the library has been initialized */ static bool DNS_LIB_INIT = false; /** Global DNS resolver mutex. * * This mutex should be acquired before any calls to non-reentrant * resolver routines, including getaddrinfo(3) and gethostbyname(3). */ mutex_t DNS_RESOLVER_MUTEX = MUTEX_INITIALIZER; /** * * Initialize the DNS stub resolver library. * * Runs a gethostname(2) and getaddrinfo(3) query. * This should ensure that the resolver libraries are loaded * into memory prior to a chroot(2) call. * */ int dns_library_init(void) { list_t *result; string_t *buf; /* Don't initialize the library twice */ if (DNS_LIB_INIT) return 0; /* Ensure that the local hostname is preloaded */ host_get_name(buf); /* Ensure that 'gethostbyname' is preloaded */ (void) gethostbyname("localhost"); /* Run a DNS lookup prior to chroot(2) but ignore the response */ str_cpy(buf, "netsol.com"); (void) dns_get_inet_by_name(result, buf); DNS_LIB_INIT = true; } /** @todo WORKAROUND: Splint doesn't like this function, so skip it.. */ #ifndef S_SPLINT_S /** * * Get a list of the MX records for a domain. * * Caveats: the caller must invoke free_mx_list() when finished * * @param dest list that will store the result * @param domain domain name to look up the MX records for * * @see http://www.woodmann.com/fravia/DNS.htm * */ int dns_get_mx_list(list_t *dest, const string_t *domain) { union { HEADER hdr; unsigned char buf[PACKETSZ]; } response; HEADER *hp; int pkt_len, len; unsigned int i, answer_count; char buf[MAXDNAME + 1]; unsigned char *cp, *end; string_t str_p = EMPTY_STRING; //string_t *item; unsigned short rec_type, rec_len, rec_pref; require (str_len(domain) > 0); /* Initialize variables */ memset(&buf, 0, sizeof(buf)); /* Remove any previous values in the list */ list_truncate(dest); #if FIXME /** @todo move this to smtp/queue.c to not pollute this library module */ /* Special case: if RELAYHOST is defined, use it */ hash_key_exists(&match, options, "relayhost"); if (options != NULL && match) { hash_get(item, options, "relayhost"); list_push(dest, item); return 0; } #endif /* Lookup the MX records for <domain> */ log_debug("looking up MX record for `%s'", domain->value); pkt_len = res_query(domain->value, C_IN, T_MX, (unsigned char *) &response, sizeof(response)); if (pkt_len < 0) return dns_log_error(domain->value, "MX lookup failed"); if ((unsigned long) pkt_len > sizeof(response)) throw("DNS response too large"); /* Move <cp> to the answer portion.. */ /* Skip the header portion */ hp = (HEADER *) &response; cp = (unsigned char *) &response + HFIXEDSZ; end = (unsigned char *) &response + pkt_len; /* Skip over each question */ i = ntohs((unsigned short)hp->qdcount); while (i > 0) { if ((len = dn_skipname(cp, end)) < 0) throw("bad hostname in question portion of dns packet"); cp += len + QFIXEDSZ; i--; } /* Process each answer */ answer_count = ntohs((unsigned short)hp->ancount); for (i = 0; i < answer_count; i++) { len = -1; len = dn_expand((unsigned char *) &response, end, cp, (char *) &buf, sizeof(buf) - 1); if (len < 0) throw("error expanding hostname in answer portion"); if (strncmp(buf, domain->value, strlen(domain->value) + 1) != 0) throw("extraneous response"); /* Jump to the record type */ cp += len; /* Check the record type */ GETSHORT(rec_type, cp); if (rec_type != T_MX) throw("bad response record: expecting type MX"); /* Skip over the class and TTL entries */ cp += INT16SZ + INT32SZ; /* Get the RR length and MX pref */ GETSHORT(rec_len, cp); GETSHORT(rec_pref, cp); //log_debug("mx pref == %d", rec_pref); /* Decode the MX hostname */ len = -1; len = dn_expand((unsigned char *) &response, end, cp, (char *) &buf, sizeof(buf) - 1); if (len < 0) throw("error decompressing RR"); /* Add the MX record to the list */ str_alias(&str_p, buf); list_push(dest, &str_p); /* Jump to the next record */ cp += len; } /** @todo Sort the resulting MX list by priority */ } #endif /** * * Print an error message to the system log along with a DNS error message. * * @param domain the domain name that caused the lookup error * @param message additional information to be appended to the log message * */ int dns_log_error(const char *domain, const char *message) { size_t sz = PATH_MAX; char buf[PATH_MAX + 1]; memset(&buf, 0, sizeof(buf)); switch (h_errno) { case HOST_NOT_FOUND: (void) snprintf((char *) &buf, sz, "Host not found"); break; case NO_DATA: (void) snprintf((char *) &buf, sz, "No records found"); break; case TRY_AGAIN: (void) snprintf((char *) &buf, sz, "No response"); break; default: (void) snprintf((char *) &buf, sz, "Unknown error"); } /* Print an error message to the system log */ log_error("%s: error: %s: %s\n", message, (char *) &buf, domain); /* This function always returns -1 */ throw("caught DNS error"); } /** * * Get a list of the system's DNS name servers from /etc/resolv.conf * * @param dest list that will store the result of the lookup operation * */ int dns_get_nameservers(list_t *dest) { list_entry_t *cur = NULL; string_t *line = NULL; string_t *buf, *path, *ns; list_t *lines; bool match; list_truncate(dest); str_cpy(path, "/etc/resolv.conf"); file_read(buf, path); str_split(lines, buf, '\n'); /* Examine each line */ for (cur = lines->head; cur; cur = cur->next) { line = cur->value; /* Skip lines that don't start with 'nameserver' */ str_match_regex(&match, line, "^nameserver"); if (!match) continue; /* Parse the nameserver value and add it to the list */ str_str_regex(line, "nameserver" "[[:space:]]+" "([A-Za-z0-9._-]+)" "[[:space:]]*$", ns, NULL); list_push(dest, ns); } } /** * Convert a protocol name into a numeric port number by consulting /etc/services. * @param dest pointer to an integer that will store the result * @param name official name of the service * @param proto protocol to use when contacting the service (tcp or udp) * */ int dns_get_service_by_name(int *dest, char_t *name, char_t *proto) { struct servent *ent; struct servent ent_copy; /* Query /etc/services in a threadsafe manner */ mutex_lock(DNS_RESOLVER_MUTEX); ent = getservbyname(name, proto); if (ent != NULL) memcpy(&ent_copy, ent, sizeof(ent_copy)); mutex_unlock(DNS_RESOLVER_MUTEX); /* Check for errors */ if (ent == NULL) throw_errno("getservbyname(3)"); *dest = ntohs(ent_copy.s_port); } /** * * Lookup the A records for a host and store the IP addresses in a list. * * @param dest list that will contain the resulting IP addresses * @param host fully qualified domain name to query * */ int dns_get_inet_by_name(list_t *dest, const string_t *host) { struct addrinfo *ai, *ai_list; struct addrinfo hint; struct sockaddr_in *sa; string_t *buf; int gai_errno; /* Initialize variables */ ai_list = NULL; memset(&hint,0,sizeof(struct addrinfo)); hint.ai_family = AF_INET; hint.ai_socktype = SOCK_STREAM; list_truncate(dest); /* Get the address of the remote host */ mutex_lock(DNS_RESOLVER_MUTEX); gai_errno = getaddrinfo(host->value, NULL, &hint, &ai_list); mutex_unlock(DNS_RESOLVER_MUTEX); if (gai_errno != 0) { log_error("while resolving `%s' ...", host->value); throwf("getaddrinfo(3): %s: %s", host, gai_strerror(gai_errno)); } /* Build a list containing each possible IP address */ for ( ai = ai_list; ai != NULL; ai = ai->ai_next) { sa = (struct sockaddr_in *) ai->ai_addr; str_from_inet(buf, sa->sin_addr); list_push(dest, buf); } finally: if (ai_list != NULL) freeaddrinfo(ai_list); } /** * Ping one or more DNS blocklists to make sure they are alive. * * Blocklists are supposed to respond affirmatively to any queries * for 127.0.0.1. Any blocklist that does not answer will be removed * from the list. * * @param list list of DNSBL hostnames * @see dns_query_blocklist() */ int dns_ping_blocklist(list_t *dnsbl) { list_entry_t *cur = NULL; string_t *suffix = NULL; string_t *query; list_t *valid; struct hostent *answer = NULL; int rc; /* For each DNSBL domain ... */ for (cur = dnsbl->head; cur; cur = cur->next) { /* Generate an A record query */ suffix = cur->value; str_sprintf(query, "2.0.0.127.%s", suffix->value); /* Call gethostbyname(3) to determine if the client is listed */ mutex_lock(DNS_RESOLVER_MUTEX); answer = gethostbyname(query->value); rc = h_errno; mutex_unlock(DNS_RESOLVER_MUTEX); /* Check for authoritative "host not found" responses */ if (answer == NULL && rc == HOST_NOT_FOUND) { log_warning("DNSBL `%s' appears to be down; it will not be used", suffix->value); } else { list_push(valid, suffix); } } /* Replace the input list with the list of valid DNSBL addresses */ list_truncate(dnsbl); list_copy(dnsbl, valid); } /** * Query one or more DNS blocklists for the IP address of the client. * * @param result result of the lookup; true, if the client is listed * @param dnsbl list of DNSBL domain names to query (e.g. `bl.spamcop.net') * @param sock socket with an active client * @see dns_ping_blocklist() */ int dns_query_blocklist(bool *result, list_t *dnsbl, const socket_t *sock) { list_entry_t *cur = NULL; string_t *domain = NULL; struct hostent *answer = NULL; string_t *addr, *rev_addr, *query; list_t *quad; int rc; *result = false; /* Generate the forward and reverse address strings */ str_from_inet(addr, sock->remote.in.sin_addr); str_split(quad, addr, '.'); list_reverse(quad); str_join(rev_addr, quad, '.'); log_debug2("addr=`%s' rev_addr=`%s'", addr->value, rev_addr->value); /* For each DNSBL domain .. */ for (cur = dnsbl->head; cur; cur = cur->next) { domain = cur->value; /* Combine the reverse address and the DNSBL domain */ str_sprintf(query, "%s.%s", rev_addr->value, domain->value); log_debug2("query=`%s'", query->value); /* Call gethostbyname(3) to determine if the client is listed */ mutex_lock(DNS_RESOLVER_MUTEX); answer = gethostbyname(query->value); rc = h_errno; mutex_unlock(DNS_RESOLVER_MUTEX); /* If there was an answer, stop looking. */ if (answer != NULL) { *result = true; break; } } } /** * Get the TXT record(s) associated with a hostname. * * @param result buffer to store the result * @param name hostname to look up the TXT record for * @bug doesn't handle multiple responses */ int dns_get_txt_record(list_t *dest, const string_t *host) { unsigned char response[PACKETSZ]; char buf[128]; //HEADER *hp; unsigned char *cp, *end; int pkt_len, exp_len; int ans_type, ans_size, txt_size; int ttl; string_t *s; /* Initialize variables */ memset(&response, 0, sizeof(response)); list_truncate(dest); pkt_len = res_search(host->value, C_IN, T_TXT, (unsigned char *) &response, sizeof(response)); if (pkt_len < 0) return dns_log_error(host->value, "TXT lookup failed"); /* Setup pointers to parts of the response */ cp = ((unsigned char *) &response); end = (unsigned char *) &response + pkt_len; /* Skip over the header */ cp += sizeof(HEADER); /* Uncompress and skip the question portion */ exp_len = dn_expand(response, response + pkt_len, cp, buf, sizeof(buf)); if (exp_len < 0) throw("dn_expand(3) failed"); cp += exp_len; #if TODO // This doesn't work because the *hp (HEADER struct) gives nonsense values /* Process each answer */ log_warning("processing %u answers", (unsigned short) hp->ancount); for (i = 0; i < (unsigned short) hp->ancount; i++) { #endif /* Make sure the answer is of type T_TXT */ GETSHORT(ans_type, cp); if (ans_type != T_TXT) throwf("invalid answer type: %d", ans_type); /* Ignore the `class' field */ cp += INT16SZ; /* Uncompress the answer portion */ exp_len = dn_expand(response, response + pkt_len, cp, buf, sizeof(buf)); if (exp_len < 0) throw("dn_expand(3) failed"); cp += exp_len; /* Make sure the answer is of type T_TXT */ GETSHORT(ans_type, cp); if (ans_type != T_TXT) throwf("invalid answer type: %d", ans_type); /* Ignore the `class' field */ cp += INT16SZ; /* Get the `TTL' and `size' fields */ GETLONG(ttl, cp); GETSHORT(ans_size, cp); txt_size = (int) *cp++; if (txt_size >= ans_size || !txt_size) throw("invalid TXT response"); /* Add the result to the list */ str_ncpy(s, (char *) cp, (size_t) txt_size); list_push(dest, s); //log_warning("resolver: txt=`%s'", s->value); #if TODO } #endif /** @bug some hosts (e.g. AOL) have more than 1 txt record, not handled yet */ }
mheily/naturalc
dns.c
C
isc
14,304
/* $OpenBSD: prcm.c,v 1.9 2014/05/08 21:17:01 miod Exp $ */ /* * Copyright (c) 2007,2009 Dale Rahn <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /*- * Copyright (c) 2011 * Ben Gray <[email protected]>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the company nor the name of the author may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY BEN GRAY ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL BEN GRAY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Driver for the Power, Reset and Clock Management Module (PRCM). */ #include <sys/types.h> #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/time.h> #include <sys/device.h> #include <machine/bus.h> #include <machine/intr.h> #include <arm/cpufunc.h> #include <armv7/armv7/armv7var.h> #include <armv7/omap/prcmvar.h> #include <armv7/omap/am335x_prcmreg.h> #include <armv7/omap/omap3_prcmreg.h> #include <armv7/omap/omap4_prcmreg.h> #define PRCM_REVISION 0x0800 #define PRCM_SYSCONFIG 0x0810 uint32_t prcm_imask_mask[PRCM_REG_MAX]; uint32_t prcm_fmask_mask[PRCM_REG_MAX]; uint32_t prcm_imask_addr[PRCM_REG_MAX]; uint32_t prcm_fmask_addr[PRCM_REG_MAX]; #define SYS_CLK 13 /* SYS_CLK speed in MHz */ struct prcm_softc { struct device sc_dev; bus_space_tag_t sc_iot; bus_space_handle_t sc_prcm; bus_space_handle_t sc_cm1; bus_space_handle_t sc_cm2; void (*sc_setup)(struct prcm_softc *sc); void (*sc_enablemodule)(struct prcm_softc *sc, int mod); void (*sc_setclock)(struct prcm_softc *sc, int clock, int speed); uint32_t cm1_avail; uint32_t cm2_avail; }; int prcm_match(struct device *, void *, void *); void prcm_attach(struct device *, struct device *, void *); int prcm_setup_dpll5(struct prcm_softc *); uint32_t prcm_v3_bit(int mod); uint32_t prcm_am335x_clkctrl(int mod); void prcm_am335x_enablemodule(struct prcm_softc *, int); void prcm_am335x_setclock(struct prcm_softc *, int, int); void prcm_v3_setup(struct prcm_softc *); void prcm_v3_enablemodule(struct prcm_softc *, int); void prcm_v3_setclock(struct prcm_softc *, int, int); void prcm_v4_enablemodule(struct prcm_softc *, int); int prcm_v4_hsusbhost_activate(int); int prcm_v4_hsusbhost_set_source(int, int); struct cfattach prcm_ca = { sizeof (struct prcm_softc), NULL, prcm_attach }; struct cfdriver prcm_cd = { NULL, "prcm", DV_DULL }; void prcm_attach(struct device *parent, struct device *self, void *args) { struct armv7_attach_args *aa = args; struct prcm_softc *sc = (struct prcm_softc *) self; u_int32_t reg; sc->sc_iot = aa->aa_iot; switch (board_id) { case BOARD_ID_AM335X_BEAGLEBONE: sc->sc_setup = NULL; sc->sc_enablemodule = prcm_am335x_enablemodule; sc->sc_setclock = prcm_am335x_setclock; break; case BOARD_ID_OMAP3_BEAGLE: case BOARD_ID_OMAP3_OVERO: sc->sc_setup = prcm_v3_setup; sc->sc_enablemodule = prcm_v3_enablemodule; sc->sc_setclock = prcm_v3_setclock; break; case BOARD_ID_OMAP4_PANDA: sc->sc_setup = NULL; sc->sc_enablemodule = prcm_v4_enablemodule; sc->sc_setclock = NULL; sc->cm1_avail = 1; sc->cm2_avail = 1; break; } if (bus_space_map(sc->sc_iot, aa->aa_dev->mem[0].addr, aa->aa_dev->mem[0].size, 0, &sc->sc_prcm)) panic("prcm_attach: bus_space_map failed!"); if (sc->cm1_avail && bus_space_map(sc->sc_iot, aa->aa_dev->mem[1].addr, aa->aa_dev->mem[1].size, 0, &sc->sc_cm1)) panic("prcm_attach: bus_space_map failed!"); if (sc->cm2_avail && bus_space_map(sc->sc_iot, aa->aa_dev->mem[2].addr, aa->aa_dev->mem[2].size, 0, &sc->sc_cm2)) panic("prcm_attach: bus_space_map failed!"); reg = bus_space_read_4(sc->sc_iot, sc->sc_prcm, PRCM_REVISION); printf(" rev %d.%d\n", reg >> 4 & 0xf, reg & 0xf); if (sc->sc_setup != NULL) sc->sc_setup(sc); } void prcm_v3_setup(struct prcm_softc *sc) { /* Setup the 120MHZ DPLL5 clock, to be used by USB. */ prcm_setup_dpll5(sc); prcm_fmask_mask[PRCM_REG_CORE_CLK1] = PRCM_REG_CORE_CLK1_FMASK; prcm_imask_mask[PRCM_REG_CORE_CLK1] = PRCM_REG_CORE_CLK1_IMASK; prcm_fmask_addr[PRCM_REG_CORE_CLK1] = PRCM_REG_CORE_CLK1_FADDR; prcm_imask_addr[PRCM_REG_CORE_CLK1] = PRCM_REG_CORE_CLK1_IADDR; prcm_fmask_mask[PRCM_REG_CORE_CLK2] = PRCM_REG_CORE_CLK2_FMASK; prcm_imask_mask[PRCM_REG_CORE_CLK2] = PRCM_REG_CORE_CLK2_IMASK; prcm_fmask_addr[PRCM_REG_CORE_CLK2] = PRCM_REG_CORE_CLK2_FADDR; prcm_imask_addr[PRCM_REG_CORE_CLK2] = PRCM_REG_CORE_CLK2_IADDR; prcm_fmask_mask[PRCM_REG_CORE_CLK3] = PRCM_REG_CORE_CLK3_FMASK; prcm_imask_mask[PRCM_REG_CORE_CLK3] = PRCM_REG_CORE_CLK3_IMASK; prcm_fmask_addr[PRCM_REG_CORE_CLK3] = PRCM_REG_CORE_CLK3_FADDR; prcm_imask_addr[PRCM_REG_CORE_CLK3] = PRCM_REG_CORE_CLK3_IADDR; prcm_fmask_mask[PRCM_REG_WKUP] = PRCM_REG_WKUP_FMASK; prcm_imask_mask[PRCM_REG_WKUP] = PRCM_REG_WKUP_IMASK; prcm_fmask_addr[PRCM_REG_WKUP] = PRCM_REG_WKUP_FADDR; prcm_imask_addr[PRCM_REG_WKUP] = PRCM_REG_WKUP_IADDR; prcm_fmask_mask[PRCM_REG_PER] = PRCM_REG_PER_FMASK; prcm_imask_mask[PRCM_REG_PER] = PRCM_REG_PER_IMASK; prcm_fmask_addr[PRCM_REG_PER] = PRCM_REG_PER_FADDR; prcm_imask_addr[PRCM_REG_PER] = PRCM_REG_PER_IADDR; prcm_fmask_mask[PRCM_REG_USBHOST] = PRCM_REG_USBHOST_FMASK; prcm_imask_mask[PRCM_REG_USBHOST] = PRCM_REG_USBHOST_IMASK; prcm_fmask_addr[PRCM_REG_USBHOST] = PRCM_REG_USBHOST_FADDR; prcm_imask_addr[PRCM_REG_USBHOST] = PRCM_REG_USBHOST_IADDR; } void prcm_setclock(int clock, int speed) { struct prcm_softc *sc = prcm_cd.cd_devs[0]; if (!sc->sc_setclock) panic("%s: not initialised!", __func__); sc->sc_setclock(sc, clock, speed); } void prcm_am335x_setclock(struct prcm_softc *sc, int clock, int speed) { u_int32_t oreg, reg, mask; /* set CLKSEL register */ if (clock == 1) { oreg = bus_space_read_4(sc->sc_iot, sc->sc_prcm, PRCM_AM335X_CLKSEL_TIMER2_CLK); mask = 3; reg = oreg & ~mask; reg |=0x02; bus_space_write_4(sc->sc_iot, sc->sc_prcm, PRCM_AM335X_CLKSEL_TIMER2_CLK, reg); } else if (clock == 2) { oreg = bus_space_read_4(sc->sc_iot, sc->sc_prcm, PRCM_AM335X_CLKSEL_TIMER3_CLK); mask = 3; reg = oreg & ~mask; reg |=0x02; bus_space_write_4(sc->sc_iot, sc->sc_prcm, PRCM_AM335X_CLKSEL_TIMER3_CLK, reg); } } void prcm_v3_setclock(struct prcm_softc *sc, int clock, int speed) { u_int32_t oreg, reg, mask; if (clock == 1) { oreg = bus_space_read_4(sc->sc_iot, sc->sc_prcm, CM_CLKSEL_WKUP); mask = 1; reg = (oreg &~mask) | (speed & mask); bus_space_write_4(sc->sc_iot, sc->sc_prcm, CM_CLKSEL_WKUP, reg); } else if (clock >= 2 && clock <= 9) { int shift = (clock-2); oreg = bus_space_read_4(sc->sc_iot, sc->sc_prcm, CM_CLKSEL_PER); mask = 1 << (shift); reg = (oreg & ~mask) | ( (speed << shift) & mask); bus_space_write_4(sc->sc_iot, sc->sc_prcm, CM_CLKSEL_PER, reg); } else panic("%s: invalid clock %d", __func__, clock); } uint32_t prcm_v3_bit(int mod) { switch(mod) { case PRCM_MMC0: return PRCM_CLK_EN_MMC1; case PRCM_MMC1: return PRCM_CLK_EN_MMC2; case PRCM_MMC2: return PRCM_CLK_EN_MMC3; case PRCM_USB: return PRCM_CLK_EN_USB; case PRCM_GPIO0: return PRCM_CLK_EN_GPIO1; case PRCM_GPIO1: return PRCM_CLK_EN_GPIO2; case PRCM_GPIO2: return PRCM_CLK_EN_GPIO3; case PRCM_GPIO3: return PRCM_CLK_EN_GPIO4; case PRCM_GPIO4: return PRCM_CLK_EN_GPIO5; case PRCM_GPIO5: return PRCM_CLK_EN_GPIO6; default: panic("%s: module not found\n", __func__); } } uint32_t prcm_am335x_clkctrl(int mod) { switch(mod) { case PRCM_TIMER2: return PRCM_AM335X_TIMER2_CLKCTRL; case PRCM_TIMER3: return PRCM_AM335X_TIMER3_CLKCTRL; case PRCM_MMC0: return PRCM_AM335X_MMC0_CLKCTRL; case PRCM_MMC1: return PRCM_AM335X_MMC1_CLKCTRL; case PRCM_MMC2: return PRCM_AM335X_MMC2_CLKCTRL; case PRCM_USB: return PRCM_AM335X_USB0_CLKCTRL; case PRCM_GPIO0: return PRCM_AM335X_GPIO0_CLKCTRL; case PRCM_GPIO1: return PRCM_AM335X_GPIO1_CLKCTRL; case PRCM_GPIO2: return PRCM_AM335X_GPIO2_CLKCTRL; case PRCM_GPIO3: return PRCM_AM335X_GPIO3_CLKCTRL; case PRCM_TPCC: return PRCM_AM335X_TPCC_CLKCTRL; case PRCM_TPTC0: return PRCM_AM335X_TPTC0_CLKCTRL; case PRCM_TPTC1: return PRCM_AM335X_TPTC1_CLKCTRL; case PRCM_TPTC2: return PRCM_AM335X_TPTC2_CLKCTRL; case PRCM_I2C0: return PRCM_AM335X_I2C0_CLKCTRL; case PRCM_I2C1: return PRCM_AM335X_I2C1_CLKCTRL; case PRCM_I2C2: return PRCM_AM335X_I2C2_CLKCTRL; default: panic("%s: module not found\n", __func__); } } void prcm_enablemodule(int mod) { struct prcm_softc *sc = prcm_cd.cd_devs[0]; if (!sc->sc_enablemodule) panic("%s: not initialised!", __func__); sc->sc_enablemodule(sc, mod); } void prcm_am335x_enablemodule(struct prcm_softc *sc, int mod) { uint32_t clkctrl; int reg; /*set enable bits in CLKCTRL register */ reg = prcm_am335x_clkctrl(mod); clkctrl = bus_space_read_4(sc->sc_iot, sc->sc_prcm, reg); clkctrl &=~AM335X_CLKCTRL_MODULEMODE_MASK; clkctrl |= AM335X_CLKCTRL_MODULEMODE_ENABLE; bus_space_write_4(sc->sc_iot, sc->sc_prcm, reg, clkctrl); /* wait until module is enabled */ while (bus_space_read_4(sc->sc_iot, sc->sc_prcm, reg) & 0x30000) ; } void prcm_v3_enablemodule(struct prcm_softc *sc, int mod) { uint32_t bit; uint32_t fclk, iclk, fmask, imask, mbit; int freg, ireg, reg; bit = prcm_v3_bit(mod); reg = bit >> 5; freg = prcm_fmask_addr[reg]; ireg = prcm_imask_addr[reg]; fmask = prcm_fmask_mask[reg]; imask = prcm_imask_mask[reg]; mbit = 1 << (bit & 0x1f); if (fmask & mbit) { /* dont access the register if bit isn't present */ fclk = bus_space_read_4(sc->sc_iot, sc->sc_prcm, freg); bus_space_write_4(sc->sc_iot, sc->sc_prcm, freg, fclk | mbit); } if (imask & mbit) { /* dont access the register if bit isn't present */ iclk = bus_space_read_4(sc->sc_iot, sc->sc_prcm, ireg); bus_space_write_4(sc->sc_iot, sc->sc_prcm, ireg, iclk | mbit); } printf("\n"); } void prcm_v4_enablemodule(struct prcm_softc *sc, int mod) { switch (mod) { case PRCM_MMC0: break; case PRCM_USBP1_PHY: case PRCM_USBP2_PHY: prcm_v4_hsusbhost_set_source(mod, 0); case PRCM_USB: case PRCM_USBTLL: case PRCM_USBP1_UTMI: case PRCM_USBP1_HSIC: case PRCM_USBP2_UTMI: case PRCM_USBP2_HSIC: prcm_v4_hsusbhost_activate(mod); return; case PRCM_GPIO0: case PRCM_GPIO1: case PRCM_GPIO2: case PRCM_GPIO3: case PRCM_GPIO4: case PRCM_GPIO5: /* XXX */ break; default: panic("%s: module not found\n", __func__); } } int prcm_v4_hsusbhost_activate(int type) { struct prcm_softc *sc = prcm_cd.cd_devs[0]; uint32_t i; uint32_t clksel_reg_off; uint32_t clksel, oclksel; switch (type) { case PRCM_USB: case PRCM_USBP1_PHY: case PRCM_USBP2_PHY: /* We need the CM_L3INIT_HSUSBHOST_CLKCTRL register in CM2 register set */ clksel_reg_off = O4_L3INIT_CM2_OFFSET + 0x58; clksel = bus_space_read_4(sc->sc_iot, sc->sc_cm2, clksel_reg_off); oclksel = clksel; /* Enable the module and also enable the optional func clocks */ if (type == PRCM_USB) { clksel &= ~O4_CLKCTRL_MODULEMODE_MASK; clksel |= /*O4_CLKCTRL_MODULEMODE_ENABLE*/2; clksel |= (0x1 << 15); /* USB-HOST clock control: FUNC48MCLK */ } break; default: panic("%s: invalid type %d", __func__, type); return (EINVAL); } bus_space_write_4(sc->sc_iot, sc->sc_cm2, clksel_reg_off, clksel); /* Try MAX_MODULE_ENABLE_WAIT number of times to check if enabled */ for (i = 0; i < O4_MAX_MODULE_ENABLE_WAIT; i++) { clksel = bus_space_read_4(sc->sc_iot, sc->sc_cm2, clksel_reg_off); if ((clksel & O4_CLKCTRL_IDLEST_MASK) == O4_CLKCTRL_IDLEST_ENABLED) break; } /* Check the enabled state */ if ((clksel & O4_CLKCTRL_IDLEST_MASK) != O4_CLKCTRL_IDLEST_ENABLED) { printf("Error: HERE failed to enable module with clock %d\n", type); printf("Error: 0x%08x => 0x%08x\n", clksel_reg_off, clksel); return (ETIMEDOUT); } return (0); } int prcm_v4_hsusbhost_set_source(int clk, int clksrc) { struct prcm_softc *sc = prcm_cd.cd_devs[0]; uint32_t clksel_reg_off; uint32_t clksel; unsigned int bit; if (clk == PRCM_USBP1_PHY) bit = 24; else if (clk != PRCM_USBP2_PHY) bit = 25; else return (-EINVAL); /* We need the CM_L3INIT_HSUSBHOST_CLKCTRL register in CM2 register set */ clksel_reg_off = O4_L3INIT_CM2_OFFSET + 0x58; clksel = bus_space_read_4(sc->sc_iot, sc->sc_cm2, clksel_reg_off); /* XXX: Set the clock source to either external or internal */ if (clksrc == 0) clksel |= (0x1 << bit); else clksel &= ~(0x1 << bit); bus_space_write_4(sc->sc_iot, sc->sc_cm2, clksel_reg_off, clksel); return (0); } /* * OMAP35xx Power, Reset, and Clock Management Reference Guide * (sprufa5.pdf) and AM/DM37x Multimedia Device Technical Reference * Manual (sprugn4h.pdf) note that DPLL5 provides a 120MHz clock for * peripheral domain modules (page 107 and page 302). * The reference clock for DPLL5 is DPLL5_ALWON_FCLK which is * SYS_CLK, running at 13MHz. */ int prcm_setup_dpll5(struct prcm_softc *sc) { uint32_t val; /* * We need to set the multiplier and divider values for PLL. * To end up with 120MHz we take SYS_CLK, divide by it and multiply * with 120 (sprugn4h.pdf, 13.4.11.4.1 SSC Configuration) */ val = ((120 & 0x7ff) << 8) | ((SYS_CLK - 1) & 0x7f); bus_space_write_4(sc->sc_iot, sc->sc_prcm, CM_CLKSEL4_PLL, val); /* Clock divider from the PLL to the 120MHz clock. */ bus_space_write_4(sc->sc_iot, sc->sc_prcm, CM_CLKSEL5_PLL, val); /* * spruf98o.pdf, page 2319: * PERIPH2_DPLL_FREQSEL is 0x7 1.75MHz to 2.1MHz * EN_PERIPH2_DPLL is 0x7 */ val = (7 << 4) | (7 << 0); bus_space_write_4(sc->sc_iot, sc->sc_prcm, CM_CLKEN2_PLL, val); /* Disable the interconnect clock auto-idle. */ bus_space_write_4(sc->sc_iot, sc->sc_prcm, CM_AUTOIDLE2_PLL, 0x0); /* Wait until DPLL5 is locked and there's clock activity. */ while ((val = bus_space_read_4(sc->sc_iot, sc->sc_prcm, CM_IDLEST_CKGEN) & 0x01) == 0x00) { #ifdef DIAGNOSTIC printf("CM_IDLEST_PLL = 0x%08x\n", val); #endif } return 0; }
orumin/openbsd-efivars
arch/armv7/omap/prcm.c
C
isc
15,850
<?php $magicWords = array(); $magicWords['en'] = array( 'currentlang' => array( 0, 'CurrentLang', 'CurrentLanguage', 'CurrLang' ), 'currentlang-desc' => "Adds a {{CURRENTLANG}} magic word for the currently used language code" ); ?>
zuzak/mw-langcode-magic
LanguageCodeMagicWord.i18n.php
PHP
isc
238
module.exports = { alt: require('./alt'), ap: require('./ap'), bimap: require('./bimap'), bichain: require('./bichain'), both: require('./both'), chain: require('./chain'), coalesce: require('./coalesce'), compareWith: require('./compareWith'), concat: require('./concat'), cons: require('./cons'), contramap: require('./contramap'), either: require('./either'), empty: require('./empty'), equals: require('./equals'), extend: require('./extend'), filter: require('./filter'), first: require('./first'), fold: require('./fold'), foldMap: require('./foldMap'), head: require('./head'), init: require('./init'), last: require('./last'), map: require('./map'), merge: require('./merge'), option: require('./option'), promap: require('./promap'), reduce: require('./reduce'), reduceRight: require('./reduceRight'), reject: require('./reject'), run: require('./run'), runWith: require('./runWith'), second: require('./second'), sequence: require('./sequence'), swap: require('./swap'), tail: require('./tail'), traverse: require('./traverse'), valueOf: require('./valueOf') }
evilsoft/crocks
src/pointfree/index.js
JavaScript
isc
1,145
/* * Copyright © 2017 <[email protected]> http://io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.jtensors.tests.storage.bytebuffered; import com.io7m.jtensors.core.unparameterized.vectors.Vector3I; import com.io7m.jtensors.core.unparameterized.vectors.Vector3L; import com.io7m.jtensors.generators.Vector3IGenerator; import com.io7m.jtensors.generators.Vector3LGenerator; import com.io7m.jtensors.storage.api.unparameterized.vectors.VectorStorageIntegral3Type; import com.io7m.jtensors.storage.bytebuffered.VectorByteBufferedIntegral3Type; import com.io7m.jtensors.storage.bytebuffered.VectorByteBufferedIntegral3s8; import com.io7m.jtensors.tests.core.TestLOps; import com.io7m.mutable.numbers.core.MutableLong; import net.java.quickcheck.Generator; import java.nio.ByteBuffer; public final class VectorByteBufferedIntegral3s8Test extends VectorByteBufferedIntegral3Contract { @Override protected VectorStorageIntegral3Type create( final int offset) { return this.create(MutableLong.create(), offset); } @Override protected VectorByteBufferedIntegral3Type create( final MutableLong base, final int offset) { return VectorByteBufferedIntegral3s8.createWithBase( ByteBuffer.allocate(BufferSizes.BUFFER_SIZE_DEFAULT), base, offset); } @Override protected Generator<Vector3L> createGenerator3L() { return Vector3LGenerator.create8(); } @Override protected Generator<Vector3I> createGenerator3I() { return Vector3IGenerator.create8(); } @Override protected void checkEquals( final long x, final long y) { TestLOps.checkEquals(x, y); } }
io7m/jtensors
com.io7m.jtensors.tests/src/test/java/com/io7m/jtensors/tests/storage/bytebuffered/VectorByteBufferedIntegral3s8Test.java
Java
isc
2,354
$ ./manage.py makemessages -a
westphahl/verleihsystem
doc/code/server_i18n_04.sh
Shell
isc
30
use std::mem::size_of; use std::sync::atomic::*; use super::{SharedMemory, open_shared}; use utils::PAGE_SIZE; /// A directory of shared structures. const MAX_LEN: usize = 256; // 255 byte names const DIRECTORY_PAGES: usize = 2; // Dedicate 2 pages to the directory. const BYTE_SIZE: usize = DIRECTORY_PAGES * PAGE_SIZE; /// Directory header for shared data. #[repr(packed, C)] pub struct DirectoryHeader { entries: AtomicUsize, // Used to signal that snapshotting is in progress. current_version: AtomicUsize, committed_version: AtomicUsize, length: usize, } #[repr(packed, C)] pub struct DirectoryEntry { pub name: [u8; MAX_LEN], } pub struct Directory { head: *mut DirectoryHeader, data: *mut DirectoryEntry, // Need this to make sure memory is not dropped _shared_memory: SharedMemory<DirectoryHeader>, entry: usize, len: usize, } impl Directory { pub fn new(name: &str) -> Directory { unsafe { let shared = open_shared(name, BYTE_SIZE); let head = shared.mem as *mut DirectoryHeader; (*head).current_version.store(1, Ordering::SeqCst); let header_size = size_of::<DirectoryHeader>(); let entry_size = size_of::<DirectoryEntry>(); let entries = (BYTE_SIZE - header_size) / entry_size; let entry = (head.offset(1) as *mut u8) as *mut DirectoryEntry; (*head).length = entries; (*head).entries.store(0, Ordering::Release); (*head).committed_version.store(1, Ordering::SeqCst); Directory { head: head, data: entry, _shared_memory: shared, entry: 0, len: entries, } } } pub fn register_new_entry(&mut self, name: &str) -> Option<usize> { let entry = self.entry; if entry >= self.len || name.len() >= MAX_LEN { None } else { unsafe { let entry_ptr = self.data.offset(entry as isize); (*entry_ptr).name.copy_from_slice(name.as_bytes()); (*self.head).entries.store(entry, Ordering::Release); } self.entry += 1; Some(entry) } } #[inline] pub fn begin_snapshot(&mut self) { unsafe { (*self.head).current_version.fetch_add(1, Ordering::SeqCst); } } #[inline] pub fn end_snapshot(&mut self) { unsafe { let version = (*self.head).current_version.load(Ordering::Acquire); (*self.head).committed_version.store(version, Ordering::Release); } } }
apanda/NetBricks
framework/src/shared_state/directory.rs
Rust
isc
2,678
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpModule } from '@angular/http'; import { MaterialModule } from '@angular/material'; import { OverviewsRoutingModule } from './overviews-routing.module'; import { OverviewsComponent } from './overviews.component'; @NgModule({ declarations: [ OverviewsComponent ], imports: [ CommonModule, HttpModule, OverviewsRoutingModule, MaterialModule, ], providers: [ ], }) export class OverviewsModule { }
nirgn975/Expenses
client/src/app/modules/overviews/overviews.module.ts
TypeScript
isc
533
'use strict' const test = require('tape') const todo = require('.') test('todo', (t) => { })
derhuerst/just-a-boring-game
test.js
JavaScript
isc
97
// Copyright (c) 2013-2014 The btcsuite developers // Copyright (c) 2017 BitGo // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package provautil import ( "hash" "github.com/btcsuite/fastsha256" "github.com/btcsuite/golangcrypto/ripemd160" ) // Calculate the hash of hasher over buf. func calcHash(buf []byte, hasher hash.Hash) []byte { hasher.Write(buf) return hasher.Sum(nil) } // Hash160 calculates the hash ripemd160(sha256(b)). func Hash160(buf []byte) []byte { return calcHash(calcHash(buf, fastsha256.New()), ripemd160.New()) }
BitGo/prova
provautil/hash160.go
GO
isc
596
<!doctype html> <html> <head> <title>markr - organize your bookmarks</title> </head> <body> {% include "navigation.html" %} <br> {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} <ul> {% for category, message in messages %} <li class="{{ category }}">{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} <br> {% block content %} {% endblock %} </body> </html>
fredmorcos/attic
projects/intramarks/markr_python/templates/base.html
HTML
isc
484
/** * Constructs a turtle object that can be used to store the locaiton of the turtle on the canvas * * @param spec A specification object {x: number, y: number}. x,y default to 300,300 if no specificaiton is given * * @returns {Object} */ let create = function (spec = {}) { // canvas will be 600,600 pixels in size. We default to starting in middle let {x = 300, y = 300} = spec; let turtle = { x, y }; /** * Retrieves the turtle state * * @returns {{x, y}} */ let get = function () { return turtle; }; /** * Updates the turtle state * * @param spec {x: number, y: number} where x,y are optional and have no effect if omitted */ let set = function (spec = {}) { let {x = turtle.x, y = turtle.y} = spec; turtle.x = x; turtle.y = y; }; return Object.freeze({ get, set }); }; export {create}
ldeavila/js-turtle-graphics
app/turtle/turtle.js
JavaScript
isc
885
/* * Copyright © 2014 <[email protected]> http://io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.jvvfs.shell; import java.io.PrintStream; import com.io7m.jfunctional.PartialFunctionType; import com.io7m.jlog.LogUsableType; import com.io7m.jvvfs.FilesystemError; import com.io7m.jvvfs.FilesystemType; import com.io7m.jvvfs.PathVirtual; final class ShellCommandMount extends ShellCommand { private final PathVirtual path; private final String archive; ShellCommandMount( final String in_archive, final PathVirtual in_path) { this.archive = in_archive; this.path = in_path; } @Override void run( final LogUsableType log, final PrintStream out, final ShellConfig config, final FilesystemType fs) throws FilesystemError { fs.mountArchive(this.archive, this.path); } static ShellCommandDefinitionType getDefinition() { return new ShellCommandDefinitionType() { @Override public PartialFunctionType<String[], ShellCommand, ShellCommandError> getParser() { return new PartialFunctionType<String[], ShellCommand, ShellCommandError>() { @Override public ShellCommand call( final String[] arguments) throws ShellCommandError { try { if (arguments.length < 3) { throw new ShellCommandError.ShellCommandParseError( "mount <archive> <path>"); } return new ShellCommandMount( arguments[1], PathVirtual.ofString(arguments[2])); } catch (final FilesystemError e) { throw new ShellCommandError.ShellCommandFilesystemError(e); } } }; } @Override public String helpText() { final StringBuilder b = new StringBuilder(); b.append("syntax: mount <archive> <path>"); b.append(System.getProperty("line.separator")); b.append(" Mount the archive <archive> at <path>"); return b.toString(); } }; } }
io7m/jvvfs
io7m-jvvfs-shell/src/main/java/com/io7m/jvvfs/shell/ShellCommandMount.java
Java
isc
2,791
declare module "ansy" { namespace fg { function hex(color: string): string; } }
bluepichu/beautiful-log
src/types/ansy.d.ts
TypeScript
isc
84
/* ISC license. */ #include <skalibs/bytestr.h> #include <s6/s6-supervise.h> int s6_svc_writectl (char const *service, char const *subdir, char const *s, unsigned int len) { unsigned int svlen = str_len(service) ; unsigned int sublen = str_len(subdir) ; char fn[svlen + sublen + 10] ; byte_copy(fn, svlen, service) ; fn[svlen] = '/' ; byte_copy(fn + svlen + 1, sublen, subdir) ; byte_copy(fn + svlen + 1 + sublen, 9, "/control") ; return s6_svc_write(fn, s, len) ; }
rmoorman/s6
src/libs6/s6_svc_writectl.c
C
isc
485
'use strict' const iq = require('../iq-caller') const {plugin, xml} = require('@xmpp/plugin') const NS_DISCO_INFO = 'http://jabber.org/protocol/disco#info' const NS_DISCO_ITEMS = 'http://jabber.org/protocol/disco#items' module.exports = plugin( 'disco-caller', { items(service, node) { return this.entity.plugins['iq-caller'] .get(xml('query', {xmlns: NS_DISCO_ITEMS, node}), service) .then(res => { return res.getChildren('item').map(i => i.attrs) }) }, info(service, node) { return this.entity.plugins['iq-caller'] .get(xml('query', {xmlns: NS_DISCO_INFO, node}), service) .then(res => { return [ res.getChildren('feature').map(f => f.attrs.var), res.getChildren('identity').map(i => i.attrs), ] }) }, }, [iq] )
ggozad/node-xmpp
packages/plugins/disco/caller.js
JavaScript
isc
855
/* * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <stdio.h> #include <stdarg.h> #include "brcups_commands.h" CMDLINELIST standard_side_commandlinelist[]; int divide_media_token(char *input,char output[5][30]); #if 0 #define DEBUGPRINT(a) fprintf(stderr,a);fflush(stdout) #define DEBUGPRINT1(a1,a2) fprintf(stderr,a1,a2);fflush(stdout) #define DEBUGPRINT2(a1,a2,a3) fprintf(stderr,a1,a2,a3);fflush(stdout) #define DEBUGPRINT3(a1,a2,a3,a4) fprintf(stderr,a1,a2,a3,a4);fflush(stdout) #define DEBUGPRINT4(a1,a2,a3,a4,a5) fprintf(stderr,a1,a2,a3,a4,a5);fflush(stdout) #define DEBUGPRINT5(a1,a2,a3,a4,a5,a6) fprintf(stderr,a1,a2,a3,a4,a5,a6);fflush(stdout) #else #define DEBUGPRINT(a) #define DEBUGPRINT1(a1,a2) #define DEBUGPRINT2(a1,a2,a3) #define DEBUGPRINT3(a1,a2,a3,a4) #define DEBUGPRINT4(a1,a2,a3,a4,a5) #define DEBUGPRINT5(a1,a2,a3,a4,a5,a6) #endif #define SETTINGFILE "/usr/local/Brother/cupswrapper/cupswrapperc" int log_level = 0; typedef struct { char value[50]; char option[50]; } SETCOMMAND; SETCOMMAND command_array[100]; int initialize_command_list(); int add_command_list(char *option,char *command); int add_command_list_brcommand(char *command); int exec_brprintconf(char *brprintconf,char *printer); char *strstr_ex(char *data , char *serch_data); char *delete_ppd_comment(char *line); char *chk_ppd_default_setting_line(char *ppd_line); char *get_token(char *input,char *output); void write_log_file(int level,char *format,...); int main(int argc,char * argv[]) { char *printer; char ppd_line[500],tmp[500],*p_tmp,tmp_n[10],tmp_op[500]; FILE *fp_ppd; char *p; char *commandline,*ppdfile; int i,ii; DEBUGPRINT("main:start\n"); if(argc < 1){ return 0; } printer = argv[1]; if(argc > 2){ ppdfile= argv[2]; } else{ ppdfile=""; } if(argc > 3){ if(argv[3][0] >= '0' && argv[3][0] <= '9'){ log_level = argv[3][0] -'0'; } else{ log_level = 0; } } else{ log_level = 0; } if(argc > 4){ commandline = argv[4]; } else{ commandline = "NULL COMMAND LINE"; } fp_ppd = fopen(ppdfile , "r"); if( fp_ppd == NULL) return 0; initialize_command_list(); DEBUGPRINT("main:set default setting\n"); write_log_file(5,"DEFAULT SETTING\n"); for ( i = 0; default_setting[i] != NULL; i ++){ p = strstr_ex(default_setting[i],"BROTHERPRINTER_XXX"); if(p){ p = strchr(p,'-'); if(p){ add_command_list_brcommand(p); } } } DEBUGPRINT("main:set PPD option (string)\n"); write_log_file(5,"PPD SETTING\n"); while(fgets(ppd_line,sizeof(ppd_line),fp_ppd)){ if(NULL == delete_ppd_comment(ppd_line))continue; if(NULL == chk_ppd_default_setting_line(ppd_line))continue; for ( i = 0; ppdcommand_all_list[i]!= NULL; i ++){ p = strstr_ex(ppd_line,ppdcommand_all_list[i]->label); if(p){ for (ii = 0; ppdcommand_all_list[i]->ppdcommandlist[ii].value != NULL; ii++){ p = strstr_ex(ppd_line,ppdcommand_all_list[i]->ppdcommandlist[ii].value); if(p){ add_command_list_brcommand(ppdcommand_all_list[i]->ppdcommandlist[ii].brcommand); break; } } } } for ( i = 0; PPDdefaultN[i].option!= NULL; i ++){ strcpy(tmp,PPDdefaultN[i].option); p_tmp = tmp; if(tmp[0] == '^')p_tmp ++; p = strstr_ex(ppd_line,p_tmp); if(p){ sprintf(tmp,"%s %s",PPDdefaultN[i].value, p + strlen(PPDdefaultN[i].option)); get_token(PPDdefaultN[i].value ,tmp_op); get_token(p + strlen(PPDdefaultN[i].option) ,tmp_n); add_command_list(tmp_op,tmp_n); } } } DEBUGPRINT("main:set brother command line option (string)\n"); write_log_file(5,"BROTHER COMMAND LINE SETTING(S)\n"); for ( i = 0; commandlinelist[i].value != NULL; i ++){ p = strstr_ex(commandline,commandlinelist[i].option); if(p){ add_command_list_brcommand(commandlinelist[i].value); } } DEBUGPRINT("main:set standard command line option (duplex)\n"); write_log_file(5,"STANDARD COMMAND LINE SETTING(DUPLEX)\n"); for ( i = 0; standard_side_commandlinelist[i].value != NULL; i ++){ p = strstr_ex(commandline,standard_side_commandlinelist[i].option); if(p){ add_command_list_brcommand(standard_side_commandlinelist[i].value); } } DEBUGPRINT("main:set standard command line option (media)\n"); write_log_file(5,"STANDARD COMMAND LINE SETTING(MEDIA)\n"); { char output[5][30]; int max; max = divide_media_token(commandline,output); for ( ii=0; ii < max; ii++){ for ( i = 0; standard_media_commandlinelist[i].value != NULL; i ++){ p = strstr_ex(output[ii],standard_media_commandlinelist[i].option); if(p){ add_command_list_brcommand(standard_media_commandlinelist[i].value); } } } } DEBUGPRINT("main:set command line option (numerical)\n"); write_log_file(5,"COMMAND LINE SETTING(N)\n"); for(i = 0; commandlinelist2[i].option != NULL; i ++){ p = strstr_ex(commandline,commandlinelist2[i].option); if(p){ get_token(commandlinelist2[i].value ,tmp_op); get_token(p + strlen(commandlinelist2[i].option) ,tmp_n); sprintf(tmp,"%s %s",tmp_op,tmp_n ); add_command_list(tmp_op,tmp_n); } } exec_brprintconf(brprintconf,printer); } int initialize_command_list(){ int i; char *p; p = (char *)command_array; for ( i = 0; i < sizeof(command_array) ; i ++){ *p = 0; p ++; } return i; } int exec_brprintconf(char *brprintconf,char *printer){ int i; char exec[300]; DEBUGPRINT("exec_brprintconf:start\n"); for ( i = 0; command_array[i].value[0] != 0; i ++ ){ sprintf(exec,"%s -P %s %s %s",brprintconf,printer, command_array[i].option, command_array[i].value); write_log_file(1,"%s\n",exec); system(exec); } } int add_command_list(char *option,char *value){ char *p; int i,ii; if(!option || !value || !option[0] || !value[0]){ return 0; } for ( i = 0; command_array[i].option[0] != 0; i ++ ){ p = strstr_ex(command_array[i].option , option); if(p){ write_log_file(3," C %s %s\n",option,value); strcpy(command_array[i].value, value); break; } } if(command_array[i].option[0] == 0){ strcpy( command_array[i].option ,option); strcpy( command_array[i].value ,value); write_log_file(3," A %s %s\n",option,value); } return 1; } int add_command_list_brcommand_sub(char *command){ char option[100],*p1,*p2; char value[100]; strncpy(option,command,sizeof(option)-1); option[sizeof(option)] = 0; p1 = strchr(option, ' '); p2 = strchr(option, '\t'); if(p1 > p2 && p2 != NULL)p1 = p2; if(p1 == NULL){ return 0; } *p1 = 0; p1 ++; while(*p1 == ' ' || *p1 == '\t') p1 ++; strcpy(value , p1); return add_command_list(option,value); } int add_command_list_brcommand(char *command){ char multi_brcommands[500]; char *p,*start; int i; strcpy(multi_brcommands,command); start = multi_brcommands; while(p = strchr(start+1,'-')){ if(p > multi_brcommands+1){ if(*(p-1) == ' ' || *(p-1) == '\t'){ *(p-1) = 0; } } add_command_list_brcommand_sub(start); start = p; } add_command_list_brcommand_sub(start); return i; } char *get_next_element(char *data,char *search_word){ char *p; p = strstr(data,search_word); if(!p)return p; p += strlen(search_word); while(*p == ' '|| *p == '\t' || *p == ';' || *p == ':')p++; return p; } char *strstr_ex(char *data , char *search_data){ char *p , *pp; p = strstr(data,search_data); if(!p)return p; pp = p; p += strlen(search_data); if(p > search_data){ if ( ! ((*(p-1) == ' '|| *(p-1) == '\t' || *(p-1) == ';' || *(p-1) == ':' || *(p-1) == 0 || *(p-1) == '\n' || *(p-1) == '*') || *(p-1) == '=' )){ if( ! (*p == ' '|| *p == '\t' || *p == ';' || *p == ':' || *p == 0 || *p == '\n' || *p == '*')) return NULL; } } if(pp > data){ p = pp-1; if( ! (*p == ' '|| *p == '\t' || *p == ';' || *p == ':' || *p == 0 || *p == '\n' || *p == '*')) return NULL; } return pp; } char *delete_ppd_comment(char *line){ char *p; p = strchr(line , '%'); if(p)*p = 0; p = strchr(line , 0x0a); if(p)*p = 0; p = strchr(line , 0x0d); if(p)*p = 0; p = strchr(line , 0x0c); if(p)*p = 0; if(line[0] == 0)return NULL; return line; } char *chk_ppd_default_setting_line(char *ppd_line){ char *p; p=strstr(ppd_line,"*Default"); if(p != ppd_line)return NULL; return p; } char *get_token(char *input,char *output){ char c,*pi,*po; po = output; pi = input; while(c = *pi){ switch(c){ case ' ': case '\t': case '=': case 0x0d: case 0x0a: case 0x0c: pi++; continue; case 0x00: break; } break; } while(c = *pi){ switch(c){ case ' ': case '\t': case '=': case 0x0d: case 0x0a: case 0x0c: case 0x00: *po = 0; return output; break; } *po = c; po ++; pi ++; } *po = 0; return output; } void write_log_file(int level,char *format,...){ FILE *fp_logfile; char logdata[300]; va_list argp; va_start(argp,format); if(log_level == 0)return; if(level > log_level)return; vsprintf(logdata,format,argp); fputs(logdata , stdout); fflush(stdout); return ; } #define MEDIAEQ "media=" int divide_media_token(char *input,char output[5][30]){ char media_command[100]; char *media,*p,*pp; int i; p = strstr(input,MEDIAEQ); if(p){ strcpy(media_command,p+strlen(MEDIAEQ)); } else{ return 0; } media_command[sizeof(media_command)-1] = 0; media_command[sizeof(media_command)-2] = 0; media_command[sizeof(media_command)-3] = 0; p = strchr(media_command,' '); if(p)*p =0; p = strchr(media_command,'\t'); if(p)*p =0; p = strchr(media_command,'\n'); if(p)*p =0; p = media_command; for (i = 0; i < 5; ){ if(*p == 0)break; pp = strchr(p , ','); if(pp) *pp = 0; strcpy(output[i],p); i ++; if(pp == NULL)break; p = pp+1; } return i; } CMDLINELIST standard_side_commandlinelist[] = { { "sides=two-sided-long-edge" , "-dx ON -dxt LONG" }, { "sides=two-sided-short-edge" , "-dx ON -dxt SHORT" }, { "sides=one-side" , "-dx OFF" }, { NULL , NULL } };
illwieckz/debian_copyist_brother
material/sources/mfc9420cncups_src/brcupsconfigcl1/brcupsconfig.c
C
isc
11,524
'use strict'; const gulp = require('gulp'); const ignore = require('gulp-ignore'); const istextorbinary = require('istextorbinary'); const conflict = require('gulp-conflict'); const installBinaryFiles = function (options) { const src = options.src; const srcDir = options.srcDir; const destDir = options.destDir; return function (cb) { gulp.src(src, {cwd: srcDir, base: srcDir}) .pipe(ignore.include(file => istextorbinary.isBinarySync(file.basename, file.contents))) .pipe(conflict(destDir, {logger: console.log})) .pipe(gulp.dest(destDir)) .on('end', cb); }; }; module.exports = installBinaryFiles;
ronik-design/slush-gh-pages
tasks/install-binary-files.js
JavaScript
isc
643
/*global describe, it, before */ var Nut = require('../lib'), expect = require('chai').expect; describe('command', function () { var not_found_re = /^Command \S+ not found/; it('should mention module and command if not found', function (done) { new Nut()._command('apidoc-almond/a/bad/value') .catch(function (err) { // General (use the same re for negation test later). expect( err.message ).to.match(not_found_re); // Specific. expect( err.message ).to.equal('Command "value" not found. Is "apidoc-almond" installed?'); done(); }).catch(done); }); it('should rethrow other errors', function (done) { // Something that require() will barf on. var badreqval = null; new Nut()._command(badreqval) .catch(function (err) { expect( err.message ).to.not.match(not_found_re); done(); }).catch(done); }); });
rwstauner/apidoc-almond
test/command_test.js
JavaScript
isc
908
@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^<target^>` where ^<target^> is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\generator.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\generator.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end
kevinastone/generator
docs/make.bat
Batchfile
isc
6,465
#!/usr/bin/env python3 import sys import os import os.path as path import subprocess import shutil import argparse import re XCLIP = shutil.which('xclip') XDOTOOL = shutil.which('xdotool') DMENU = shutil.which('dmenu') PASS = shutil.which('pass') STORE = os.getenv('PASSWORD_STORE_DIR', path.normpath(path.expanduser('~/.password-store'))) XSEL_PRIMARY = "primary" def get_xselection(selection): if not selection: # empty or None return None for option in [XSEL_PRIMARY, "secondary", "clipboard"]: if option[:len(selection)] == selection: return option return None def check_output(args): output = subprocess.check_output(args) output = output.decode('utf-8').split('\n') return output def dmenu(choices, args=[], path=DMENU): """ Displays a menu with the given choices by executing dmenu with the provided list of arguments. Returns the selected choice or None if the menu was aborted. """ dmenu = subprocess.Popen([path] + args, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE) choice_lines = '\n'.join(map(str, choices)) choice, errors = dmenu.communicate(choice_lines.encode('utf-8')) if dmenu.returncode not in [0, 1] \ or (dmenu.returncode == 1 and len(errors) != 0): print("'{} {}' returned {} and error:\n{}" .format(path, ' '.join(args), dmenu.returncode, errors.decode('utf-8')), file=sys.stderr) sys.exit(1) choice = choice.decode('utf-8').rstrip() return choice if choice in choices else None def collect_choices(store, regex=None): choices = [] for dirpath, dirs, files in os.walk(store, followlinks=True): dirsubpath = dirpath[len(store):].lstrip('/') for f in files: if f.endswith('.gpg'): full_path = os.path.join(dirsubpath, f[:-4]) if not regex or re.match(regex, full_path): choices += [full_path] return choices def xdotool(entries, press_return, delay=None, window_id=None): getwin = "" always_opts = "--clearmodifiers" if delay: always_opts += " --delay '{}'".format(delay) if not window_id: getwin = "getactivewindow\n" else: always_opts += " --window {}".format(window_id) commands = [c for e in entries[:-1] for c in ( "type {} '{}'".format(always_opts, e), "key {} Tab".format(always_opts))] if len(entries) > 0: commands += ["type {} '{}'".format(always_opts, entries[-1])] if press_return: commands += ["key {} Return".format(always_opts)] for command in commands: input_text = "{}{}".format(getwin, command) subprocess.check_output([XDOTOOL, "-"], input=input_text, universal_newlines=True) def get_pass_output(gpg_file, path=PASS, store=STORE): environ = os.environ.copy() environ["PASSWORD_STORE_DIR"] = store passp = subprocess.Popen([path, gpg_file], env=environ, stderr=subprocess.PIPE, stdout=subprocess.PIPE) output, err = passp.communicate() if passp.returncode != 0: print("pass returned {} and error:\n{}".format( passp.returncode, err.decode('utf-8')), file=sys.stderr) sys.exit(1) return output.decode('utf-8').split('\n') def get_user_pw(pass_output): password = None if len(pass_output) > 0: password = pass_output[0] user = None if len(pass_output) > 1: userline = pass_output[1].split() if len(userline) > 1: # assume the first 'word' after some prefix is the username # TODO any better, reasonable assumption for lines # with more 'words'? user = userline[1] elif len(userline) == 1: # assume the user has no 'User: ' prefix or similar user = userline[0] return user, password def main(): desc = ("A dmenu frontend to pass." " All passed arguments not listed below, are passed to dmenu." " If you need to pass arguments to dmenu which are in conflict" " with the options below, place them after --." " Requires xclip in default 'copy' mode.") parser = argparse.ArgumentParser(description=desc) parser.add_argument('-c', '--copy', dest='copy', action='store_true', help=('Use xclip to copy the username and/or ' 'password into the primary/specified ' 'xselection(s). This is the default mode.')) parser.add_argument('-t', '--type', dest='autotype', action='store_true', help=('Use xdotool to type the username and/or ' 'password into the currently active window.')) parser.add_argument('-r', '--return', dest='press_return', action='store_true', help='Presses "Return" after typing. Forces --type.') parser.add_argument('-u', '--user', dest="get_user", action='store_true', help='Copy/type the username.') parser.add_argument('-P', '--pw', dest="get_pass", action='store_true', help=('Copy/type the password. Default, use -u -P to ' 'copy both username and password.')) parser.add_argument('-s', '--store', dest="store", default=STORE, help=('The path to the pass password store. ' 'Defaults to ~/.password-store')) parser.add_argument('-d', '--delay', dest="xdo_delay", default=None, help=('The delay between keystrokes. ' 'Defaults to xdotool\'s default.')) parser.add_argument('-f', '--filter', dest="filter", default=None, help='A regular expression to filter pass filenames.') parser.add_argument('-B', '--pass', dest="pass_bin", default=PASS, help=('The path to the pass binary. ' 'Cannot find a default path to pass, ' 'you must provide this option.' if PASS is None else 'Defaults to ' + PASS)) parser.add_argument('-D', '--dmenu', dest="dmenu_bin", default=DMENU, help=('The path to the dmenu binary. ' 'Cannot find a default path to dmenu, ' 'you must provide this option.' if DMENU is None else 'Defaults to ' + DMENU)) parser.add_argument('-x', '--xsel', dest="xsel", default=XSEL_PRIMARY, help=('The X selections into which to copy the ' 'username/password. Possible values are comma-' 'separated lists of prefixes of: ' 'primary, secondary, clipboard. E.g. -x p,s,c. ' 'Defaults to primary.')) parser.add_argument('-e', '--execute', dest="execute", default=None, help=('The path to a command to execute. The whole ' 'content of the decrypted gpg file from pass ' 'is provided to it on standard input. The full ' 'password name (within the store) is provided as ' 'first parameter. Arguments -s and -f are ' 'forwarded as parameters.' 'The command is executed in addition to and ' 'after specified -t, -c options are handled.')) split_args = [[]] curr_args = split_args[0] for arg in sys.argv[1:]: if arg == "--": split_args.append([]) curr_args = split_args[-1] continue curr_args.append(arg) args, unknown_args = parser.parse_known_args(args=split_args[0]) if not args.get_user and not args.get_pass: args.get_pass = True if args.press_return: args.autotype = True if not args.autotype and not args.execute: args.copy = True error = False if args.pass_bin is None: print("You need to provide a path to pass. See -h for more.", file=sys.stderr) error = True if args.dmenu_bin is None: print("You need to provide a path to dmenu. See -h for more.", file=sys.stderr) error = True prompt = "" if args.autotype: if XDOTOOL is None: print("You need to install xdotool.", file=sys.stderr) error = True if args.press_return: prompt = "enter" else: prompt = "type" if args.copy: if XCLIP is None: print("You need to install xclip.", file=sys.stderr) error = True prompt += ("," if prompt != "" else "") + "copy" if args.execute: if shutil.which(args.execute) is None: print("The command to execute is not executable or does not exist.") error = True else: prompt += (("," if prompt != "" else "") + os.path.basename(args.execute)) # make sure the password store exists if not os.path.isdir(args.store): print("The password store location, " + args.store + ", does not exist.", file=sys.stderr) error = True if shutil.which(args.pass_bin) is None: print("The pass binary, {}, does not exist or is not executable." .format(args.pass_bin), file=sys.stderr) error = True if error: sys.exit(1) dmenu_opts = ["-p", prompt] + unknown_args # XXX for now, append all split off argument lists to dmenu's args for arg_list in split_args[1:]: dmenu_opts += arg_list # get active window id now, it may change between dmenu/rofi and xdotool window_id = None if args.autotype: window_id = check_output([XDOTOOL, 'getactivewindow'])[0] choices = collect_choices(args.store, args.filter) choice = dmenu(choices, dmenu_opts, args.dmenu_bin) # Check if user aborted if choice is None: sys.exit(0) pass_output = get_pass_output(choice, args.pass_bin, args.store) user, pw = get_user_pw(pass_output) info = [] if args.get_user and user is not None: info += [user] if args.get_pass and pw is not None: info += [pw] clip = '\n'.join(info).encode('utf-8') if args.autotype: xdotool(info, args.press_return, args.xdo_delay, window_id) if args.copy: for selection in args.xsel.split(','): xsel_arg = get_xselection(selection) if xsel_arg: xclip = subprocess.Popen([XCLIP, "-selection", xsel_arg], stdin=subprocess.PIPE) xclip.communicate(clip) else: print("Warning: Invalid xselection argument: {}." .format(selection), file=sys.stderr) if args.execute: cmd_with_args=([args.execute, choice, "-s", args.store] + (["-f", args.filter] if args.filter else [])) cmd = subprocess.Popen(cmd_with_args, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) output, _ = cmd.communicate('\n'.join(pass_output).encode('utf-8')) if cmd.returncode != 0: print("Command {} returned {} and output:\n{}".format( args.execute, cmd.returncode, output.decode('utf-8')), file=sys.stderr) sys.exit(1) else: print(output.decode('utf-8'), end='') if __name__ == "__main__": main()
Narrat/passdmenu
passdmenu.py
Python
isc
12,057
#! /bin/sh # # run.sh # Copyright (C) 2015 Rafal Gumienny <[email protected]> # # Distributed under terms of the GPL license. # # end when error set -e # raise error when variable is unset set -u # raise error when in pipe set -o pipefail for i in 1 2 3 4 5 6 do python test_MetaProfile.py &> ${i}.log & done
guma44/MetaProfile
tests/run.sh
Shell
isc
317
# encoding: utf-8 class Faculty < ActiveRecord::Base has_many :courses, :inverse_of => :faculty has_many :course_profs, :through => :courses validates_presence_of :shortname, :longname validates_uniqueness_of :shortname, :longname # returns true if there are any courses associated with this faculty def critical? courses.size > 0 end # returns array of integer-barcodes for all associated CourseProfs def barcodes course_profs.map { |cp| cp.id } end end
breunigs/gnt-eval
web/app/models/faculty.rb
Ruby
isc
486
// ==UserScript== // @id iitc-plugin-highlight-needs-recharge@vita10gy // @name IITC plugin: hightlight portals that need recharging // @category 螢光筆 // @version 0.1.2.@@DATETIMEVERSION@@ // @namespace https://github.com/jonatkins/ingress-intel-total-conversion // @updateURL @@UPDATEURL@@ // @downloadURL @@DOWNLOADURL@@ // @description [@@BUILDNAME@@-@@BUILDDATE@@] Use the portal fill color to denote if the portal needs recharging and how much. Yellow: above 85%. Orange: above 50%. Red: above 15%. Magenta: below 15%. // @include https://*.ingress.com/intel* // @include http://*.ingress.com/intel* // @match https://*.ingress.com/intel* // @match http://*.ingress.com/intel* // @include https://*.ingress.com/mission/* // @include http://*.ingress.com/mission/* // @match https://*.ingress.com/mission/* // @match http://*.ingress.com/mission/* // @grant none // ==/UserScript== @@PLUGINSTART@@ // PLUGIN START //////////////////////////////////////////////////////// // use own namespace for plugin window.plugin.portalHighlighterNeedsRecharge = function() {}; window.plugin.portalHighlighterNeedsRecharge.highlight = function(data) { var d = data.portal.options.data; var health = d.health; if(health !== undefined && data.portal.options.team != TEAM_NONE && health < 100) { var color,fill_opacity; if (health > 95) { color = 'yellow'; fill_opacity = (1-health/100)*.50 + .50; } else if (health > 75) { color = 'DarkOrange'; fill_opacity = (1-health/100)*.50 + .50; } else if (health > 15) { color = 'red'; fill_opacity = (1-health/100)*.75 + .25; } else { color = 'magenta'; fill_opacity = (1-health/100)*.75 + .25; } var params = {fillColor: color, fillOpacity: fill_opacity}; data.portal.setStyle(params); } } var setup = function() { window.addPortalHighlighter('Needs Recharge (Health)', window.plugin.portalHighlighterNeedsRecharge.highlight); } // PLUGIN END ////////////////////////////////////////////////////////// @@PLUGINEND@@
ifchen0/IITC_TW
plugins/portal-highlighter-needs-recharge.user.js
JavaScript
isc
2,177
package com.lagopusempire.homes.jobs.admin; import com.lagopusempire.homes.HomeManager; import com.lagopusempire.homes.jobs.ListHomesJobBase; import com.lagopusempire.homes.load.Loader; import com.lagopusempire.homes.messages.MessageKeys; import com.lagopusempire.homes.messages.Messages; import com.lagopusempire.homes.util.Util; import java.util.HashSet; import java.util.Set; import java.util.UUID; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; /** * * @author MrZoraman */ public class ListOthersHomeJob extends ListHomesJobBase { private final Set<? extends Player> onlinePlayers; private volatile UUID target; public ListOthersHomeJob(JavaPlugin plugin, HomeManager homeManager, Player player, String targetName) { super(plugin, homeManager, player, targetName); this.onlinePlayers = new HashSet<>(plugin.getServer().getOnlinePlayers()); } @Override protected void addSteps(Loader loader) { loader.addStep(this::retrieveTarget, true); loader.addStep(this::verifyTarget, false); super.addSteps(loader); } private boolean retrieveTarget() { target = Util.getPlayer(targetName, plugin.getLogger(), onlinePlayers); return true; } private boolean verifyTarget() { if (target == null) { Util.sendMessage(player, Messages.getMessage(MessageKeys.PLAYER_NOT_FOUND) .replace("player", targetName) .colorize()); return false; } return true; } @Override protected UUID getTarget() { return target; } @Override protected MessageKeys getHomeListNone() { return MessageKeys.HOME_LIST_OTHER_NONE; } @Override protected MessageKeys getHomeListInitial() { return MessageKeys.HOME_LIST_OTHER_INITIAL; } @Override protected MessageKeys getHomeListFormat() { return MessageKeys.HOME_LIST_OTHER_FORMAT; } @Override protected MessageKeys getStripLength() { return MessageKeys.HOME_LIST_OTHER_END_STRIP_LENGTH; } @Override protected int getTargetMaxHomes() { return -1; } @Override protected MessageKeys getListImplicitHome() { return MessageKeys.HOME_LIST_OTHER_IMPLICIT_HOME; } }
MrZoraman/Homes
src/main/java/com/lagopusempire/homes/jobs/admin/ListOthersHomeJob.java
Java
isc
2,408
<html> <head> <meta name="generator" content="Microsoft Visual Studio"> <title>Network Options</title> <link rel="stylesheet" href="asset://rapture/jquery/jquery-ui.min.css"> <link rel="stylesheet" href="asset://rapture/jquery/jquery-ui.structure.min.css" /> <link rel="stylesheet" href="asset://rapture/jquery/jquery-ui.theme.min.css" /> <script type="text/javascript" src="asset://rapture/jquery/jquery-2.1.1.min.js"></script> <script type="text/javascript" src="asset://rapture/jquery/jquery-ui.min.js"></script> </head> <body> <div id="network-options" title="Network Options"> <div> <table class="ui-state-default ui-widget-content" style="width:100%;padding:10px;" cellpadding="2"> <tr> <td style="padding:20px;"> Max Clients <br /> <form> <p> <input type="text" id="text-maxclients" style="width:20%;float:left;" /> <div id="slider-maxclients" style="width:60%;float:right;"></div> </p> </form> </td> <td rowspan="2" style="padding:20px;"> <fieldset> <label for="ipv6">IPv6 Enabled</label> <input type="checkbox" name="checkbox_ipv6" id="checkbox_ipv6"/> </fieldset> </td> </tr> <tr> <td style="padding:20px;"> Timeout (milliseconds) <br /> <form> <p> <div id="slider-timeout"></div> <br /> <input type="text" id="text-timeout" /> </p> </form> </td> </tr> </table> </div> </div> <script type="text/javascript"> function ModalWindowClosed() { parent.Engine.setCvarBoolean("net_ipv6", $("#checkbox_ipv6").prop( "checked" )); parent.ModalClosed(); } function UpdateProtocol() { $("#checkbox_ipv6").prop("checked", parent.Engine.getCvarBoolean("net_ipv6")); } $("#network-options").dialog({ autoOpen: false, modal: true, resizable: true, width: 500, close: ModalWindowClosed, buttons: { OK: function () { $(this).dialog("close"); } } }) $("#slider-timeout").slider({ min: 15000, max: 300000, step: 1000, value: parent.Engine.getCvarInteger("net_timeout"), slide: function (event, ui) { $("#text-timeout").val(ui.value); parent.Engine.setCvarInteger("net_timeout", parseInt(ui.value)); } }); $("#slider-maxclients").slider({ min: 1, max: 32, step: 1, value: parent.Engine.getCvarInteger("net_maxclients"), slide: function (event, ui) { $("#text-maxclients").val(ui.value); parent.Engine.setCvarInteger("net_maxclients", parseInt(ui.value)); } }); $("#text-timeout").change(function () { var value = this.value; console.log("net_timeout changed to " + value); $("#slider-timeout").slider("value", parseInt(value)); parent.Engine.setCvarInteger("net_maxclients", parseInt(value)); }); $("#text-timeout").val(parent.Engine.getCvarInteger("net_timeout")); $("#text-maxclients").val(parent.Engine.getCvarInteger("net_maxclients")); $("#text-maxclients").change(function () { var value = this.value; console.log("net_maxclients changed to " + value); $("#slider-maxclients").slider("value", parseInt(value)); parent.Engine.setCvarInteger("net_maxclients", parseInt(value)); }); $('input').addClass("ui-widget ui-widget-content ui-corner-all"); UpdateProtocol(); $("#network-options").dialog("open"); </script> </body> </html>
eezstreet/Rapture
Rapture/core/ui/network-menu.html
HTML
isc
4,920
'use strict' const {Suite} = require('benchmark') const autocomplete = require('.') new Suite() .add('basic query, one token', function () { autocomplete('Bellevue', 3) }) .add('basic query, two tokens', function () { autocomplete('U Seestr.', 3) }) .add('no completion – "U friedr"', function () { autocomplete('U friedr', 3, false, false) }) .add('completion – "U friedr"', function () { autocomplete('U friedr', 3, false, true) }) .add('completion – "meh"', function () { autocomplete('meh', 3, false) }) .add('complex', function () { autocomplete('S+U Warschauer Straße', 3) }) .add('umlauts', function () { autocomplete('U märkisches museum', 3) }) .add('non-fuzzy – "U mehringdamm"', function () { autocomplete('U mehringdamm', 3) }) .add('fuzzy – "U mehrigndamm"', function () { autocomplete('U mehrigndamm', 3, true) }) .add('100 results – "U friedr"', function () { autocomplete('U friedr', 100) }) .on('cycle', (e) => { console.log(e.target.toString()) }) .run()
derhuerst/vbb-stations-autocomplete
benchmark.js
JavaScript
isc
1,008
/** * shallow layer over git commands * Q: why's everything sync instead of async? * A: because there's no concurrency required in this tool. */ import { execSync } from "child_process"; import * as util from "util"; function execSyncUTF8(command: string): string { return execSync(command, {encoding: "utf8"}).trim(); } export function root(): string { let root = execSyncUTF8("git rev-parse --show-toplevel"); return root; } export function lsTree(): string[] { let output = execSyncUTF8("git ls-tree HEAD --name-only"); let files = output.split("\n"); return files; } export function diffNames(commit1: string, commit2: string): string[] { let command = util.format("git diff-tree --name-only -r %s %s", commit1, commit2); let output = execSyncUTF8(command); let files = output.split("\n"); return files; } export interface DiffInfo { filename: string, linesAdded: number, linesRemoved: number } export function getDiff(filename: string, commit1: string, commit2: string | null): DiffInfo | null { if (commit2 === null) { let command = util.format("git diff-tree --numstat -r --root %s -- %s", commit1, filename) let output = execSyncUTF8(command); if (output.length === 0) { return null } else { // skip first line of output since it outputs commit hash when --root passed in let outputInfo = output.split("\n")[1].split("\t"); let diffInfo: DiffInfo = { filename, linesAdded: parseInt(outputInfo[0]), linesRemoved: parseInt(outputInfo[1]) }; return diffInfo; } } else { let command = util.format("git diff-tree --numstat -r %s %s -- %s", commit1, commit2, filename); let output = execSyncUTF8(command); if (output.length === 0) { return null } else { let outputInfo = output.split("\t"); let diffInfo: DiffInfo = { filename, linesAdded: parseInt(outputInfo[0]), linesRemoved: parseInt(outputInfo[1]) }; return diffInfo; } } } export function getCurrentCommit(): string { let output = execSyncUTF8("git rev-parse HEAD"); output = output.trim(); return output; }
jpanda109/ghcr
src/lib/git.ts
TypeScript
isc
2,366
package com.stentle; /** * Created by gioiaballin on 05/11/15. */ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import com.mongodb.MongoClient; /** * Test configuration to connect to a MongoDB named "test" and using a {@link MongoClient}. * * @author Gioia Ballin * */ @Configuration @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } /** * Create a new {@link LocalValidatorFactoryBean} to get the validation on nested objects. * */ @Bean public LocalValidatorFactoryBean localValidatorFactoryBean() { return new LocalValidatorFactoryBean(); } }
gioiab/stentle-project
src/main/java/com/stentle/Application.java
Java
mit
1,050
QUnit.test("The Canary test", function( assert ) { assert.ok(true, "your message") });
crolek/letskillsomecanaries
Example/Canary/test.js
JavaScript
mit
92
using System; using System.Web.Mvc; using D2DQuest.Contracts.Queries; using D2DQuest.Web.MessageHelpers; namespace D2DQuest.Web.Controllers { public class RaffleController : Controller { private readonly IWinnerQuery _winnerQuery; private readonly Lazy<IRaffleMessageHelper> _messageHelper; public RaffleController(IWinnerQuery winnerQuery, Lazy<IRaffleMessageHelper> messageHelper) { if (winnerQuery == null) throw new ArgumentNullException("winnerQuery"); if (messageHelper == null) throw new ArgumentNullException("messageHelper"); _winnerQuery = winnerQuery; _messageHelper = messageHelper; } public ActionResult Raffle() { string result = null; try { var visiter = _winnerQuery.GetWinner(); result = String.Format("{0} [{1}]", visiter.Name, visiter.Uid); } catch (Exception exc) { result = _messageHelper.Value.GetErrorMessage(exc); } return View((object)result); } } }
dev2dev-community/d2dquest
src/D2DQuest.Web/Controllers/RaffleController.cs
C#
mit
1,186
# Release History ## 1.0.0-beta.3 (Unreleased) ### Features Added ### Breaking Changes ### Bugs Fixed ### Other Changes ## 1.0.0-beta.2 (2021-09-14) ### Features Added - Added ArmClient extension methods to support [start from the middle scenario](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/resourcemanager/Azure.ResourceManager#managing-existing-resources-by-id). ## 1.0.0-beta.1 (2021-08-31) ### Breaking Changes Guidance to migrate from previous version of Azure Management SDK ### General New Features - Support MSAL.NET, Azure.Identity is out of box for supporting MSAL.NET - Support [OpenTelemetry](https://opentelemetry.io/) for distributed tracing - HTTP pipeline with custom policies - Better error-handling - Support uniform telemetry across all languages > NOTE: For more information about unified authentication, please refer to [Azure Identity documentation for .NET](https://docs.microsoft.com//dotnet/api/overview/azure/identity-readme?view=azure-dotnet) #### Package Name The package name has been changed from `Microsoft.Azure.Management.KeyVault` to `Azure.ResourceManager.KeyVault` #### Management Client Changes Example: Create a Key Vault Instance: Before upgrade: ```csharp using Microsoft.Azure.Management.KeyVault; using Microsoft.Azure.Management.KeyVault.Models; using Microsoft.Rest; var tokenCredentials = new TokenCredentials("YOUR ACCESS TOKEN"); var keyVaultManagementClient = new KeyVaultManagementClient(tokenCredentials); var vault = await keyVaultManagementClient.Vaults.BeginCreateOrUpdateAsync ( resourceGroupName, vaultName, parameters ); ``` After upgrade: ```csharp using Azure.Identity; using Azure.ResourceManager.KeyVault; using Azure.ResourceManager.KeyVault.Models; ArmClient client = new ArmClient(new DefaultAzureCredential()); ResourceGroup resourceGroup = await armClient.DefaultSubscription.GetResourceGroups().GetAsync("myRgName"); VaultContainer vaultContainer = resourceGroup.GetVaults(); VaultCreateOrUpdateOperation lro = await vaultsOperations.CreateOrUpdateAsync(vaultName, parameters); Vault vault = lro.Value; ``` #### Object Model Changes Example: Create a Permissions Model Before upgrade: ```csharp var permissions = new Permissions { Keys = new string[] { "all" }, Secrets = new string[] { "all" }, Certificates = new string[] { "all" }, Storage = new string[] { "all" }, } ``` After upgrade: ```csharp var permissions = new Permissions { Keys = new [] { new KeyPermissions("all") }, Secrets = new [] { new SecretPermissions("all") }, Certificates = new [] { new CertificatePermissions("all") }, Storage = new [] { new StoragePermissions("all") }, }; ```
AsrOneSdk/azure-sdk-for-net
sdk/keyvault/Azure.ResourceManager.KeyVault/CHANGELOG.md
Markdown
mit
2,972
<?php get_header(); ?> <section class="error"> <div class="content"> <div class="top-secret"></div> <h1>Access Denied!</h1> <?php get_search_form(); ?> </div> </section> <?php get_footer(); ?>
AgtLucas/Drifter
404.php
PHP
mit
207
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Option extends Component { static propTypes = { cid: PropTypes.string, value: PropTypes.any, text: PropTypes.any, onMouseEnter: PropTypes.func, className: PropTypes.string, onClick: PropTypes.func, }; optionClickHandler = event => { this.props.onClick(event, this.props.cid); }; render() { const { className, text, value } = this.props; return ( <span value={value} className={className} onClick={this.optionClickHandler} onMouseEnter={this.props.onMouseEnter} > {text} </span> ); } } export default Option;
boldr/boldr-ui
src/Select/components/Option.js
JavaScript
mit
705
package com.refinedmods.refinedstorage.screen.widget.sidebutton; import com.mojang.blaze3d.vertex.PoseStack; import com.refinedmods.refinedstorage.api.network.grid.IGrid; import com.refinedmods.refinedstorage.container.GridContainerMenu; import com.refinedmods.refinedstorage.screen.BaseScreen; import net.minecraft.ChatFormatting; import net.minecraft.client.resources.language.I18n; public class GridSortingDirectionSideButton extends SideButton { private final IGrid grid; public GridSortingDirectionSideButton(BaseScreen<GridContainerMenu> screen, IGrid grid) { super(screen); this.grid = grid; } @Override protected String getTooltip() { return I18n.get("sidebutton.refinedstorage.grid.sorting.direction") + "\n" + ChatFormatting.GRAY + I18n.get("sidebutton.refinedstorage.grid.sorting.direction." + grid.getSortingDirection()); } @Override protected void renderButtonIcon(PoseStack poseStack, int x, int y) { screen.blit(poseStack, x, y, grid.getSortingDirection() * 16, 16, 16, 16); } @Override public void onPress() { int dir = grid.getSortingDirection(); if (dir == IGrid.SORTING_DIRECTION_ASCENDING) { dir = IGrid.SORTING_DIRECTION_DESCENDING; } else if (dir == IGrid.SORTING_DIRECTION_DESCENDING) { dir = IGrid.SORTING_DIRECTION_ASCENDING; } grid.onSortingDirectionChanged(dir); } }
raoulvdberge/refinedstorage
src/main/java/com/refinedmods/refinedstorage/screen/widget/sidebutton/GridSortingDirectionSideButton.java
Java
mit
1,447
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.contracts.productruntime; import java.util.List; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.joda.time.DateTime; import com.mozu.api.contracts.productruntime.AttributeDetail; import com.mozu.api.contracts.productruntime.ProductOptionValue; /** * Represents configurable options that a shopper can choose when ordering a product, such as a t-shirt color and size. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ProductOption implements Serializable { // Default Serial Version UID private static final long serialVersionUID = 1L; /** * The fully qualified name of the attribute, which is a user defined attribute identifier. */ protected String attributeFQN; public String getAttributeFQN() { return this.attributeFQN; } public void setAttributeFQN(String attributeFQN) { this.attributeFQN = attributeFQN; } /** * If true, the product attribute or option has multiple values. */ protected Boolean isMultiValue; public Boolean getIsMultiValue() { return this.isMultiValue; } public void setIsMultiValue(Boolean isMultiValue) { this.isMultiValue = isMultiValue; } /** * If true, the entity is required for the request to return a valid response. */ protected Boolean isRequired; public Boolean getIsRequired() { return this.isRequired; } public void setIsRequired(Boolean isRequired) { this.isRequired = isRequired; } /** * Details of the product option attribute. */ protected AttributeDetail attributeDetail; public AttributeDetail getAttributeDetail() { return this.attributeDetail; } public void setAttributeDetail(AttributeDetail attributeDetail) { this.attributeDetail = attributeDetail; } /** * List of possible values for a product option attribute. */ protected List<ProductOptionValue> values; public List<ProductOptionValue> getValues() { return this.values; } public void setValues(List<ProductOptionValue> values) { this.values = values; } }
eileenzhuang1/mozu-java
mozu-java-core/src/main/java/com/mozu/api/contracts/productruntime/ProductOption.java
Java
mit
2,208
require 'rack' module Shig class Web class Request < Rack::Request def initialize(env) super(env) end end end end
murooka/shig
lib/shig/web/request.rb
Ruby
mit
149
<?php class addUserController{ public function addUser(){ require_once("/application/models/addUserModel.php"); $addUser = new addUserModel(); $reqaddUser = $addUser->getAddUser(); require_once("/application/views/IMIE/addUser.php"); } } ?>
hyorek/IMIESHPERE
application/controleurs/addUserControler.php
PHP
mit
255
<?php namespace Illuminate\Foundation\Http; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Http\JsonResponse; use Illuminate\Routing\Redirector; use Illuminate\Container\Container; use Illuminate\Contracts\Validation\Validator; use Illuminate\Validation\ValidationException; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Validation\ValidatesWhenResolvedTrait; use Illuminate\Contracts\Validation\ValidatesWhenResolved; use Illuminate\Contracts\Validation\Factory as ValidationFactory; class FormRequest extends Request implements ValidatesWhenResolved { use ValidatesWhenResolvedTrait; /** * The container instance. * * @var \Illuminate\Container\Container */ protected $container; /** * The redirector instance. * * @var \Illuminate\Routing\Redirector */ protected $redirector; /** * The URI to redirect to if validation fails. * * @var string */ protected $redirect; /** * The route to redirect to if validation fails. * * @var string */ protected $redirectRoute; /** * The controller action to redirect to if validation fails. * * @var string */ protected $redirectAction; /** * The key to be used for the view error bag. * * @var string */ protected $errorBag = 'default'; /** * The input keys that should not be flashed on redirect. * * @var array */ protected $dontFlash = ['password', 'password_confirmation']; /** * Get the validator instance for the request. * * @return \Illuminate\Contracts\Validation\Validator */ protected function getValidatorInstance() { $factory = $this->container->make(ValidationFactory::class); if (method_exists($this, 'validator')) { $validator = $this->container->call([$this, 'validator'], compact('factory')); } else { $validator = $this->createDefaultValidator($factory); } if (method_exists($this, 'withValidator')) { $this->withValidator($validator); } return $validator; } /** * Create the default validator instance. * * @param \Illuminate\Contracts\Validation\Factory $factory * @return \Illuminate\Contracts\Validation\Validator */ protected function createDefaultValidator(ValidationFactory $factory) { return $factory->make( $this->validationData(), $this->container->call([$this, 'rules']), $this->messages(), $this->attributes() ); } /** * Get data to be validated from the request. * * @return array */ protected function validationData() { return $this->all(); } /** * Handle a failed validation attempt. * * @param \Illuminate\Contracts\Validation\Validator $validator * @return void * * @throws \Illuminate\Validation\ValidationException */ protected function failedValidation(Validator $validator) { throw new ValidationException($validator, $this->response( $this->formatErrors($validator) )); } /** * Get the proper failed validation response for the request. * * @param array $errors * @return \Symfony\Component\HttpFoundation\Response */ public function response(array $errors) { if ($this->expectsJson()) { return new JsonResponse($errors, 422); } return $this->redirector->to($this->getRedirectUrl()) ->withInput($this->except($this->dontFlash)) ->withErrors($errors, $this->errorBag); } /** * Format the errors from the given Validator instance. * * @param \Illuminate\Contracts\Validation\Validator $validator * @return array */ protected function formatErrors(Validator $validator) { return $validator->getMessageBag()->toArray(); } /** * Get the URL to redirect to on a validation error. * * @return string */ protected function getRedirectUrl() { $url = $this->redirector->getUrlGenerator(); if ($this->redirect) { return $url->to($this->redirect); } elseif ($this->redirectRoute) { return $url->route($this->redirectRoute); } elseif ($this->redirectAction) { return $url->action($this->redirectAction); } return $url->previous(); } /** * Determine if the request passes the authorization check. * * @return bool */ protected function passesAuthorization() { if (method_exists($this, 'authorize')) { return $this->container->call([$this, 'authorize']); } return false; } /** * Handle a failed authorization attempt. * * @return void * * @throws \Illuminate\Auth\Access\AuthorizationException */ protected function failedAuthorization() { throw new AuthorizationException('This action is unauthorized.'); } /** * Get custom messages for validator errors. * * @return array */ public function messages() { return []; } /** * Get custom attributes for validator errors. * * @return array */ public function attributes() { return []; } /** * Set the Redirector instance. * * @param \Illuminate\Routing\Redirector $redirector * @return $this */ public function setRedirector(Redirector $redirector) { $this->redirector = $redirector; return $this; } /** * Set the container implementation. * * @param \Illuminate\Container\Container $container * @return $this */ public function setContainer(Container $container) { $this->container = $container; return $this; } }
joko-wandiro/framework
src/Illuminate/Foundation/Http/FormRequest.php
PHP
mit
6,106
/* * Copyright (C) 2009 Ashley J. Wilson, Roger E. Ostrander * This software is licensed as described in the file COPYING in the root * directory of this distribution. * * */
smashwilson/objectlite
obl/storage/chunk.c
C
mit
183
package drones.flightcontrol; /** * A pair consisting of two elements. * * Created by Sander on 5/05/2015. */ public class Pair<K, V> { public final K key; public final V value; public Pair(K first, V second) { this.key = first; this.value = second; } public K getKey() { return key; } public V getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; if (!key.equals(pair.key)) return false; if (!value.equals(pair.value)) return false; return true; } @Override public int hashCode() { int result = key.hashCode(); result = 31 * result + value.hashCode(); return result; } }
ugent-cros/cros-core
app/drones/flightcontrol/Pair.java
Java
mit
873
FROM ubuntu:latest ARG zookeeper_version=3.4.12 ARG zookeeper_home=/opt/apache-zookeeper ARG zookeeper_data_dir=/var/lib/apache-zookeeper ARG zookeeper_log_dir=${zookeeper_home}/logs ARG zookeeper_distribution_url=https://archive.apache.org/dist/zookeeper/zookeeper-${zookeeper_version}/zookeeper-${zookeeper_version}.tar.gz ENV ZOO_LOG_DIR ${zookeeper_log_dir} RUN apt-get update && \ apt-get install -y openjdk-8-jdk && \ apt-get install -y sudo \ curl \ wget \ unzip \ vim && \ apt-get clean RUN adduser --disabled-login --gecos '' zookeeper && \ usermod -G sudo zookeeper RUN echo "Defaults:zookeeper !requiretty" >> /etc/sudoers.d/zookeeper && \ echo "zookeeper ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/zookeeper && \ chmod 440 /etc/sudoers.d/zookeeper RUN cd /opt && \ wget -q ${zookeeper_distribution_url} && \ tar -zxf zookeeper-${zookeeper_version}.tar.gz && \ mv zookeeper-${zookeeper_version} apache-zookeeper && \ chown -R zookeeper.zookeeper apache-zookeeper zookeeper-${zookeeper_version}.tar.gz RUN mkdir -p ${zookeeper_data_dir} ${zookeeper_log_dir} && \ chown zookeeper.zookeeper ${zookeeper_data_dir} ${zookeeper_log_dir} WORKDIR ${zookeeper_home} ADD docker-entrypoint.sh docker-entrypoint.sh RUN chown -R zookeeper.zookeeper docker-entrypoint.sh && \ chmod a+x docker-entrypoint.sh USER zookeeper EXPOSE 2181 ENTRYPOINT ["/opt/apache-zookeeper/docker-entrypoint.sh"]
kazuhira-r/dockerfiles
apache-zookeeper/Dockerfile
Dockerfile
mit
1,591
/* Foment */ #ifdef FOMENT_WINDOWS #include <windows.h> #endif // FOMENT_WINDOWS #ifdef FOMENT_UNIX #include <pthread.h> #include <stdlib.h> #endif // FOMENT_UNIX #include <stdio.h> #include "foment.hpp" #include "execute.hpp" #include "syncthrd.hpp" EternalSymbol(WrongNumberOfArguments, "wrong number of arguments"); EternalSymbol(NotCallable, "not callable"); EternalSymbol(UnexpectedNumberOfValues, "unexpected number of values"); EternalSymbol(UndefinedMessage, "variable is undefined"); EternalSymbol(ExceptionHandlerSymbol, "exception-handler"); EternalSymbol(NotifyHandlerSymbol, "notify-handler"); EternalSymbol(SigIntSymbol, "sigint"); // ---- Roots ---- FObject InteractiveThunk = NoValueObject; static FObject ExecuteThunk = NoValueObject; static FObject NotifyHandler = NoValueObject; static FObject RaiseHandler = NoValueObject; // ---- Procedure ---- FObject MakeProcedure(FObject nam, FObject fn, FObject ln, FObject cv, long_t ac, ulong_t fl) { FProcedure * p = (FProcedure *) MakeObject(ProcedureTag, sizeof(FProcedure), 4, "%make-procedure"); p->Name = SyntaxToDatum(nam); p->Filename = fn; p->LineNumber = ln; p->Code = cv; p->ArgCount = (uint16_t) ac; p->Flags = (uint8_t) fl; return(p); } void WriteProcedure(FWriteContext * wctx, FObject obj) { FCh s[16]; long_t sl = FixnumAsString((long_t) obj, s, 16); wctx->WriteStringC("#<procedure: "); wctx->WriteString(s, sl); if (AsProcedure(obj)->Name != NoValueObject) { wctx->WriteCh(' '); wctx->Write(AsProcedure(obj)->Name); } if (AsProcedure(obj)->Flags & PROCEDURE_FLAG_CLOSURE) wctx->WriteStringC(" closure"); if (AsProcedure(obj)->Flags & PROCEDURE_FLAG_PARAMETER) wctx->WriteStringC(" parameter"); if (AsProcedure(obj)->Flags & PROCEDURE_FLAG_CONTINUATION) wctx->WriteStringC(" continuation"); if (StringP(AsProcedure(obj)->Filename) && FixnumP(AsProcedure(obj)->LineNumber)) { wctx->WriteCh(' '); wctx->Write(AsProcedure(obj)->Filename); wctx->WriteCh('['); wctx->Write(AsProcedure(obj)->LineNumber); wctx->WriteCh(']'); } // wctx->WriteCh(' '); // wctx->Write(AsProcedure(obj)->Code); wctx->WriteCh('>'); } // ---- Dynamic ---- #define AsDynamic(obj) ((FDynamic *) (obj)) #define DynamicP(obj) BuiltinP(obj, DynamicType) EternalBuiltinType(DynamicType, "dynamic", 0); typedef struct { FObject BuiltinType; FObject Who; FObject CStackPtr; FObject AStackPtr; FObject Marks; } FDynamic; static FObject MakeDynamic(FObject who, FObject cdx, FObject adx, FObject ml) { FAssert(FixnumP(cdx)); FAssert(FixnumP(adx)); FDynamic * dyn = (FDynamic *) MakeBuiltin(DynamicType, 5, "make-dynamic"); dyn->Who = who; dyn->CStackPtr = cdx; dyn->AStackPtr = adx; dyn->Marks = ml; return(dyn); } static FObject MakeDynamic(FObject dyn, FObject ml) { FAssert(DynamicP(dyn)); return(MakeDynamic(AsDynamic(dyn)->Who, AsDynamic(dyn)->CStackPtr, AsDynamic(dyn)->AStackPtr, ml)); } // ---- Continuation ---- #define AsContinuation(obj) ((FContinuation *) (obj)) #define ContinuationP(obj) BuiltinP(obj, ContinuationType) EternalBuiltinType(ContinuationType, "continuation", 0); typedef struct { FObject BuiltinType; FObject CStackPtr; FObject CStack; FObject AStackPtr; FObject AStack; } FContinuation; static FObject MakeContinuation(FObject cdx, FObject cv, FObject adx, FObject av) { FAssert(FixnumP(cdx)); FAssert(VectorP(cv)); FAssert(FixnumP(adx)); FAssert(VectorP(av)); FContinuation * cont = (FContinuation *) MakeBuiltin(ContinuationType, 5, "make-continuation"); cont->CStackPtr = cdx; cont->CStack = cv; cont->AStackPtr = adx; cont->AStack = av; return(cont); } // ---- Instruction ---- static const char * Opcodes[] = { "check-count", "rest-arg", "make-list", "push-cstack", "push-no-value", "push-want-values", "pop-cstack", "save-frame", "restore-frame", "make-frame", "push-frame", "get-cstack", "set-cstack", "get-frame", "set-frame", "get-vector", "set-vector", "get-global", "set-global", "make-box", "get-box", "set-box", "discard-result", "pop-astack", "duplicate", "return", "call", "call-proc", "call-prim", "tail-call", "tail-call-proc", "tail-call-prim", "set-arg-count", "make-closure", "if-false", "if-eqv?", "goto-relative", "goto-absolute", "check-values", "rest-values", "values", "apply", "case-lambda", "capture-continuation", "call-continuation", "abort", "return-from", "mark-continuation", "pop-mark-stack", }; void WriteInstruction(FWriteContext * wctx, FObject obj) { FAssert(InstructionP(obj)); FCh s[16]; long_t sl = FixnumAsString(InstructionArg(obj), s, 10); wctx->WriteStringC("#<"); if (InstructionOpcode(obj) < 0 || InstructionOpcode(obj) >= sizeof(Opcodes) / sizeof(char *)) wctx->WriteStringC("unknown"); else wctx->WriteStringC(Opcodes[InstructionOpcode(obj)]); wctx->WriteStringC(": "); wctx->WriteString(s, sl); wctx->WriteCh('>'); } // -------- static FObject MarkListRef(FObject ml, FObject key, FObject def) { while (PairP(ml)) { FAssert(PairP(First(ml))); if (EqP(First(First(ml)), key)) return(Rest(First(ml))); ml = Rest(ml); } FAssert(ml == EmptyListObject); return(def); } static FObject MarkListUpdate(FObject ml, FObject key, FObject val) { FAssert(PairP(ml)); FAssert(PairP(First(ml))); if (EqP(First(First(ml)), key)) return(MakePair(MakePair(key, val), Rest(ml))); return(MakePair(First(ml), MarkListUpdate(Rest(ml), key, val))); } static FObject MarkListSet(FObject ml, FObject key, FObject val) { FAssert(val != NotFoundObject); if (MarkListRef(ml, key, NotFoundObject) == NotFoundObject) return(MakePair(MakePair(key, val), ml)); return(MarkListUpdate(ml, key, val)); } static FObject FindMark(FObject key, FObject dflt) { FThreadState * ts = GetThreadState(); FObject ds = ts->DynamicStack; while (PairP(ds)) { FAssert(DynamicP(First(ds))); FObject ret = Assq(key, AsDynamic(First(ds))->Marks); if (ret != FalseObject) { FAssert(PairP(ret)); FAssert(EqP(First(ret), key)); return(Rest(ret)); } ds = Rest(ds); } FAssert(ds == EmptyListObject); return(dflt); } static long_t PrepareHandler(FThreadState * ts, FObject hdlr, FObject key, FObject obj) { if (ProcedureP(hdlr)) { FObject lst = FindMark(key, EmptyListObject); if (PairP(lst)) { ts->ArgCount = 2; ts->AStack[ts->AStackPtr] = obj; ts->AStackPtr += 1; ts->AStack[ts->AStackPtr] = lst; ts->AStackPtr += 1; ts->Proc = hdlr; ts->IP = 0; ts->Frame = NoValueObject; return(1); } else { FAssert(lst == EmptyListObject); } } return(0); } static FObject Execute(FThreadState * ts) { FObject op; for (;;) { if (ts->NotifyFlag) { ts->NotifyFlag = 0; PrepareHandler(ts, NotifyHandler, NotifyHandlerSymbol, ts->NotifyObject); } CheckForGC(); FAssert(VectorP(AsProcedure(ts->Proc)->Code)); FAssert(ts->IP >= 0); FAssert(ts->IP < (long_t) VectorLength(AsProcedure(ts->Proc)->Code)); FObject obj = AsVector(AsProcedure(ts->Proc)->Code)->Vector[ts->IP]; ts->IP += 1; if (InstructionP(obj) == 0) { ts->AStack[ts->AStackPtr] = obj; ts->AStackPtr += 1; //WritePretty(StandardOutput, obj, 0); //printf("\n"); } else { //printf("%s.%d %d %d\n", Opcodes[InstructionOpcode(obj)], InstructionArg(obj), ts->CStackPtr, ts->AStackPtr); switch (InstructionOpcode(obj)) { case CheckCountOpcode: if (ts->ArgCount != InstructionArg(obj)) RaiseException(Assertion, AsProcedure(ts->Proc)->Name, WrongNumberOfArguments, EmptyListObject); break; case RestArgOpcode: FAssert(InstructionArg(obj) >= 0); if (ts->ArgCount < InstructionArg(obj)) RaiseException(Assertion, AsProcedure(ts->Proc)->Name, WrongNumberOfArguments, EmptyListObject); else if (ts->ArgCount == InstructionArg(obj)) { ts->AStack[ts->AStackPtr] = EmptyListObject; ts->AStackPtr += 1; } else { FObject lst = EmptyListObject; long_t ac = ts->ArgCount; while (ac > InstructionArg(obj)) { ts->AStackPtr -= 1; lst = MakePair(ts->AStack[ts->AStackPtr], lst); ac -= 1; } ts->AStack[ts->AStackPtr] = lst; ts->AStackPtr += 1; } break; case MakeListOpcode: { FAssert(InstructionArg(obj) > 0); FObject lst = EmptyListObject; long_t ac = InstructionArg(obj); while (ac > 0) { ts->AStackPtr -= 1; lst = MakePair(ts->AStack[ts->AStackPtr], lst); ac -= 1; } ts->AStack[ts->AStackPtr] = lst; ts->AStackPtr += 1; break; } case PushCStackOpcode: { long_t arg = InstructionArg(obj); while (arg > 0) { FAssert(ts->AStackPtr > 0); ts->AStackPtr -= 1; ts->CStack[- ts->CStackPtr] = ts->AStack[ts->AStackPtr]; ts->CStackPtr += 1; arg -= 1; } break; } case PushNoValueOpcode: { long_t arg = InstructionArg(obj); while (arg > 0) { ts->CStack[- ts->CStackPtr] = NoValueObject; ts->CStackPtr += 1; arg -= 1; } break; } case PushWantValuesOpcode: ts->CStack[- ts->CStackPtr] = WantValuesObject; ts->CStackPtr += 1; break; case PopCStackOpcode: FAssert(ts->CStackPtr >= InstructionArg(obj)); ts->CStackPtr -= InstructionArg(obj); break; case SaveFrameOpcode: ts->CStack[- ts->CStackPtr] = ts->Frame; ts->CStackPtr += 1; break; case RestoreFrameOpcode: FAssert(ts->CStackPtr > 0); ts->CStackPtr -= 1; ts->Frame = ts->CStack[- ts->CStackPtr]; break; case MakeFrameOpcode: ts->Frame = MakeVector(InstructionArg(obj), 0, NoValueObject); break; case PushFrameOpcode: ts->AStack[ts->AStackPtr] = ts->Frame; ts->AStackPtr += 1; break; case GetCStackOpcode: FAssert(InstructionArg(obj) <= ts->CStackPtr); FAssert(InstructionArg(obj) > 0); ts->AStack[ts->AStackPtr] = ts->CStack[- (ts->CStackPtr - InstructionArg(obj))]; ts->AStackPtr += 1; break; case SetCStackOpcode: FAssert(InstructionArg(obj) <= ts->CStackPtr); FAssert(InstructionArg(obj) > 0); FAssert(ts->AStackPtr > 0); ts->AStackPtr -= 1; ts->CStack[- (ts->CStackPtr - InstructionArg(obj))] = ts->AStack[ts->AStackPtr]; break; case GetFrameOpcode: FAssert(VectorP(ts->Frame)); FAssert((ulong_t) InstructionArg(obj) < VectorLength(ts->Frame)); ts->AStack[ts->AStackPtr] = AsVector(ts->Frame)->Vector[InstructionArg(obj)]; ts->AStackPtr += 1; break; case SetFrameOpcode: FAssert(VectorP(ts->Frame)); FAssert((ulong_t) InstructionArg(obj) < VectorLength(ts->Frame)); FAssert(ts->AStackPtr > 0); ts->AStackPtr -= 1; // AsVector(ts->Frame)->Vector[InstructionArg(obj)] = ts->AStack[ts->AStackPtr]; ModifyVector(ts->Frame, InstructionArg(obj), ts->AStack[ts->AStackPtr]); break; case GetVectorOpcode: FAssert(ts->AStackPtr > 0); FAssert(VectorP(ts->AStack[ts->AStackPtr - 1])); FAssert((ulong_t) InstructionArg(obj) < VectorLength(ts->AStack[ts->AStackPtr - 1])); ts->AStack[ts->AStackPtr - 1] = AsVector(ts->AStack[ts->AStackPtr - 1])->Vector[ InstructionArg(obj)]; break; case SetVectorOpcode: FAssert(ts->AStackPtr > 1); FAssert(VectorP(ts->AStack[ts->AStackPtr - 1])); FAssert((ulong_t) InstructionArg(obj) < VectorLength(ts->AStack[ts->AStackPtr - 1])); // AsVector(ts->AStack[ts->AStackPtr - 1])->Vector[InstructionArg(obj)] = // ts->AStack[ts->AStackPtr - 2]; ModifyVector(ts->AStack[ts->AStackPtr - 1], InstructionArg(obj), ts->AStack[ts->AStackPtr - 2]); ts->AStackPtr -= 2; break; case GetGlobalOpcode: FAssert(ts->AStackPtr > 0); FAssert(GlobalP(ts->AStack[ts->AStackPtr - 1])); FAssert(BoxP(AsGlobal(ts->AStack[ts->AStackPtr - 1])->Box)); if (AsGlobal(ts->AStack[ts->AStackPtr - 1])->State == GlobalUndefined) { FAssert(AsGlobal(ts->AStack[ts->AStackPtr - 1])->Interactive == TrueObject); RaiseException(Assertion, AsProcedure(ts->Proc)->Name, UndefinedMessage, List(ts->AStack[ts->AStackPtr - 1])); } ts->AStack[ts->AStackPtr - 1] = Unbox( AsGlobal(ts->AStack[ts->AStackPtr - 1])->Box); break; case SetGlobalOpcode: FAssert(ts->AStackPtr > 1); FAssert(GlobalP(ts->AStack[ts->AStackPtr - 1])); FAssert(BoxP(AsGlobal(ts->AStack[ts->AStackPtr - 1])->Box)); if (AsGlobal(ts->AStack[ts->AStackPtr - 1])->State == GlobalImported || AsGlobal(ts->AStack[ts->AStackPtr - 1])->State == GlobalImportedModified) { FAssert(AsGlobal(ts->AStack[ts->AStackPtr - 1])->Interactive == TrueObject); // AsGlobal(ts->AStack[ts->AStackPtr - 1])->Box = MakeBox( // ts->AStack[ts->AStackPtr - 2]); Modify(FGlobal, ts->AStack[ts->AStackPtr - 1], Box, MakeBox(ts->AStack[ts->AStackPtr - 2])); // AsGlobal(ts->AStack[ts->AStackPtr - 1])->State = GlobalDefined; Modify(FGlobal, ts->AStack[ts->AStackPtr - 1], State, GlobalDefined); } SetBox(AsGlobal(ts->AStack[ts->AStackPtr - 1])->Box, ts->AStack[ts->AStackPtr - 2]); ts->AStackPtr -= 2; break; case MakeBoxOpcode: FAssert(ts->AStackPtr > 0); ts->AStack[ts->AStackPtr - 1] = MakeBox(ts->AStack[ts->AStackPtr - 1]); break; case GetBoxOpcode: FAssert(ts->AStackPtr > 0); FAssert(BoxP(ts->AStack[ts->AStackPtr - 1])); ts->AStack[ts->AStackPtr - 1] = Unbox(ts->AStack[ts->AStackPtr - 1]); break; case SetBoxOpcode: FAssert(ts->AStackPtr > 1); FAssert(BoxP(ts->AStack[ts->AStackPtr - 1])); SetBox(ts->AStack[ts->AStackPtr - 1], ts->AStack[ts->AStackPtr - 2]); ts->AStackPtr -= 2; break; case DiscardResultOpcode: FAssert(ts->AStackPtr >= 1); ts->AStackPtr -= 1; break; case PopAStackOpcode: FAssert(ts->AStackPtr >= InstructionArg(obj)); ts->AStackPtr -= InstructionArg(obj); break; case DuplicateOpcode: FAssert(ts->AStackPtr >= 1); ts->AStack[ts->AStackPtr] = ts->AStack[ts->AStackPtr - 1]; ts->AStackPtr += 1; break; case ReturnOpcode: FAssert(ts->CStackPtr >= 2); FAssert(FixnumP(ts->CStack[- (ts->CStackPtr - 1)])); FAssert(ProcedureP(ts->CStack[- (ts->CStackPtr - 2)])); ts->CStackPtr -= 1; ts->IP = AsFixnum(ts->CStack[- ts->CStackPtr]); ts->CStackPtr -= 1; ts->Proc = ts->CStack[- ts->CStackPtr]; FAssert(VectorP(AsProcedure(ts->Proc)->Code)); ts->Frame = NoValueObject; break; case CallOpcode: FAssert(ts->AStackPtr > 0); ts->AStackPtr -= 1; op = ts->AStack[ts->AStackPtr]; if (ProcedureP(op)) { CallProcedure: if ((ulong_t) ts->AStackPtr + 128 > ts->Stack.BottomUsed / sizeof(FObject)) { if (GrowMemRegionUp(&ts->Stack, (ts->AStackPtr + 128) * sizeof(FObject)) == 0) Raise(ExecuteStackOverflow); } if ((ulong_t) ts->CStackPtr + 128 > ts->Stack.TopUsed / sizeof(FObject)) { if (GrowMemRegionDown(&ts->Stack, (ts->CStackPtr + 128) * sizeof(FObject)) == 0) Raise(ExecuteStackOverflow); } if (ts->AStackPtr > ts->AStackUsed) ts->AStackUsed = ts->AStackPtr; if (ts->CStackPtr > ts->CStackUsed) ts->CStackUsed = ts->CStackPtr; ts->CStack[- ts->CStackPtr] = ts->Proc; ts->CStackPtr += 1; ts->CStack[- ts->CStackPtr] = MakeFixnum(ts->IP); ts->CStackPtr += 1; ts->Proc = op; FAssert(VectorP(AsProcedure(ts->Proc)->Code)); ts->IP = 0; ts->Frame = NoValueObject; } else if (PrimitiveP(op)) { CallPrimitive: FAssert(ts->AStackPtr >= ts->ArgCount); FObject ret = AsPrimitive(op)->PrimitiveFn(ts->ArgCount, ts->AStack + ts->AStackPtr - ts->ArgCount); ts->AStackPtr -= ts->ArgCount; ts->AStack[ts->AStackPtr] = ret; ts->AStackPtr += 1; } else RaiseException(Assertion, AsProcedure(ts->Proc)->Name, NotCallable, List(op)); break; case CallProcOpcode: FAssert(ts->AStackPtr > 0); ts->AStackPtr -= 1; op = ts->AStack[ts->AStackPtr]; FAssert(ProcedureP(op)); goto CallProcedure; case CallPrimOpcode: FAssert(ts->AStackPtr > 0); ts->AStackPtr -= 1; op = ts->AStack[ts->AStackPtr]; FAssert(PrimitiveP(op)); goto CallPrimitive; case TailCallOpcode: FAssert(ts->AStackPtr > 0); ts->AStackPtr -= 1; op = ts->AStack[ts->AStackPtr]; TailCall: if (ProcedureP(op)) { TailCallProcedure: ts->Proc = op; FAssert(VectorP(AsProcedure(ts->Proc)->Code)); ts->IP = 0; ts->Frame = NoValueObject; } else if (PrimitiveP(op)) { TailCallPrimitive: FAssert(ts->AStackPtr >= ts->ArgCount); FObject ret = AsPrimitive(op)->PrimitiveFn(ts->ArgCount, ts->AStack + ts->AStackPtr - ts->ArgCount); ts->AStackPtr -= ts->ArgCount; ts->AStack[ts->AStackPtr] = ret; ts->AStackPtr += 1; FAssert(ts->CStackPtr >= 2); ts->CStackPtr -= 1; ts->IP = AsFixnum(ts->CStack[- ts->CStackPtr]); ts->CStackPtr -= 1; ts->Proc = ts->CStack[- ts->CStackPtr]; FAssert(ProcedureP(ts->Proc)); FAssert(VectorP(AsProcedure(ts->Proc)->Code)); ts->Frame = NoValueObject; } else RaiseException(Assertion, AsProcedure(ts->Proc)->Name, NotCallable, List(op)); break; case TailCallProcOpcode: FAssert(ts->AStackPtr > 0); ts->AStackPtr -= 1; op = ts->AStack[ts->AStackPtr]; FAssert(ProcedureP(op)); goto TailCallProcedure; case TailCallPrimOpcode: FAssert(ts->AStackPtr > 0); ts->AStackPtr -= 1; op = ts->AStack[ts->AStackPtr]; FAssert(PrimitiveP(op)); goto TailCallPrimitive; case SetArgCountOpcode: ts->ArgCount = InstructionArg(obj); break; case MakeClosureOpcode: { FAssert(ts->AStackPtr > 0); FObject v[3]; ts->AStackPtr -= 1; v[0] = ts->AStack[ts->AStackPtr - 1]; v[1] = ts->AStack[ts->AStackPtr]; v[2] = MakeInstruction(TailCallProcOpcode, 0); FObject proc = MakeProcedure(NoValueObject, NoValueObject, NoValueObject, MakeVector(3, v, NoValueObject), 0, PROCEDURE_FLAG_CLOSURE); ts->AStack[ts->AStackPtr - 1] = proc; break; } case IfFalseOpcode: FAssert(ts->AStackPtr > 0); FAssert(ts->IP + InstructionArg(obj) >= 0); ts->AStackPtr -= 1; if (ts->AStack[ts->AStackPtr] == FalseObject) ts->IP += InstructionArg(obj); break; case IfEqvPOpcode: FAssert(ts->AStackPtr > 1); FAssert(ts->IP + InstructionArg(obj) >= 0); ts->AStackPtr -= 1; if (ts->AStack[ts->AStackPtr] == ts->AStack[ts->AStackPtr - 1]) ts->IP += InstructionArg(obj); break; case GotoRelativeOpcode: FAssert(ts->IP + InstructionArg(obj) >= 0); ts->IP += InstructionArg(obj); break; case GotoAbsoluteOpcode: FAssert(InstructionArg(obj) >= 0); ts->IP = InstructionArg(obj); break; case CheckValuesOpcode: FAssert(ts->AStackPtr > 0); FAssert(InstructionArg(obj) != 1); if (ValuesCountP(ts->AStack[ts->AStackPtr - 1])) { ts->AStackPtr -= 1; if (AsValuesCount(ts->AStack[ts->AStackPtr]) != InstructionArg(obj)) RaiseException(Assertion, AsProcedure(ts->Proc)->Name, UnexpectedNumberOfValues, EmptyListObject); } else RaiseException(Assertion, AsProcedure(ts->Proc)->Name, UnexpectedNumberOfValues, EmptyListObject); break; case RestValuesOpcode: { FAssert(ts->AStackPtr > 0); FAssert(InstructionArg(obj) >= 0); long_t vc; if (ValuesCountP(ts->AStack[ts->AStackPtr - 1])) { ts->AStackPtr -= 1; vc = AsValuesCount(ts->AStack[ts->AStackPtr]); } else vc = 1; if (vc < InstructionArg(obj)) RaiseException(Assertion, AsProcedure(ts->Proc)->Name, UnexpectedNumberOfValues, EmptyListObject); else if (vc == InstructionArg(obj)) { ts->AStack[ts->AStackPtr] = EmptyListObject; ts->AStackPtr += 1; } else { FObject lst = EmptyListObject; while (vc > InstructionArg(obj)) { ts->AStackPtr -= 1; lst = MakePair(ts->AStack[ts->AStackPtr], lst); vc -= 1; } ts->AStack[ts->AStackPtr] = lst; ts->AStackPtr += 1; } break; } case ValuesOpcode: if (ts->ArgCount != 1) { if (ts->CStackPtr >= 3 && WantValuesObjectP(ts->CStack[- (ts->CStackPtr - 3)])) { ts->AStack[ts->AStackPtr] = MakeValuesCount(ts->ArgCount); ts->AStackPtr += 1; } else { FAssert(ts->CStackPtr >= 2); FAssert(FixnumP(ts->CStack[- (ts->CStackPtr - 1)])); FAssert(ProcedureP(ts->CStack[- (ts->CStackPtr - 2)])); FAssert(VectorP(AsProcedure(ts->CStack[- (ts->CStackPtr - 2)])->Code)); FObject cd = AsVector(AsProcedure( ts->CStack[- (ts->CStackPtr - 2)])->Code)->Vector[ AsFixnum(ts->CStack[- (ts->CStackPtr - 1)])]; if (InstructionP(cd) == 0 || InstructionOpcode(cd) != DiscardResultOpcode) RaiseExceptionC(Assertion, "values", "caller not expecting multiple values", List(AsProcedure(ts->CStack[- (ts->CStackPtr - 2)])->Name)); if (ts->ArgCount == 0) { ts->AStack[ts->AStackPtr] = NoValueObject; ts->AStackPtr += 1; } else { FAssert(ts->AStackPtr >= ts->ArgCount); ts->AStackPtr -= (ts->ArgCount - 1); } } } break; case ApplyOpcode: { if (ts->ArgCount < 2) RaiseExceptionC(Assertion, "apply", "expected at least two arguments", EmptyListObject); FObject prc = ts->AStack[ts->AStackPtr - ts->ArgCount]; FObject lst = ts->AStack[ts->AStackPtr - 1]; long_t adx = ts->ArgCount; while (adx > 2) { ts->AStack[ts->AStackPtr - adx] = ts->AStack[ts->AStackPtr - adx + 1]; adx -= 1; } ts->ArgCount -= 2; ts->AStackPtr -= 2; if ((ulong_t) ts->CStackPtr + 128 > ts->Stack.TopUsed / sizeof(FObject)) { if (GrowMemRegionDown(&ts->Stack, (ts->CStackPtr + 128) * sizeof(FObject)) == 0) Raise(ExecuteStackOverflow); } long_t ll = ListLength("apply", lst); if ((ulong_t) ts->AStackPtr + ll + 128 > ts->Stack.BottomUsed / sizeof(FObject)) { if (GrowMemRegionUp(&ts->Stack, (ts->AStackPtr + ll + 128) * sizeof(FObject)) == 0) Raise(ExecuteStackOverflow); } if (ts->AStackPtr > ts->AStackUsed) ts->AStackUsed = ts->AStackPtr; if (ts->CStackPtr > ts->CStackUsed) ts->CStackUsed = ts->CStackPtr; FObject ptr = lst; while (PairP(ptr)) { ts->AStack[ts->AStackPtr] = First(ptr); ts->AStackPtr += 1; ts->ArgCount += 1; ptr = Rest(ptr); FAssert((ulong_t) ts->AStackPtr <= ts->Stack.BottomUsed / sizeof(FObject)); } if (ptr != EmptyListObject) RaiseExceptionC(Assertion, "apply", "expected a proper list", List(lst)); ts->AStack[ts->AStackPtr] = prc; ts->AStackPtr += 1; break; } case CaseLambdaOpcode: { long_t cc = InstructionArg(obj); long_t idx = 0; while (cc > 0) { FAssert(VectorP(AsProcedure(ts->Proc)->Code)); FAssert(ts->IP + idx >= 0); FAssert(ts->IP + idx < (long_t) VectorLength(AsProcedure(ts->Proc)->Code)); FObject prc = AsVector(AsProcedure(ts->Proc)->Code)->Vector[ts->IP + idx]; FAssert(ProcedureP(prc)); if (((AsProcedure(prc)->Flags & PROCEDURE_FLAG_RESTARG) && ts->ArgCount + 1 >= AsProcedure(prc)->ArgCount) || AsProcedure(prc)->ArgCount == ts->ArgCount) { ts->Proc = prc; FAssert(VectorP(AsProcedure(ts->Proc)->Code)); ts->IP = 0; ts->Frame = NoValueObject; break; } idx += 1; cc -= 1; } if (cc == 0) RaiseExceptionC(Assertion, "case-lambda", "no matching case", List(MakeFixnum(ts->ArgCount))); break; } case CaptureContinuationOpcode: { FAssert(ts->AStackPtr > 0); FMustBe(ts->ArgCount == 1); op = ts->AStack[ts->AStackPtr - 1]; FMustBe(ProcedureP(op)); ts->AStack[ts->AStackPtr - 1] = MakeContinuation(MakeFixnum(ts->CStackPtr), MakeVector(ts->CStackPtr, ts->CStack - ts->CStackPtr + 1, NoValueObject), MakeFixnum(ts->AStackPtr - 1), MakeVector(ts->AStackPtr - 1, ts->AStack, NoValueObject)); goto TailCall; } case CallContinuationOpcode: { FAssert(ts->AStackPtr > 1); FMustBe(ts->ArgCount == 2); FObject cont = ts->AStack[ts->AStackPtr - 2]; op = ts->AStack[ts->AStackPtr - 1]; FMustBe(ContinuationP(cont)); FMustBe(ProcedureP(op) || PrimitiveP(op)); FAssert(FixnumP(AsContinuation(cont)->AStackPtr)); ts->AStackPtr = AsFixnum(AsContinuation(cont)->AStackPtr); FAssert(VectorP(AsContinuation(cont)->AStack)); for (long_t adx = 0; adx < ts->AStackPtr; adx++) ts->AStack[adx] = AsVector(AsContinuation(cont)->AStack)->Vector[adx]; FAssert(FixnumP(AsContinuation(cont)->CStackPtr)); ts->CStackPtr = AsFixnum(AsContinuation(cont)->CStackPtr); FAssert(VectorP(AsContinuation(cont)->CStack)); FObject * cs = ts->CStack - ts->CStackPtr + 1; for (long_t cdx = 0; cdx < ts->CStackPtr; cdx++) cs[cdx] = AsVector(AsContinuation(cont)->CStack)->Vector[cdx]; ts->ArgCount = 0; goto TailCall; } case AbortOpcode: { FMustBe(ts->ArgCount == 2); ts->AStackPtr -= 1; FObject thnk = ts->AStack[ts->AStackPtr]; ts->AStackPtr -= 1; FObject dyn = ts->AStack[ts->AStackPtr]; FMustBe(ProcedureP(thnk)); FMustBe(DynamicP(dyn)); FAssert(FixnumP(AsDynamic(dyn)->CStackPtr)); FAssert(FixnumP(AsDynamic(dyn)->AStackPtr)); ts->CStackPtr = AsFixnum(AsDynamic(dyn)->CStackPtr); ts->AStackPtr = AsFixnum(AsDynamic(dyn)->AStackPtr); ts->ArgCount = 0; ts->Proc = thnk; ts->IP = 0; ts->Frame = NoValueObject; break; } case ReturnFromOpcode: FAssert(ts->AStackPtr == 1); FAssert(ts->CStackPtr == 0); return(ts->AStack[0]); case MarkContinuationOpcode: { FAssert(ts->ArgCount == 4); FAssert(ts->AStackPtr >= 4); FObject thnk = ts->AStack[ts->AStackPtr - 1]; FObject val = ts->AStack[ts->AStackPtr - 2]; FObject key = ts->AStack[ts->AStackPtr - 3]; FObject who = ts->AStack[ts->AStackPtr - 4]; ts->AStackPtr -= 4; long_t idx = ts->CStackPtr - 3; // WantValuesObject, Proc, IP if (PairP(ts->DynamicStack)) { FAssert(DynamicP(First(ts->DynamicStack))); FObject dyn = First(ts->DynamicStack); FAssert(FixnumP(AsDynamic(dyn)->CStackPtr)); if (AsDynamic(dyn)->Who == who && AsFixnum(AsDynamic(dyn)->CStackPtr) == idx) { ts->DynamicStack = MakePair(MakeDynamic(dyn, MarkListSet(AsDynamic(dyn)->Marks, key, val)), Rest(ts->DynamicStack)); ts->ArgCount = 0; op = thnk; goto TailCall; } } ts->DynamicStack = MakePair(MakeDynamic(who, MakeFixnum(ts->CStackPtr), MakeFixnum(ts->AStackPtr), MarkListSet(EmptyListObject, key, val)), ts->DynamicStack); ts->ArgCount = 0; ts->AStack[ts->AStackPtr] = thnk; ts->AStackPtr += 1; break; } case PopDynamicStackOpcode: FAssert(PairP(ts->DynamicStack)); ts->DynamicStack = Rest(ts->DynamicStack); break; default: FAssert(0); break; } } } } FObject ExecuteProc(FObject op) { FThreadState * ts = GetThreadState(); ts->AStackPtr = 1; ts->AStack[0] = op; ts->ArgCount = 1; ts->CStackPtr = 0; ts->Proc = ExecuteThunk; FAssert(ProcedureP(ts->Proc)); FAssert(VectorP(AsProcedure(ts->Proc)->Code)); ts->IP = 0; ts->Frame = NoValueObject; ts->DynamicStack = EmptyListObject; for (;;) { try { return(Execute(ts)); } catch (FObject obj) { if (PrepareHandler(ts, RaiseHandler, ExceptionHandlerSymbol, obj) == 0) throw obj; } catch (FNotifyThrow nt) { ((FNotifyThrow) nt); ts->NotifyFlag = 0; if (PrepareHandler(ts, NotifyHandler, NotifyHandlerSymbol, ts->NotifyObject) == 0) ThreadExit(ts->NotifyObject); } } } Define("procedure?", ProcedurePPrimitive)(long_t argc, FObject argv[]) { OneArgCheck("procedure?", argc); return((ProcedureP(argv[0]) || PrimitiveP(argv[0])) ? TrueObject : FalseObject); } Define("%map-car", MapCarPrimitive)(long_t argc, FObject argv[]) { // (%map-car lists) FMustBe(argc == 1); FObject ret = EmptyListObject; FObject lst = argv[0]; while (PairP(lst)) { if (PairP(First(lst)) == 0) return(EmptyListObject); ret = MakePair(First(First(lst)), ret); lst = Rest(lst); } return(ReverseListModify(ret)); } Define("%map-cdr", MapCdrPrimitive)(long_t argc, FObject argv[]) { // (%map-cdr lists) FMustBe(argc == 1); FObject ret = EmptyListObject; FObject lst = argv[0]; while (PairP(lst)) { if (PairP(First(lst)) == 0) return(EmptyListObject); ret = MakePair(Rest(First(lst)), ret); lst = Rest(lst); } return(ReverseListModify(ret)); } Define("%map-strings", MapStringsPrimitive)(long_t argc, FObject argv[]) { // (%map-strings index strings) FMustBe(argc == 2); FMustBe(FixnumP(argv[0])); FMustBe(AsFixnum(argv[0]) >= 0); long_t idx = AsFixnum(argv[0]); FObject ret = EmptyListObject; FObject lst = argv[1]; while (PairP(lst)) { StringArgCheck("string-map", First(lst)); if (idx == (long_t) StringLength(First(lst))) return(EmptyListObject); ret = MakePair(MakeCharacter(AsString(First(lst))->String[idx]), ret); lst = Rest(lst); } return(ReverseListModify(ret)); } Define("%map-vectors", MapVectorsPrimitive)(long_t argc, FObject argv[]) { // (%map-vectors index vectors) FMustBe(argc == 2); FMustBe(FixnumP(argv[0])); FMustBe(AsFixnum(argv[0]) >= 0); long_t idx = AsFixnum(argv[0]); FObject ret = EmptyListObject; FObject lst = argv[1]; while (PairP(lst)) { VectorArgCheck("vector-map", First(lst)); if (idx == (long_t) VectorLength(First(lst))) return(EmptyListObject); ret = MakePair(AsVector(First(lst))->Vector[idx], ret); lst = Rest(lst); } return(ReverseListModify(ret)); } Define("%execute-thunk", ExecuteThunkPrimitive)(long_t argc, FObject argv[]) { // (%execute-thunk <proc>) FMustBe(argc == 1); FMustBe(ProcedureP(argv[0])); ExecuteThunk = argv[0]; return(NoValueObject); } Define("%set-raise-handler!", SetRaiseHandlerPrimitive)(long_t argc, FObject argv[]) { // (%set-raise-handler! <proc>) FMustBe(argc == 1); FMustBe(ProcedureP(argv[0])); RaiseHandler = argv[0]; return(NoValueObject); } Define("%set-notify-handler!", SetNotifyHandlerPrimitive)(long_t argc, FObject argv[]) { // (%set-notify-handler! <proc>) FMustBe(argc == 1); FMustBe(ProcedureP(argv[0])); NotifyHandler = argv[0]; return(NoValueObject); } Define("%interactive-thunk", InteractiveThunkPrimitive)(long_t argc, FObject argv[]) { // (%interactive-thunk <proc>) FMustBe(argc == 1); FMustBe(ProcedureP(argv[0])); InteractiveThunk = argv[0]; return(NoValueObject); } Define("%bytes-allocated", BytesAllocatedPrimitive)(long_t argc, FObject argv[]) { // (%bytes-allocated) FMustBe(argc == 0); ulong_t ba = BytesAllocated; BytesAllocated = 0; return(MakeFixnum(ba)); } #define ParameterP(obj) (ProcedureP(obj) && (AsProcedure(obj)->Flags & PROCEDURE_FLAG_PARAMETER)) Define("%dynamic-stack", DynamicStackPrimitive)(long_t argc, FObject argv[]) { // (%dynamic-stack) // (%dynamic-stack <stack>) FMustBe(argc == 0 || argc == 1); FThreadState * ts = GetThreadState(); FObject ds = ts->DynamicStack; if (argc == 1) { FMustBe(argv[0] == EmptyListObject || PairP(argv[0])); ts->DynamicStack = argv[0]; } return(ds); } Define("%dynamic-marks", DynamicMarksPrimitive)(long_t argc, FObject argv[]) { // (%dynamic-marks <dynamic>) FMustBe(argc == 1); FMustBe(DynamicP(argv[0])); return(AsDynamic(argv[0])->Marks); } Define("%parameters", ParametersPrimitive)(long_t argc, FObject argv[]) { // (%parameters) FMustBe(argc == 0); return(GetThreadState()->Parameters); } Define("%procedure->parameter", ProcedureToParameterPrimitive)(long_t argc, FObject argv[]) { // (%procedure->parameter <proc>) FMustBe(argc == 1); FMustBe(ProcedureP(argv[0])); AsProcedure(argv[0])->Flags |= PROCEDURE_FLAG_PARAMETER; return(NoValueObject); } Define("%parameter?", ParameterPPrimitive)(long_t argc, FObject argv[]) { // (%parameter? <obj>) FMustBe(argc == 1); return(ParameterP(argv[0]) ? TrueObject : FalseObject); } Define("%index-parameter", IndexParameterPrimitive)(long_t argc, FObject argv[]) { // (%index-parameter <index>) // (%index-parameter <index> <value>) FMustBe(argc >= 1 && argc <= 2); FMustBe(FixnumP(argv[0]) && AsFixnum(argv[0]) >= 0 && AsFixnum(argv[0]) < INDEX_PARAMETERS); if (argc == 1) { FAssert(PairP(GetThreadState()->IndexParameters[AsFixnum(argv[0])])); return(GetThreadState()->IndexParameters[AsFixnum(argv[0])]); } FAssert(PairP(argv[1])); GetThreadState()->IndexParameters[AsFixnum(argv[0])] = argv[1]; return(NoValueObject); } Define("%find-mark", FindMarkPrimitive)(long_t argc, FObject argv[]) { // (%find-mark <key> <default>) FMustBe(argc == 2); return(FindMark(argv[0], argv[1])); } static FObject Fold(FObject key, FObject val, void * ctx, FObject htbl) { FAssert(ParameterP(key)); HashTableSet(htbl, key, PairP(val) ? MakePair(First(val), EmptyListObject) : EmptyListObject); return(htbl); } FObject CurrentParameters() { FObject htbl = MakeEqHashTable(32, 0); FThreadState * ts = GetThreadState(); if (HashTableP(ts->Parameters)) HashTableFold(ts->Parameters, Fold, 0, htbl); return(htbl); } static FObject Primitives[] = { ProcedurePPrimitive, MapCarPrimitive, MapCdrPrimitive, MapStringsPrimitive, MapVectorsPrimitive, ExecuteThunkPrimitive, SetRaiseHandlerPrimitive, SetNotifyHandlerPrimitive, InteractiveThunkPrimitive, BytesAllocatedPrimitive, DynamicStackPrimitive, DynamicMarksPrimitive, ParametersPrimitive, ProcedureToParameterPrimitive, ParameterPPrimitive, IndexParameterPrimitive, FindMarkPrimitive }; void SetupExecute() { FObject v[7]; RegisterRoot(&InteractiveThunk, "interactive-thunk"); RegisterRoot(&ExecuteThunk, "execute-thunk"); RegisterRoot(&NotifyHandler, "notify-handler"); RegisterRoot(&RaiseHandler, "raise-handler"); WrongNumberOfArguments = InternSymbol(WrongNumberOfArguments); NotCallable = InternSymbol(NotCallable); UnexpectedNumberOfValues = InternSymbol(UnexpectedNumberOfValues); UndefinedMessage = InternSymbol(UndefinedMessage); ExceptionHandlerSymbol = InternSymbol(ExceptionHandlerSymbol); NotifyHandlerSymbol = InternSymbol(NotifyHandlerSymbol); SigIntSymbol = InternSymbol(SigIntSymbol); FAssert(WrongNumberOfArguments == StringCToSymbol("wrong number of arguments")); FAssert(NotCallable == StringCToSymbol("not callable")); FAssert(UnexpectedNumberOfValues == StringCToSymbol("unexpected number of values")); FAssert(UndefinedMessage == StringCToSymbol("variable is undefined")); FAssert(ExceptionHandlerSymbol == StringCToSymbol("exception-handler")); FAssert(NotifyHandlerSymbol == StringCToSymbol("notify-handler")); FAssert(SigIntSymbol == StringCToSymbol("sigint")); for (ulong_t idx = 0; idx < sizeof(Primitives) / sizeof(FPrimitive *); idx++) DefinePrimitive(Bedrock, BedrockLibrary, Primitives[idx]); v[0] = MakeInstruction(ValuesOpcode, 0); v[1] = MakeInstruction(ReturnOpcode, 0); LibraryExport(BedrockLibrary, EnvironmentSetC(Bedrock, "values", MakeProcedure(StringCToSymbol("values"), MakeStringC(__FILE__), MakeFixnum(__LINE__), MakeVector(2, v, NoValueObject), 1, PROCEDURE_FLAG_RESTARG))); v[0] = MakeInstruction(ApplyOpcode, 0); v[1] = MakeInstruction(TailCallOpcode, 0); LibraryExport(BedrockLibrary, EnvironmentSetC(Bedrock, "apply", MakeProcedure(StringCToSymbol("apply"), MakeStringC(__FILE__), MakeFixnum(__LINE__), MakeVector(2, v, NoValueObject), 2, PROCEDURE_FLAG_RESTARG))); v[0] = MakeInstruction(SetArgCountOpcode, 0); v[1] = MakeInstruction(CallOpcode, 0); v[2] = MakeInstruction(ReturnFromOpcode, 0); ExecuteThunk = MakeProcedure(NoValueObject, MakeStringC(__FILE__), MakeFixnum(__LINE__), MakeVector(3, v, NoValueObject), 1, 0); // (%return <value>) v[0] = MakeInstruction(ReturnFromOpcode, 0); LibraryExport(BedrockLibrary, EnvironmentSetC(Bedrock, "%return", MakeProcedure(StringCToSymbol("%return-from"), MakeStringC(__FILE__), MakeFixnum(__LINE__), MakeVector(1, v, NoValueObject), 1, 0))); // (%capture-continuation <proc>) v[0] = MakeInstruction(CaptureContinuationOpcode, 0); LibraryExport(BedrockLibrary, EnvironmentSetC(Bedrock, "%capture-continuation", MakeProcedure(StringCToSymbol("%capture-continuation"), MakeStringC(__FILE__), MakeFixnum(__LINE__), MakeVector(1, v, NoValueObject), 1, 0))); // (%call-continuation <cont> <thunk>) v[0] = MakeInstruction(CallContinuationOpcode, 0); LibraryExport(BedrockLibrary, EnvironmentSetC(Bedrock, "%call-continuation", MakeProcedure(StringCToSymbol("%call-continuation"), MakeStringC(__FILE__), MakeFixnum(__LINE__), MakeVector(1, v, NoValueObject), 2, 0))); // (%mark-continuation <who> <key> <value> <thunk>) v[0] = MakeInstruction(CheckCountOpcode, 4); v[1] = MakeInstruction(MarkContinuationOpcode, 0); v[2] = MakeInstruction(PushWantValuesOpcode, 0); v[3] = MakeInstruction(CallOpcode, 0); v[4] = MakeInstruction(PopCStackOpcode, 1); v[5] = MakeInstruction(PopDynamicStackOpcode, 0); v[6] = MakeInstruction(ReturnOpcode, 0); LibraryExport(BedrockLibrary, EnvironmentSetC(Bedrock, "%mark-continuation", MakeProcedure(StringCToSymbol("%mark-continuation"), MakeStringC(__FILE__), MakeFixnum(__LINE__), MakeVector(7, v, NoValueObject), 4, 0))); // (%abort-dynamic <dynamic> <thunk>) v[0] = MakeInstruction(AbortOpcode, 0); LibraryExport(BedrockLibrary, EnvironmentSetC(Bedrock, "%abort-dynamic", MakeProcedure(StringCToSymbol("%abort-dynamic"), MakeStringC(__FILE__), MakeFixnum(__LINE__), MakeVector(1, v, NoValueObject), 2, 0))); }
leftmike/foment
src/execute.cpp
C++
mit
48,072
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Bookmarks</title> <link rel="stylesheet" type="text/css" href="css/main.css"> </head> <body> <ul> <li><a href="/?ip[]=184.105.139.66-184.105.139.126&ip[]=184.105.247.194-184.105.247.254&ip[]=74.82.47.1-74.82.47.63&ip[]=216.218.206.66-216.218.206.126">shadowserver.org</a></li> <li><a href="/?ip[]=71.6.216.32/27">labs.rapid7.com</a></li> <li><a href="/?ip[]=66.240.192.138&ip[]=66.240.236.119&ip[]=71.6.135.131&ip[]=71.6.165.200&ip[]=71.6.167.142&ip[]=82.221.105.6&ip[]=82.221.105.7&ip[]=85.25.43.94&ip[]=85.25.103.50&ip[]=93.120.27.62&ip[]=104.131.0.69&ip[]=104.236.198.48&ip[]=162.159.244.38&ip[]=188.138.9.50&ip[]=198.20.69.74&ip[]=198.20.69.98&ip[]=198.20.70.114&ip[]=198.20.99.130&ip[]=208.180.20.97">shodan.io</a></li> <li><a href="/?ip[]=204.42.253.2&ip[]=204.42.253.130&ip[]=204.42.253.131&ip[]=204.42.253.132&ip[]=204.42.254.5">open(snmp|ssdp|ntp|resolver)project.org</a></li> <li><a href="/?ip[]=141.212.121.0/24&ip[]=141.212.122.0/24">eecs.umich.edu</a></li> <li><a href="/?ip[]=129.82.138.12&ip[]=129.82.138.31&ip[]=129.82.138.32&ip[]=129.82.138.33&ip[]=129.82.138.34&ip[]=129.82.138.44">netsec.colostate.edu</a></li> <li><a href="/?ip[]=128.9.168.98&ip[]=203.178.148.18&ip[]=203.178.148.19">ant.isi.edu</a></li> <li><a href="/?ip[]=169.229.3.89&ip[]=169.229.3.90&ip[]=169.229.3.91&ip[]=169.229.3.92&ip[]=169.229.3.93&ip[]=169.229.3.94">eecs.berkeley.edu</a></li> </ul> </body> </html>
stamparm/tsusen
html/bookmarks.html
HTML
mit
1,622
namespace _03.Card_Power { public enum Rank { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } }
sevdalin/Software-University-SoftUni
C-sharp-Web-Developer/C# OOP Advanced/04. Enums and Attributes/07. Deck Of Cards/Rank.cs
C#
mit
245
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>monae: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.9.1 / monae - 0.0.6</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> monae <small> 0.0.6 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-01-31 22:04:34 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-31 22:04:34 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.9.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/affeldt-aist/monae&quot; bug-reports: &quot;https://github.com/affeldt-aist/monae/issues&quot; dev-repo: &quot;git+https://github.com/affeldt-aist/monae.git&quot; license: &quot;GPL-3.0-or-later&quot; authors: [ &quot;Reynald Affeldt&quot; &quot;David Nowak&quot; &quot;Takafumi Saikawa&quot; &quot;Jacques Garrigue&quot; &quot;Celestine Sauvage&quot; &quot;Kazunari Tanaka&quot; ] build: [ [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] depends: [ &quot;coq&quot; { &gt;= &quot;8.10&quot; &amp; &lt; &quot;8.12~&quot; } &quot;coq-infotheo&quot; { &gt;= &quot;0.0.7&quot; &amp; &lt; &quot;0.1&quot; } ] synopsis: &quot;Monae&quot; description: &quot;&quot;&quot; This repository contains a formalization of monads including several models, examples of monadic equational reasoning, and an application to program semantics. &quot;&quot;&quot; tags: [ &quot;category:Computer Science/Semantics and Compilation/Semantics&quot; &quot;keyword: monads&quot; &quot;keyword: effects&quot; &quot;keyword: probability&quot; &quot;keyword: nondeterminism&quot; &quot;logpath:monae&quot; &quot;date:2019-12-06&quot; ] url { http: &quot;https://github.com/affeldt-aist/monae/archive/0.0.6.tar.gz&quot; checksum: &quot;sha512=6b4d32e7fe1833c4b481135e2a8e2c70c290d182e9c63fe42ca499f16647a6b24746f246edec136692aa82a2d37e4d3df58440d116022b29cae459413ed7ceb3&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-monae.0.0.6 coq.8.9.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.9.1). The following dependencies couldn&#39;t be met: - coq-monae -&gt; coq &gt;= 8.10 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-monae.0.0.6</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.08.1-2.0.5/released/8.9.1/monae/0.0.6.html
HTML
mit
7,206
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>stalmarck: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.12.0 / stalmarck - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> stalmarck <small> 8.9.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-08-26 04:03:56 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-26 04:03:56 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.12.0 Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.10.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.0 Official release 4.10.0 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-community/stalmarck&quot; dev-repo: &quot;git+https://github.com/coq-community/stalmarck.git&quot; bug-reports: &quot;https://github.com/coq-community/stalmarck/issues&quot; license: &quot;LGPL-2.1-or-later&quot; synopsis: &quot;Proof of Stålmarck&#39;s algorithm in Coq&quot; description: &quot;&quot;&quot; A two-level approach to prove tautologies using Stålmarck&#39;s algorithm in Coq. &quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;category:Computer Science/Decision Procedures and Certified Algorithms/Decision procedures&quot; &quot;category:Miscellaneous/Extracted Programs/Decision procedures&quot; &quot;keyword:boolean formula&quot; &quot;keyword:tautology checker&quot; &quot;logpath:Stalmarck&quot; &quot;date:2019-05-19&quot; ] authors: [ &quot;Pierre Letouzey&quot; &quot;Laurent Théry&quot; ] url { src: &quot;https://github.com/coq-community/stalmarck/archive/v8.9.0.tar.gz&quot; checksum: &quot;sha256=c0c6958e059d632cca0d0e67ff673d996abb0c9e389ecdffa9d1e1186884168b&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-stalmarck.8.9.0 coq.8.12.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.12.0). The following dependencies couldn&#39;t be met: - coq-stalmarck -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-stalmarck.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.10.0-2.0.6/released/8.12.0/stalmarck/8.9.0.html
HTML
mit
6,893
# 0.2.1 * Fixed: the module failing with TypeError in Node.js 0.12. # 0.2.0 * Added: `parent` property to all nodes that are inside a container. * Added: `colon` type of a node. # 0.1.0 Initial release
ChesterHub/RFLCTT
node_modules/postcss-media-query-parser/CHANGELOG.md
Markdown
mit
214
# Kanboard Kanboard is a simple visual task board web application. Official website: http://kanboard.net - Inspired by the Kanban methodology - Get a visual and clear overview of your project - Multiple boards with the ability to drag and drop tasks - Minimalist software, focus only on essential features (Less is more) - Open source and self-hosted - Super simple installation # Documentation This installation is using Nginx, php5-fpm and SQLite to download and run the latest kanboard. ## Usage _tl;dr_ Simply type the following command: <code>docker run -d --name=kanboard -p 80:80 benoit/kanboard</code> Now open your brower to http://127.0.0.1/kanboard and log in as admin/admin. You can provide custom config files for nginx and php-fpm using external volumes: - Nginx config file is /etc/nginx/nginx.conf - php-fpm config file is /etc/php/fpm/php-fpm.conf Users are strongly advised to store datas outside your Docker Container. You should have the folder /usr/share/nginx/html/kanboard/data mounted from an external volume. Adapt the command line and your configuration to your needs.
benoit-g/kanboard
README.md
Markdown
mit
1,104
from r_support import * from loda_support import * from test_setups import * from alad import * def test_load_model_csv(opts): opts.set_multi_run_options(1, 1) modelmanager = ModelManager.get_model_manager("csv") model = modelmanager.load_model(opts) print "model loaded..." def test_load_data(args): filepath = os.path.join(args.filedir, args.dataset + "_1.csv") print filepath data = read_csv(filepath, header=True) print "data loaded..." def test_load_samples(opts): alldata = load_all_samples(opts.dataset, opts.filedir, [1], opts) #logger.debug(alldata[0].lbls) #logger.debug(alldata[0].fmat) print "Loaded samples..." def test_loda(opts): alldata = load_all_samples(opts.dataset, opts.filedir, [1], opts) #logger.debug(alldata[0].lbls) #logger.debug(alldata[0].fmat) print "Loaded samples..." a = alldata[0].fmat logger.debug(a.shape) if opts.randseed > 0: np.random.seed(opts.randseed) #args.original_dims = True lodares = loda(a, sparsity=opts.sparsity, mink=opts.mink, maxk=opts.maxk, keep=opts.keep, exclude=opts.exclude, original_dims=opts.original_dims) model = generate_model_from_loda_result(lodares, a, alldata[0].lbls) logger.debug("The neg-log-lik scores in the model will be treated as ensemble scores") logger.debug("model.nlls.shape: %s;\nThere are %d instances and %d ensemble members (each LODA projection is one member)" % (str(model.nlls.shape), model.nlls.shape[0], model.nlls.shape[1])) logger.debug(model.nlls) print "Completed LODA..." def pdf_hist_bin(x, h, minpdf=1e-8): """Returns the histogram bins for input values. Used for debugging only... """ n = len(x) pd = np.zeros(n, dtype=int) for j in range(n): # use simple index lookup in case the histograms are equal width # this returns the lower index i = get_bin_for_equal_hist(h.breaks, x[j]) if i >= len(h.density): i = len(h.density)-1 # maybe something else should be done here pd[j] = i+1 # adding 1 to make it like R # max(h.density[i], minpdf) return pd # get all bins from individual histograms. def get_all_hist_pdf_bins(a, w, hists): """Returns the histogram bins for input values. Used for debugging only... """ x = a.dot(w) bins = np.zeros(shape=(len(x), len(hists)), dtype=int) for i in range(len(hists)): bins[:, i] = pdf_hist_bin(x[:, i], hists[i]) return bins def test_show_baseline(opts): data = load_all_samples(opts.dataset, opts.filedir, range(opts.minfid, opts.maxfid + 1), opts) logger.debug("data loaded...") modelmanager = ModelManager.get_model_manager(opts.cachetype) ensembles = get_loda_alad_ensembles(range(opts.minfid, opts.maxfid + 1), range(1, opts.reruns + 1), data, opts) for i, fid in enumerate(range(opts.minfid, opts.maxfid+1)): fensembles = ensembles[i] for j, runidx in enumerate(range(1, opts.reruns+1)): opts.set_multi_run_options(fid, runidx) model = None if False: lodares = modelmanager.load_model(opts) model = generate_model_from_loda_result(lodares, data[i].fmat, data[i].lbls) ensemble = LodaEnsemble.ensemble_from_lodares(lodares, data[i].fmat, data[i].lbls) if False: hpdfs = get_all_hist_pdfs(data[i].fmat, lodares.pvh.pvh.w, lodares.pvh.pvh.hists) prefix = opts.model_file_prefix() fname = os.path.join(opts.cachedir, "%s-hpdfs.csv" % (prefix,)) np.savetxt(fname, hpdfs, fmt='%.15f', delimiter=',') logger.debug(lodares.pvh.pvh.hists[0].breaks) logger.debug(lodares.pvh.pvh.hists[0].density) else: ensemble = fensembles[j] #logger.debug("model loaded...") #nll = np.mean(model.nlls, axis=1, dtype=float) #logger.debug("#scores: %d" % (len(nll),)) #logger.debug(nll) #logger.debug("#anoms: %d" % (np.sum(data[0].lbls),)) #logger.debug(data[0].lbls) if model is not None: ordered = order(model.anom_score, decreasing=True) logger.debug("\n%s" % (list(np.cumsum(model.lbls[ordered])[0:opts.budget]),)) #logger.debug(data[0].lbls[ordered]) ordered = order(ensemble.agg_scores, decreasing=True) logger.debug("\n%s" % (list(np.cumsum(ensemble.labels[ordered])[0:opts.budget]),)) def test_histogram(opts): data = load_all_samples(opts.dataset, opts.filedir, range(opts.minfid, opts.maxfid + 1), opts) logger.debug("data loaded...") logger.debug(ncol(data[0].fmat)) for i in range(ncol(data[0].fmat)): x = data[0].fmat[:, i] #logger.debug(x) hist = histogram_r(x) #logger.debug(hist.breaks) #logger.debug(hist.counts) logger.debug(hist.density) def test_ensemble_load(opts): samples = load_samples(opts.datafile, opts) logger.debug("Loaded samples...") em = PrecomputedEnsemble(opts) ensemble = em.load_data(samples.fmat, samples.lbls, opts) logger.debug("Loaded ensemble...") def test_alad(opts): alad_results = alad(opts) write_sequential_results_to_csv(alad_results, opts) logger.debug("completed test_alad...") def run_test(args): configure_logger(args) opts = Opts(args) logger.debug(opts.str_opts()) if args.op == "load": test_load_data(opts) elif args.op == "samples": test_load_samples(opts) elif args.op == "loda": test_loda(opts) elif args.op == "csvmodel": test_load_model_csv(opts) elif args.op == "baseline": test_show_baseline(opts) elif args.op == "hist": test_histogram(opts) elif args.op == "ensemble": test_ensemble_load(opts) elif args.op == "alad": test_alad(opts) else: raise ValueError("Invalid operation: %s" % (args.op,))
shubhomoydas/pyaad
pyalad/unit_tests.py
Python
mit
6,173
// // GameView.h // Yoga // // Created by Van on 12/07/2013. // Copyright (c) 2013 ustwo. All rights reserved. // #import <SpriteKit/SpriteKit.h> #import "CGPointExtension.h" #import "ShapeNode.h" #import "MouseJoint.h" #import "ScreenUtil.h" @interface BaseScene : SKScene <SKPhysicsContactDelegate> { } @property (nonatomic) NSTimeInterval lastUpdateTimeInterval; // the previous update: loop time interval @property (nonatomic) CFTimeInterval timeSinceLast; // the previous update: loop time interval @end
vanustwo/gogoFishing
gogofishing/Classes/BaseScene.h
C
mit
519
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <base data-ice="baseUrl" href="../../"> <title data-ice="title">src/debug.js | F.lux API Document</title> <link type="text/css" rel="stylesheet" href="css/style.css"> <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css"> <script src="script/prettify/prettify.js"></script> <script src="script/manual.js"></script> </head> <body class="layout-container" data-ice="rootContainer"> <header> <a href="./">Home</a> <a href="identifiers.html">Reference</a> <a href="source.html">Source</a> <a data-ice="repoURL" href="https://github.com/akrumel/f.lux" class="repo-url-github">Repository</a> <div class="search-box"> <span> <img src="./image/search.png"> <span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span> </span> <ul class="search-result"></ul> </div> </header> <nav class="navigation" data-ice="nav"><div> <ul> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/Access.js~Access.html">Access</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/ArrayProperty.js~ArrayProperty.html">ArrayProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/ArrayShadow.js~ArrayShadow.html">ArrayShadow</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/AutoShader.js~AutoShader.html">AutoShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/IndexedApi.js~IndexedApi.html">IndexedApi</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/IndexedProperty.js~IndexedProperty.html">IndexedProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/IndexedShadow.js~IndexedShadow.html">IndexedShadow</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/IndexedShadowImpl.js~IndexedShadowImpl.html">IndexedShadowImpl</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/IsolatedAccess.js~IsolatedAccess.html">IsolatedAccess</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/IsolatedApi.js~IsolatedApi.html">IsolatedApi</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/IsolatedObjectShadowImpl.js~IsolatedObjectShadowImpl.html">IsolatedObjectShadowImpl</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/IsolatedProperty.js~IsolatedProperty.html">IsolatedProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/IsolatedShadow.js~IsolatedShadow.html">IsolatedShadow</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/IsolatedShadowImpl.js~IsolatedShadowImpl.html">IsolatedShadowImpl</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/KeyedApi.js~KeyedApi.html">KeyedApi</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/MapProperty.js~MapProperty.html">MapProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/MapShadow.js~MapShadow.html">MapShadow</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/ObjectProperty.js~ObjectProperty.html">ObjectProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/ObjectShadowImpl.js~ObjectShadowImpl.html">ObjectShadowImpl</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/PrimitiveProperty.js~PrimitiveProperty.html">PrimitiveProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/PrimitiveShadowImpl.js~PrimitiveShadowImpl.html">PrimitiveShadowImpl</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/Property.js~Property.html">Property</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/PropertyFactoryShader.js~PropertyFactoryShader.html">PropertyFactoryShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/Shader.js~Shader.html">Shader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/Shadow.js~Shadow.html">Shadow</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/ShadowImpl.js~ShadowImpl.html">ShadowImpl</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/StateType.js~StateType.html">StateType</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/Store.js~Store.html">Store</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/TransientProperty.js~TransientLock.html">TransientLock</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/TransientProperty.js~TransientProperty.html">TransientProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/TransientProperty.js~TransientShadow.html">TransientShadow</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/TransientsProperty.js~TransientsProperty.html">TransientsProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/TransientsProperty.js~TransientsShadow.html">TransientsShadow</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-createPropertyClass">createPropertyClass</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">__tests__</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/__tests__/LifecycleProperty.js~LifecycleProperty.html">LifecycleProperty</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">collection</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/collection/CollectionProperty.js~CollectionProperty.html">CollectionProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/collection/CollectionShadow.js~CollectionShadow.html">CollectionShadow</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/collection/ModelAccess.js~ModelAccess.html">ModelAccess</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/collection/ModelProperty.js~ModelProperty.html">ModelProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/collection/PojoEndpointProperty.js~PojoEndpointProperty.html">PojoEndpointProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/collection/PojoQueryBuilder.js~PojoQueryBuilder.html">PojoQueryBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/collection/RestEndpointProperty.js~RestEndpointProperty.html">RestEndpointProperty</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/collection/RestQueryBuilder.js~RestQueryBuilder.html">RestQueryBuilder</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/collection/ShadowModelAccess.js~ShadowModelAccess.html">ShadowModelAccess</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-extendOptions">extendOptions</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-getOptions">getOptions</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-setOptions">setOptions</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-DEFAULTS_OPTION">DEFAULTS_OPTION</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-MERGE_OPTION">MERGE_OPTION</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-NONE_OPTION">NONE_OPTION</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-REPLACE_OPTION">REPLACE_OPTION</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-AllOp">AllOp</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-ChangeEvent">ChangeEvent</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-CreateOp">CreateOp</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-DeletedEvent">DeletedEvent</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-DestroyOp">DestroyOp</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-ErrorEvent">ErrorEvent</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-FetchOp">FetchOp</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-FetchedEvent">FetchedEvent</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-FindOp">FindOp</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-FoundEvent">FoundEvent</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-SavedEvent">SavedEvent</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-UpdateOp">UpdateOp</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">decorators</div><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-automount">automount</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-mixin">mixin</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-shadow">shadow</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-shadowBound">shadowBound</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-shadowPropertyHelper">shadowPropertyHelper</a></span></span></li> <li data-ice="doc"><div data-ice="dirPath" class="nav-dir-path">listeners</div><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/listeners/Logger.js~Logger.html">Logger</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-createConsoleLogger">createConsoleLogger</a></span></span></li> </ul> </div> </nav> <div class="content" data-ice="content"><h1 data-ice="title">src/debug.js</h1> <pre class="source-code line-number raw-source-code"><code class="prettyprint linenums" data-ice="content">import { isNative } from &quot;akutils&quot;; var debug = isNative() ?require(&quot;react-native-debug&quot;) :require(&quot;debug&quot;); //----------------------------------------------------------------------------------------------------------- // Debug level functions //----------------------------------------------------------------------------------------------------------- const ErrorKey = &apos;f.lux:error&apos;; const InfoKey = &apos;f.lux:info&apos;; const WarningKey = &apos;f.lux:warn&apos;; if (process.env.NODE_ENV !== &apos;production&apos;) { // comment out one or more of following line to disable error/warning reporting debug.enable(ErrorKey); debug.enable(InfoKey); debug.enable(WarningKey); } /** @ignore */ export const error = debug(ErrorKey); /** @ignore */ export const info = debug(InfoKey); /** @ignore */ export const warn = debug(WarningKey); //----------------------------------------------------------------------------------------------------------- // Functional flags //----------------------------------------------------------------------------------------------------------- /** @ignore */ export const AllKey = &apos;f.lux:*&apos;; /** @ignore */ export const CollectionAllKey = &apos;f.lux:collection:*&apos;; /** @ignore */ export const CollectionPropertyKey = &apos;f.lux:collection:property&apos;; /** @ignore */ export const CollectionRestEndpointPropertyKey = &apos;f.lux:collection:restEnpointProperty&apos;; /** @ignore */ export const CollectionPojoEndpointPropertyKey = &apos;f.lux:collection:pojoEnpointProperty&apos;; /** @ignore */ export const ShadowImplKey = &apos;f.lux:shadowImpl&apos;; /** @ignore */ export const StoreKey = &apos;f.lux:store&apos;; /** @ignore */ export const TransientKey = &apos;f.lux:transient&apos;; // uncomment to turn on all postop-stores logging (or selectively using one of keys above) //debug.enable(AllKey); function debugoff() { } /** @ignore */ export default function devDebug(modname) { if (process.env.NODE_ENV !== &apos;production&apos;) { let appDebug = debug(modname); return function appDebugFn(cb) { cb(appDebug); } } else { return debugoff; } }</code></pre> </div> <footer class="footer"> Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(0.5.2)</span><img src="./image/esdoc-logo-mini-black.png"></a> </footer> <script src="script/search_index.js"></script> <script src="script/search.js"></script> <script src="script/pretty-print.js"></script> <script src="script/inherited-summary.js"></script> <script src="script/test-summary.js"></script> <script src="script/inner-link.js"></script> <script src="script/patch-for-local.js"></script> </body> </html>
akrumel/f.lux
docs/api/file/src/debug.js.html
HTML
mit
17,684
using Fpm.MainUI.Helpers; using Fpm.MainUI.Models; using Fpm.ProfileData; using Fpm.ProfileData.Entities.Profile; using Newtonsoft.Json; using System; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace Fpm.MainUI.Controllers { [RoutePrefix("documents")] public class DocumentsController : Controller { public const int MaxFileSizeInBytes = 50000000/*50MB*/; private readonly IProfilesReader _reader; private readonly IProfilesWriter _writer; public DocumentsController(IProfilesReader reader, IProfilesWriter writer) { _reader = reader; _writer = writer; } [Route] public ActionResult DocumentsIndex(int profileId = ProfileIds.Undefined) { var user = UserDetails.CurrentUser(); if (profileId != ProfileIds.Undefined && user.HasWritePermissionsToProfile(profileId) == false) { profileId = ProfileIds.Undefined; } var viewModel = GetViewModel(profileId); viewModel.ProfileList = ProfileMenuHelper.GetProfileListForCurrentUser(); ViewBag.DocumentItems = _reader.GetDocumentsWithoutFileData(profileId); ViewBag.ProfileId = profileId; return View(viewModel); } [HttpPost] [Route("upload")] public ActionResult Upload(int uploadProfileId) { if (Request != null) { HttpPostedFileBase file = Request.Files["fileToBeUploaded"]; if (file != null) { byte[] uploadedFile = new byte[file.InputStream.Length]; file.InputStream.Read(uploadedFile, 0, uploadedFile.Length); if (uploadedFile.Length > MaxFileSizeInBytes) { throw new FpmException("Max file upload size is 50 MB"); } var fileName = Path.GetFileName(file.FileName); // check is filename unique. var docs = _reader.GetDocumentsWithoutFileData(fileName); if (docs.Count > 0) { // now check is this name used with current profile. var docFromDatabase = docs.FirstOrDefault(x => x.ProfileId == uploadProfileId); if (docFromDatabase != null) { docFromDatabase.ProfileId = uploadProfileId; docFromDatabase.FileName = fileName; docFromDatabase.FileData = uploadedFile; docFromDatabase.UploadedBy = UserDetails.CurrentUser().Name; docFromDatabase.UploadedOn = DateTime.Now; _writer.UpdateDocument(docFromDatabase); } } else { // else overwrite current file for selected profile. var doc = new Document { ProfileId = uploadProfileId, FileName = fileName, FileData = uploadedFile, UploadedBy = UserDetails.CurrentUser().Name, UploadedOn = DateTime.Now }; _writer.NewDocument(doc); } } } return RedirectToAction("DocumentsIndex", new { profileId = uploadProfileId }); } [Route("is-filename-unique")] public ActionResult IsFileNameUnique(string filename, int profileId) { var isUnique = new FileNameHelper(_reader).IsUnique(filename, profileId); return new JsonResult { Data = isUnique, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } [HttpPost] [Route("delete")] public ActionResult Delete(int id) { Document doc = _reader.GetDocumentWithoutFileData(id); if (doc == null) { throw new FpmException("Content item could not be deleted with id " + id); } if (UserDetails.CurrentUser().HasWritePermissionsToProfile(doc.ProfileId)) { _writer.DeleteDocument(doc); return new JsonResult { Data = "Success", JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } throw new FpmException("User does not have the right to delete document " + id); } [HttpPost] [Route("publish")] public async Task<ActionResult> Publish(int id) { // Read the live update key from the configuration string liveUpdateKey = AppConfig.GetLiveUpdateKey(); // Read the api url from the configuration string apiUrl = AppConfig.GetLiveSiteWsUrl(); apiUrl = apiUrl + "api/document"; // Read the document with file data to be published Document document = _reader.GetDocumentWithFileData(id); // If document not found then throw exception if (document == null) { throw new FpmException("Content item could not be published with id " + id); } // Setup the http client object and post asynchronously to the web api method // to publish the document on live server using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(apiUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // Serialise and add the live update key and document to the multi part form data content using (var formData = new MultipartFormDataContent()) { formData.Add(new StringContent(JsonConvert.SerializeObject(liveUpdateKey)), "LiveUpdateKey"); formData.Add(new StringContent(JsonConvert.SerializeObject(document)), "Document"); // Post asynchronously the request to the web api method HttpResponseMessage response = await client.PostAsync(apiUrl, formData); // If the publishing of the document succeeded then return a json result if (response.IsSuccessStatusCode) { return new JsonResult { Data = "Success", JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } } } // If the code execution reached here throw exception throw new FpmException("Publishing live failed for the document " + id); } private static DocumentsGridModel GetViewModel(int profileId) { var viewModel = new DocumentsGridModel { SortBy = "Sequence", SortAscending = true, CurrentPageIndex = 1, PageSize = 100, ProfileId = profileId }; return viewModel; } } }
PublicHealthEngland/fingertips-open
FingertipsProfileManager/MainUI/Controllers/DocumentsController.cs
C#
mit
7,714